text:
Q: Testing JavaScript in CakePHP In my CakePHP project, I'd like to run unit-tests of my JavaScript codes for the views. I'm trying to use QUnit for testing JavaScript.

*

*Is CakePHP's testing framework capable of integrating JavaScript tests?

*Where should I put the test codes?

*Is there any example or information for that?

*Should I consider Selenium for this purpose?

A: *

*It is a php framework, what makes you think you can test another
language with that?

*I would not put them into webroot/js/test and disable access to that folder via .htaccess
in the live environment

*http://qunitjs.com/cookbook/

*Yes, because it sounds you want to test that the whole rendered page works. I'm not sure what you exactly want to test.


text:
Q: Dynamic data type choosing based on template suppose I have an object like this:
class Spline {
public:
    Spline(std::size_t const dim);
    // Quite a few functions here. One of those:
    vec operator()(double const t) const; // Returns vector of dimension d
}

Now, at most uses of this class, the dimension will already be determined at compile time, thus it would be a good idea (for performance reasons) to change the class like this:
template <std::size_t dim>
class Spline {
public:
    Spline();
    // Quite a few functions here. One of those:
    vec::fixed<dim> operator()(double const t) const; // Returns vector of dimension d
}

(For those who wonder, vec and vec::fixed are objects defined by the armadillo linear algebra library). Now I would like to have both versions living in parallel, thus being able to choose the dimension at compile time as well as during runtime. In short, I would like to create the equivalent of vec::fixed<dim> as Spline::fixed<dim>, but without implementing all functions twice. Especially, I would have to choose the return type of all those functions depending on whether there is a template argument present or not.
Do you have any idea how I might accomplish this, especially thinking in terms of a clear and maintainable design? (In the hope that I made myself clear, which I am not totally sure about.)

A: Use a simple traits metastruct and specialize that.
template<std::size_t dim>
struct spline_return_traits{
  typedef vec::fixed<dim> type;
};

template<>
struct spline_return_traits<0>{ // 0 is a special marker for runtime dimensions
  typedef vec type;
};

template<std::size_t dim>
class Spline_impl{
  typedef typename spline_return_traits<dim>::type spline_return;
public:
  spline_return operator()(double const t) const;
// if <dim> is 0, then the dynamic vec will be chosen as the return type
  // all your functions
};

class Spline : public Spline_impl<0>{ // default is dynamic
public:
  template<int dim>
  struct fixed : public Spline_impl<dim>{
  };
};

Now you simple use that. :) Every operator, constructor and function of Spline_impl should be available in the subclasses. For the implementation of each function, you need to do some branching where it's a must to decide between runtime or fixed vec:
if(dim == 0){
  // runtime specific stuff
}else{
  // compile-time specific stuff
}

Use as:
Spline dynamic_spline;
Spline::fixed<10> fixed_10_spline;

Only problem being that the Spline class will be double the size of Spline_impl... :/ Lemme think if I can find a solution to that too.
Edit: If you don't want Spline to be double the size of Spline_impl, one possibility is to add a little verbosity and a typedef:
class Spline : public Spline_impl<0>{ // default is dynamic size
public:
  template<std::size_t dim>
  struct fixed{
    typedef Spline_impl<dim> type;
  };
};

And use as
Spline dynamic_spline;
typename Spline::fixed<10>::type fixed_10_spline;

A: If I understand your question correctly, you want a struct for compile time usage and runtime usage as well with preferably same name. In my opinion, you can declare the class as template and then specialize one of its instance (say size_t = 0xffffffff), which you may not be using. You can declare all your definitions for runtime usage in that instance.
For example,
template<std::size_t dim = ~0> // choose default dimension(0xffffffff) not to be used
class Spline {
public:
  Spline () {}
  vec::fixed<dim> operator () (double const t) const {}
};
template<>
class Spline<~0> {  // specialize the default dimension for runtime use
public:
  Spline (std::size_t const dim) {}
  vec operator () (double const t) const {}
};

It can be used as below:
Spline<5> o5;  // compile time dimensions
Spline<> o0(3); // run time dimensions (don't mention anything in template)

A: You can just overload it. Making a non-duplicate implementation, however, is a problem with no generic solution, unless you have more template magic that can do this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How I can get the Sum from following Query? DECLARE @VARIABLE AS BIGINT
SET @VARIABLE = Sum((Select Top 5 SUM(Quantity) FROM Orders Group by MenuItemName Order by Quantity Desc))
Print @VARIABLE

This Will Return a Error :

Cannot perform an aggregate function on an expression containing an
  aggregate or a subquery

How I can Achieve that ?

A: Considering you want to order the records in sum(Quantity) not just Quantity
Try this way
DECLARE @VARIABLE AS BIGINT

SET @VARIABLE = (SELECT Sum(Quantity)
                 FROM   (SELECT TOP 5 sum(Quantity) Quantity
                         FROM   Orders
                         GROUP  BY MenuItemName
                         ORDER  BY Quantity DESC) a)

PRINT @VARIABLE

A: You can use select @variable =, and you should probably be ordering by sum(Quantity) desc.
declare @variable as bigint;

select @variable = Sum(SumQuantity)
  from (
    select top 5
        SumQuantity=Sum(Quantity)
      from Orders
      group by MenuItemName
      order by Sum(Quantity) desc
   ) as x;

print @variable;


text:
Q: How to databind a local variable in an ASPX template? I have a UserControl named SlidingScaleTableReadonly with a bindable public member ScaleEntries, which take a List of struct instances. In the parent page, these lists are stored in a dictionary (InsulinSlidingScaleProtocolEntries), and I must render one SlidingScaleTableReadonly for each entry in this dictionary. Here's my template code so far:
<%@ Register TagPrefix="uc" TagName="SlidingScaleTableReadonly"  Src="~/Patient/SlidingScaleTableReadonly.ascx" %>

<asp:Content ContentPlaceHolderID="phContent" runat="server">

Échelles

    <% For Each drug In InsulinSlidingScaleProtocolEntries %>

<%= drug.Key %>

        <uc:SlidingScaleTableReadonly runat="server" ScaleEntries="<%# drug.Value %>" />
    <% Next %>
</asp:Content>

My problem is at line 7:

BC30451 'drug' is not declared. It may be inaccessible due to its protection level.

If I replace drug.Value with a property available in code behind, the new variable can be found. I'm guessing it's not possible to directly data-bind local variables in ASPX? If that's the case, how can I use data-binding inside an iteration?
Edit - Changing the provenance of the bound value
I've changed the code a bit. Right after the "For Each" loop opening, a code-behind property named CurrentDrug is reassigned with the value of drug.Value, and uc:SlidingScaleTableReadonly get it's ScaleEntry from that new property. But that doesn't work either, the reassignment won't do shuck and ScaleEntry is always Nothing (or whatever initial value I gave to CurrentDrug).
Here's the new template:
<%@ Register TagPrefix="uc" TagName="SlidingScaleTableReadonly"  Src="~/Patient/SlidingScaleTableReadonly.ascx" %>

<asp:Content ContentPlaceHolderID="phContent" runat="server">

Échelles

    <% For Each drug In InsulinSlidingScaleProtocolEntries
        CurrentDrug = drug.Value %>

<%= drug.Key %>

        <uc:SlidingScaleTableReadonly runat="server" ScaleEntries="<%# CurrentDrug  %>" />
    <% Next %>
</asp:Content>

And code-behind:
Public CurrentDrug As List(Of ScaleEntry)

Public Property InsulinSlidingScaleProtocolEntries As Dictionary(Of String, List(Of ScaleEntry))
    '...
End Property

Edit - (Not) a solution: Stopped using aspx templates
I have to move on, and it seems like I'm not going to do any progress with aspx templates. I've rewritten the page so the UserControl is declared and inserted in code-behind. I think that's not how one should build an interface, that's not where that kind of logic should be place but I really want to move on.
Here's the new template code:
<asp:Content ContentPlaceHolderID="phContent" runat="server">

Échelles

</asp:Content>

Code-behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each prescription In InsulinSlidingScaleProtocolEntries
        Dim label As New HtmlGenericControl("h2") With {
            .InnerText = prescription.Key
        }

        Dim table = CType(Page.LoadControl("~/Patient/SlidingScaleTableReadonly.ascx"), SlidingScaleTableReadonly)
        table.ScaleEntries = prescription.Value

        scaleContainer.Controls.Add(label)
        scaleContainer.Controls.Add(table)
    Next
End Sub

If you have a better solution, I'll be happy to see it.


text:
Q: jQuery Promise for asynchronous loops I need to wait for an asynchronous call, then go to the next "i" and continue the loop.
My code:
function getUserInfo(length) {
    var peoplepickerarray = [1,2,3,4,5,6,7,8];

    for (var i = 0; i < 1; i++) {
        var keys = peoplepickerArray[i].GetAllUserKeys();
        getUserId(keys);
    }
}

function getUserId(loginName) {
    var context = new SP.ClientContext.get_current();
    user = context.get_web().ensureUser(loginName);
    context.load(user);
    context.executeQueryAsync(function() {
        userId = user.get_id();
        console.log(userId)
        PPuserIds.push(userId);
    }, function(sender, args) {
        console.log('Query failed. Error: ' + args.get_message());
    });
}

I should wait for the "executeQueryAsync", don't have any idea though. I don't understand the jQuery documentation of promise...

A: Instead of dealing with async functions inside a loop, there is a feature in SharePoint CSOM API called Request Batching that in my opinion better suits this scenario. The main advantage of this approach that the number of requests to the server could be minimized.
The below example demonstrates how to load multiple users by login names using a single request too the server:
function loadUsers(loginNames,success,error) {
       var result = [];
       var ctx = new SP.ClientContext.get_current();
       for(var i = 0; i < loginNames.length;i++){
          var user = ctx.get_web().ensureUser(loginNames[i]);
          ctx.load(user);
          result.push(user);
       }
       ctx.executeQueryAsync(
            function() {
                success(result);
            },
            error);
}

Usage
loadUsers(['username@tenant.onmicrosoft.com'],
   function(users){
       for(var i = 0; i < users.length;i++){
           console.log(users[i].get_id());
       }
   },
   function(sender, args) {
          console.log('An error occured: ' + args.get_message());
   });

A: Modern, yet nicely working example:
const getUserInfo = async () => {
    var peoplepickerarray = [1, 2, 3, 4, 5, 6, 7, 8];

    const pickerPromises = peoplepickerarray.map(picker =>
        getUserId(picker.GetAllUserKeys())
    );

    const userIds = await Promise.all(pickerPromises);
    console.log(userIds);
};

const context = new SP.ClientContext.get_current();

const getUserId = async loginName =>
    new Promise((resolve, reject) => {
        const user = context.get_web().ensureUser(loginName);
        context.load(user);
        context.executeQueryAsync(() => {
            resolve(user.get_id());
        }, reject);
    });


text:
Q: Using JS in Swift to hide WKWebView collection elements I have a website that I have loaded into WKWebView. I want to hide the header of this website, so that I can use a native header that I have built in storyboard instead. The header element can only be referred to by class (i.e. "header-layout-bar").
I have been using this code as reference in order to hide the header.
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finishload")
    let element = "header-layout-bar"
    let removeElementScript = "var element = document.getElementsByClassName('\(element)'); element.parentElement.removeChild(element); console.log(element);"
    webView.evaluateJavaScript(removeElementScript) { (response, error) in
        debugPrint("Am here")
    }
}

When I print out element in the console to see whether it has been selected, it prints an empty HTML Collection Array. Removing it this way does not hide it.
I have tried several variations on this theme to no avail (e.g. selecting it using getElementsByTagName).
Nothing works. Can someone provide a solution?

A: You could try hiding it with css:
let removeElementScript = "document.querySelector('.header-layout-bar').style.display='none';"
webView.evaluateJavaScript(removeElementScript) { (response, error) in
    debugPrint("Am here")
}


text:
Q: eclipse export jar java.lang.NoClassDefFoundError problem When compile and run using eclipse there is no problem , but when I exported as jar with these setting , i got Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: gnu/io/SerialPortEventListener .
The jar exporter didn't export my extended jar library?

A: This sentence from the Exceptions JavaDoc helps to understand what went wrong:

The searched-for class definition existed when the currently executing class was compiled, but the definition can no longer be found.

You've build the application on eclipse with no errors. So the classpath definition inside eclipse was good enough to compile all classes.
Now you export it, run it out of eclipse and encounter that error. The exported application does not use the eclipse projects classpath definition any more. And the currrent one does not include the library which contains the gnu.io.SerialPortEventListener.
The general solution is: fix the classpath problems for the exported jar.

A: It could be a dependency issue, however, don't confuse ClassNotFoundException and NoClassDefFoundError. Basically, it is saying there was a problem in the initialization of: gnu/io/SerialPortEventListener I would check that class for errors as a starting point.

A: I have solve it by using fatjar

A: You may also consider using the open source tool called WinRun4J .
This is available at http://winrun4j.sourceforge.net/ .
I found this easy and effective to use .


text:
Q: How to login to server using private key? I have a private key provided to login to the server.
I have convert the private key to the ppk format using puttygen. But, when I tried to login, poup says disconnected: No supported authentication methods available(server sent:public key,gssapi-keyex,gssapi-with-mic) appear. why I cannot proceed the process?

A: First, you need to load your ppk into pageant (this is your private key). You may have to type your pass phrase to unlock it into pageant.
Second, you need your public key uploaded to the remote server, for the unix account you'll be using. You should ask an admin to do it for you.
Then, you should be able to login through ssh without entering a password for this unix account.


text:
Q: Center last line of the paragraph; but I don't like small lines Attention: This is an advanced TeX problem.
I usually dislike lines that are too small, and so I tend to add
\parfilskip=2em plus 0.6\textwidth

to my documents (apart from small lines, this also avoids last lines that end too close to the right margin, making sure the paragraph ends at least 2ems from the margin).
My problem is on figures, in which I also like to have a centred last line. Memoir and other classes/packages provide a macro for this effect, eg \centerlastline from Memoir, which is defined as:
\leftskip=0pt plus 1fil
\rightskip=0pt plus -1fil
\parfilskip=0pt plus 2fil

This clever code allows the last line to be centred, but sometimes the last line is short (for example, only one word). What I would like to do is tweak that macro so that the stretchability is not an infinite stretch. My first approach was to try
\leftskip=0pt plus 0.3\textwidth
\rightskip=0pt plus -0.3\textwidth
\parfillskip=0pt plus 0.6\textwidth

My intuition was that for mid-paragraph lines, stretchability would be calculated as 0 and they would therefore be written in their right place, while the last like would have enough stretchability on the left and right to be absolutely centred. Unfortunately, this does not work, as the paragraph is then typeset in a wobbly way
\documentclass[10pt,a4paper]{article}
\usepackage{lipsum}
\begin{document}

\leavevmode \vskip-10em \parindent=0pt \hsize=12cm

\textbf{REGULAR}\par
\lipsum[1] \vskip\baselineskip

\textbf{REGULAR / NOT SMALL}\par
{\parfillskip=2em plus 0.6\textwidth
 \lipsum[1]} \vskip\baselineskip

\textbf{CENTRED}\par
{\leftskip=0pt plus 1fil
 \rightskip=0pt plus -1fil
 \parfillskip=0pt plus 2fil
 \lipsum[1]} \vskip\baselineskip

\textbf{CENTRED / NOT SMALL}\par
{\leftskip=0pt plus 0.3\textwidth
 \rightskip=0pt plus -0.3\textwidth
 \parfillskip=0pt plus 0.6\textwidth
 \lipsum[1]} \vskip\baselineskip

\end{document}

The problem (as far as I can see) is that spaces also contribute to the stretchability of a line. This means that:

*

*the total stretchability of the mid-paragraph lines is not 0

*and so it gets distributed,

*which means that the left margin gets a positive value and the right margin the corresponding negative value

*finally leading to loose lines being shifted to the right (tight lines do not stretch at all and so they are set in place).

Any thoughts on this problem?

A: touhami's suggestion in the comments made me find an answer for this admittedly niche problem. The solution is to construct the paragraph as if it was being normally typeset and then handle the positioning of the last paragraph manually. Here's how it goes:
\textbf{CENTRED / NOT SMALL}\par
{
    % Typeset as we did previously for the "regular / not small" case
    % by specifying a custom \parfillskip
    \parfillskip=2em plus 0.6\textwidth
    % Create a vbox with the content needed
    \setbox0=\vbox{\lipsum[1]}
    \setbox1=\vbox{%
        % Unwind the previously build box
        \unvbox0
        % put the last box (which is the last line of the paragraph)
        % in its own register
        \setbox2=\lastbox
        % place this box on a new hbox but remove the two last
        % glues, which are the parfillskip and the right margin
        % this box also has \hfill on both sides to centre it
        \hbox to \textwidth{\hfill\unhcopy2 \unskip\unskip\hfill}
    }
    % Unwind the vertical box previously constructed
    \unvbox1
}

The result is that the last line, indeed, is not as short as in the uncustomised paragraph and is also centred:


text:
Q: ExtJs 4 and asp.net mvc 3 data load issue. I have problem with binding data from controller to store.
On JS side I have following code:
function buildGrid() {
    console.log("0");
    var store = new Ext.data.JsonStore(
    {
        url: '@Url.Content("~/Home/GridData")',
        root: 'data',
        totalProperty: 'total',
        fields: ['Id', 'Name', 'State', 'Age']
    });
    console.log("1");
    store.load({ params: { start: 0, limit: 15} });
    console.log("2");
}

The controller code loks like:
public JsonResult GridData(int start, int limit)
{
    var contact = new List<Contact> {
        new Contact(){ Name= "Smith", State = "NU",  Age =24},
        new Contact(){ Name= "Adam", State= "LU", Age =32},
        new Contact(){ Name = "Eve", State= "WA", Age=18},
        new Contact(){ Name= "Chun Li", State="LI", Age=34}
    };
    return Json(new { total = contact.Count, data = contact, }, JsonRequestBehavior.AllowGet);
}

I can see 0 and 1 on FireBug console but instead of 2 i get an error:
url is undefined
 return url + (url.indexOf('?') === -1 ? '?' : '&') + s;

ext-all-debug.js (line 5040)

I have no idea what I am doing wrong.
Thanks in advance for any suggestions.

A: I havn't solved the problem however i did rid of the error by creating model.
Ext.define('Contact', {
    extend: 'Ext.data.Model',
    fields: ['Id', 'Name', 'State', 'Age']
});

var store = Ext.create('Ext.data.Store', {
    model: 'Contact',
    proxy: {
        type: 'ajax',
        url: 'GridData',
        reader: {
            type: 'json',
            record: 'data',
            totalProperty: 'total'
        }
    }
});

A: here's the proxy I define on my store
proxy: {
    type: 'ajax',
    batchActions: false,
    reader: {
        type: 'json',
        root: 'data'
    },
    api: {
        create: 'CreateOrder.json',
        read: 'ReadOrder.json',
        update: 'UpdateOrder.json',
        destroy: 'DestroyOrder.json'
    },
    listeners: {
        exception: function (proxy, response, operation) {
            Ext.Msg.show({
                title: response.statusText,
                msg: Ext.decode(response.responseText).message,
                buttons: Ext.Msg.OK,
                icon: Ext.window.MessageBox.ERROR
            });
        }
    }
}

You could try out this library, which helps me
extjs4efj

A: Maybe you should check Dextop. It's an application framework completely dedicated to boost development of Ext/.NET based applications.


text:
Q: NetBeans - lots of unnecessary Java warnings NetBeans IDE 12.4 (Java AdoptOpenJDK 11) displays dozens of warnings "This anonymous inner class creation can be turned into a lambda expression" in its ActionItems docked window. Simultaneously it locks this code (locks body of initComponents of jFrame to protect it against modification) making it impossible to change these anonymous to lambdas to get rid of display these warnings.
Any changes in Tools/Options/Editor/Hints options does not affect these specific warnings.
So I have unuseful warnings. In practice means that I do not pay attention to any warnings anymore.
However, I wish I could find warning messages list in ActionItems window useful.
Can something be done about it?
(revised and supplemented)

A: Same problem, I disable warnings :

But warnings stays listed on "Action Items" tab (even after clean/build, clean cache and NetBeans relaunch) :

The only change, are the underlined code warning, has gone :


text:
Q: K&R Exercise 1-9 solution C programming The task is to make a C program that replaces multiple blanks with a single blank and I found this solution on another StackOverflow question:
int c;
while ((c = getchar()) != EOF) {
    if (c == ' ') {
        while ((c = getchar()) == ' ')
            ;
        putchar(' ');
        if (c == EOF) break;
    }
    putchar(c);
}

It works but I am puzzled by the second while loop:
while ((c = getchar()) == ' ')
            ;

How does line this even remove any white spaces? I thought it just does nothing until it comes across another non-blank character. So then if a sentence had 4 blanks then I would expect it to turn into 5 blanks because your just adding another blank with putchar(' ') ? Does it remove the excess blank spaces in a way I'm not aware of?

A: while ((c = getchar()) == ' ')
            ;

This bit skips over spaces. After skipping all of them,
putchar(' ');

puts one space.
This replaces groups of spaces with one.

A: getchar reads one character at a time. At each iteration it reads a character and check if it is a space or not. If the character read is a space then read another one until it finds a non-white-space character. After break out of loop putchar(' '); is executed and prints a space.

A: The program reads (using getchar) a string from standard input and the outputs (using putchar) the same string to standard output but leaving out the excess spaces.  So effectively it "removes" the extra spaces.
The while loop skips over a consecutive block of whitespace in the input while outputting nothing, and then after the loop is done, outputs a single space.  That's how it "removes" the spaces.


text:
Q: How to Prevent Wordpress to encode html in post As as title, how to prevent wp not to encode html in a post?
currently i just need  to prevent '&' change to '&'
The result need to be looks like on editor with html tab mode selected.
$content = $wpdb->get_row("SELECT post_content FROM $wpdb->posts WHERE ID=xxx");
$content = str_replace('amp;','',$content->post_content);//remove amp;

$wpdb->query("UPDATE $wpdb->posts SET post_content = $content WHERE ID = xxx;");

but that code still encode the html.
update:
and also how to implement content filter(prevent to encode some text) in collaboration with wp_insert_post() function
update[SOLVED]: stackexchange
$content = get_post_field('post_content', XXX, 'raw');
$content = str_replace('amp;', '', $content);
$wpdb->update( $wpdb->posts, array( 'post_content' => $content ), array( 'ID' => XXX ) );

A: <?php $content = htmlentities( html_entity_decode($content) ); ?>

This code will print HTML tags, and then decode HTML entities (like & to &).
Oh, and with wp_insert_post(), do:
// Create post object
$my_post = array(
  'post_content' => $content,
  'post_id' => POST_ID # update the post with the same ID as POST_ID
);

You can use the escape function as a shortcode:
function escape_html_func( $attrs, $content = "" ) {
  return htmlentities( html_entity_decode($content) );
}
add_shortcode( 'escape', 'escape_html_func' );

like [escape]Hello![/escape] in blog posts. Is this what you meant by content filter?


text:
Q: Is a for(auto ...) of list where we append new elements within the loop guaranteed to work against all the elements? I have a class with an f_next field that looks like so:
class process
{
public:
    typedef std::shared_ptr<process> pointer_t;
    typedef std::list<pointer_t> list_t;

    void add_next_process(pointer_t p);
    void wait();

private:
    list_t f_next = list_t();
};

The add_next_process() simply appends p to f_next:
f_next.push_back(p);

As a result, the wait() has to gather all the processes and wait for all of them. I'd like to avoid recursion and instead generate a list of all the f_next like so:
list_t n(f_next);
for(auto & it : n)
{
    n.insert(n.end(), it->f_next.begin(), it->f_next.end());
}

Is n guaranteed to include all the items once the for() loop exits?
I know that std::list::insert() does not change the iterator:

No iterators or references are invalidated.

but I'm wondering whether the for(auto ...) will continue through all the items that I appended along the way.

A: For-range is just a syntactic sugar for a classic for loop operating on iterators.
As long as your container implements begin and end (or you have free overloads), and don't invalidate the iterator in the process, this should technically be fine.
Other thing is whether this is a good and maintainable idea.
Before C++17:
auto && __range = range-expression ;
for (auto __begin = begin_expr, __end = end_expr; __begin != __end; ++__begin) {
  range-declaration = *__begin;
  loop-statement
}

From C++17:
auto && __range = range-expression ;
auto __begin = begin_expr ;
auto __end = end_expr ;
for ( ; __begin != __end; ++__begin) {
  range-declaration = *__begin;
  loop-statement
}


text:
Q: How to use if then else to build a string in a crystal reports formula This is Crystal Reports 9 in Visual Studio 2003 by the way
Simple question about crystal reports formula syntax:  How do I build the formula's result using if then clauses?
Specifically I would like something like this:
dim val as string
val = {table.level}
if {table.uom_id} = 5 then
  val = val & ' feet'
else
  val = val $ ' meters'
end if

and val should be the result of the formula.
As long as we're at it, are there any shortcuts for writing these?  These are horribly verbose, the ternary operator would be very welcome.

A: Your example is close.  Just use Crystal syntax, as shown here:
stringvar val := {table.level};

if {table.uom_id} = 5 then
  val := val + ' feet'
else
  val := val + ' meters';

//to return a value, just plop it down at the end
val

But if you want something a little more concise, use this:
if {table.uom_id} = 5 then
  {table.level} + ' feet'
else
  {table.level} + ' meters';


text:
Q: How do I revert back to a previous SVN commit? Suppose I'm at revision 50.
But, I want to revert back to revision 45, and commit back as the stable version.
How do I do that, in the most simple way?

*

*What if I want to do that with one file?

*What if I want to do that with the entire repository?

A: Reverse merge those revisions that you want to undo. This can be done on one or multiple files. By reverse merging, your working copy gets changed to the state without that revision, which you then can commit.

A: I'm not sure what you mean by "commit back as the stable version", but depending on what you're trying to accomplish I recommend:
svn update -r45
This will rebase your working copy at revision 45.
or:
svn merge -c -50,-49,-48,-47,-46
This will update (by reverse-merging) your working copy by removing all the changes between 45 and 50.  Now if you make changes and commit, it will be like you have removed 46-50 from the repository and made the HEAD revision (51?) to be r45 + your change.

A: You can simply do an update to revision using
svn up -r 45

But this will not let you commit the changes as SVN needs you to update your working copy to HEAD before you can commit. What you can do instead is
svn merge -r HEAD:45 yourFile
svn ci yourFile -m "Reverting back to rev 45"

A: I think one simple way should be this:

*

*checkout revision 45 to a temporary directory

*copy one or alle files to your working directory

*commit


text:
Q: Fragment implementing AsyncTask and Listview in android Here is my Java code
but it doesnt work i dont get my error.

package info.androidhive.slidingmenu;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class CommunityFragment extends Fragment {

    public CommunityFragment(){}

    // Declare Variables
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String RANK = "rank";
    static String COUNTRY = "country";
    static String POPULATION = "population";
    static String FLAG = "flag";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_community, container, false);

        new DownloadJSON().execute();
        return rootView;
    }
    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(CommunityFragment.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Student Government App");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            // Retrieve JSON Objects from the given URL address
            jsonobject = JSONFunctions
                    .getJSONfromURL("http://app-dlslsg.azurewebsites.net/json/postList.php");

            try {
                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("post");

                for (int i = 0; i < jsonarray.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jsonobject = jsonarray.getJSONObject(i);
                    // Retrive JSON Objects
                    map.put("rank", jsonobject.getString("id"));
                    map.put("country", jsonobject.getString("body"));
                    map.put("population", jsonobject.getString("stamp"));
                    map.put("flag", jsonobject.getString("image"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                    //Log.i("body",COUNTRY);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
            listview = (ListView) findViewById(R.id.listview);
            // Pass the results into ListViewAdapter.java
            adapter = new ListViewAdapter(CommunityFragment.this, arraylist);
            // Set the adapter to the ListView
            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();
        }
    }

}

I tried searching all over the net today but i don't get a chance to see any related problems.
Will someone help me to figure out this? i will reply asap on those responses
advance thanks for help!

A: A fragment is not a Context. You have to use getActivity() where you're using CommunityFragment.this.
replace
mProgressDialog = new ProgressDialog(CommunityFragment.this);

with
mProgressDialog = new ProgressDialog(getActivity());

and
adapter = new ListViewAdapter(CommunityFragment.this, arraylist);

with
adapter = new ListViewAdapter(getActivity(), arraylist);

A: Oke, so there are multiple errors:

*

*The ListViewAdapter constructor requires an Activity (or Context), but you are passing a Fragment. You can use Fragment.getActivity() to obtain the Activity for the Fragment, but only if it is attached.

*The ProgressDialog constructor requires a Context object, but again you pass a Fragment. A Fragment does not extend the Context, but the Activity class does. Again, you can pass Fragment.getActivity().

*Lastly, you try to call findViewById() form inside the AsyncTask. This is a method that is only available inside the Activity, so again you need to obtain the Activity and call the method via the Activity object.


text:
Q: How to create a text field on a form with an associated dropdown box to select from ( multiple times )? I have been requested to create a text field paired with an associated dropdown box to define it.
For example:
Text Field : Favorite Movie
Dropdown Box Select: Independent Or Commercial
I am boggled on how to do this.
Further more they would like to give the user a chance to do make up to 5 entries.
I was asked not to use InfoPath.
I am using SharePoint Designer 2010.


text:
Q: Problem with gnome-tweak-tool running from applications menu i have gnome-tweak tool running on a install of Debian 8 with gdm3 installed, how do i allow this application to run with full permissions? When i run "sudo gnome-tweak-tool" the program runs as expected, but when i try to run some programs from the applications menu or just using the app name without sudo from terminal, there are problems. With gnome-tweak-tool it runs but it's not possible to change anything, and it opens with a theme different to the system theme.
I don't have this problem on Ubuntu gnome, could someone please explain why that would be, what am i missing, how do i fix it without adding sudo or gksu to the exec line of every .desktop file?
This is what i expect to happen:

Here's what's actually happening without running with sudo from terminal:

A: There was a problem with gnome install.
I ran these commands in the terminal;
sudo apt-get --reinstall install gdm3 -y
sudo apt-get --reinstall install gnome -y
sudo apt-get --reinstall install gnome-shell -y

Now gnome-tweak-tool works fine when launched from the applications menu.

A: First try to find what is going wrong. Run gnome-tweaks from terminal simply typing gnome-tweaks in the terminal. In Tweak will make some changes and see the log in the terminal. If it says

Cannot open dconf database: invalid gvdb header

~/.config/dconf/user* files might have corrupted. Try the following command, it should recreate a new one and allow you to store your settings persistently:
mv ~/.config/dconf/ ~/.config/dconf.bak

Note that you may loose some customization that you may have set on your system as all of them will be reset.
If it does not solve your problem all you have to do is:
mv ~/.config/dconf.bak ~/.config/dconf/


text:
Q: create site in IIS with powershell Working with an mvc4 application that runs in IIS 7.5, the site though exist once on disk, has over a 100 url's pointing to it. This is because the site displays content based on the country that needs to access it.
Due to this, the site can have over a 100 bindings, which is very hard to manage.
I am looking to automate the creating of the site in IIS using powershell. I would run this during each deployment to ensure each of my environments are identical (dev, qa, production).
The powershell script would delete the site and recreate it, applying bindings, configuring it etc. I am a newbie to powershell so I would appreciate any help with this.

A: You should be able to use the PowerShell IIS Administrative Cmdlets. I show how to automate creating and deleting web applications using them on my blog that should get you started.

A: I have a script I use when creating a website and AppPool in IIS 7+ (under .net4, Integrated pipeline, etc) and thought you might find it useful as its a bit simpler than some of the other answers. It will delete the site and replace it if it already exists making it good in continuous integration scenarios.
Use it as so:
CreateSite.ps1 [WebsiteName] [AppPoolName] [Port] [Path]

If you are reinstalling the site, you will need to stop it first. That is done as so:
StopSite.ps1 [WebsiteName] [AppPoolName]

you gan grab the scripts from my gist

A: There is an IIS provider for PowerShell which you can use to manage IIS from PowerShell.
Take a look at the available cmdlets.


text:
Q: Disable Bootstrap accordion after opening I have a multiple bootstrap accordion running and would like to disable once clicked. One tab has to remain open at all times.
For example, Link1 is already open so link1 should be disabled. Only link2 and link3 should be clickable. How should I achieve this?
Here's the code:

    Link 1

    Link 2

    Link 3

    This is the description 1

    This is the description 2

    This is the description 3

Javascript:
$('#accordion').on('show.bs.collapse', function () {
    $('#accordion .in').collapse('hide');
});

JSFiddle Link Demo:
https://jsfiddle.net/DTcHh/19604/

A: This would give you that result.
$('#accordion').on('show.bs.collapse', function () {
    $('#accordion .in').collapse('hide');
});

$('a').on('click',function(){
  // enable all
  $('a').each( function(){
     $(this).removeAttr('disabled')
  })
  // disable me
  $(this).attr('disabled', 'disabled')
})

jsFiddle: https://jsfiddle.net/DTcHh/19608/

A: Just remove the classes collapse in from the element for which you want to disable accordion. Like here it is link1.
$('#accordion').on('show.bs.collapse', function () {
   $('#accordion .in').collapse('hide');
});
$(".collapse.in").removeClass('collapse in');

I hope this is what you wanted. Check this fiddle.
Update:
Final Fiddle with a proper solution.


text:
Q: How to set restorationIdentifier in swift? I've created a UIView, appended it to a UIViewController, and next I want to set its (UIView) unique identifier for next-time selection without saving UIView in a var.
How can I do this? I've tried setValue and directly changing the identifier but haven't found anything.
--updated
I find this string in docs https://developer.apple.com/library/ios/featuredarticles/ViewControllerPGforiPhoneOS/PreservingandRestoringState.html "You can assign restoration identifiers programmatically or in your storyboard file.", but how can i do this ???

A: Simply type
self.restorationIdentifier = "/*name it here*/"

or for a view:
view.restorationIdentifier = "/*name it here*/"

Hope that helps :)


text:
Q: fix magento menue from displaying in the wrong area I was editing the menu in magento and i changed the text from

and i changed it to

now the navigation has moved below the black area i didn't not change any code i dont understad how this happen to have a look at the website it is http://truckpartsactions.com/  to take a look at the origianl website http://65enginespart.com/

A: It has nothing to do with the text, it is because of the new logo dimensions
The original logo is 151*100
Your logo is 200*121
If you resize the new logo or just add in styles.css:
.logo img { height:100px; } //or max-height:100px;

The menu will come back to the black area


text:
Q: NPM does not publish dependencies I have been fooling around with Node and npm Packages as CLI applications. I have a project with a package.json, all filled in correctly. When I run the application with different arguments via WebStorm, it all works fine. If I publish the npm package however... there are no dependencies... the npm site can't find one.. and when I install the CLI application, it fails running because yeah... the dependencies aren't pulled in...
This is my package.json
 {
  "name": "wmg",
  "version": "0.0.8",
  "description": "A Commandline Foolin around",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/Arvraepe/wmg.git"
  },
  "keywords": ["Stuff", "Foolin"],
  "target": "main",
  "preferGlobal": true,
  "bin": {
    "wmg": "wmg.js"
  },
  "author": "Arne Van Raepenbusch <arvraepe@gmail.com>",
  "license": "ISC",
  "devDependencies": {
    "prompt": "^0.2.14",
    "restify": "^3.0.3",
    "underscore": "^1.8.3"
  }
}

I tried running pakmanager deps, but that gave me this strange error
======================= WARNING =======================
Assuming browser mode by default is deprecated.
  Include browserDependencies in your package.json
  -- OR --
  pakmanager -e browser build

In the next release of pakmanager, the node environment will be assumed as default
=======================================================

Targeted Environment: browser
[[[deps]]]
[ERROR] The following packages are `require`d, but not in the package, nor on npm:
  wmg
pakmanager {}

======================= WARNING =======================
Assuming browser mode by default is deprecated.
  Include browserDependencies in your package.json
  -- OR --
  pakmanager -e browser build

In the next release of pakmanager, the node environment will be assumed as default
=======================================================

Surely my package isn't supposed to be dependent on itself?
Can someone shed some more light on this?

A: I looked at your package, and as others have noted you have devDependencies listed but no dependencies.   Typically devDependencies is for things like test frameworks, which you need to work on the package but not to use it.  Both prompt and restify are used in your app and should be listed in a dependencies object instead of devDependencies.

A: Your package.json file contains no dependencies. Only devDependencies which npm assumes are required only for development (mocha for example) and are not required for installation.
If any of your devDependencies are actual user dependencies move them to dependencies.


text:
Q: DOM traversal without exluded elements I'm creating a simple script that traverses the DOM and returns a tree object with the elements found in the DOM. Recursive traversal itself is quite simple but I want/need to skip certain elements and include other elements. How do I do this?
This is my HTML:

skip me

awesome text

      awesome text

        other text

...

And my recursive traversal code:
const root = document.querySelector('[data-element="from-here"]');

function traverse(node) {
  return {
    element: node.dataset.element,
    children: Array.from(node.querySelectorAll(':scope > div')).map(childNode => traverse(childNode)),
  };
}

traverse(root);

As you can see the code queries all div elements but I only need the elements with a data-element attribute. I can't just do `node.querySelectorAll(':scope > [data-element]') because that won't reach past the first div.
This is the result I want:
{
  element: 'from-here',
  children: [
    {
      element: 'awesome',
      children: [],
    },
    {
      element: 'collect-me',
      children: [
        {
          element: 'also-me',
          children: [],
        }
      ]
    }
  ]
}

Any help would be greatly appreciated!

A: You can use Array.filter() to filter out the elements without data-element attribute.
But in order to include the wrapper div, you may need to add data-element attribute too, as followings.

const root = document.querySelector('[data-element="from-here"]');

function traverse(node) {
  if (node.dataset.element) {
    return {
      element: node.dataset.element,
      children: Array.from(node.querySelectorAll(':scope > div'))
        .filter(child => {
          return child.dataset.element || Array.from(child.children).some(grandChild => grandChild.dataset.element)
         // If element has dataset     or  The child has some children with dataset attribute
        })
        .map(childNode => traverse(childNode)),
    };
  } else if (Array.from(node.children).some(child => child.dataset.element)) {
    return Array.from(node.querySelectorAll(':scope > div')).filter(child => child.dataset.element).map(childNode => traverse(childNode))
  }
}

console.log(traverse(root));

skip me

awesome text

      awesome text

        other text

...

A: Use of Array.prototype.flatMap can drastically reduce the complexity of your transformation -

*

*If the node does not have a data-element value,

*Do not include the node; include only the results of its children.

*Otherwise (by induction) the node does have a data-element value. Include this element in the output as well as this node's children.

Numbered points above correspond to source comments below -

const root = document.querySelector('[data-element="from-here"]');

const toTree = ({ dataset = {}, children = [] }) =>
  dataset.element === undefined              // 1
    ? Array.from(children).flatMap(toTree)   // 2
    : [ { element: dataset.element           // 3
        , children: Array.from(children).flatMap(toTree)
        }
      ]

console.log(toTree(root)[0])

skip me

awesome text

      awesome text

        other text

...

Above, notice we did not use querySelectorAll as no additional document queries are needed. However, some obvious improvements would be -

*

*define your tree's shape as a separate function, branch

*define a helper for repeated task, allToTree
const branch = (element = "", children = []) =>    // 1
  ({ element, children })

const allToTree = (nodes = []) =>                  // 2
  Array.from(nodes).flatMap(toTree)

toTree is now free from complexity. Our intention is clear and each function is easy to write, test, and maintain -
const toTree = ({ dataset = {}, children = [] }) =>
  dataset.element === undefined
    ? allToTree(children)
    : [ branch(dataset.element, allToTree(children) ]

A: Why not use using node.querySelectorAll(':scope [data-element]') instead? That would cover all elements having the attribute and not only the first layer of children.
Here is a fiddle: https://jsfiddle.net/cp21ykng/2/ or am I missing something?


text:
Q: .Net Core JWT Authentication with custom API Key Middleware I have a .Net Core 2.0 application that uses JWT tokens to authorize the user.
This all works fine but I want to have some sort of API Key mechanism to allow other applications to integrate but I cannot seem to get this to work with the current authentication.
Code:
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            IMemoryCache cache, IServiceProvider serviceProvider)
{
    app.UseAuthentication();

    ApiKeyMiddlewear(app, serviceProvider);

    app.UseMvc(routes =>
    {
        routes.MapRoute(
               name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}

    private static void ApiKeyMiddlewear(IApplicationBuilder app, IServiceProvider serviceProvider)
    {
        app.Use(async (context, next) =>
        {
            if (context.Request.Path.StartsWithSegments(new PathString("/api")))
            {
                // Let's check if this is an API Call
                if (context.Request.Headers["ApiKey"].Any())
                {
                    // validate the supplied API key
                    // Validate it
                    var headerKey = context.Request.Headers["ApiKey"].FirstOrDefault();
                    var settingsProvider = serviceProvider.GetService<ISettingsService<OmbiSettings>>();
                    var ombiSettings = settingsProvider.GetSettings();
                    var valid = ombiSettings.ApiKey.Equals(headerKey, StringComparison.CurrentCultureIgnoreCase);
                    if (!valid)
                    {
                        context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                        await context.Response.WriteAsync("Invalid API Key");
                    }
                    else
                    {
                        var identity = new GenericIdentity("API");
                        identity.AddClaim(new System.Security.Claims.Claim("Origin", "Api"));
                        identity.AddClaim(new System.Security.Claims.Claim("role", "Admin"));

                        var principal = new GenericPrincipal(identity, new[] {"ApiUser"});
                        context.User = principal;
                        await next();
                    }
                }
                else
                {
                    await next();
                }
            }
            else
            {
                await next();
            }
        });
    }
}

So in the code above you can see that I am intercepting the HTTP requests that provide a header called ApiKey and then validate it to what I have stored. This part all works but when calling an API Method with the Authorize attribute this does not work and I get the following error logs:
2017-09-19 08:15:17.280 +01:00 [Information] Request starting HTTP/1.1 POST http://localhost:52038/api/v1/Identity/ application/json 372
2017-09-19 08:15:21.967 +01:00 [Information] Authorization failed for user: "API".
2017-09-19 08:15:21.976 +01:00 [Information] Authorization failed for the request at filter '"Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter"'.
2017-09-19 08:15:21.981 +01:00 [Information] Executing ForbidResult with authentication schemes ([]).
2017-09-19 08:15:21.991 +01:00 [Information] AuthenticationScheme: "Bearer" was forbidden.
2017-09-19 08:15:21.996 +01:00 [Information] Executed action "Ombi.Controllers.IdentityController.CreateUser (Ombi)" in 38.8268ms
2017-09-19 08:15:22.004 +01:00 [Information] Request finished in 4723.032ms 403

Now I'm guessing this is to do with the request only supplying a ApiKey header and not a Authorization header with a correct JWT token.
How am I able to only supply a ApiKey header and when there is no ApiKey header then fallback to requiring a JWT token?

A: Applying Claim("role", "Admin") to GenericPrincipal will not affect anything, because GenericPrincipal have nothing to do with Role Claims. So if you want to apply admin role to GenericPrincipal, you need to add it in constructor parameter:
 var principal = new GenericPrincipal(identity, new[] {"Admin","ApiUser"});
 context.User = principal;


text:
Q: How to show ripple effect on Container as IconButton child in Flutter? Standard IconButton doesn't show any ripple effect on child:
IconButton(
 icon: Container(color: Colors.red,),
 onPressed: () {},
)

So I tried fix it with Stack:
class MyIconButton extends StatelessWidget {
  const MyIconButton({Key key}) : super(key: key);

    @override
    Widget build(BuildContext context) {
      return Container(
        height: 100,
        width: 100,
        child: Stack(
          fit: StackFit.loose,
          children: [
            Positioned.fill(
              child: Container(
                width: 40,
                height: 40,
                color: Colors.deepPurple,
              ),
            ),
            Positioned.fill(
              child: Material(
                type: MaterialType.transparency,
                shape: const CircleBorder(),
                child: IconButton(
                  splashRadius: 50,
                  icon: Container(),
                  onPressed: () {
                  },
                ),
              ),
            )
          ],
        ),
      );
    }
  }

But this widget needs to have defined size of container, and when I define that size I can't show ripple effect outside of that container. I am open for suggestions.

A: Replace your Container with Ink widget.
IconButton(
  onPressed: () {},
  icon: Ink(color: Colors.red),
)

Ink:

A convenience widget for drawing images and other decorations on Material widgets, so that InkWell and InkResponse splashes will render over them.


text:
Q: How do I toggle play/pause with SoundJS? Im using SoundJS to build a psuedo MPC. I have the sound kit buttons programmed the way I want, but I cannot get the loops to work the way I want.

*

*I would like the user to click on "loop1" and it plays.

*If the user clicks "loop1" again, it should stop and resets.

*If the user clicks "loop2" while "loop1" is playing, then "loop1" stops and resets while "loop2" starts to play.

How could I master this problem. Warning, I'm a UI/UX designer at heart and still learning Javascript, so if you could give me a bit more detail when explaining, that would be great. Thanks!
Here's some of my code below, but to see it in action, check here: http://nowthatsgenius.com/clients/beatbox/

Loop 1

Loop 2

            V1

A: You can modify sounds after you've started playing them by assigning them to a variable. In this case, I've created variables loop1 and loop2.
// Creating variables outside playSound() so they exist in the global scope.
var loop1 = null;
var loop2 = null;

function playSound(target) {
    if(loop1){  // If loop1 exists, stop it.
        loop1.stop();
    }
    if(loop2){  // If loop2 exists, stop it.
        loop2.stop();
    }

    if(target.id == "loop1"){
        // Assign value to var loop1
        loop1 = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_NONE);
    }
    else if(target.id == "loop2"){
        // Assign value to var loop2
        loop2 = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_NONE);
    }
    else{
        // Otherwise, create generic sound
        var instance = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_NONE);
    }

    $(".player-controls-button").click(function(event) {
        if (instance.playState == createjs.Sound.PLAY_SUCCEEDED) {
            instance.stop();
        }else {
            instance.play(target.id, createjs.Sound.INTERRUPT_NONE);
        }
    });

    console.log(instance.playState);
}

I recommend you separate your playSound(target) function for sound effects, and create a new one named playLoop(target) for your music loops, just to make it easier to read. But that's up to you.
Version 2
var loop1 = null;
var loop2 = null;
function playLoop(target){

    // If loop1 exists, stop it and delete it
    if(loop1){
        loop1.stop();
        loop1 = null;
    }else if(target.id == "loop1"){
        loop1 = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_NONE);
    }

    // If loop2 exists, stop it and delete it
    if(loop2){
        loop2.stop();
        loop2 = null;
    }else if(target.id == "loop2"){
        loop2 = createjs.Sound.play(target.id, createjs.Sound.INTERRUPT_NONE);
    }
}

When you assign createjs.Sound.play() to a variable, the variable becomes an AbstractSoundInstance object. You can modify it in many cool ways, here's the documentation if you want to learn what more you can do with these variables.


text:
Q: How do I determine the convergence of $\sum_{n=1}^\infty (-1)^n n\sin(\frac{1}{n^2})$ I tried to prove whether $\sum_{n=1}^\infty (-1)^n n\sin(\frac{1}{n^2})$ converges or not for some long time.
Of course it is alternating, but the positive term is not monotonically decreasing. Liouville's theorem implies that $n\sin(\frac{1}{n^2})\leq \frac{A}{n}$ for some positive constant $A$. But this is not relevant to determine the convergence of the series. Even though it has a bound, it need not be monotonic.
How do I prove this? Thank you in advance.

A: Let us look at the behaviour of $n\sin(1/n^2)$ for large $n$.
Let $f(t)=\frac{\sin(t^2)}{t}$.
We have
$$f'(t)=\frac{2t^2\cos(t^2)-\sin(t^2)}{t^2}.$$
The numerator can be rewritten as $\frac{1}{t^2\cos^2 t}\left(2-\frac{\tan(t^2)}{t^2}\right)$.
Since $\frac{\tan u}{u}\to 1$ as $u\to 0$, it follows that for small positive $t$ the function $f'(t)$ is positive.
So for large enough $n$ the function $n\sin(1/n^2)$ is decreasing, and we can use the alternating series test.

A: You have
$$
\sin\frac1{n^2}=\frac1{n^2}+\frac{\cos(c(n))}6\,\frac1{n^6},
$$
where $c(n)$ is a number between $0$ and $1/n^2$.
Then
$$
\sum_{n=1}^\infty (-1)^n n\sin(\frac{1}{n^2})
=\sum_{n=1}^\infty (-1)^n n\,\frac1{n^2}+\sum_{n=1}^\infty (-1)^n n \,\frac{\cos(c(n))}6\,\frac1{n^6}\\
=\sum_{n=1}^\infty (-1)^n \,\frac1{n}+\sum_{n=1}^\infty (-1)^n \,\frac{\cos(c(n))}{6n^5}.
$$
The two series on the right converge, so the series on the left converges.

A: $x - \frac{1}{6} x^3 \le \sin(x) \le x$ for any $x \ge 0$  [which can be proven by differentiation].
$\def\nn{\mathbb{N}}$
Thus $n \sin(\frac{1}{n^2}) \in \frac{1}{n} + [\frac{1}{6n^5}]$  [where "$[r]$" denotes "$\{ x : x \in \mathbb{R} \land |x| \le |r| \}$"].
Thus $\sum_{n=1}^m (-1)^n n \sin(\frac{1}{n^2}) \in \sum_{n=1}^m \left( (-1) \frac{1}{n} + [\frac{1}{6n^5}] \right)$
$\quad \subseteq \sum_{n=1}^m (-1) \frac{1}{n} + [ \sum_{n=1}^m \frac{1}{6n^5} ]$ which is bounded over all $m \in \nn^+$
Thus $\left( \sum_{n=1}^m (-1) n \sin(\frac{1}{n^2}) \right)_{m \in \nn}$ has a convergent subsequence
Thus $\sum_{n=1}^\infty (-1) n \sin(\frac{1}{n^2})$ converges since each term goes to $0$ as $n \to \infty$.

A: For $0<x\leq 1$ we have $$x> \sin x =[x- \frac {x^3}{3!}]+ [\frac {x^5}{5!}-\frac {x^7}{7!}] +[\frac {x^9}{9!}-\frac {x^{11}}{11!}]+... >x-\frac {x^3}{3!}.$$ So for $n\in N$ we have $$n\sin [n^{-2}]> \frac {1}{n}-\frac {1}{3!n^5}>\frac {1}{n+1}>(n+1)\sin [(n+1)^{-2}]>0.$$ So we have an alternating series of terms whose absolute values are monotonically decreasing to $0$.
We can obtain $\;[x>0\implies \sin x>x-x^3/3!]\;$ without using the whole power series, as follows:$$(1)...x>0\implies x>\sin x\implies x^2/2=\int_0^x t\;dt>\int_0^x \sin t\;dt=1-\cos x.$$ $$ \text {(2)... Therefore } x>0 \implies   x^3/3!=\int_0^x (t^2/2)\;dt>\int_0^x(1-\cos t)\;dt=x-\sin x.$$


text:
Q: Magento 2 don't show some product in macrocategorie after migration from Magento 1.9 I've done a migration from Magento 1.9 to Magento 2.1.5. All product are present in catalogue and subcategories, but some product (not all) are not rendered on the frontend in the page of macrogategories.
I've checked from the admin if there are some difference in the congiguration of the products, but all have the same and I can't understand where is the problem.

A: Try to go to Products > Catalog select all and go to Actions > Change Status > Disable and then Enable.
Then add this two files on original modules folder.
app\code\Modules\Catalog\etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Model\Indexer\Category\Product\Action\Full" type="Modules\Catalog\Model\Indexer\Category\Product\Action\Full" />
</config>

app\code\Modules\Catalog\Model\Indexer\Category\Product\Action\Full.php
<?php
namespace Modules\Catalog\Model\Indexer\Category\Product\Action;

/**
 * Class AbstractAction
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/

class Full extends \Magento\Catalog\Model\Indexer\Category\Product\Action\Full {

    public function isRangingNeeded() {
        return false; // It was "True" as default setting.
    }
}

And go to Stores > Configuration > Catalog > Inventory > Stock Options and make Display Out of Stock Products set to Yes.
Then, run this command.
php bin/magento cache:clean
php bin/magento indexer:reindex


text:
Q: Mi app crashea cuando de AppCompatActivity a Fragment estaba siguiendo un tutorial ya que soy nuevo desarrollando app en Android Studio, y vi que mi clase tenia extends AppCompatActivity, por lo que decidi cambiarlo por extends Fragment, sin que, dentro de la clase, me muestre un error.
El problema es que cuando ejecuto la aplicación, se me abre correctamente, pero cuando quiero mostrar la vista que pertenece a ese Fragment, la app crashea, es decir, se cierra sola y frena la depuración. Eh intentado poner breakpoints pero la app se cierra antes.
Esta es mi clase:
public class Registrarse extends Fragment {

    private EditText dni;
    private EditText contrasenia;
    private EditText peso;
    private EditText altura;
    private EditText sexo;
    private EditText mail;
    private UserBusiness userBusiness;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_registrarse, container, false);
        dni = (EditText) view.findViewById(R.id.idDni);
        contrasenia = (EditText)  view.findViewById(R.id.idContrasnia);
        peso = (EditText) view.findViewById(R.id.idPeso);
        altura = (EditText) view.findViewById(R.id.idAltura);
        sexo = (EditText) view.findViewById(R.id.idSexo);
        mail = (EditText) view.findViewById(R.id.idMail);
        return view;
    }

Y ésta es mi vista principal o main_activity:
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void Registrarse(View view){
        Intent register = new Intent(this, Registrarse.class);
        startActivity(register);
    }

    public void MenuPrincipal(View view){
        Intent menu = new Intent(this, MenuPrincipal.class);
        startActivity(menu);
    }

    public void Prueba(View view){
        Intent menu = new Intent(this, EjercicioSeleccionado.class);
        startActivity(menu);
    }
}

Para aquellos que no puedan ver la foto, es mi emulador con un popup diciendo: 'Nutrain keeps stopping'
Alguien me puede ayudar a ver el problema?
vi que el problema era porque tenía startActivity() en lugar de startService(), así que cambié pero ahora no falla pero no pasa nada, osea toco el botón pero no redirige ni hace nada, ni muestra mensaje en el LogCat

A: Creo que tu error es porque metes un fragment en el intent, y los intent solo manejan Activities.
https://developer.android.com/guide/components/intents-filters?hl=es-419
para utilizar fragments, necesitas hacer un navHostFragment(buscalo) y ahí dentro del host, empezar a utilizarlos


text:
Q: Node ssh2 sends multiple data events for a simple ls command I am trying to do a simple 'ls' using node ssh connection on localhost. The code is like this,
var Connection = require('ssh2');
var conn = new Connection();
conn.on('ready', function() {
  conn.shell('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data) {
      console.log('STDOUT: ' + data);
    });
    stream.end('ls');
  });
}).connect({
  host: '127.0.0.1',
  port: 22,
  username: '*****',
  password: '*****'
});

And i am getting multiple data events, with the output like this,
STDOUT: Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation:  https://help.ubuntu.com/
STDOUT:
Last login: Sun Dec 28 09:28:21 2014 from localhost
STDOUT: ls
STDOUT: sk@sk-box:~$ l
STDOUT: s

what am i doing wrong here?

A: Append newline character after ls command.
var Connection = require('ssh2');
var conn = new Connection();
conn.on('ready', function() {
  conn.shell('uptime', function(err, stream) {
    if (err) throw err;
    stream.on('data', function(data) {
      console.log('STDOUT: ' + data);
    });
    stream.end('ls\n');
  });
}).connect({
  host: '127.0.0.1',
  port: 22,
  username: '*****',
  password: '*****'
});


text:
Q: ApplicationPoolIdentity Environment variables IIS Is it possible to set Environment Variables for ApplicationPoolIdentity virtual accounts? The documentation on this is practically-non existent.
I would like to inject an Environment Variable for just that Application Pool. It seems to be the case that people create unique accounts for the app pool to do this, but what I've read about virtual accounts implies I wouldn't have to, but doesn't explain at all how to do this.

A: Yes! (As long as you're using IIS 7.0+) You need to set the loadUserProfile setting for the Application Pool Identity to true. The Application Pool Identity will now have a user profile under \Users\[Application Pool Name]. You can then edit this profile to have custom environment variables, etc.
IIS 7 Tip # 3 You can now load the user profile of the application pool identity
EDIT: I just tested this (in IIS 10), because of your comment, and it's definitely working here.

*

*In IIS, I created a new Application Pool named Testing

*I changed the Application Pool Defaults to set Load User Profile to True

*I started the Application Pool, Testing

*I checked to see if the user profile was created at \Users\Testing: no

*I added a website to the Application Pool and restarted the website

*I checked again to see if the user profile was created: still no

*I navigated to the website in my browser, so the application pool would load

*I checked a third time to see if the user profile was created: yes

*I checked to see if the user registry was loaded in HKEY_USERS, (by checking HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist to see whether the NTUSER.DAT file located at [...]\Users\Testing\NTUSER.DAT was loaded, and it was, with SID S-1-5-82-454248297-962034619-2554273252-202815998-4121577539)

*I checked for the presence of the HKEY_Users\[SID]\Environments key, it's present, and has values TEMP and TMP pointing to %USERPROFILE%\AppData\Local\Temp.

The reason I had to do a page load is because I forgot to change the Start Mode from OnDemand to AlwaysRunning. When I created another Application Pool with Start Mode set to AlwaysRunning, the user profile was created when I assigned a  web site to the Application Pool and restarted the website.
More useful information on Application Pool Identities:
Application Pool Identities


text:
Q: Is there a way to redirect all traffic from HTTP to HTTPS on my MeteorJS app deployed on Heroku? Basically what the title says ;).
I've seen an npm package for Express (https://www.npmjs.org/package/heroku-ssl-redirect), but not for MeteorJS.

A: Assuming you have configured SSL this package should come handy
meteor add force-ssl

It worked on 0.9.4, I'm not sure it's working now


text:
Q: How to write batch of data to Django's sqlite db from a custom written file? For a pet project I am working on I need to import list of people to sqlite db. I have 'Staff' model, as well as a users.csv file with list of users. Here is how I am doing it:
import csv
from staff.models import Staff

with open('users.csv') as csv_file:
    csv_reader = csv.DictReader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        firstname = row['firstname']
        lastname = row['lastname']
        email = row['email']
        staff = Staff(firstname=firstname, lastname=lastname, email=email)
        staff.save()

    csv_file.close()

However, I am getting below error message:
raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Is what I am doing correct? If yes what I am missing here?

A: Django needs some environment variables when it is being bootstrapped to run. DJANGO_SETTINGS_MODULE is one of these, which is then used to configure Django from the settings. Typically many developers don't even notice because if you stay in Django-land it isn't a big deal. Take a look at manage.py and you'll notice it sets it in that file.
The simplest thing is to stay in django-land and run your script in its framework. I recommend creating a management command. Perhaps a more proper way is to create a data migration and put the data in a storage place like S3 if this is something many many people need to do for local databases... but it seems like a management command is the way to go for you. Another option (and the simplest if this is really just a one-time thing) is to just run this from the django shell. I'll put that at the bottom.
It's very simple and you can drop in your code almost as you have it. Here are the docs :) https://docs.djangoproject.com/en/3.2/howto/custom-management-commands/
For you it might look something like this:
/app/management/commands/load_people.py <-- the file name here is what manage.py will use to run the command later.
from django.core.management.base import BaseCommand, CommandError
import csv
from staff.models import Staff

class Command(BaseCommand):
    help = 'load people from csv'

    def handle(self, *args, **options):
        with open('users.csv') as csv_file:
            csv_reader = csv.DictReader(csv_file, delimiter=',')
            line_count = 0
            for row in csv_reader:
                firstname = row['firstname']
                lastname = row['lastname']
                email = row['email']
                staff = Staff(firstname=firstname, lastname=lastname, email=email)
                staff.save()

    # csv_file.close() # you don't need this since you used `with`

which you would call like this:
python manage.py load_people

Finally, the simplest solution is to just run the code in the Django shell.
python manage.py shell
will open up an interactive shell with everything loaded properly. You can execute your code there and it should work.


text:
Q: why does bigger malloc cause exception? I'm trying to do a modified Gauss-Jordan Elimination for computing inverses. With this I take a matrix and find the inverse. Although I can get the matrix using malloc When I try to double the size of a new matrix it causes an exception
int main (int argc, char *argv[]) {
    FILE *train, *test;

    train = fopen(argv[1], "r");
    test = fopen(argv[2], "r");

    int abutes,examples;
    fscanf(train," %d %d",&abutes,&examples);  /*scan in number of examples and attributes*/

    int i,j, abuteswp;
    abuteswp=abutes+1;
    double (*trainA)[10000] = malloc(sizeof(double[10000][10000]));
    for (j=0;j<examples;j++){
        for ( i=1; i <abuteswp+1; i++){
            fscanf(train," %lf %[^,]",&trainA[j][i]);}}

            int p;
            /*add in 1s to matrix*/
            for (p=0;p<examples;p++)    {
                trainA[p][0]=1;
            }

            /*take out price*/
            double trainatt[examples][abuteswp];
            for ( i=0; i <examples; i++){
                for ( j=0;j<abuteswp;j++){
                    trainatt[i][j]=trainA[i][j];
                }
            }

After doing some computations with the matrix I need to augment it and double the columns. After I try testing this causes an exception
    double ** trainaug = NULL;
    int aug;
    aug=examples*2;
    trainaug = malloc (examples * sizeof(double *));

    for(i = 0; i < examples; i++)
    {
        trainaug[i] = malloc (aug * sizeof(double));
    }
    for(i = 0; i <examples; i++)
    {
        trainaug[i] = malloc (examples * sizeof(double));
    }
    for ( i=0; i <examples; i++){
        for ( j=0;j<examples;j++){
            trainaug[i][j]=trainmult[i][j];}
        }
        for ( i=0; i <examples; i++){
            for ( j=examples;j<aug;j++){
                trainaug[i][j]=0;}
            }
            for ( j=0;j<examples;j++){
                i=examples;
                trainaug[j][i]=1;
                i++;
            }

Even without the for loops this causes an exception. Am I doing malloc the wrong way or is my code not right? I am freeing my pointers as I go along


text:
Q: Why I must specify whole string in Java regular expression? Suppose, I have a string:
String str = "some strange string with searched symbol";

And I want to search in it some symbols, suppose it will be "string". So we have a following:
str.matches("string"); //false
str.matches(".*string.*"); //true

So, as stated in the title, why I must specify whole string in Java regular expression?
Java documentation says:

public boolean matches(String regex)
Tells whether or not this string matches the given regular expression.

It doesn't says

Tells whether or not this whole string matches the given regular expression.

For example, in the php it would be:
$str = "some strange string with searched symbol";
var_dump(preg_match('/string/', $str)); // int(1)
var_dump(preg_match('/.*string.*/', $str)); //int(1)

So, both of the regex's will be true.
And I think this is correct, because if I want to test whole string I would do str.matches("^string$");
PS: Yes, I know that is to search a substring, simpler and faster will be to use str.indexOf("string") or str.contains("string"). My question regards only to Java regular expression.

UPDATE: As stated by @ChrisJester-Young (and @GyroGearless) one of the solutions, if you want to search regex that is part of a subject string, is to use find() method like this:
    String str = "some strange string with searched symbol";
    Matcher m = Pattern.compile("string").matcher(str);
    System.out.println(m.find()); //true

A: As the documentation you suggest,

public boolean matches(String regex)
Tells whether or not this string matches the given regular expression.

What it means is whether that string matches with the given regex. i.e. matches verifies whether your string is an instance of the given regex.
not whether it contains a substring which is an instance of the given regex. As Chris suggested you can use find instead or for your problem you can use contains.

A: matches always matches the whole input string. If you want to allow substrings to match, use find.

A: Yes, as you already know (now) that matches() will return true only for the complete string.
But, in your update, you have stated that:

As stated by @ChrisJester-Young (and @GyroGearless) the only solution, if you want to search regex that is part of a subject string, is to use find() method...

I would like to say that using find() is not the only solution. There is at least one more, which I know :
String str = "some strange string with searched symbol";
boolean found = str.split("string").length>1;
System.out.println(found);

This prints true. And this will work for all regular expressions. Though this is not the way to do it, and is instead a hack.
There may be many more solutions.


text:
Q: Are static resources loaded via api like read.csv refreshed during each microbatch when a stream-static join is done in spark Are static resources loaded via api like read.csv refreshed during each microbatch when a stream-static join is done in spark.
var a = sparkSession.read.csv(directory).as[A]
var b = sparkSession.readStream... # kafka stream
a.join(b, expr("some expre"), "inner") # Will the changes in  directory made after the spark run started. be reflected in the join? Or is it completely static.

Why I am asking this question is because in some cases I have seen the data from static resources are also refreshed. But couldn't justify why it is refreshed during a run.
I couldn't find anything around this in the documentation.


text:
Q: Entering data into mysql database using php Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below):

    <form action="register.php" method="post">
        Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/>

        <input type="submit" value="Enter"/>
    </form>

I want to create a variable called pathway. At the moment I can get text entered into the correct row in the mysql database (I can get John printed in the database), but not the correct text that was entered into the form (i.e. $pathway).
I want to create a variable because after saving the pathway in the database i also want to use it in an export.php.
I am assuming i also need something like this:
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $pathway = mysql_real_escape_string($_POST['pathway']);
// but i can't seem to piece it altogether.

    <?php
    $servername = "localhost";
    $username = "";
    $password = "";
    $dbname = "first_db";
    $table_users = $row['pathway'];
    $pathway = "pathway";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $dbname);
    // Check connection
    if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO users (pathway)
    VALUES ('John')";

    if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
    } else {
    echo "Error: " . $sql . "
" . mysqli_error($conn);
    }

    mysqli_close($conn);
    ?>

A: This shoud work, if not then check your usename and password...
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "first_db";
$pathway = $_POST['username'];  username - is the name of your input.

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn)
{
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO users (pathway)
    VALUES ('$pathway')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "
" . mysqli_error($conn);
}

mysqli_close($conn);
?>

A: your DB username is Null
Change $username = ""; to $username = "root";

A: Your input field name is username
change it to pathway for $_POST['pathway'] to work
<form action="register.php" method="post">
    Enter file pathway where CSV will be saved:
     <input type="text" name="pathway" required="required"/>

    <input type="submit" value="Enter"/>
</form>

A: First of all, you've got 'username' as the name of the field using for type a pathway, so rename it to 'pathway'.
I don't know if I understand you, but do you just want to read posted content?
Try something like:
$pathway = $_POST['pathway']

I strongly recommend to use object-oriented style with
$conn = new mysqli...

and then
mysqli->prepare(), mysqli->bind_param(), mysqli->execute()

With this you won't have to deal with mysqli_real_escape_string etc.


text:
Q: Visual Studio 2013 User Defined Literals - Latest CTP Microsoft is previewing a new CTP for Visual Studio 2013. Click here . How to check if it will have support for C++11 User Defined Literals?
I know that previous versions of VS 2013, including the November CTP did not support UDLs, and VS 2015 will have support for UDLs.
If not in this CTP, is there a possibility that VS will ever support UDLs?

A: You can start from THIS site, there is a lot of links you may find for possible Microsoft Visual Studio CTP updates.


text:
Q: Assigning Figures to a Variable with an operator i'm fairly new to Python (using 2.7) and have run into an issue with assigning to variables.
I'm trying to assign a number to a variable and then use that variable to create a new variable and assign a list (or a value) to it. For example:
x = 15
"MA"+str(x) = [12,54]
print MA15

The print MA15 should return the list [12,54]. The error I get is 'SyntaxError: can't assign to operator'.
I've tried other methods such as {"%s%s" % ("MA", str(Days))}, {exec()}, and {setattr()} functions.

A: try using exec:
x=15
string="MA%d=[12,54]"%(x)
exec(string)


text:
Q: cache provider for hibernate + jsf + spring Which cache provider is suggested for an application that uses

*

*Hibernate3

*Spring

*JSF2

A: EhCache is the obvious choice. Unless you have a reason to pick something else, then pick that one.

A: EHCache (originally "Easy Hibernate Cache") has been used in Hibernate for a long time, so it's the first choice.


text:
Q: Max# of Children per Parent? Is there a maximum number of Child accounts you can you have for a 'Parent Account'?

A: As a best practice the documentation says that you shouldn't have more than 10K child records in a master detail relationship. Please see the link       http://resources.docs.salesforce.com/198/16/en-us/sfdc/pdf/salesforce_app_limits_cheatsheet.pdf


text:
Q: how do you convert current date time in NY time to epoch in python I need to convert current date time to epoch time in python.
I have tried this, but I am not sure is this tz="New_York/Americas". Is below right?
import time

epoch_time = int(time.time())

A: You can use python's calendar module for this.
from datetime import datetime
from calendar import timegm

current_time = datetime.utcnow()
epoch_time = timegm(current_time.utctimetuple())

For more, visit calendar's timegm.


text:
Q: subprocess problem with phpmentor/workflower I'm trying to draw a bpmn diagram with subprocess and then run it in php workflow. My problem is that the subprocess tag is not detected by the phpmentor workflow. Does anyone know why it happens??

A: According to https://github.com/phpmentors-jp/workflower/blob/master/docs/quick-start-guide.md#workflow-elements-supported-by-workflower  phpmentor workflow doe snot support subprocesses.


text:
Q: What it's wrong with this if-else? I'm creating an app for make the flash camera blink, but I have a problem with switching off the method. These are my variables:
Camera camera = null;
Parameters parameters;
int delay = 600;
int period = 600;
int delay1 = 300;
int period1 = 600;
Timer timer, timer2;

This method I'm using to make the flash camera blink:
timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            cameraOn();
            }
    },delay1,period1);

    timer2 = new Timer();
    timer2.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            cameraOff();
            }
    },delay,period);

And now is when the problem comes, there's a button to switch off all this, but sometimes it works and sometimes it doesn't. Sometimes it switches off perfect, sometimes it goes back to the previous activity like I want, but the flash camera stays switched on. What is wrong? Here are the methods to switch on-off the camera flash:
private void cameraOff() {
     parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
     camera.setParameters(parameters);
     camera.release();
     camera = null;
}

private void cameraOn() {
     camera = Camera.open();
     parameters = camera.getParameters();
     parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
     camera.setParameters(parameters);
}

And here is the button:
@Override
public void onClick(View arg0) {
    timer.cancel();
    timer2.cancel();
    if(camera != null){
        cameraOff();
    }else{
        finish();
    }
}

A: Your application (as provided) is never going to work, due to a design flaw:
In the cameraOff() method you set camera to null. This method is triggered at a fixed interval, so next time the method is called again you have a NullPointerException as camera was set to null...
I do not know why you feel the urge to set it to null, but you need to do so elsewhere, or add checks whether camera is null or not.
Furthermore (to probable cause of your problem), the TimerTasks are executed on a different thread. When you cancel your timers, the value of camera is unknown and it might be possible that cameraOff() is called twice. Once from the TimerTask thread (as it was about to execute) and once from your main thread (because camera was not yet set so null).
Again, I wonder why you need to set camera to null, as this seems to cause most of your problems.


text:
Q: Cocoa File Opened Event - Detect if a file was opened I want to ask if it is possible to detect if a file was opened in Finder. I watched at the File System Events API and it seems not possible to listen to such an event.

Anyone knows if it is possible?

A: It's possible with DTrace so it should be possible (with likely a great deal of work) from the high level of your Cocoa app (but your question is too broad to answer without writing such an app for you). Unfortunately no convenient API exists to do what you request.


text:
Q: Express view render using HBS strips (consumes?) Handlebars client side templates Using Express with Don Park's HBS as the view engine, with the intention of using the same templating style for both client and server code. However I have run into a bit of a snag.
With the index.hbs shown here,

{{title}}

Welcome to {{title}}

Heres what renders to the browser:

Express

Welcome to Express

The Express View render process seems to have consumed the template block intended for use in the browser. As far as I can tell, the view renderer just takes the entire file.hbs as a string tempate to render, not distinguishing the script block from server view.
Any ideas/workarounds for this?

A: I'm using Handlebars in the same way and ran into the same problem.
I worked around it by storing this part:

In a separate static file and then loading it via ajax after the page has rendered. This way my client-side template doesn't get mistakenly rendered by Express.
It would be nice though if there were a way to add a tag to let Express know to ignore blocks like that and leave them for the client-side.

A: If handlebars is truly compatible with Mustache, then this should work:
Change your delimiter first by putting this somewhere at the top of your template ( before any template placeholders )
{{=<% %>=}}

So now anything you want rendered by the server you will do:
<% foo %>

And anything you want rendered on the client like so:
{{ bar }}

More info is at the bottom of the Mustache manual here - http://mustache.github.com/mustache.5.html

A: For handlebars, uou can use backslash to escape the double braces, like so:


text:
Q: i have a problem while using cnn to classify more then 10000 class. how can i solve it? this is my model using conv1d
the model have a 5000 class so, how can i create layers using tensorflow or keras
if i increase epochs my system getting loaded and hanged. here i was applied adam optimizer and mean_square_error loss function so i got very very low level accuracy. how can i fix it
'''
epochs = 3
batch_size = 35
model = Sequential()
print(x_train.shape[1],1)

model.add(Conv1D(16, 3, padding='same', activation='relu', input_shape=(128,1)))#x.shape[1:])) # Input shape: (96, 96, 1)
model.add(MaxPooling1D(pool_size=1))

model.add(Conv1D(32, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=1))
model.add(Dropout(0.25))
model.add(Conv1D(64, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=1))
model.add(Conv1D(128, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=1))
model.add(Conv1D(256, 3, padding='same', activation='relu'))
model.add(MaxPooling1D(pool_size=1))
# Convert all values to 1D array
model.add(Flatten())
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(5823))

##checkpointer = ModelCheckpoint(filepath='checkpoint1.hdf5', verbose=1, save_best_only=True)

# Complie Model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
history=model.fit(x_train, y_train_binary,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test_binary))

'''

A: you have to activate your last layer with a function like softmax (best choice for muli classification). As said in the comments, it is better to use the loss function
categorical_crossentropy in your case if your labels are one-hot encoded (if not use sparse_categorical_crossentropy).


text:
Q: Implement text editing feature with custom keyboard in Flutter I have implemented the custom keyboard (with the help of Table->card->button widgets)  which looks like below, If the user press the button then I capture the text and just display it in to the screen.

By using this, user can enter the data but they cannot edit it.
How can I implement the text editing feature in this case ?
I have tried to use the TextField widget to fit in my case, it gives all the features including text editing. But it does not allow to use the custom keyboard.

A: You could use the readOnly and showCursor properties of the TextField like this:
TextField(
  controller: _textController,
  readOnly: true,
  showCursor: true,
),

And then you could replace the selected text or insert a new text, like this:
@override
void initState() {
  super.initState();
  _textController = TextEditingController();
}

_insertText(String textToInsert) {
  if (_textController.selection.start >= 0) {
    int newPosition = _textController.selection.start + textToInsert.length;
    _textController.text = _textController.text.replaceRange(
      _textController.selection.start,
      _textController.selection.end,
      textToInsert,
    );
    _textController.selection = TextSelection(
      baseOffset: newPosition,
      extentOffset: newPosition,
    );
  } else {
    _textController.text += textToInsert;
  }
}

Widget _buildRow(List<String> texts) {
  return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: texts
          .map((text) => RaisedButton(
              child: Text(text), onPressed: () => _insertText(text)))
          .toList());
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: Text("Calc")),
    body: Column(
      children: <Widget>[
        Padding(
          padding: EdgeInsets.all(16.0),
          child: TextField(
            controller: _textController,
            readOnly: true,
            showCursor: true,
          ),
        ),
        _buildRow(["1", "2", "3"]),
        _buildRow(["4", "5", "6"]),
        _buildRow(["7", "8", "9"]),
      ],
    ),
  );
}


text:
Q: Error building nodejs from source on Debian I keep getting the same error when running make on nodejs source code. I've looked and some common problems seem to be lack of a c compilier or install g++. I have these and have double checked.
Here is the last few lines showing the error:
../deps/v8/src/assembler.cc: In static member function 'static void v8::internal::ExternalReference::InitializeMathExpData()':
../deps/v8/src/assembler.cc:914:66: internal compiler error: Illegal instruction
Please submit a full bug report,
with preprocessed source if appropriate.
See <file:///usr/share/doc/gcc-4.7/README.Bugs> for instructions.
Preprocessed source stored into /tmp/ccRCiDl6.out file, please attach this to your bugreport.
make[1]: *** [/home/labnosh/node-v0.12.7/out/Release/obj.target/v8_base/deps/v8/src/assembler.o] Error 1
make[1]: Leaving directory `/home/labnosh/node-v0.12.7/out'
make: *** [node] Error 2


text:
Q: no data inserted to MS Access database from java GUI Every other button is working fine only problem is with the save button.
I am doing project in netbeans and it is not showing any errors eighter yet data is not getting into database from java GUI
        b1.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed (ActionEvent e)

            String fname=t1.getText();
            String lname=t2.getText();
            int age=Integer.parseInt(t3.getText());
            String city=t4.getText();
            String State=t5.getText();

            try{
                rs.moveToInsertRow();//moves cursor to new row

                rs.updateString("Fname", fname);
                rs.updateString("Lname", lname);
                rs.updateInt("age", age);
                rs.insertRow();

                JOptionPane.showMessageDialog(null, "updated!");
                //close two variable
                st.close();
                rs.close();

               }
            catch(Exception ex){

            }

        }
    });


text:
Q: Task Error handling - Visual studio stops so basically I want to test Tasks in c#.
My code is the following:
    Task tm = new Task(Test);
    tm.ContinueWith(ExceptionHandler, TaskContinuationOptions.OnlyOnFaulted);
    tm.Start();

    void ExceptionHandler(Task task)
    {
        var ex = task.Exception;
        ex.Handle((x) =>
            {
                if(x is PictureNotRecognized)
                {
                    MessageBox.Show(String.Format("An exception occured" + Environment.NewLine + "Program aborted: {0}" + Environment.NewLine + "Step: {1}" + Environment.NewLine + "Error Message: {2}", (x as PictureNotRecognized).Aborted, (x as PictureNotRecognized).CurrentStep, (x as PictureNotRecognized).Message));
                    return true;
                }
                return false;
            });
    }

    void Test()
    {
        throw new Exception();
    }

So, when I run the application it throws the exception and visual studio stops. only if I press F5 again it continues and jumps to ExceptionHandler. How can I deactivate this in Visual studio? it should not break the program if the exception is created by the user with throw new XXXX

A: You can disable break of exceptions in Debug -> Exceptions -> Command Language Runtime Exceptions -> System -> System.Exception -> Uncheck "User-unhandled".
Except the breaking is only when debugging and the user won't notice the exception break! But Visual Studio notices you  that you didn't handle the exception like a Try Catch construction. For more information about exception handeling with Task's see:
http://msdn.microsoft.com/en-us/library/dd997415(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/dd537614(v=vs.110).aspx


text:
Q: Math Modules Relevant Finance I'm a student going into my final year, my course is International Finance & Economics with a Maths Minor. I have to select 4 Maths modules for the final year but I'm having trouble selecting which ones. I want to choose the modules most relevant to Finance, and all suggestions are welcome.
Here they are;
- ANALYSIS 1 (C)
- CODAIGH & CÓRAIS DHINIMICIÚLA RÉADACHA
- EUCLIDEAN & NON-EUCLIDEAN GEOMETRY
- EXPERIMENTAL AND COMPUTATIONAL MATHEMATICS
- GRAPH THEORY
- HISTORY OF MATHEMATICS
- MATHEMATICAL BIOLOGY
- PARTIAL DIFFERENTIAL EQUATIONS
- GROUPS
If any extra clarification is needed I'm happy to provide (Oh and I'm not choosing the second module). My current choices are Analysis 1 (C), Euclidean & Non-Euclidean Geometry, Graph Theory and Groups/Partial Derivatives.
Thanks for any help!

A: I suggest you experimental and computational mathematics because in these days computer and programming language are very important especially of you have to plot or do some manipulations on databases. Also if, for example, you have to find a general formula on datas.


text:
Q: Time addition not working in PHP I have assigned the variable as
$tot_time=strtotime("h:i:s",  time());

then i add the time using a loop with:
$tot_time=  strtotime($tot_time)+strtotime($result_row->time);

then, i print the total time after the loop using:
echo date("h:i:s",$tot_time);

i get the last values from the loop.

A: You're badly abusing strtotime(). WHy not just leave the time values as integers as they already are?
$tot_time += strtotime($result_row->time);

$tot_time is ALREADY an integer, so there is literally no point in running it through strtotime(). And you can't really use this method for adding together time intervals. PHP's date system works on timestamps, which are seconds-since-1970.
If your $tot_time naturally exceeds 24 hours, you're going to get a "tomorrow" time, e.g. You yon't get "25 hours", you'll get "1 day and 1 hour". You'll only print out "1hour", and now your time interval is very very wrong.


text:
Q: Ionic2 Default http headers I am following this one here How do I set default Http Headers for all requests in Ionic 2?
This works fine and in all http calls it pass the headers I put.
But my problem is when I inject any service to this MyRequestOptions constructor this service is undefined and cant use it...
Anyone know why? I need to inject here my custom AuthService to also put the JWT token.

A: It's because the BaseReqestOptions uses @Injectable, which cases the BaseRequestOptions constructor to be called instead of your subclass constructor. So you could either:
Use a factory
providers: [{
  provide: RequestOptions,
  deps: [ Config ],
  useFactory: (config: Config) => {
    return new DefaultRequestOptions(config);
  }
}]

This will allow you to create the service yourself, without Angular trying to inject it. Or you could
Extend RequestOptions instead
@Injectable()
class DefaultRequestOptions extends RequestOptions {
  constructor(public config: Config) {
    super({method: RequestMethod.Get, headers: new Headers()})

    this.headers.append('data', this.config.data);
  }
}

RequestOptions isn't decorated with @Injectable. And if you look at the source code for BaseRequestOptions, you see all it does is the same thing we are doing above (with the super call).

I need to inject here my custom AuthService to also put the JWT token

You need to be careful with this if AuthService is injecting Http. You might get a circular dependency error (because Http uses RequestOptions and your RequestOptions needs Http). One way to handle this is to inject the Injector, instead Http into the service. Then just get the Http from the Injector.


text:
Q: javax.resource.ResourceException: IJ000459 Transaction is not active I am using JBOSS EAP7 and EJB3.0.
I have some functionality like whenever I got some Exception, I need to log it.
But when I get a Exception and trying to log it, I am getting an exception like Transaction is not active. I am using Container Managed Transaction and Attribute type as Required.
Please help me to resolve it.
Thanks in Advance.