text:
Q: ES6 Promise.all progress I have several promises that I need to resolve before going further.
Promise.all(promises).then((results) => {
  // going further
});

Is there any way I can have the progress of the Promise.all promise?
From the doc, it appears that it is not possible. And this question doesn't answer it either.
So:

*

*Don't you agree that this would be useful? Shouldn't we query for this feature?

*How can one implement it manually for now?

A: I've knocked up a little helper function that you can re-use.
Basically pass your promises as normal, and provide a callback to do what you want with the progress..

function allProgress(proms, progress_cb) {
  let d = 0;
  progress_cb(0);
  for (const p of proms) {
    p.then(()=> {
      d ++;
      progress_cb( (d * 100) / proms.length );
    });
  }
  return Promise.all(proms);
}

function test(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
       console.log(`Waited ${ms}`);
       resolve();
     }, ms);
  });
}

allProgress([test(1000), test(3000), test(2000), test(3500)],
  (p) => {
     console.log(`% Done = ${p.toFixed(2)}`);
});

A: This has a few advantages over Keith's answer:

*

*The onprogress() callback is never invoked synchronously. This ensures that the callback can depend on code which is run synchronously after the call to Promise.progress(...).

*The promise chain propagates errors thrown in progress events to the caller rather than allowing uncaught promise rejections. This ensures that with robust error handling, the caller is able to prevent the application from entering an unknown state or crashing.

*The callback receives a ProgressEvent instead of a percentage. This eases the difficulty of handling 0 / 0 progress events by avoiding the quotient NaN.

Promise.progress = async function progress (iterable, onprogress) {
  // consume iterable synchronously and convert to array of promises
  const promises = Array.from(iterable).map(this.resolve, this);
  let resolved = 0;

  // helper function for emitting progress events
  const progress = increment => this.resolve(
    onprogress(
      new ProgressEvent('progress', {
        total: promises.length,
        loaded: resolved += increment
      })
    )
  );

  // lift all progress events off the stack
  await this.resolve();
  // emit 0 progress event
  await progress(0);

  // emit a progress event each time a promise resolves
  return this.all(
    promises.map(
      promise => promise.finally(
        () => progress(1)
      )
    })
  );
};

Note that ProgressEvent has limited support. If this coverage doesn't meet your requirements, you can easily polyfill this:
class ProgressEvent extends Event {
  constructor (type, { loaded = 0, total = 0, lengthComputable = (total > 0) } = {}) {
    super(type);
    this.lengthComputable = lengthComputable;
    this.loaded = loaded;
    this.total = total;
  }
}

A: You can add a .then() to each promise to count whos finished.
something like :

var count = 0;

var p1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 5000, 'boo');
});
var p2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 7000, 'yoo');
});
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 3000, 'foo');
});

var promiseArray = [
  p1.then(function(val) {
    progress(++count);
    return val
  }),
  p2.then(function(val) {
    progress(++count);
    return val
  }),
  p3.then(function(val) {
    progress(++count);
    return val
  })
]

function progress(count) {
  console.log(count / promiseArray.length);
}

Promise.all(promiseArray).then(values => {
  console.log(values);
});

A: @Keith in addition to my comment, here is a modification
(edited to fully detail hopefuly)
// original allProgress
//function allProgress(proms, progress_cb) {
//  let d = 0;
//  progress_cb(0);
//  proms.forEach((p) => {
//    p.then(()=> {
//      d ++;
//      progress_cb( (d * 100) / proms.length );
//   });
//  });
//  return Promise.all(proms);
//}

//modifying allProgress to delay 'p.then' resolution
//function allProgress(proms, progress_cb) {
//     let d = 0;
//     progress_cb(0);
//     proms.forEach((p) => {
//       p.then(()=> {
//         setTimeout( //added line
//           () => {
//                 d ++;
//                 progress_cb( (d * 100) / proms.length );
//           },       //added coma :)
//           4000);   //added line
//       });
//     });
//     return Promise.all(proms
//            ).then(()=>{console.log("Promise.all completed");});
//            //added then to report Promise.all resolution
// }

//modified allProgress
// version 2 not to break any promise chain
function allProgress(proms, progress_cb) {
    let d = 0;
    progress_cb(0);
    proms.forEach((p) => {
      p.then((res)=> {                        //added 'res' for v2
        return new Promise((resolve) => {     //added line for v2
          setTimeout(   //added line
              () => {
                    d ++;
                    progress_cb( (d * 100) / proms.length );
                    resolve(res);             //added line for v2
              },        //added coma :)
            4000);      //added line
        });                                   //added line for v2
      });
    });
    return Promise.all(proms
                   ).then(()=>{console.log("Promise.all completed");});
                   //added then chaining to report Promise.all resolution
}

function test(ms) {
  return new Promise((resolve) => {
    setTimeout(() => {
       console.log(`Waited ${ms}`);
       resolve();
     }, ms);
  });
}

allProgress([test(1000), test(3000), test(2000), test(3500)],
  (p) => {
     console.log(`% Done = ${p.toFixed(2)}`);
});

"Promise.all completed" will output before any progress message
here is the output that I get
% Done = 0.00
Waited 1000
Waited 2000
Waited 3000
Waited 3500
Promise.all completed
% Done = 25.00
% Done = 50.00
% Done = 75.00
% Done = 100.00

A: Here's my take on this. You create a wrapper for the progressCallback and telling how many threads you have. Then, for every thread you create a separate callback from this wrapper with the thread index. Threads each report through their own callback as before, but then their individual progress values are merged and reported through the wrapped callback.
function createMultiThreadProgressWrapper(threads, progressCallback) {
  var threadProgress = Array(threads);

  var sendTotalProgress = function() {
    var total = 0;

    for (var v of threadProgress) {
      total = total + (v || 0);
    }

    progressCallback(total / threads);
  };

  return {
    getCallback: function(thread) {
      var cb = function(progress) {
        threadProgress[thread] = progress;
        sendTotalProgress();
      };

      return cb;
    }
  };
}

// --------------------------------------------------------
// Usage:
// --------------------------------------------------------

function createPromise(progressCallback) {
  return new Promise(function(resolve, reject) {
    // do whatever you need and report progress to progressCallback(float)
  });
}

var wrapper = createMultiThreadProgressWrapper(3, mainCallback);

var promises = [
  createPromise(wrapper.getCallback(0)),
  createPromise(wrapper.getCallback(1)),
  createPromise(wrapper.getCallback(2))
];

Promise.all(promises);

A: You can use my npm package with an extended version of the native promise, that supports advanced progress capturing, including nested promises, out of the box Live sandbox
import { CPromise } from "c-promise2";

(async () => {
  const results = await CPromise.all([
    CPromise.delay(1000, 1),
    CPromise.delay(2000, 2),
    CPromise.delay(3000, 3),
    CPromise.delay(10000, 4)
  ]).progress((p) => {
    console.warn(`Progress: ${(p * 100).toFixed(1)}%`);
  });

  console.log(results); // [1, 2, 3, 4]
})();

Or with concurrency limitation (Live sandbox):
import { CPromise } from "c-promise2";

(async () => {
  const results = await CPromise.all(
    [
      "filename1.txt",
      "filename2.txt",
      "filename3.txt",
      "filename4.txt",
      "filename5.txt",
      "filename6.txt",
      "filename7.txt"
    ],
    {
      async mapper(filename) {
        console.log(`load and push file [${filename}]`);
        // your async code here to upload a single file
        return CPromise.delay(1000, `operation result for [${filename}]`);
      },
      concurrency: 2
    }
  ).progress((p) => {
    console.warn(`Uploading: ${(p * 100).toFixed(1)}%`);
  });

  console.log(results);
})();

A: const dataArray = [];
let progress = 0;

Promise.all(dataArray.map(async (data) => {
    await something();

    console.log('progress = ', Math.celi(progress++ * 100 / dataArray.length))
}))


text:
Q: Similar tool as java2html but with support for Java 8 I am searching for an up-to-date java2html tool, which supports Java 8. In the past I used java2html.com which created created really useful HTML code. However, I am in trouble now, because this tool not even supports Java 7 language constructs, not mentioning Java 8. If you know any similar standalone tool, which not only transfers the Java code to HTML, but also generates a browser and even it is a piece of cake to integrate it with Ant/Maven/Gradle, please let me know.

A: One solution is to use javadoc's -linksource option, however, it does not colour the code. A workaround might be a javascript solution running on node.js and colouring the code with highlight.js. I chose this solution and automated the highlight.js integration with gradle.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Render partial with different link_to paths I am trying to render a partial that displays a list of names (that I created using :resource :create) and link_to their respective pages.  However, I want to implement this twice such that one list links to the show pages and the other links to their edit pages.
I would prefer to use one partial to accomplish this because they are exactly identical except for their url_path.
footer.html.erb:

                                <%= render current_user.apps %>

                                <%= render current_user.apps %>

_app.html.erb:
Show should have app and
Edit should have edit_app_path(app) for link_to's second argument

    <%= link_to app.name, app %>

A: If your partial contains only

      <%= link_to app.name, app %>

I would suggest to write it two times as as list without css classes isn't enough for a partial imho.
But if you really want to use a partial you can do it with a local variable in Rails 3 way:

        <%= link_to @app.name, @path %>

and
    <%= render "shared/apps", :collection => current_user.apps, :locals => {:path=> @app} %>
    <%= render "shared/apps", :collection => current_user.apps, :locals => {:path=> edit_app_path(app)} %>


text:
Q: Internet timeout or not loading webpages completely, however works in Windows I am running Ubuntu 12.04 64bit at the moment, however, I have been experiencing the problem since about 11.04. (Tried 32 and 64bit versions)
My problem is that when browsing the internet, pages really struggle to load. Sometimes they load fast without any problem. Other times, they time-out and I have to refresh the page a couple of times before the page loads. Sometimes, even if the page starts loading, it does not load the entire page.
For example, sometimes, it will not load css for a page and the entire page will just be plain html. Other times, pictures and other embedded content fail to load. It has come to the point where I have installed a plug-in for Firefox to auto refresh my pages. Usually, it takes about 7 seconds of refreshing before the page starts loading, and that's if it completes the loading.
Sometimes, certain applications have similar symptoms. For example, when using apt-get in the terminal to install or update, it sometimes fail to connect to sources and I have to try again until it connects.
Here are some facts and things I have tried regarding the problem:

*

*I have no connection problems in Windows. (Windows XP, Windows Vista, Windows 7)

*Using a different connection works without a problem. (Used a mobile 3G connection)

*I have tried using different browsers. (Firefox,Chromium)

*I have tried a different Network manager. (Wicd if I remember correctly)

*I have set the time-out time to 100. (sudo sysctl net.ipv4.tcp_fin_timeout=100)

*My installation is up to date.

*I have no problem when downloading files. (Once a download starts, there is no problem.)

I have spoken to my ISP and they said everything is fine from their side and besides, my internet works without any problem in windows.
I would really like if it worked in Ubuntu as it is my primary operating system, but you can understand how frustrating and unproductive it can be when your web pages times out all the time. Please help.
T.I.A.
EDIT 1:

If that image is difficult to read, http://i47.tinypic.com/2r5f22u.png
http://i46.tinypic.com/1zw2rgj.png
http://i48.tinypic.com/2ccml8j.png
http://i49.tinypic.com/j7yxw9.png
EDIT 2:
http://i47.tinypic.com/qx1mvc.png

A: Two suggestions:

*

*In 12.04, here were changes the way DNS lookup was done (http://www.stgraber.org/2012/02/24/dns-in-ubuntu-12-04/). You can disable dnsmasq as described in the above article and try.

*Try another modem: I had the same problem. I use ADSL connection with wireless router. Pages load perfectly with 3G modem, but load slowly with ADSL modem + wireless router. I tried with a different ADSL Modem from my friend and it worked perfectly with my Linux mint 13 (based on Ubuntu 12.04).


text:
Q: glUnmapBuffer while keeping glMapBuffer memory valid as read-only Is it possible to glUnmapBuffer a GL_STREAM_DRAW pixel-buffer-object and still keep the data pointed to by the pointer returned previously by glMapBuffer valid for read-only operations using SSE 4.1 streaming loads?
If not, is there any technical reason for this? Or was this "feature" just left out?

A: The purpose of map and unmap is to say "I need a pointer to this." and "I'm finished using the pointer to this." That's what the functions do.
When you unmap a buffer, the driver is now free to:

*

*Copy the data you wrote (if you wrote anything) to the buffer object, if the mapped pointer is not a direct pointer to that buffer.

*Move the buffer object around in GPU memory, if the mapped pointer is a pointer to that object.

Remember: mapping a pointer does not have to return an actual pointer to that buffer. It simply returns a pointer that when read, will have the data stored in that buffer, and when written, the written bytes will be transferred into the buffer upon unmapping.
Furthermore, the only reason to do what you're suggesting is because you want to read the data in the buffer. Well, since you just mapped the buffer (presumably for writing, or else you wouldn't have unmapped it), you know what's in it. If you needed CPU access to it, you should have just stored the data locally; you'll get a lot more reliable access to it that way.
And if you do another pixel transfer, reading from that pointer it means that OpenGL would have to execute a synchronization, because the whole point of PBO is asynchornous transfer. That is, when you execute glReadPixels or whatever, OpenGL can wait to actually finish this operation until you map the buffer or use glGetBufferSubData.
But if the buffer is mapped for reads, then OpenGL doesn't know when you're going to read from it (since it can't tell when you read from a pointer). So OpenGL can't guarantee the storage within it. In short: undefined behavior. You could get anything at that point.
So what you're talking about doesn't make sense.


text:
Q: How can I clear the corners outside of a rounded rect using the iPhone SDK? I am attempting to implement a custom view. This view should display an image surrounded by a gray, rounded rect border. I can get the image to display fine, as well as the border, however, since the border has rounded corners, I need a way to clear those corners such that they correctly display whatever is behind the view. How can I accomplish this?
It seems like I might be able to use CGContextClearRect, but then wouldn't I have to call this multiple times, reconstructing the area outside of my rounded corner? That sounds overly complicated.
Is there a better way to create this view?
Here is my current code:
- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();

    // Draw the image. This will completely fill the current rect.
    [image drawInRect:self.bounds];

    // Ensure we draw completely within our bounds instead of straddling it.
    CGRect rrect = self.bounds;
    rrect.size.height = rrect.size.height - 1.0;
    rrect.size.width = rrect.size.width - 1.0;
    rrect.origin.x = rrect.origin.x + (1.0 / 2);
    rrect.origin.y = rrect.origin.y + (1.0 / 2);

    CGFloat radius = 5.0;
    CGFloat minx = CGRectGetMinX(rrect);
    CGFloat midx = CGRectGetMidX(rrect);
    CGFloat maxx = CGRectGetMaxX(rrect);
    CGFloat miny = CGRectGetMinY(rrect);
    CGFloat midy = CGRectGetMidY(rrect);
    CGFloat maxy = CGRectGetMaxY(rrect);

    // Draw the rounded rect border.
    CGContextSetRGBStrokeColor(context, 0.6, 0.6, 0.6, 1.0);
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.0);
    CGContextSetLineWidth(context, 1.0);
    CGContextMoveToPoint(context, minx, midy);
    CGContextAddArcToPoint(context, minx, miny, midx, miny, radius);
    CGContextAddArcToPoint(context, maxx, miny, maxx, midy, radius);
    CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, radius);
    CGContextAddArcToPoint(context, minx, maxy, minx, midy, radius);
    CGContextClosePath(context);
    CGContextDrawPath(context, kCGPathFillStroke);
}

A: Add the rounded-rect path to the clipping path before drawing the image.

A: Last week I was trying to do something similar.
With your question, the answer and other Q&A I created an example with a solution.
https://github.com/GabrielMassana/TransparentRoudRectButton


text:
Q: Prove that for a subsequence of natural numbers ${n_k}$, $k ≤ n_k$. Prove that for a subsequence of natural numbers ${n_k}$, $k ≤ n_k$.

*

*I know I have to prove it using induction. I don't know if I'm supposed to prove this by showing two different sequences ${n_k}$ and ${k}$ converge. Other than that I am not sure what direction to go moving forward, any help would be much appreciated.

A: What you forgot to mention is that $\{n_k\}_{k=1}^{\infty}$ is a strictly increasing sequence of natural numbers. That's what you need in order to define the subsequence of a sequence.
Fortunately, it is easy to show that this holds for such a sequence. Define the following set:
$$S = \{k \in \mathbb{N}: n_k \geq k\}$$
where $\{n_k\}_{k=1}^{\infty}$ is understood to be a strictly increasing sequence of natural numbers. We know that $1 \in S$. This should be rather obvious. Now, suppose that $k \in S$. Then:
$$n_{k+1} \geq n_k+1 \geq k+1$$
which shows that $k+1 \in S$. So, $S = \mathbb{N}$ and the given result holds.
I mean, you should already be noticing something wrong with the assertion that you have to show that the sequence $k$ converges. That sequence does not converge at all.
Besides, how would that help you show that $\forall k \in \mathbb{N}: n_k \geq k$? The point is that there are a few good ways of reflecting on the ideas that you're coming up with to attack a given problem.


text:
Q: simpleXML_load_file does not work i use this php commands in localhost.
$bookXML = simpleXML_load_file($bookURL,'SimpleXMLElement',LIBXML_NOCDATA);
if($bookXML== FALSE)
         echo "FALSE";

The variable $bookURL is a link:
http://127.0.0.1/funtrain/resa2/./php/makebooking.php?excode=GR CAN&ticknum=28084&date=2013-05-10&salesman=ALEXANDRA&name=.&adults=2&children=0&infants=0&price1=16&price2=8&pickup=Z_ALEX&time=11:40:00&hotel=Z_ALEX&remarks=&bigremarks=&trf1=0&tax1=0&trf2=0&tax2=0

The link works in browser and return:
<book_reference><number>19793</number></book_reference>

The "simpleXML_load_file" return false...
I use error_reporting(E_ALL|E_STRICT); but do not return anything.
Can anybody help me. I use Xampp v3.1.0.1.0 in windows7 64bit
Thanks in advance.

A: simpleXML_load_file needs a path to the (local) XML file as first Parameter, not a URL

A: Try this
$bookXML = simpleXML_load_file($bookURL,'SimpleXMLElement',LIBXML_NOCDATA);
if($bookXML=== FALSE){
  echo "FALSE";
}else{

}


text:
Q: Is it possible to pivot a table in excel and report all the values I'm not sure this is possible but I'm trying to do the following in excel. I have a table with the names of people and the team they belong to, and I want to make a roster for each team. So I have something like this:
Michael Jordan Bulls
Dennis Rodman Bulls
Kobe Bryant Lakers
Steve Nash Lakers

And I want to get something like:
Bulls Lakes
Michale Kobe
Dennis Steve

Is there a strait-forward way to do this?

A: Create a PivotTable with both Team and Name as Row Labels and Show in Tabular Form. To show the teams side by side, copy and Paste Special Values the PT then select and drag one team to suit.


text:
Q: Third party pack cannot be found likely because the corresponding app is restricted When i add sticker from assets it was working but when i have to Download my custome stickerpack from serve and add to it whatsapp then getting same issue "Third party pack cannot be found likely because the corresponding app is restricted, sdk: 29 ,power saving mode: false"
my "Add to whatsapp" button code is
intent.setAction("com.whatsapp.intent.action.ENABLE_STICKER_PACK");
                intent.putExtra(EXTRA_STICKER_PACK_ID, stickerPack.identifier.replace(" ",""));
                intent.putExtra(EXTRA_STICKER_PACK_AUTHORITY, BuildConfig.CONTENT_PROVIDER_AUTHORITY);
                intent.putExtra(EXTRA_STICKER_PACK_NAME, *stickerPack.name*);
                try {
                    startActivityForResult(intent, ADD_PACK);
                } catch (ActivityNotFoundException e) {
                    Log.d(TAG+"aba", "onCreate: "+e.toString());
                }


text:
Q: Classicthesis: control horizontal space between chapter number and headline on even pages I am using classicthesis, and I noticed that the space between the chapter number and the headline is larger on even pages than on odd pages. How can I reduce this space so that it is about as large as on the odd pages?
\documentclass[twoside,a4paper,11pt]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[T2A, T1]{fontenc}
\usepackage[eulerchapternumbers,listings,pdfspacing]{classicthesis}

\begin{document}
\chapter{First chapter - space is ok}
\chapter{Second chapter - space is too large}
\end{document}

A: The classicthesis package assumes openright. You can fix it:
\documentclass[twoside,a4paper,11pt]{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[T2A, T1]{fontenc}
\usepackage[eulerchapternumbers,listings,pdfspacing]{classicthesis}
\usepackage{etoolbox}

\makeatletter
\patchcmd\ttlf@chapter
  {\oldmarginpar}
  {\oldmarginpar[\vspace*{-3\baselineskip}\color{halfgray}\hfill\chapterNumber\thechapter]}
  {}{}
\makeatother

\begin{document}
\chapter{First chapter - space is ok}
\setcounter{chapter}{0} % just to make a fair comparison
\chapter{Second chapter - space is too large}
\end{document}


text:
Q: Как присвоить класс при нажатии на внутренний блок? Есть несколько таких блоков кода, как при нажатии на кнопку отправить присвоить классу mainli ещё один класс active?

Text

Title6

...

...

...

...

...

 txt

 txt

txt

                390

    Отправить

Мой код присваивает всем mainli класс актив можно как-то это исправить?

A:

A: в зависимости текущего элемента $(this) и на его ближайшего подходящего родителя .closest(".mainli")

$(document).ready(function() {
  $(".buys").click(function() {
    $(".mainli").removeClass("active");
    $(this).closest(".mainli").addClass("active"); // По правке Igor
    return false;
  });
});
body {
  background: gray;
}

a {
  cursor: pointer;
}

.mainli.active {
  background: #f00;
}

Text

Title6

...

...

...

...

...

 txt

 txt

txt

                390

    Отправить


text:
Q: Google map direction services waypoints more than 50 Documentation says that waypoints limit is 8 points. But I have to find best waypoints order list from more than 50 waypoints. How to do that?
I am able to find waypoints order by using Start + Destination + 8 Waypoints But I need help for more than 50 Waypoints

A: I've created a workaround but it is a bit more expensive (in terms of API calls) to use.
Instead of creating a single call with the start, end, and waypoints LatLngs, I split the waypoints into pairs make the calls per pair.
Example:
Problem: Route and get Directions for 100 points
Solution:

*

*Call 1: Point 1 and Point 2

*Call 2: Point 2 and Point 3

*Call 3:
Point 3 and Point 4
... and so on.
With this solution you'll never have to worry about the 8 waypoint limitation since you're only making a 2 point query every time. The weakness of this solution is you will be creating a lot of calls and it will eat up your 2500 free calls per day if not used properly.

A:

function initMap() {
    var service = new google.maps.DirectionsService;
    var map = new google.maps.Map(document.getElementById('map'));

    // list of points
    var stations = [
        {lat: 48.9812840, lng: 21.2171920, name: 'Station 1'},
        {lat: 48.9832841, lng: 21.2176398, name: 'Station 2'},
        {lat: 48.9856443, lng: 21.2209088, name: 'Station 3'},
        {lat: 48.9861461, lng: 21.2261563, name: 'Station 4'},
        {lat: 48.9874682, lng: 21.2294855, name: 'Station 5'},
        {lat: 48.9909244, lng: 21.2295512, name: 'Station 6'},
        {lat: 48.9928871, lng: 21.2292352, name: 'Station 7'},
        {lat: 48.9921334, lng: 21.2246742, name: 'Station 8'},
        {lat: 48.9943196, lng: 21.2234792, name: 'Station 9'},
        {lat: 48.9966345, lng: 21.2221262, name: 'Station 10'},
        {lat: 48.9981191, lng: 21.2271386, name: 'Station 11'},
        {lat: 49.0009168, lng: 21.2359527, name: 'Station 12'},
        {lat: 49.0017950, lng: 21.2392890, name: 'Station 13'},
        {lat: 48.9991912, lng: 21.2398272, name: 'Station 14'},
        {lat: 48.9959850, lng: 21.2418410, name: 'Station 15'},
        {lat: 48.9931772, lng: 21.2453901, name: 'Station 16'},
        {lat: 48.9963512, lng: 21.2525850, name: 'Station 17'},
        {lat: 48.9985134, lng: 21.2508423, name: 'Station 18'},
        {lat: 49.0085000, lng: 21.2508000, name: 'Station 19'},
        {lat: 49.0093000, lng: 21.2528000, name: 'Station 20'},
        {lat: 49.0103000, lng: 21.2560000, name: 'Station 21'},
        {lat: 49.0112000, lng: 21.2590000, name: 'Station 22'},
        {lat: 49.0124000, lng: 21.2620000, name: 'Station 23'},
        {lat: 49.0135000, lng: 21.2650000, name: 'Station 24'},
        {lat: 49.0149000, lng: 21.2680000, name: 'Station 25'},
        {lat: 49.0171000, lng: 21.2710000, name: 'Station 26'},
        {lat: 49.0198000, lng: 21.2740000, name: 'Station 27'},
        {lat: 49.0305000, lng: 21.3000000, name: 'Station 28'},
    ];

    // Zoom and center map automatically by stations (each station will be in visible map area)
    var lngs = stations.map(function(station) { return station.lng; });
    var lats = stations.map(function(station) { return station.lat; });
    map.fitBounds({
        west: Math.min.apply(null, lngs),
        east: Math.max.apply(null, lngs),
        north: Math.min.apply(null, lats),
        south: Math.max.apply(null, lats),
    });

    // Show stations on the map as markers
    for (var i = 0; i < stations.length; i++) {
        if (!stations[i].name)
            continue;
        new google.maps.Marker({
            position: stations[i],
            map: map,
            title: stations[i].name
        });
    }

    // Divide route to several parts because max stations limit is 25 (23 waypoints + 1 origin + 1 destination)
    for (var i = 0, parts = [], max = 8 - 1; i < stations.length; i = i + max)
        parts.push(stations.slice(i, i + max + 1));

    // Callback function to process service results
    var service_callback = function(response, status) {
        if (status != 'OK') {
            console.log('Directions request failed due to ' + status);
            return;
        }
        var renderer = new google.maps.DirectionsRenderer;
        renderer.setMap(map);
        renderer.setOptions({ suppressMarkers: true, preserveViewport: true });
        renderer.setDirections(response);
    };

    // Send requests to service to get route (for stations count <= 25 only one request will be sent)
    for (var i = 0; i < parts.length; i++) {
        // Waypoints does not include first station (origin) and last station (destination)
        var waypoints = [];
        for (var j = 1; j < parts[i].length - 1; j++)
            waypoints.push({location: parts[i][j], stopover: false});
        // Service options
        var service_options = {
            origin: parts[i][0],
            destination: parts[i][parts[i].length - 1],
            waypoints: waypoints,
            travelMode: 'WALKING'
        };
        // Send request
        service.route(service_options, service_callback);
    }
  }
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}
#map {
    height: 100%;
    width: 100%;
    height: 100%;
}

With following code you can use as many waypoints as you need and you will never get error MAX_WAYPOINTS_EXCEEDED. Do not forget to replace "YOUR_API_KEY" to your API KEY or remove &key=YOUR_API_KEY from google API URL and set variable "max" to 8 (max = 25 when using API KEY, max = 8 when not using API KEY).

A: Ufortunately it is not possible to do.
I'f you have a business account you can add up to around 25 waypoints. A business account is quite expensive.
You need to look for another vendor if you need to use more than 25 waypoints.

A: I have found this workaround.
It seems like it does exactly what you need. take a look: http://lemonharpy.wordpress.com/2011/12/15/working-around-8-waypoint-limit-in-google-maps-directions-api/

A: HERE Maps (https://developer.here.com/blog/delivery-made-easy-with-the-here-waypoint-sequence-api) offers Waypoints Optimization up to 120 waypoints. Check them out, their prices are very reasonable as well


text:
Q: How many 4 digit integers using digits 1-9 are there so that the sum of digits is even?
How many 4 digit integers using digits 1-9 are there so that the sum of digits is even?

I divide it into cases.

*

*Case 1, all even: $4^4$

*Case 2, no even: $5^4$

*Case 3, two even, two odd. How should this be done?

A: For case 3:

*

*Pick which two of the four digits are even: $\binom42=6$

*Assign the digits: $5^2\cdot4^2$

There are $6\cdot5^2\cdot4^2$ integers in this case. The total number of integers is $4^4+5^4+6\cdot5^2\cdot4^2=3281$.

A: You need to choose two (out of four) of the digits to be odd, which you can do in ${}^4 C_2$ ways. Once you've decided which digits are going to be odd and which are going to be even, you can just select the digits in order, for which you have $4^2 5^2$ choices.


text:
Q: Hodge structure and rational coefficients Suppose $X$ is a complex projective variety with a model $X_\mathbb{Q}$ defined over the rational numbers. Then there is a rational de Rham lattice $H^k_{dR}(X_\mathbb{Q}, \mathbb{Q})\subset H^k(X, \mathbb{C})$ coming from the hypercohomology of the de Rham complex with rational coefficients. Hodge theory implies a formality quasiisomorphism $H^*(X, \mathbb{C})\to C^*(X, \mathbb{C})$ which is compatible with multiplication, and even (see this paper of Guillen, Navarro, Pascual and Roig) functorial in a dg sense with respect to maps between projective varieties. Now I want to understand the map from the sub-lattice $H^*_{dR}(X_{\mathbb{Q}}, \mathbb{Q})\to C^*(X, \mathbb{C}).$ I have two questions.

*

*Is there a way to characterize the forms in the image of $H^*(X_\mathbb{Q}, \mathbb{Q})$ in terms of Dolbeault forms? For example are they in some sense local linear combinations of rational holomorphic forms wedged with rational antiholomorphic forms?

*Is there a canonical way to relate $H^*_{dR}(X_\mathbb{Q}, \mathbb{Q})$ with the hypercohomology complex $C^*_{dR}(X_{\mathbb{Q}}. \mathbb{Q})$ via a canonical chain of quasiisomorphisms? By canonical I mean at least compatible with rational closed immersions, but hopefully more generally with all maps of rational projective varieties?


text:
Q: most efficient way to read data from stdin in python I know the most efficient way to read data from file in chunks. But I want to read data from stdin and I want the fastest way to read data because time is a constraint in the execution of the code. I want to do this in python 2.7.
Edit:
Judging the best method to read data from stdin will depend on a lot of parameters. What things should I take into consideration in order to read data faster?
Code:
from itertools import permutations
line=raw_input().splitlines()[0].split(" ")
word=line[0]
k=int(line[1])
words=list(permutations(word,k))
finalList=[]
for word in words:
    wo=""
    for w in word:
        wo=wo+w
    finalList.append(wo)
finalList.sort()
for i in finalList:
    print i

A: You can use the fileinput module. A good way to read from STDIN using this is as such
import fileinput as fi

for line in fi.input():
  // DO SOMETHING


text:
Q: No discharge from capacitor I'm currently trying to make an electrical discharge machining (EDM) machine that uses electrical discharge to erode away metal.
Right now, I'm just trying to test it out with a 200V 100uF capacitor, and a heating element acting as a resistor (measured at about 11 ohms) to limit the current (as I'll literally be short-circuiting).
I'm using a flyback as the power supply and varying the voltage going to the ZVS driver to vary the output from the transformer.
I'm not getting any sparks at the receiving end when I put the electrode and workpiece close together in that plastic container full of distilled water.
The capacitor I think is still getting charged though (I disconnected it and when discharged made a lot of sparks).
Here is a video of what I'm trying to achieve

This is the circuit diagram I was going off of, just without the IGBT and pulse generator because this was just a test (planning to add later.)
Can someone help me troubleshoot the problem (I can provide more info) and what to change?

A: You have to pulse the discharge through the workpiece.  As you have it, it will discharge once, then never be able to charge the capacitor again.  You have only (at most) the current through the heating element.
Here's how it is supposed to work:

*

*Capacitor charges through the resistor.

*The electrode is moved to nearly touching the workpiece.

*The electrode and the workpiece are connected to the capacitor.

*The capacitor discharges a high current through the electrode and the workpiece, eroding the workpiece.

*The capacitor is disconnected from the electrode and the workpiece.

*The capacitor is charged through the resistor.

*The electrode is moved a tiny bit closer to the workpiece.

*Repeat from step 3 until the task is complete.

*

*You can work from a low current supply if you give the capacitor enough time to charge between discharges.

*A higher voltage means you can have a larger gap between the electrode and the workpiece.

*If that high voltage flyback produces more than 200VDC, then you have destroyed your capacitor.

A: The flyback is woefully inadequate for this application. It outputs way too much voltage and way too little current.
You'd get much better results from a Variac + isolation transformer + diode bridge. Of course this becomes very dangerous.
The application, is 10-30A sparks, from 100-300VDC.
There must exist something to interrupt the spark current. When an arc occurs, the impedance of the arc goes from very high to very low, and will consume all of the available power, preventing another recharge from ever happening - indefinitely.  Real machines pulse this current 50,000 times or more per second.
This high frequency may require the use of litz wire to the work to reduce losses.  The whole EDM process is a huge generator of electrical interference - radio waves - don't be surprised if nearby electronics start misbehaving. Hopefully nobody nearby has a pacemaker.
The ionic conductivity of the water also matters. Cannot use distilled water, as it's conductivity is too low, requiring the electrode/work to be impossibly close, welding the tool and work frequently. And cannot use tap water, as the conductivity is too high, leading to electrolysis and loss of cutting resolution. EDM machines using water employ a conductivity tester and ionic filter to regulate the ion concentration. Others use a special oil. Both require exotic filters to remove particulate and control ion concentration.


text:
Q: Binding to properties of a control in a tooltip I want to display some properties of a (custom) Label in its Tooltip,
but I can't seem to get it working correctly so must be doing something wrong:
<Label.ToolTip>
    <Border BorderBrush="Gray" CornerRadius="5" Margin="5" Padding="5">
       <Label Content="{Binding Path=Width, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Label}}}"/>
    </Border>
</Label.ToolTip>

Any ideas?

A: I've found the solution
<ToolTip  DataContext="{Binding Path=PlacementTarget, RelativeSource={x:Static RelativeSource.Self}}">

Thnx to Karl!
http://karlshifflett.wordpress.com/2007/12/29/wpf-sample-series-data-binding-in-tooltip/


text:
Q: Bootstrap panels being pushed down with too much text in heading I've just been watching some videos trying to learn how to use Bootstrap, it's going fine until i started adding too much text into the panel-heading.
Here is the code (repeated several times)

Game Name - US

<button class="btn btn-success btn-sm text-center" type="button">Game Info</button>

                                Added on 2015-03-31

This is what's happening, should just be 2 rows of 3.

A: I answered a similar question here: Bootstrap 3 broken row on mobile only
One option is to use a css clearfix every 3 cols:
Codeply link
Another options is to truncate the heading text on smaller screens to prevent wrapping (which will make each panel the same height):
Codeply Link

A: .equateRow, .equateRow > div[class*='col-'] {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex:1 1 auto;
}
/*add a class of equateRow around in the row that has the panels and you are good to go*/

Found a good bootply link


text:
Q: High potential energy but low potential I'm really struggling to understand electric potential. My textbook makes this example:

Could you please elaborate a little more one why the potential at point $a$ is higher than the potential at point $b$? Is it because the negative plate as been taken as zero potential? If the zero potential is chosen arbitrarily, what would happen if I'd consider the positive plate as the zero? Could you help me clarify this please?

A:
Could you please elaborate a little more one why the potential at
point $a$ is higher than the potential at point $b$?

The definition of high and low potential is based on positive electric charge.
The potential at $a$ is higher than at $b$ because it takes work by an external agent to move positive charge from the negative plate to the positive plate against the direction of the repulsive force exerted by the electric field $E$.
The force exerted by the electric field (assumed constant between the plates) is
$$F=QE$$
If the distance between the plates is $d$, then the work done moving the charge from the negative to positive plate giving the charge potential energy is
$$W=Fd=QEd$$
The potential difference, $V_{ab}$ between the plates is related to the electric field by
$$E=\frac{V_{ab}}{d}$$
Therefore, the work and potential energy can be written as
$$W=QV_{ab}$$
The gravitational analogy is lifting an object a height $h$ against the downward force of the gravitational field. The gravitational field near the surface of the earth is $g$ and the gravitational force is $F=mg$. When lifted the height $h$ its gravitational potential energy is $mgh$.

Is it because the negative plate as been taken as zero potential?

No, it is because a negatively charged plate will always be at lower potential than a positively charged plate. The negative plate does not have to be taken as zero potential. But whatever potential it is it has to be lower than the potential of the positive plate because it takes work to move positive charge against the direction of the electric field, which is defined as the direction of the force that a positive charge would experience if placed in the field. The work moving the charge from the negative to positive plate increases both the potential and potential energy of the positive charge.

what would happen if I'd consider the positive plate as the zero?

If you did assign it zero potential, then the potential of the negative plate would have to be some negative value so that $V_{a}>V_{b}$ and $V_{ab}=V_{a}-V_{b}>0$.
For example, if $V_{a}=0$ volts, then $V_{b}<$ 0, for example -5 volts. Then $V_{a}-V_{b}=0-(-5)=+5$ volts

I think I understand, the definition of $V_{ab}$ is
$V_{ab}=V_{a}-V_{b}=(U_{a}-U_{b})q$, since in this case, as the book
says too, $U_{a}-U_{b}<0$ and $q<0$, $V_{a}-V_{b}>0$, and therefore
$V_{a}>V_b$. Correct right?

You got it. The key is the potential energy of the negative charge ($q<0$) is lower at $a$ than at $b$ whereas the potential energy of the positive charge ($q>0$) is higher at $a$ than at $b$. I think this should also help you regarding your prior, similar question.

Can I ask you one more thing please? The books says that $V_{a}-V_{b}=
 -W_{ab}/q$, where $W_{ab}$ is the work done by the electric field as the charge moves from  to

Yes. As I said in the beginning, because the potential is greater at $a$ than $b$ an external (to the field) agent is needed to do work to move positive charge from $b$ to $a$. Since the direction of the external force is the same as the direction of movement (displacement) of the charge, the work it does is positive. The gravity analogy is an external force (e.g., you) lifting an object to increase its gravitational potential and gravitational potential energy.
At the same time the external force is doing positive work, the electric field is doing an equal amount of negative work when the positive charge moves from $b$ to $a$. This is because the force of the electric field is opposite the direction of movement (displacement) of the positive charge. In doing negative work the electric field takes the energy supplied by the external agent and stores it as electrical potential energy of the charge/field system.

and then it says that the potentials $V_a$ and $V_b$ (or the electric potentials in general) are due to the
charges on the plates, not due to the test charge between the plates.

That's correct, as long as the test charges remain between the plates and are not allowed to combine with charges on the plates. If the figure, if the negative charge is released and allowed to combine with the positive charges on the positive plate the net positive charge on the positive plate will be reduced, altering the electric field and electric potential between the plates.

Is this because:$V_{a}-V_{b}=-W_{ab}/q=-Eqd/q=-Ed$ and therefore since
the electric field depends only on the charge that produces the field,
$V_{ab}$ depends only on the charges on the plates? –

Yes, because the $q$ in the equation is the test charge $q$, and not the $q$ on the plates.
Hope this helps.

A: The electric potential is related to the field this way
$$\vec{E}=-\vec{\nabla}V.$$
In case you are not familiar with this expression, it means that the electric field points towards regions with lower potential. If you placed the zero at the positive plate, the value of the potential at the negative plate would be negative.


text:
Q: Thunderbird 7 with email notification indicator doesn't seems to work I just realized that in Ubuntu 11.10 fresh install the message indicator menu doesn't notify me if I have new mail, just in case of starting Thunderbird. The email setup completed, when Thunderbird is running and downloading new email, the indicator works well.
But, when Thunderbird is not running, i thought the indicator checks for new email in the background without i need to start Thunderbird manually.
Checking for new emails is set for 1 minute period under settings menu (Thunderbird).
Is there something that i need to set for that checking period also applied for the indicator menu, or i'm missing something during the program setup, or is this a known bug?
Thanks in advance!

A: The indicator is part of Thunderbird. That means, if Thunderbird isn't running, it won't check for emails and therefore won't notify you of emails. It is not a bug, though it may be considered a missing feature.

A: I think this is a known "shortcoming". There are several bugs filed in the tracking system related to this topic. E.g.:

*

*Minimize to Messaging Menu

*Messaging menu TB extension disappears when TB is closed
This is still under active development, you can keep an eye on the progress starting from the Mozilla Labs Ubuntu Unity Messaging Menu page.


text:
Q: New AD users not being added to Global Address List / unable to configure new user on outlook I just added a new user to AD and generated a mail box for her. When I go to configure outlook on her machine, I get the error "The name cannot be resolved. The name cannot be matched to a name in the address list"
I've regenerated the OAB and even recreated the AD object with no luck. I can not see the new user from the GAL on my machine, even when working online vs. cached.
However, I can log in to the new mailbox via OWA, see the recipient in that address list, and send and receive mail.
I've tried just about every fix I've stumbled upon with no success.
Using exchange 2010 on a single domain with less than 200 users. We are using outlook 2007 as the client.
Any guidance would be most appreciated! Thank you

A: Microsoft has a wonderful step-by-step guide called "Troubleshooting Check Name errors" for this exact type of situation.
If you have already verified that the object has properly replicated after creation, this is definitely a place to start.
The most interesting part starts at step 3:

Verify that the user account has been stamped by the Recipient Update
  Service after you mailbox-enable the user account. To do so, start
  Ldp.exe, use the user credentials to bind, and then verify that the
  following attributes have been populated to the account:

*

*showInAddressBook()

*textEncodedORAddress

*msExchUserAccountControl

*msExchALObjectVersion

*msExchPoliciesIncluded
If these attributes are populated, the Recipient Update Service has
  stamped this user account. If these attributes have not been
  populated, troubleshoot the Recipient Update Service and the recipient
  policies to determine why the attributes have not been stamped.

Another place to go if you have Outlook connectivity issues is Microsoft's onlince Remote Connectivity tool: https://www.testexchangeconnectivity.com/


text:
Q: Convert struct to char array in C I have below structure which I need to send across a network.
typedef struct {
    u_int16_t dataSize;
    u_int16_t *positions;
    char *dataLoad;
} TransferData

positions and dataLoad variables can contain any number of ints and characters.
I have tried this using,
TransferData m;

//adding data to the structure
size_t len = snprintf(NULL, len, "%p, %d, %s", m.positions, m.dataSize, m.dataLoad);
char *apstr = calloc(1, sizeof *apstr * len + 1);
if (!apstr) {
    fprintf(stderr, "%s() error: virtual memory allocation failed.\n", __func__);
}

if (snprintf(apstr, len + 1, "%p,%d,%s",m.positions,m.dataSize,m.dataLoad) > len + 1) {
    fprintf(stderr, "%s() error: snprintf returned truncated result.\n", __func__);

}

The code works for char* and u_int16_t but not for u_int16_t *.Is there any way that I can convert this struct to a char array??


text:
Q: is there a way to reset a linux machine should the primary disk fail? I have a small embedded Linux device where the root filesystem is mounted over a USB connection
the device can handle a reset quite well (it'll wait for the USB disk to arrive should it be unplugged at boot)
however should the disk be unplugged the device tends to wedge,  I'd prefer if it just reset?
is there a kernel option that would get the kernel to reset should the primary disk disappear?

A: This is quite easy.
You'll need to create a udev rule triggered on the USB unplug event for that device. These would be files in etc/udev/rules.d. Take a look at this question over at ServerFault for details.
So, we've established that you can trigger arbitrary commands on USB unplug events with the PROGRAM keyword.
The second part to this is to use the "magic" sysrq key. See this article about Magic SysRq on Wikipedia for things you can do with the sysrq key. The key can also be triggered by echoing the letter of the action to /proc/sysrq-trigger. This will have the same effect as pressing the key combination on your physically attached keyboard.
Therefore, the udev rule would be:
DRIVER="some_device", ACTION="remove", PROGRAM="/bin/echo b > /proc/sysrq-trigger"

This will trigger the system to reboot when the device some_device is removed.
And this of course assumes that by "wedged" you don't mean "kernel panic".


text:
Q: Generate database table from text file with php I host a bunch of Wordpress sites, and I want to make a script that will check their version every day and if they don't match with Wordpress' latest version, it would notify me.
Right now the easiest way I found to check their versions is looking into the wp-includes/version.php file, so I made this:
grep "$wp_version =" /home/*/public_html/wp-includes/version.php > /~/wordpress/versions.txt
The line above will be put on the cron to be executed once a day.
Now I want to make a php script that will organize each line of the above script into a table, like this:
Folder (in which the wordpress site is installed) ; Version
Then, I want the script to check if the above "Version" matches with the variable $wp_latest_version that I will set. If they match, the "Version" cell will turn green and if they don't, the "Version" will turn red so me or and peers can know which sites we need to update.
I have sort of an idea of how I will do the last part, but right now I'm stuck in the "translate .txt file to table" process.
Any suggestions?
Also, should I use MySQL or not?
This is part of the output text that I want to translate into a table:
/home/alton/public_html/wp-includes/version.php:$wp_version = '3.5.2';
/home/boutaces/public_html/wp-includes/version.php:$wp_version = '3.4';
/home/byseacom/public_html/wp-includes/version.php:$wp_version = '3.5.2';
/home/capricho/public_html/wp-includes/version.php:$wp_version = '3.5.1';
/home/carlosva/public_html/wp-includes/version.php:$wp_version = '3.6.1';
/home/cerimoni/public_html/wp-includes/version.php:$wp_version = '3.5.1';
/home/cotaksis/public_html/wp-includes/version.php:$wp_version = '3.6.1';
/home/crisblog/public_html/wp-includes/version.php:$wp_version = '3.5';
/home/customup/public_html/wp-includes/version.php:$wp_version = '3.5.2';
/home/dentist/public_html/wp-includes/version.php:$wp_version = '3.4.2';

A: foreach($lines as $line)
{
    if(preg_match('|\/home\/(.+?)\/public_html\/wp-includes\/version.php:\$wp_version = '(.+?)';|', $line, $matches))
    {
        $folder = $matches[1];
        $version = $matches[2];
    }
}

Once you have the values separated from the string, write them either into a db of your choice or into a file.


text:
Q: NSStream delegate not firing errors I'm struggling with an issue with the NSStream Delegate.
My app creates and opens 10 concurrent TCP clients and connects to 10 TCP Servers in devices I am controlling.
I am creating the 10 sockets each with their own unique input and output streams.
They all feed back in to one stream delegate to process the stream events.
I am able to connect and communicate on all 10 sockets without issue.
However when I unplug one or more of my servers my connections on the iPad still show their state as established and a [outputStream status] message returns 2.
I expected the stream to show an error event when the server is disconnected but this doesn't seem to be happening.
Is this me doing something wrong by connecting multiple streams to a single delegate or is there some other more fundamental issue?
an example of my socket creation which sets the delegate:
-(void)connectToHub0 {
    launchflag = 1;

    NSLog(@"trying to connect to hub 0");

    /
    UInt32 port;
    port = 40000;

    launchTimer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector (launchTimeOut:) userInfo:nil repeats:NO];

    Hub *currentHub = [Hubs objectAtIndex:0];

    /
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)currentHub.ipAddress, port, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;

    [inputStream setDelegate:self];
    [outputStream setDelegate:self];

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];
    [outputStream open];
}

The delegate is set in my viewController.m as:
@interface viewController()<NSStreamDelegate>

A: This is normal behaviour of a TCP socket.  One way to detect this type of disconnection is to use a keep-alive packet as part of your network protocol.
See this interesting article for a more detailed answer.


text:
Q: Finding a user is Admin or Not with Decalarative Authorization I have implemented declarative authorization in my blog app. Now I have three layouts each for an Admin, Authenticated User and guest user. So I need to check what type of user is using the app at a particular time. We have User model, Role model and Assignment Model.
User.rb
class User < ActiveRecord::Base

  attr_accessible :login, :email, :password, :password_confirmation, :role_ids

  has_many :articles
  has_many :comments
  has_many :assignments

  has_many :roles, :through => :assignments

  def role_symbols
    roles.map do |role|
      role.name.underscore.to_sym
    end
  end

  acts_as_authentic do |c|
    c.login_field = :login
  end

  def deliver_password_reset_instructions!
    reset_perishable_token!
    Notifier.deliver_password_reset_instructions(self)
  end

end

Assignment.rb
class Assignment < ActiveRecord::Base
  belongs_to :user
  belongs_to :role
end

Role.rb
class Role < ActiveRecord::Base
  attr_accessible :name
  has_many :assignments
  has_many :users, :through => :assignments
end

Any solution?

A: You could simplify your structure with this gem:
https://github.com/platform45/easy_roles
Follow the instructions on github and modify your models like described there.
It is really easy, just a few steps. You just need your user model, and that´s it!
Additionally I would reccomend the cancan gem (https://github.com/ryanb/cancan).
easy_roles and cancan are a good combination to define roles and permissions quite easily!


text:
Q: Compare arrays with different sizes with strcmp() I'm currently learning C and I have this question...
char name[6] = "Pedro";
char test[25];

printf("Insert a name: ");
fgets(test, 25, stdin);

if(!strcmp(name, test))
   puts("They are equal...");

During the execution, strcmp doesn't return 0 when I insert the value "Pedro" in the array "test"...
I know the array "test" have a size of 25 instead of 6, but since C dettects the end of a string with '\0', how can I use the fgets in this situation?
Thank you very much...

A: fgets keeps the '\n' at the end of the line, it must be removed before the comparison. Example:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main(void)
{
    char name[6] = "Pedro";
    char test[25];

    printf("Insert a name: ");
    fgets(test, 25, stdin);

    test[strcspn(test, "\n")] = '\0';

    if(!strcmp(name, test))
        puts("They are equal...");

    return 0;
}

A: The function fgets can append to the entered sequence of characters the new line character '\n' that corresponds to the pressed key Enter.
You need to remove it before calling strcmp like for example
test[ strcspn( test, "\n" ) ] = '\0';

Pay attention that it will be more safer to write
char name[] = "Pedro";

instead of
char name[6] = "Pedro";

Otherwise in general you can make a mistake counting characters in a string literal.
Also instead if this line
fgets(test, 25, stdin);

it will be better to write
fgets(test, sizeof( test ), stdin);

without using the magic number 25.


text:
Q: Implementing HTTP caching Etag feature using MD5 in ASP.NET Web Api I was reading Google performance document about HTTP caching at https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching, This document says that we should use ETags when possible. I am using ASP.NET Web Api 2.2. I am now trying to implement ETag in all of my public apis. I am thinking to implement ETag using MD5. I mean, I will hash the json response on each request using MD5. Is there any performance hit of using MD5.calculateHash on each request? My json response size are not too big(within the range of 1 to 20KB).

A: Yes there will be a performance hit.  Calculating a hash takes time.  However, you may find that the cost of calculating that hash is not significant in comparison to the performance saved by transferring unchanged bytes over the wire to the client.
However, there is no guarantee that you will get a perf improvement with Etags.  It depends on many things.  Are you going to regenerate the Etag on the server on every request to compare it with the incoming request?  Or are you going to create a cache of etag values and invalidate them when the resource changes?
If you are going to regenerate the etag on every request then it is possible that the time spent pulling data from the database and formatting the representation will be significantly higher than the time it takes to send a few bytes over the wire.  Especially if the entire representation can fit in a single network packet.
The key here is to ask if you really need the performance gain of Etags and is it worth the cost of doing the implementation.  Setting cache control headers to enable client side private caching may give you all the benefits that you need without having to implement etags.
I have a number of posts that go into this subject in more detail:

*

*http://www.bizcoder.com/using-etags-and-last-modified-headers-to-improve-performance-with-http-conditional-requests

*http://bizcoder.com/implementing-conditional-request-handling-for-your-api


text:
Q: How to release multiple dependent android librarys with consistent versioning? Given a multi module gradle project consisting of:

*

*app

*library A

*library B

*library C

Where

*

*app has dependencies on A,B,C

*B has dependencies on A

*C has dependencies on A

*A has no dependencies

How do you configure your dependencies to perform a maven release to a maven repository (i.e. uploadArchives) so that all artifacts (the app and libraries A,B and C) are released with the same version and dependent on the same version of the corresponding libraries?
For example:
To start with, the dependencies look like this
APP
compile project(':A')
compile project(':B')
compile project(':C')

B
compile project(':A')

C
compile project(':A')

This guarantees that when I build the project all libraries and app are compiled using the current codebase.
What I want to do is update one property in gradle.properties, and have all the artifacts released with that version, have dependencies on that version, and still be built using the current codebase (because the current codebase will be that version)
gradle.properties
PROJECT_VERSION=1.2.0

Ultimately I want the released versions to look like this:
APP
compile ('com.my.groupid:A:1.2.0')
compile ('com.my.groupid:B:1.2.0')
compile ('com.my.groupid:C:1.2.0')

B
compile ('com.my.groupid:A:1.2.0')

C
compile ('com.my.groupid:A:1.2.0')

What is the correct approach to achieving this?

A: You can use somenthing like this.
APP
compile project(':A')
compile project(':B')
compile project(':C')

B
compile project(':A')

C
compile project(':A')

In top-level build.gradle use:
ext{
    VERSION_NAME = 1.1.2
}

Then in your update script use:
afterEvaluate { project ->
    uploadArchives {
        repositories {
            mavenDeployer {
                beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

                pom.groupId = GROUP
                pom.artifactId = POM_ARTIFACT_ID
                pom.version = rootProject.ext.VERSION_NAME

                //....other parts
            }
        }
    }
}

Define a task like:
task uploadAllArchives {
    description 'Upload all modules to Maven Repository'
    println ''
    println '---------------------------------'
    println 'Version: ' + version
    println 'UPLOAD ALL ARCHIVES'
    println '---------------------------------'
    println ''
    doLast{
        println ''
        println '---------------------------------'
        println 'Version: ' + version
        println 'UPLOAD ALL ARCHIVES FINISHED'
        println '---------------------------------'
        println ''
    }
}
uploadAllArchives.dependsOn(
        ':libraryA:uploadArchives',
        ':libraryB:uploadArchives',
        ':libraryC:uploadArchives')


text:
Q: Extract details from a filename in a folder My filename looks like 23_10_2020_15_47_06_1550_5.png.
I want to extract the last _5 part of it so that I can compare it to another file ending in 23_10_2020_15_47_06_1050_R_5 which is in another folder and use these files for my further operations.
Can someone help me with how to do it?

A: Here is how you can use the list.rsplit() method:
from glob import glob

files1 = glob("Folder1\\*.png") # List of all png files in Folder1
files2 = glob("Folder2\\*.png") # List of all png files in Folder2

lst = [f.rsplit('_', 1)[-1][:-4] for f in files1] # List of all the last numbers in the files1 list


text:
Q: Using media query and show a div below another div which is written before Hello all what i am trying to do is that i have a HTML page where i have 2 divs div1 and div2 both are float left and obviously div1 comes before div2 but what i want is that with the help of media query i want div1 to get below div2 as soon as page size gets below 400px

@media only screen and (max-width: 400px) {
  .div1,
  .div2 {
    width: 100%;
  }
}

//1

//2

The code is right but the div comes before div2 i want div2 to come before div1 .
can anyone please suggest me something .
this is just a test html i have more divs in page.

A: You can do that with plain CSS3 Flexbox model.
try out the following code:-
Apply the following style to parent element

parent-element {
  display: flex; /* or inline-flex */
}

And in media queries target the child element you want to move, in your case it would be:-

@media (max-width:400px) {
    div2 {
       order: 1;
    }
    div1 {
       order:2;
    }
}

This code would work fine.

A: You can do with CSS3 flexbox layout.

*

*Wrap a parent container over the two elements. Set flex display and direction to be column(for vertical placement)

*Reorder your first div to be second element using order: 2

@media (max-width: 800px) { /* Change this to 400px, 800px for demo purpose */
  .wrapper {
    display: flex;
    flex-direction: column; /* For vertical placement of items */
  }
  .div1 {
    order: 2;
  }
}

    1

    2

A: Try this with jquery:

if ($(window).width() < 400) {
   $('.div2').insertBefore('.div1');
}


text:
Q: How do I formulate this proof that these spaces are not deform retracts? Given $B = \{(x,y,z) : x^2 + y^2 = 1, z^2 \leq 1\}$, $A = B \cup \{(x,y,z) : x^2 + y^2 \leq 1, z^2 = 1\}$, prove that $B$ isn't a retract of $A$.
Intuitively, I notice straight away that the fundamental group of B is isomorphic to $\mathbb{Z}$ and the fundamental group of $A$ is trivial.
If we were to assume that there exists a retract from $A$ to $B$, $f$, then $f\circ \gamma = \gamma$ for a loop on $B$. Then I want to get a contradiction using the fundamental groups.
My two biggest problems are that I don't know how to formally prove my intuitions about the fundamental groups of $A$,$B$ and that I don't know how to use the induced homomorphism to reach a contradiction.
Any advice is welcome.

A: Since the unit circle is a retract of the cylinder $B$, they are homotopy equivalent, and so have isomorphic fundamental groups. Since the unit disc is a retract of the full-cylinder $A$, they are also homotopy equivalent, and so have isomorphic fundamental groups. Since the unit-disc is contractible, $A$ has a trivial fundamental group whereas $B$ does not, as you already have guessed. Now, if $B$ is a retract of $A$, $i:B\to A$ the inclusion map, and $r:A\to B$ the retract mapping such that $ri$ is the identity on $B$, then $i$ induces a homomorphism $F(i):\pi_1(B)\to \pi_1(A)$, and $r$ induces a homomorphism $F(r):\pi_1(A)\to\pi_1(B)$, and you must have that $F(r)F(i)$ equals the identity of $\pi_1(B)$. But that is not possible if $\pi_1(A)$ is trivial and $\pi_1(B)$ is not.


text:
Q: How does one get the text from html while ignoring formatting tags using BeautifulSoup? The following code is used to grab continuous segments of text from within html.
    for text in soup.find_all_next(text=True):
        if isinstance(text, Comment):
            # We found a comment, ignore
            continue
        if not text.strip():
            # We found a blank text, ignore
            continue
        # Whatever is left must be good
        print(text)

Text items are broken up by structure tags like
 or
 but also formatting tags like  and . This causes me some inconvenience in further parsing of the text and I would like to be able to grab continuous text items while ignoring any formatting tags interior to the text.
For example, soup.find_all_next(text=True) would take the html code
This is important text
 and return a single string, This is important text instead of three strings, This is, important, and text.
I'm not sure if that's clear... Let me know if it's not.
EDIT: The reason I'm walking through the html text item by text item is that I'm only beginning the walk after I see a specific "begin" comment tag and I'm stopping when I reach a specific "end" comment tag. Are there any solutions that work within this context of needing to walk item by item? The full code I'm using is below.
soup = BeautifulSoup(page)
for instanceBegin in soup.find_all(text=isBeginText):
    # We found a start comment, look at all text and comments:
    for text in instanceBegin.find_all_next(text=True):
        # We found a text or comment, examine it closely
        if isEndText(text):
            # We found the end comment, everybody out of the pool
            break
        if isinstance(text, Comment):
            # We found a comment, ignore
            continue
        if not text.strip():
            # We found a blank text, ignore
            continue
        # Whatever is left must be good
        print(text)

Where the two functions isBeginText(text) and isEndText(text) return true if the string passed to them matches my starting or ending comment tags.

A: If you grab the parent element containing your children elements and do get_text(), BeautifulSoup will strip out all html tags for you and only return a continuous string of text.
You can find an example here
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
print(soup.get_text())

A: How about using find_all_next twice, once for each of the beginning and ending tag and taking the difference of the two generated lists?
As an example, I'll use a modified version of the html_doc from the documentation of BeautifulSoup:
import bs4

html_doc = """
<title>The Dormouse's story</title>

The Dormouse's story

Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.

...

"""

soup = bs4.BeautifulSoup(html_doc, 'html.parser')
comments = soup.findAll(text=lambda text:isinstance(text, bs4.Comment))

# Step 1: find the beginning and ending markers
node_start = [ cmt for cmt in comments if cmt.string == " START" ][0]
node_end = [ cmt for cmt in comments if cmt.string == " END " ][0]

# Step 2, subtract the 2nd list of strings from the first
all_text = node_start.find_all_next(text=True)
all_after_text = node_end.find_all_next(text=True)

subset = all_text[:-(len(all_after_text) + 1)]
print(subset)

# ['Lacie', ' and\n', 'Tillie', ';\nand they lived at the bottom of a well.']


text:
Q: AWS - Connecting an ec2 instance with a private ip and an ec2 instance with a public ip in the same public subnet? I would appreciate any help on the following scenario in AWS:
Instance 1 : I have a public subnet which has an internet facing web server. So basically an ec2 instance with a public ipv4 address and port 443 open to all.
Instance 2 : I want to spin up an ec2 instance with a private ipv4 address in the same subnet and be able to communicate with the ec2 instance of the web sever.
Question:
Is this communication possible?
What I have tried so far:
I noticed that Instance 2 with a private ipv4 cannot communicate with Instance 1. But it can if it is has a public ipv4 address.
As far as I know this is happening via the internet.
My original design:
Instance 2 was spun up in its own private subnet and had its own security group to communicate with Instance 1 in its public subnet. Which is a better design in this scenario? Having them in the same public subnet or separate them out in public and private subnets?
Background:
Instance 1 hosts a web server and Instance 2 is a worker. Workers are added on demand by the server.

A: Instance 2 should be able to communicate with instance 1 in the same subnet without needing to have a public IP. Instance 1, even though a public EC2, should also have a private IP.
You should be able to communicate from instance 2 using that IP and it will not use the internet to communicate rather the private VPC network. Just make sure you open the port you are using to communicate in the security group of instance 2.

A: All Amazon EC2 instances are assigned a private IP address and can communicate with other instances in the same VPC.
If you want the two instances to communicate, you will need to configure the security groups to allow communication. I would recommend:

*

*A security group on the web server (Web-SG) that permits Inbound access on port 80 from the anywhere (0.0.0.0/0) and allows all Outbound access

*A security group on the private instance (Private-SG) that allows all Outbound access

*The private instance should communicate with the web server via its private IP address
Please note that if the private instance does not have a public IP address then you will not be able to connect to that instance (SSH/RDP). You could use AWS Systems Manager Session Manager to login, but that would also require either a public IP address or the use of a NAT Gateway (with the private instance launched in a private subnet).
Correct use of Security Groups can be just as secure as using a private subnets. You do not need to use private subnets to maintain security.


text:
Q: Display content based on roles When an is_admin user looks at the profile of another user I want to be able to control the type of information that is displayed based on the users profile roles. My code below displays nothing, what am I doing wrong?
Path: adminView.js
Template.adminView.helpers({
    profile: ()=> {
        var id = FlowRouter.getParam('id');

        return Meteor.users.findOne({_id: id});
    },
    userRole: function () {
        var roles = this.roles;

        if (roles === "is_student") {
            return true;
        }
    }
});

Path: adminView.html
{{#with profile}}
    {{#if userRole}}
        display user
    {{/if}}
{{/with}}

A: Since roles is an array you have to check for existence of the value in the array, not equality:
userRole: function () {
    var roles = this.roles;
    return (roles.indexOf("is_student") > -1 );
}


text:
Q: Can we append angular material form fields within a div? I have a div tag and I want to append the angular material form fields inside that div. The problem is it's not rendering that tags. Can we do this using any method?
enter image description here

A: The angular way is has an array of object, e,g.
data=[{placeholder:"Enter Name",label:"Name"},
      {placeholder:"Enter surname",label:"Surname"}]

and make some like
<mat-card *ngFor="let item of data">
   <div class="row">
     {{item.label}}<input mat-input [placeholder]="item.placeholder">
   </div>
</mat-card>

A: When you are using angular, never manipulate the DOM manually (via native DOM APIs or jQuery).
When you are using a component or a directive in an angular template (ie. the html of your component), that is not real html, that is transformed to javascript. So when the application is running, where you wrote <mat-car> in you template and you also see <mat-card> in the DOM, that was actually put there by the code generated by angular, but a lot other things also happened (ie. the mat-card component was initialised).
When you just put the components selector manually into the DOM, nothing will happen, because the component is not initialised. To make it work, you have to use the material components from another components' template. Further reading: https://angular.io/guide/architecture-components
Suggestion: don't even import jQuery into the project at all, that way you won't even be tempted to do this.


text:
Q: usage of paintComponent and JPanel in java import java.awt.Color;
import java.awt.Graphics;
//import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class GuiDemo1 extends JPanel{

    public static void main(String[] args){
            JPanel panel=new JPanel();
            JFrame frame=new JFrame();
            frame.getContentPane().add(panel);
            frame.setVisible(true);
            frame.setSize(500, 400);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void paintComponent(Graphics g)
        {

            g.setColor(Color.red);
            g.fillRect(20, 50, 100, 100);
        }

}

I am newbie to JAVA.I have written this sample program.However this is not working.Can some one point out the mistakes I have done.
And generally what is the use of calling super.paintComponent(g)?

A: Your custom painting was added to the GuiDemo1 class not the JPanel class:
//JPanel panel=new JPanel();
JPanel panel=new GuiDemo1();

and generally what is the use of calling super.paintComponent(g)?>

You want that at the start of the paintComponent(...) method because it will do the default painting for the component, which in the case of a JPanel is basically just to paint the background. Try adding:
panel.setBackground( Color.BLUE );

and see what happens with/without the super.paintComponent(g).


text:
Q: What does public protected mean? I am trying to create a instance of class but I keep on getting the following error message.

candidate function(s) not accessible

After going through the definition of the class which I was trying to instantiate, I realised that the constructor is declared as
public protected:  Class name (paramters);

What does "public protected" together at the same time mean?

A: Quoting the documentation:

Member is public inside the assembly but protected outside the assembly.


text:
Q: get 404 error by batch file upload via google-api-javascript-client library I'm trying to upload whole folder to google drive.
I could successfully upload one file by one request.
But I met rateLimitExceed error while upload whole files.
So, I tried to use batch request.
Creating folders with batch request are successfully done.
but when I trying to upload file by batch request, it returns 404 error. ( Not Found )
Is this google drive's bug?
If so, should I do time delay for upload many files?
        var boundary = '--314159265358979323846';
        var delimiter = "\r\n--" + boundary + "\r\n";
        var close_delim = "\r\n--" + boundary + "--";

        var contentType = 'text/plain';
        var metadata = {
            'title': 'test1.txt',
            'mimeType': contentType
        };

        var base64Data = btoa('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
        var multipartRequestBody =
           delimiter +
           'Content-Type: application/json\r\n\r\n' +
           JSON.stringify(metadata) +
           delimiter +
           'Content-Type: ' + contentType + '\r\n' +
           'Content-Transfer-Encoding: base64\r\n' +
           '\r\n' +
           base64Data +
           close_delim;

        var request = gapi.client.request({
           'path': '/upload/drive/v2/files',
           'method': 'POST',
           'params': {'uploadType': 'multipart'},
           'headers': {
             'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
           },
           'body': multipartRequestBody});

        var httpBatch = gapi.client.newHttpBatch();
        httpBatch.add(request, {
            callback: function(resp, rawResp){
                console.log(rawResp);
            }
        });
        httpBatch.execute(function(resp, rawResp){
            console.log(rawResp)
        });

error is here:
{"id":"1171148984","result":false}

{"gapiRequest":{"data":{"body":"--batch_YZmy6yr9vIk=_ABqi-xumfFQ=\r\nContent-Type: application/http\r\nContent-ID: <response-1171148984>\r\n\r\nHTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\nDate: Mon, 21 Oct 2013 07:53:20 GMT\r\nExpires: Mon, 21 Oct 2013 07:53:20 GMT\r\nCache-Control: private, max-age=0\r\nContent-Length: 9\r\n\r\nNot Found\r\n--batch_YZmy6yr9vIk=_ABqi-xumfFQ=--\r\n","headers":{"pragma":"no-cache","date":"Mon, 21 Oct 2013 07:53:20 GMT","server":"GSE","content-type":"multipart/mixed; boundary=batch_YZmy6yr9vIk=_ABqi-xumfFQ=","cache-control":"no-cache, no-store, max-age=0, must-revalidate","content-length":"349","expires":"Fri, 01 Jan 1990 00:00:00 GMT"},"status":200,"statusText":"OK"}}}

A: Uploading cannot be batched, please run the upload requests individually.


text:
Q: SQLite Studio - Update with Join I have read that update joins in SQLite are not supported, is there a way to convert a SQL update to SQLite?
Update Items
    Set Monitored = '1'

from Items
left join ItemsLoc on ItemsLoc.ItemId = Item.Id

where ItemsLoc.Loc is null

I am looking to update a column from Items table where the table/column ItemsLoc.Loc has a null value

A: Looks like I figured it out.
Update Items
Set Monitored ='1'
Where Items.Id in (Select Items.Id from Items Left Join ItemsLoc on ItemsLoc.ItemID = Items.Id where ItemsLoc.Loc is null)

A: If ItemsLoc.Loc is not nullable then
UPDATE Items
SET Monitored = '1'
WHERE NOT EXISTS ( SELECT NULL
                   FROM ItemsLoc
                   WHERE ItemsLoc.ItemId = Item.Id )


text:
Q: Are the eigenvectors and eigenvalues of a tensor covariant? A lot of online searching hasn't turned up a direct answer to this question.  Evidently the eigenvalues and eigenvectors of a tensor are unique (up to a scale factor), so I imagine they would transform the same way the tensor does.  However, I haven't found a clear statement to that effect.  I'm hoping someone can provide a proof, or provide a link to a source of a proof, one way or the other.

A: Well, I guess it is not clear, what do you mean by eigenvalues of a tensor. One can assign an eigenvalue to a matrix or to an operator.
If your tensor is once covariant and once contravariant, then it acts on vectors as a matrix or an operator and transforms simply as if you changed the basis for the operator. So, the eigenvalues are preserved (i.e. transform as scalars) and the eigenvectors transform as vectors.


text:
Q: Transform a common variable within a series of datasets without placing those datasets in a list in R This seems like something I should know how to do. But say I have a series of datasets
df1 <- data.frame(x = letters[1:6], y = rnorm(6))
df2 <- data.frame(x = letters[1:6], y = rnorm(6))
df3 <- data.frame(x = letters[1:6], y = rnorm(6))

And what if I want to change all of x variables in these datasets to factors instead of character vectors. I can put the datasets into a list
dfList <- list(df1, df2, df3)

And then loop over that list performing the necessary transformation
for (i in 1:length(dfList)) {
  dfList[[i]][,"x"] <- factor(dfList[[i]][,"x"])
}

str(dfList[[2]])

# 'data.frame': 6 obs. of  1 variable:
#   $ x: Factor w/ 6 levels "a","b","c","d",..: 1 2 3 4 5 6

But now the only way I can access the transformed version of the datasets is thorugh the list. How do I transform the datasets without having to place them inside the list?
I tried this
for (i in c(df1, df2, df3)) {
  i[,"x"] <- factor(i[,"x"])
}

But got an error.
# Error in i[, "x"] : incorrect number of dimensions

A: It is usually advised to keep the data in a list and work with it. In case, if you want to transfer the changed values to individual dataframes you can use list2env function.
dfList <- dplyr::lst(df1, df2, df3)
dfList <- lapply(dfList, function(df) transform(df, x = factor(x)))
list2env(dfList, .GlobalEnv)

str(df1)
#'data.frame':  6 obs. of  2 variables:
# $ x: Factor w/ 6 levels "a","b","c","d",..: 1 2 3 4 5 6
# $ y: num  -0.867 0.198 -1.628 -0.481 1.228 ...

The benefit of using dplyr::lst over base::list is that it gives us a named list which is important to have for list2env to work.


text:
Q: Is a Python closure a good replacement for `__all__`? Is it a good idea to use a closure instead of __all__ to limit the names exposed by a Python module? This would prevent programmers from accidentally using the wrong name for a module (import urllib; urllib.os.getlogin()) as well as avoiding "from x import *" namespace pollution as __all__.
def _init_module():
   global foo
   import bar
   def foo():
       return bar.baz.operation()
   class Quux(bar.baz.Splort): pass
_init_module(); del _init_module

vs. the same module using __all__:
__all__ = ['foo']
import bar
def foo():
    return bar.baz.operation()
class Quux(bar.baz.Splort): pass

Functions could just adopt this style to avoid polluting the module namespace:
def foo():
    import bar
    bar.baz.operation()

This might be helpful for a large package that wants to help users distinguish its API from the package's use of its and other modules' API during interactive introspection. On the other hand, maybe IPython should simply distinguish names in __all__ during tab completion, and more users should use an IDE that allows them to jump between files to see the definition of each name.

A: I am a fan of writing code that is absolutely as brain-dead simple as it can be.
__all__ is a feature of Python, added explicitly to solve the problem of limiting what names are made visible by a module.  When you use it, people immediately understand what you are doing with it.
Your closure trick is very nonstandard, and if I encountered it, I would not immediately understand it.  You would need to put in a long comment to explain it, and then you would need to put in another long comment to explain why you did it that way instead of using __all__.
EDIT: Now that I understand the problem a little better, here is an alternate answer.
In Python it is considered good practice to prefix private names with an underscore in a module.  If you do from the_module_name import * you will get all the names that do not start with an underscore.  So, rather than the closure trick, I would prefer to see correct use of the initial-underscore idiom.
Note that if you use the initial underscore names, you don't even need to use __all__.

A: The problem with from x import * is that it can hide NameErrors which makes trivial bugs hard to track down. "namespace pollution" means adding stuff to the namespace that you have no idea where it came from.
Which is kind of what your closure does too. Plus it might confuse IDEs, outlines, pylint and the like.
Using the "wrong" name for a module is not a real problem either. Module objects are the same from wherever you import them. If the "wrong" name disappears (after a update) it should be clear why and motivate the programmer to do it properly next time. But it doesn't cause bugs.

A: Okay, I'm beginning to understand this issue a bit more.  The closure really does allow for hiding private stuff.  Here's a simple example.
Without the closure:
# module named "foo.py"
def _bar():
    return 5

def foo():
    return _bar() - 2

With the closure:
# module named "fooclosure.py"
def _init_module():
    global foo
    def _bar():
        return 5

    def foo():
        return _bar() - 2

_init_module(); del _init_module

Sample of usage:
>>> import foo
>>> dir(foo)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', '_bar', 'foo']
>>>
>>> import fooclosure
>>> dir(fooclosure)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'foo']
>>>

This is actually disturbingly subtle.  In the first case, function foo() simply has a reference to the name _bar(), and if you were to remove _bar() from the name space, foo() would stop working.  foo() looks up _bar() each and every time it runs.
In contrast, the closure version of foo() works without _bar() existing in the name space.  I'm not even certain how it works... is it holding a reference to the function object created for _bar(), or is it holding a reference to a name space that still exists, such that it can look up the name _bar() and find it?


text:
Q: Clip content with jQuery to just get the number inside span, use the code below:

test inside 123458

alert($('h3 span').text().match(/\d/))
//123458

And to just get the content h3, without taking the span of content, how?

A: jQuery solution
alert( $('h3').clone().find('span').remove().end().text() );

pure JS solution
alert( document.getElementsByTagName('h3')[0].childNodes[0].textContent );

examples : http://jsfiddle.net/2mTLg/1

A: If you want to parse just the number then try this:

test inside 123458

Hope this helps. Here is a jsFiddle to play with: http://jsfiddle.net/pkMB2/1/
Bob


text:
Q: the accelerometer which detect the movement of the device that want to change the ringer mode of the phone to Ringer_Mode_silent *i have an application  trying to use the accelerometer which detect the movement of the device that want  to change the ringer mode of the phone to Ringer_Mode_silent * i realized the service which detected incoming call but i can't inderstand how to change the mode of phone in background when i move the device,please can i help me to realized this application.
public class MainActivity extends Activity  implements SensorEventListener{
 private SensorManager mSensorManager;
  private Sensor mAccelerometre;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
    mAccelerometre =   mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)

Button b1=(Button)findViewById(R.id.start);
Button b2=(Button)findViewById(R.id.stop);
b1.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        //Intent intent=new Intent(Main.this,ServiceReceiver.class);
          Intent serv = new Intent(MainActivity.this, ServiceBroadcast.class);
  startService(serv);
    }

});
  b2.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        //Intent intent=new Intent(Main.this,ServiceReceiver.class);
          Intent serv = new Intent(MainActivity.this, ServiceBroadcast.class);
          stopService(serv);

}

 public void onSensorChanged()(SensorEvent event) {
    float azimuth,pitch,roll;
    if(mSensorManager==SensorManager.Sensor_Accelerometer)
     {
    azimuth = event.values[0];
    pitch = event.values[1];
    roll = event.values[2];
    ((TextView)findViewById(R.id.azimuth)).setText("Axe x "+azimuth);
    ((TextView)findViewById(R.id.pitch)).setText("Axe y "+pitch);
    ((TextView)findViewById(R.id.roll)).setText("Axe z "+roll);
}
  }

A: Simple movement detection is easy with accelerometer ( pattern detecting is difficult )just take sqrt(x^2+y^2+z^2) -9.81) which give you movement,where x,y,z are accelerometer readings.Compare with some threshold and change your profile mode when it crosses.
Note:
as you mentioned in your code accelerometer dont give azimuthla,roll,pitch.
values[0]: Acceleration minus Gx on the x-axis
values[1]: Acceleration minus Gy on the y-axis
values[2]: Acceleration minus Gz on the z-axis


text:
Q: Trouble closing if statement and while loop in PHP I'm trying to display some html inside a php "if statement" and during a "While" Loop.
I keep getting unexpected end of file error and I know there are two braces missing but I can't see where to close the while loop properly.
I'm still new to coding so please be gentle... :-)
tried php syntax checker and other similar posts here
<?php include 'includes/header.php';?>

<?php include 'includes/navbar.php';?>
<?php
if (isset($_GET['post'])) {
    $post = $_GET['post'];
    if (!is_numeric($post)) {
      header("location:index.php");

    }
}
else {
    header('location: index.php');
}
$query = "SELECT * FROM posts WHERE id=$post";
$run_query = mysqli_query($conn, $query) or die(mysqli_error($conn)) ;
if (mysqli_num_rows($run_query) > 0 ) {
while ($row = mysqli_fetch_array($run_query)) {
    $post_title = $row['title'];
    $post_id = $row['id'];
    $post_author = $row['author'];
    $post_date = $row['postdate'];
    $post_image = $row['image'];
    $post_content = $row['content'];
    $post_tags = $row['tag'];
    $post_status = $row['status'];
  $img_ext = explode(".", $post_image);
    ?>

<?php echo $post_title; ?>

by <?php echo $post_author; ?>

Posted on <?php echo $post_date; ?>

            <?php if ($img_ext=="mp4"): ?>
                <video controls width="400" height="300">
                <source src="allpostpics/<?php echo $post_image; ?>" type="video/mp4">
                Video tag is not supported in this browser.
                </video>
            <?php else : ?>
                <img class="img-responsive img-rounded" src="allpostpics/<?php echo $post_image; ?>" alt="900 * 300">

<?php echo $post_content; ?>

            <?php include 'includes/sidebar.php'; ?>

       <?php include 'includes/footer.php';?>

A: PHP is syntatically more similar to C than to Python or VisualBasic. Indentation means nothing here. Code blocks need to be explicitly open and closed.
There are 2 types to quote the if-else blocks but you did neither of those.
You can either:
use brackets if { ... } else { ... }
Example:
            <?php if ($img_ext=="mp4") { ?>
                <video controls width="400" height="300">
                <source src="allpostpics/<?php echo $post_image; ?>" type="video/mp4">
                Video tag is not supported in this browser.
                </video>
            <?php } else { ?>
                <img class="img-responsive img-rounded" src="allpostpics/<?php echo $post_image; ?>" alt="900 * 300">

<?php echo $post_content; ?>

            <?php } ?>

use colon and keyworkds if, endif
Example,
            <?php if ($img_ext=="mp4"): ?>
                <video controls width="400" height="300">
                <source src="allpostpics/<?php echo $post_image; ?>" type="video/mp4">
                Video tag is not supported in this browser.
                </video>
            <?php else: ?>
                <img class="img-responsive img-rounded" src="allpostpics/<?php echo $post_image; ?>" alt="900 * 300">

<?php echo $post_content; ?>

            <?php endif ?>

Just chose which one to go for.
Similarly, you have to close your while-loop with either bracket } or endwhile, depends of your syntax of choice.

A: you opened the if statement and forgot to close it also while is not closed closed it after the container gets closed

A: Try below:
<?php include 'includes/header.php'; ?>

<?php include 'includes/navbar.php'; ?>
<?php
if (isset($_GET['post'])) {
  $post = $_GET['post'];
  if (!is_numeric($post)) {
    header("location:index.php");

  }
} else {
  header('location: index.php');
}
$query = "SELECT * FROM posts WHERE id=$post";
$run_query = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (mysqli_num_rows($run_query) > 0) {
while ($row = mysqli_fetch_array($run_query)) {
$post_title = $row['title'];
$post_id = $row['id'];
$post_author = $row['author'];
$post_date = $row['postdate'];
$post_image = $row['image'];
$post_content = $row['content'];
$post_tags = $row['tag'];
$post_status = $row['status'];
$img_ext = explode(".", $post_image);
?>

<?php echo $post_title; ?>

by <?php echo $post_author; ?>

Posted on <?php echo $post_date; ?>

          <?php if ($img_ext == "mp4"): ?>
              <video controls width="400" height="300">
                  <source src="allpostpics/<?php echo $post_image; ?>" type="video/mp4">
                  Video tag is not supported in this browser.
              </video>
          <?php else : ?>
            <img class="img-responsive img-rounded" src="allpostpics/<?php echo $post_image; ?>"
                 alt="900 * 300">
          <?php endif; ?>

<?php echo $post_content; ?>

          <?php include 'includes/sidebar.php'; ?>

  <?php include 'includes/footer.php'; ?>

<?php
} // End while
} // End if

Note: your code was missing <?php endif; ?> and two braces at the end.


text:
Q: More concise option to `separate` a column in R (maybe through some RegEx)? I have a dataframe where I want to separate a column that contains month and year:
library(tidyverse)
df <- data.frame(
  month_year = c("Januar / Janvier 1990", "Februar / Février 1990","März / Mars 1990")
)

# df
#               month_year
# 1  Januar / Janvier 1990
# 2 Februar / Février 1990
# 3       März / Mars 1990

The following works, but seems quite a bit clunky:
df %>%
  separate(month_year, c("month","nothing","nothing2", "year"), sep = " ") %>%
  select(-starts_with("nothing"))

#     month year
# 1  Januar 1990
# 2 Februar 1990
# 3    März 1990

Is there a more concise option to achieve the same result?

A: base R
strcapture("^(.*)\\s+/.*\\s+([^\\s]+)$", df$month_year, proto = c(month="", year=1L))
#     month year
# 1  Januar 1990
# 2 Februar 1990
# 3    März 1990

Perhaps a little clunky:
setNames(do.call(rbind.data.frame,
    lapply(strsplit(df$month_year, "\\s+"), function(z) z[c(1, length(z))])),
  c("month", "year"))

dplyr
A ever-so-slight reduction of your code, with a different regex:
library(dplyr)
df %>%
  separate(month_year, c("month", "ign", "year"), "[ /]+") %>%
  select(-ign)

or
df %>%
  mutate(month_year = gsub("/.* ", "", month_year)) %>%
  separate(month_year, c("month", "year"), " ")

A: We could use word from stringr package:
library(dplyr)
library(stringr)

df %>%
  mutate(month = word(month_year, 1),
         year = word(month_year, 4), .keep="unused")

    month year
1  Januar 1990
2 Februar 1990
3    März 1990

A: Try the following base R code with read.table + gsub
read.table(
  text = c(names(df), gsub("\\s+.*\\s+", "_", df$month_year)),
  sep = "_",
  header = TRUE
)

which gives
    month year
1  Januar 1990
2 Februar 1990
3    MΣrz 1990

A: Tidyverse + stringr
library(stringr)
df %>% mutate(year = as.numeric(str_extract(.$month_year, '\\d+'))) %>%
        mutate(month = str_extract(.$month_year, '[^ /]+') )
              month_year year   month
1  Januar / Janvier 1990 1990  Januar
2 Februar / Février 1990 1990 Februar
3       März / Mars 1990 1990    März

'\\d+' captures all digits; [^ /] captures substring before the first occurrence of  /.

A: 1) separate Use NA to omit the unwanted field like this:
library(tidyr)

df %>% separate(month_year, c("month", NA, "year"))
##     month year
## 1  Januar 1990
## 2 Februar 1990
## 3    März 1990

@Otto pointed out that this has problems in UTF8.  If that is your situation add the sep= value shown.  separate uses a default of "[^[:alnum:]]+" which does not handle UTF8 but we can specify either of these instead:

*

*"[^\\p{L}\\d]+" .  This replaces "[:alnum:]" with "\\p{L}" which is any letter in any language and "\\d" which is any digit, or

*"(*UCP)[^[:alnum:]]+" which uses a unicode specifier as a prefix

This shows an example.  First we create an input df2 which exhibits the problem and then we use one of the above two sep values with it.
df <- data.frame(
  month_year = c("Januar / Janvier 1990", "Februar / Février 1990","März / Mars 1990"))
df2 <- df %>% mutate(month_year = iconv(month_year, to = "UTF8"))

df2 %>% separate(month_year, c("month", NA, "year"), sep = "[^\\p{L}\\d]+")
##     month year
## 1  Januar 1990
## 2 Februar 1990
## 3    März 1990

2) read.table and here is a base solution:
read.table(text = df[[1]], col.names = c("month", NA, NA, "year"))[-(2:3)]
##     month year
## 1  Januar 1990
## 2 Februar 1990
## 3    März 1990

3) read.pattern This picks out the desired fields using read.pattern. (\\w+) captures the first word and (\\d+) captures the year.
library(gsubfn)

pat <- "(\\w+).* (\\d+)"
read.pattern(text = df[[1]], pattern = pat, col.names = c("month", "year"))
##     month year
## 1  Januar 1990
## 2 Februar 1990
## 3    März 1990