text:
Q: iOS 6 streaming player com.apple.coremedia.networkbuffering bug I'm having trouble on make my app(music and video stream player) running on iOS 6 simulator.
When I start a music ou video it crashes showing an error on this thread: com.apple.coremedia.networkbuffering
and this on log info:
2012-09-13 17:45:09.260 app[32563:c07] [MPAVController] Autoplay: Disabling autoplay for pause
2012-09-13 17:45:09.260 app[32563:c07] [MPAVController] Autoplay: Disabling autoplay
2012-09-13 17:45:09.305 app[32563:c07] [MPAVController] Autoplay: Enabling autoplay
2012-09-13 17:45:09.307 app[32563:c07] handlePlaybackNowPlayingNotification
2012-09-13 17:45:09.308 app[32563:c07] [MPAVController] Autoplay: Likely to keep up or full buffer: 0
2012-09-13 17:45:09.308 app[32563:c07] [MPAVController] Autoplay: Skipping autoplay, not enough buffered to keep up.
2012-09-13 17:45:09.318 app[32563:c07] [MPAVController] Autoplay: Enabling autoplay
2012-09-13 17:45:09.320 app[32563:c07] [MPCloudAssetDownloadController] Prioritization requested for media item ID: 0

I'm using MPMoviePlayerController with http based stream, and it works fine on iOS 4 or iOS 5
Any ideas on how to fix it?

A: i have verified using xcode 4.5+SDK6.0 versus xcode 4.4.1+SDK5.1 combinations that there is an issue with ios 6 version of the MPMoviePlayerController. i have only worked with iPads though.
here are my observations:-
- i have never seen the video play on ios 6.0 with my code that uses MPMoviePlayerController.
- with xcode 4.4.1 and SDK 5.1, i have seen the code work on ios versions 5.1, 5.0 and 4.3.
- with xcode 4.5 and SDK 6.0, the player always fails in the simulator, but most installations on ios 5.1 device work. i kept reinstalling the app on ios 5.1 device and trying out the player. it only failed once.
here are my observations when the player failed:
- some times when the player failed, i saw the logs that you mentioned above. other times, i didnt even see the logs.
- i put a breakpoint in the function that got the MPMoviePlayerPlaybackDidFinishNotification notification. then i looked for the errorLog in the player and there was none. i looked for MPMoviePlayerPlaybackDidFinishReasonUserInfoKey and it was 0 (MPMovieFinishReasonPlaybackEnded). so MPMoviePlayerController had no clue anything had gone wrong!
conclusion: ios6 and/or SDK 6 have got a bug.

A: NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp4"]];
MPMoviePlayerViewController  *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

moviePlayer.view.frame = self.view.frame;
moviePlayer.moviePlayer.shouldAutoplay=YES;
moviePlayer.moviePlayer.controlStyle = MPMovieControlStyleNone;
[moviePlayer.moviePlayer setFullscreen:YES animated:YES];
[self.view addSubview:moviePlayer.view];
[moviePlayer.moviePlayer play];

Note : Before iOS 6, no need to call [moviePlayer.moviePlayer play]; once you add player view to a view it will start to play but in iOS 6, you need to call play function explicitly

A: I was having the exact same problem...
try to do this just after you instantiate your player:
[player prepareToPlay];

It should be called automatically when you call play but apparently on iOS 6 something goes wrong if you don't call it explicitly.
In my case it solved the problem.

A: What you are observing is not a crash but an exception. You most likely have an exception breakpoint enabled and that leads you to the assumption that the app crashes.
That exception actually is properly handled (cought) by the SDK and does not cause an app crash.
Please note that this is only happening on the simulator, not on the device.
The issue is closely related to this issue what-does-this-gdb-output-mean. The difference is that you won't get those error messages anymore but the exception's still are thrown (but also cought).

A: i am having the same issue with MPMoviePlayerController for ios6. So i changed my code to fllowing and now it is working fine..
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"sample" ofType:@"mp4"]];
MPMoviePlayerViewController  *moviePlayer = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

moviePlayer.view.frame = self.view.frame;
moviePlayer.moviePlayer.shouldAutoplay=YES;
moviePlayer.moviePlayer.controlStyle = MPMovieControlStyleNone;
[moviePlayer.moviePlayer setFullscreen:YES animated:YES];
[self.view addSubview:moviePlayer.view];
[moviePlayer.moviePlayer play];

A: I have not solved this problem yet, but it seems to be related in my particular case when MPMoviePlayerController is going to enter full screen, or when there is a potential lag for the controller.
I am not streaming content from the web, the content is on the device, so initially the content displays fine in the view.
My guess is that they have implemented a new feature into MPMoviePlayerController to prevent "dead time" during playback.  I have seen some apps that just hang when the movie data goes offline or you happen to walk out of range of your wifi"
My attempt to resolve this issue will be to look at the notification message passed to -
(void)moviePlayBackDidFinish: (NSNotification*)notification

this is done by querying the user info dictionary
NSDictionary *userInfo = [notification userInfo];

the value for MPMoviePlayerPlaybackDidFinishReasonUserInfoKey is 0 in the case of this type of failure.
It's a starting point. My thought is to re-instate the movie at this point on this unique failure.
I will keep you posted on the results.

A: first I had done something like below
[self.player.moviePlayer prepareToPlay];
[self.player.moviePlayer play];
self.player.moviePlayer.shouldAutoplay = YES;

and when i deleted the below line
self.player.moviePlayer.shouldAutoplay = YES;

problem was solved.

A: I'm having problem with the code below, the player goes on full screen, but right after that, it closes and doesn't play the video at all.
NSURL *url = [NSURL URLWithString:@"http://streaming.disponivel.uol.com.br/video360p2/288148-1192657.mp4"];
    _player = [[MPMoviePlayerViewController alloc] initWithContentURL:url];

    [_player.moviePlayer setMovieSourceType:MPMovieSourceTypeFile];

    [_player.moviePlayer setControlStyle:MPMovieControlStyleDefault];

    [_player.moviePlayer setFullscreen:YES animated:YES];

    [self presentMoviePlayerViewControllerAnimated:_player];

    [_player.moviePlayer prepareToPlay];

    [_player.moviePlayer play];

A: I am also using the MPMoviePlayerViewController to show live video on my app and I'm getting the same list of errors as above. I've found that MPMoviePlayer does not support larger data to show video but if you use smaller video data it works fine, throwing no errors. In fact it is not a problem of prepare to play and play properties of movie player.
If you need to show larger data then use webview on your app.


text:
Q: Is there a way to detect if background image loaded properly or not in angular? I have an Angular 7 app in which I am displaying a div background image. But sometimes link is broken.
My image is bound in my HTML like this
<div [ngStyle]="{'background-image': 'url(' + row?.coverUrl + ')', 'background-size': 'cover', 'background-position' : 'center'}" class="img-area cursor-pointer" (click)="navigateToCOmpany(row)" *ngIf="row.coverUrl !== ''">
</div>

The problem is that sometimes row?.coverUrl is broken link. So how can I detect that link is broken so that I can bind a default image?

A: There are some workarounds which you can use:

*

*Use an invisible img tag (as suggested by user3723763) and in the
error handler update the row.coverUrl which will update your DIV's background image also.

*Multiple URLs can be passed in
the background-image, pass the fallback image as the 2nd URL and it
will start showing if the first one breaks. NOTE: this will
correctly work only if your images are not transparent, refer the
sample code from here: 2 URLs as background-image

A: Although there is no professional solution I still wanted to show the different ways if you like you can use it.
<div [ngStyle]="backgroundObj" class="img-area cursor-pointer"></div>
<img hidden [src]="brokenImageUrl" (error)="doSomethingOnError($event)" />

  brokenImageUrl = null // or try -> 'https://placebeard.it/640x360';
  brokeImage =
    'https://serpstat.com/img/blog/how-to-detect-broken-images-on-the-website/16451874451570033394image1-min.png';
  image = 'https://placebeard.it/640x360';
  backgroundObj = {
    width: '500px',
    height: '500px',
    'background-image': 'url(' + this.image + ')',
    'background-repeat': 'no-repeat',
  };

  doSomethingOnError(event: any) {
    if (event) {
      this.backgroundObj = {
        width: '500px',
        height: '500px',
        'background-image': 'url(' + this.brokeImage + ')',
        'background-repeat': 'no-repeat',
      };
    }
  }

stackblitz

A: I think this is the solution for your problem
 <div [ngStyle]="{'background-image': 'url(' + row.coverUrl? row.coverUrl :
  deafultUrl + ')', 'background-size': 'cover', 'background-position' :
  'center'}" class="img-area cursor-pointer"
  (click)="navigateToCOmpany(row)" *ngIf="row.coverUrl !== ''">
</div>

A: I wanted to have an image with a spinner while loading. For this, I used an Image to load the image, and once loaded, I made a data URL from it that I passed to the <img>. Given this method, I knew exactly when the image was loading, loaded or errored.
Just be wary when changing image to same URL, it might get confused.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to run Java web application using Nginx server only without tomcat server? Is it possible to run Java web application using Nginx server only without tomcat server ?

A: I guess it's not possible since Nginx is not a servlet container.

A servlet container is an application server that implements some version of the Java Servlet Specification.

And this is not the case of Nginx.

A: nginx has no understanding of what a .war file is as it is not a servlet container. So, answer to your question is No! it is not possible.
However, you can configure nginx to act as a reverse proxy in front of a Tomcat server.
Also, this   link  may help you in details about nginx

A: If you only use static files and restful services (access by javascript framework) you can try Nginx-Clojure
and its sub-project Nginx-Jersey.
If you use servlet/jsp based web application you can try Nginx-Clojure
and its sub-project Nginx-Tomcat8 which does not use tomcat as a server but only a servlet package and does use Nginx as the HTTP server.

A: Nowadays frameworks such as Spring come with embedded application servers. Spring use Tomcat by default as application server and we don't have to worry about it.
Now, to answer your question, when you say webapplication, it can mean three things,

*

*Just Frontend (to serve static files / html,js,css)

*Just Backend (May be Rest API's etc where your users can hit api's using Postman, curl etc.. or may be just a tier-2 backend server to serve tier-1 backend server)

*Frontend(static/dynamic content) + Backend

I Suppose you meant 3,
Now we are in System design,
Case 1: If you have your UI content as pure static (html, js, css)
a) Front end code directly written in html, js, css
b) Front end code written in React, Angular, they provide compilers/builds to convert the React/Angular understandable code to just pure static html, js, css.
Take the build and keep handy,
Approach 1:
Bundle the build together as jar (as part of your spring jar) and serve both backend and frontend using the embedded application server.
Approach 2
Run a proxy webserver (I meant webserver! here not application server) in front (nginx or apacheHTTP server may be) and route traffic between frontend and backend spring application server.
Note: All you need to let webservers (via conf files) know is the location of your html files (which internally have access to js/css code) to route traffic to frontend. But for backend, it already runs in Tomcat application server (servlet container).
Case 2: If you have your UI content are not pure static (html, js, css)
Approach 1:
If you are using JSP, thymeleaf, then bundle them together as jar and serve via application server only. Because JSP, thymeleaf prepares html,js,css dynamically (using your api request, java models etc..). You cannot serve frontend like a raw static content here directly using webservers.


text:
Q: как правильно сделать обработать событие на клик и изменение поля инпут? как одновременно проверять либо изменен .quantity_product либо .qnt-plus или .qnt-minus нужно считать data-id="15" и value="5"

      <input class="quantity_product" type="text" data-id="15" value="5">

      <input class="quantity_product" type="text" data-id="15" value="5">

A: Если я правильно понял, вы хотите сделать возможно увеличение\уменьшение значение инпута стрелками.
Если да, то вот вариант на jQuery:

$('.prod-li-qnt-wrap').on('click', '.change-arrow', function(){ // Вешаем делегирование события клика на кнопки
  let parent = $(this).closest('.qnt-wrap'), // Находим родителя
      input = parent.find('.quantity_product'), // Находим инпут
      val = Number(input.val()), // Получим значение инпута
      id = input.attr('data-id'); // Получим data-id инпута

  if($(this).hasClass('qnt-plus')) { // Если нажат qnt-plus
    val++;
  } else if($(this).hasClass('qnt-minus')) { // Если нажат qnt-minus
    val--;
  }
  input.val(val); // Возвращаем значение в инпут
  console.info(id, val);
  //
  return false; // Т.к. нажатая кнопка - ссылка, отменим действие ссылки
}).on('change', '.quantity_product', function(){ // Вешаем ещё такое же событие на изменение инпута
  let val = $(this).val(), // Получаем значение инпута
      id = $(this).attr('data-id'); // Получаем его data-id
  console.info(id, val);
});
.icon::before {
  display: inline-block;
  font-size: 20px;
  color: #000;
  text-decoration: none;
}

.icon.ion-arrow-up-b::before {
  content: '↑';
}

.icon.ion-arrow-down-b::before {
  content: '↓';
}

      <input class="quantity_product" type="text" data-id="15" value="5">

      <input class="quantity_product" type="text" data-id="15" value="5">

С ограничением, чтобы не уйти в минус

$('.prod-li-qnt-wrap').on('click', '.change-arrow', function(){ // Вешаем делегирование события клика на кнопки
  let parent = $(this).closest('.qnt-wrap'), // Находим родителя
      input = parent.find('.quantity_product'), // Находим инпут
      val = Number(input.val()), // Получим значение инпута
      id = input.attr('data-id'); // Получим data-id инпута

  if($(this).hasClass('qnt-plus')) { // Если нажат qnt-plus
    val++;
  } else if($(this).hasClass('qnt-minus')) { // Если нажат qnt-minus
    val--;
    if(val < 0) val = 0;
  }
  input.val(val); // Возвращаем значение в инпут
  console.info(id, val);
  //
  return false; // Т.к. нажатая кнопка - ссылка, отменим действие ссылки
}).on('change', '.quantity_product', function(){ // Вешаем ещё такое же событие на изменение инпута
  let val = Number($(this).val()), // Получаем значение инпута
      id = $(this).attr('data-id'); // Получаем его data-id
  val = val < 0 ? 0 : val;
  $(this).val(val);
  console.info(id, val);
});
.icon::before {
  display: inline-block;
  font-size: 20px;
  color: #000;
  text-decoration: none;
}

.icon.ion-arrow-up-b::before {
  content: '↑';
}

.icon.ion-arrow-down-b::before {
  content: '↓';
}

      <input class="quantity_product" type="text" data-id="15" value="5">

      <input class="quantity_product" type="text" data-id="15" value="5">

С ограничением в атрибутах, аналогично min и max в input[type="number"]

$('.prod-li-qnt-wrap').on('click', '.change-arrow', function(){ // Вешаем делегирование события клика на кнопки
  let parent = $(this).closest('.qnt-wrap'), // Находим родителя
      input = parent.find('.quantity_product'), // Находим инпут
      val = Number(input.val()), // Получим значение инпута
      id = input.attr('data-id'), // Получим data-id инпута
      min = Number(input.attr('data-min')),
      max = Number(input.attr('data-max'));
  if($(this).hasClass('qnt-plus')) { // Если нажат qnt-plus
    val++;
  } else if($(this).hasClass('qnt-minus')) { // Если нажат qnt-minus
    val--;
  }

  if(val >= max) val = max;
  if(val <= min) val = min;

  input.val(val); // Возвращаем значение в инпут
  console.info(id, val);
  //
  return false; // Т.к. нажатая кнопка - ссылка, отменим действие ссылки
}).on('change', '.quantity_product', function(){ // Вешаем ещё такое же событие на изменение инпута
  let val = Number($(this).val()), // Получаем значение инпута
      id = $(this).attr('data-id'), // Получаем его data-id
      min = Number($(this).attr('data-min')),
      max = Number($(this).attr('data-max'));

  if(val <= min) val = min;
  if(val >= max) val = max;

  $(this).val(val);
  console.info(id, val);
});
.icon::before {
  display: inline-block;
  font-size: 20px;
  color: #000;
  text-decoration: none;
}

.icon.ion-arrow-up-b::before {
  content: '↑';
}

.icon.ion-arrow-down-b::before {
  content: '↓';
}

      <input class="quantity_product" type="text" data-id="15" data-min="0" value="5" data-max="10">

      <input class="quantity_product" type="text" data-id="15" data-min="-5" value="5" data-max="5">

A: data-id = let di = $that.attr('data-id');
Ниже использовал евент для всех инпутов, даже для динамических, лучше\можно так:
$('.quantity_product').on('input', ({currentTarget})=>{
    console.log(currentTarget.className, currentTarget.value);
    const $that = $(currentTarget);
    console.log($that.attr('class'), $that.attr('data-id'), $that.val());
});

$(document).on('input', 'input', ({currentTarget})=>{
    console.log(currentTarget.className, currentTarget.value);
    const $that = $(currentTarget);
    console.log($that.attr('class'), $that.val());
});

        <input class="quantity_product i1" type="text" data-id="15" value="5">

        <input class="quantity_product i2" type="text" data-id="15" value="5">

A:

$(".quantity_product").on('input', function() {
if ($(this).val()) {
var obj = $(this);
change_product(obj);
}
});
$(".change-arrow").on('click', function() {
var obj = $(this);
obj = obj.siblings(".quantity_product");
if (obj.val()) {
change_product(obj);
}
});


text:
Q: if it's been designed correctly is AOP useful?
Possible Duplicate:
Are certain problems solved more elegantly with AOP?

I don't know much about aspect oriented programming (AOP) but I looked at a few examples and it seems to me more of a debugging tool or patching things. I looked over the examples and I can't think of anywhere I'd use them in -my- code.
Assuming the code has been design right and the language supports it (such as AspectJ) what are real world uses where using AOP is good design and can't be done as easily with traditional well designed classes/code/software?

A: AOP solves some problems, but is not useful in all cases.
Typically, AOP provides tools to manage separation of concerns. In many projects, you'll find yourself writing the same code repeatedly. A typical example is checking access:
if(!user.hasAccess(functionality)) throw new SecurityException();
// Functionality implementation.

This is not clean code, because the problem of checking access is spread across the whole code base. It is error prone, which is not what you want in general, but even worse here, because an error is a security flaw.
AOP is definitively useful here, because it will allow you to define security at one place and functionality at another.
You'll find other patterns, like connecting to a database, doing some operation, and disconnecting. You'll have to handle all special cases (SQL error, network error, etc . . .) and be sure you rollback cleanly if something happens and disconnect properly. AOP could also help you here, avoiding the need to have all the error handling boilerplate spread over multiple functionalities.
Another problem is synchronization. As the system gets more and more distributed (multicore, network, cloud, GPGPU, etc . . .) it is of increasing importance.
Definitively, AOP is useful in some cases.

A: A lot of frameworks and products use AOP "under the hood". For instance, it's heavily used in Spring for things like transaction handling and method caching. Hibernate leverages AOP-style dynamic proxying to enable persistent collections.

A: I bet you are using AOP in your code (or have in the past) and you didn't even know it.  MVC web frameworks often have filters that are used in a very AOP-like way, and even something like an HttpModule in ASP.NET I would call AOP (I'm not sure what the analog is in the Java world).
Debugging, logging, tracing, are certainly the "killer apps" of AOP, but any time where you have boilerplate or repetitive code that you can't otherwise refactor using normal OO techniques is a great place to consider AOP.
It's not a silver bullet, but it's a great tool to have in your SOLID toolbox.


text:
Q: What happens if you accidently flag a post incorrectly?
Possible Duplicate:
Flag removal: Is it possible to remove your flag or otherwise indicate it should be unflagged?

I was just  doing "my bit" on SO and was flagging a series of answers as spam... I got a little over-zealous and accidently flagged Facebook friend counter as spam, and it's not... Is there anyway to retract a flag? Or, do I just have to stick with looking like a plonker?

A: Tim Post comes to your house and beats you to death with a giant flag.
Naw; whatever moderator handles it ends up rolling their eyes and dismissing it. No one  even sees your name on spam flags - so your mistake gets chalked up to the big "SO users click things randomly" tally and folks get on with their lives.
See: Flag removal: Is it possible to remove your flag or otherwise indicate it should be unflagged?


text:
Q: Is there a "JOIN" query to show the first name and last name of the employees who do not work in the same locations with their manager I am stuck on a query to find employees who do not work at the same location as their manager based on the attached schema.
DB schema

A: You need to join four tables, as shown below:
select
  e.employee_id,
  ed.location_id as employee_location_id,
  m.employee_id as manager_id,
  md.location_id as manager_location_id
from employees e
join departments ed on e.department_id = ed.department_id
join employees m on e.manager_id = e.employee_id
join departments md on m.department_id = md.department_id
where ed.location_id <> md.location_id


text:
Q: Read XML with Elements and csv's into 2D array using XDocument in C#/XNA I have an XML File with Elements that look like the following:
<level>
        <name>Name of Level 1</name>
        <number>1</number>
        <authorTime>8.55</authorTime>
        <scoringTime>20</scoringTime>
        <map width="19" height="15"><!--Level1-->
            <row>0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0</row>
            <row>2,-1,-1,-1,-1,-1,-1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,2</row>
            <row>2,-1,-1,-1,0,1,0,-1,2,-1,0,-1,-1,-1,-1,-1,0,-1,2</row>
            <row>0,1,0,-1,2,-1,-1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,2</row>
            <row>2,-1,-1,-1,2,-1,0,1,0,1,0,-1,0,0,-1,0,0,-1,2</row>
            <row>2,-1,0,1,0,-1,-1,-1,2,-1,-1,-1,-1,2,-1,-1,2,-1,2</row>
            <row>2,-1,-1,3,2,-1,0,-1,2,-1,0,-1,-1,2,-1,-1,2,-1,2</row>
            <row>2,-1,0,1,0,0,0,-1,0,-1,0,1,1,0,-1,-1,2,-1,2</row>
            <row>0,1,0,-1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2,-1,2</row>
            <row>2,-1,2,-1,-1,0,1,0,1,0,-1,0,1,0,1,1,0,-1,2</row>
            <row>2,-1,0,0,-1,-1,-1,0,-1,2,-1,2,-1,0,-1,-1,2,-1,2</row>
            <row>2,-1,2,-1,-1,0,-1,-1,-1,2,-1,2,-1,-1,-1,-1,2,-1,2</row>
            <row>2,-1,0,0,-1,0,1,1,1,0,1,0,-1,0,1,1,0,-1,2</row>
            <row>2,5,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,2</row>
            <row>0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0</row>
        </map>
    </level>

And I want to use an XDocument (in C#/XNA) to read the "map" into a 2D rectangular array (y,x) - so in this example case it would be int[15,19].
All I can think of is creating a jagged array and converting to a rectangular one later - something like
int[][] test = ((from level in xDoc.Descendants("level")
                select (from map in level.Element("map")
                            select (from row in map.Elements("row")
                                    select (int.Parse(row.Value))).ToArray()).ToArray()));

But I know I need a string split on commas in here somewhere; and anyway I get a "select not found" error on level.Element("map").
My finished array should look like {{0,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,0},{2,-1,-1,-1,-1,-1,-1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,2},...
Can anyone help?
--EDIT--
I now have:
    var test = (from level in xDoc.Descendants("level")
                    select (from row in level.Elements("map").Elements("row")
                        select (from col in row.Value.Split(',')
                            select (int.Parse(col))).ToArray()).ToArray());

which is giving me the data I want, but the "test" output is showing up in the debug as being of type: {System.Linq.Enumerable.WhereSelectEnumerableIterator<System.Xml.Linq.XElement,int[][]>}
Getting closer, but still not quite right!

A: Just make it
select (from row in map.Elements("row").Value.Split(',')
        select (int.Parse(row) ...

And then it might just make sense to call it col instead of row.

All I can think of is creating a jagged array and converting to a rectangular one later

Why convert?  A jagged array seems fine.

Edit
I gave it a test :
        var test =
            from level in doc.Descendants("level")
            select (from map in level.Elements("map")
                select (from row in map.Elements("row")
                        select (from col in row.Value.Split(',')
                          select int.Parse(col)).ToArray()).ToArray() );

Which gives you an IEnumerabl<IEnumerable<int[][]>> (level and map lists).
So test.First().First() is your first array.


text:
Q: Internal page hidden dropdown menu from boxes (Wordpress) I am trying to fulfill an odd request that I have not done before. I can't link to the page in question because it is behind an authentication wall, but this is more of a general question about how to accomplish this.
Here is a screenshot of the part of the mockup that is relevant: http://imgur.com/a/l7TJ6
I've got these boxes with their images and titles, etc. lined up in 2 rows like they are in the mockup, but I'm not sure of the best way to go about making this collapsible, hidden menu for the items or the left and right navigations parts on the bottom.
Any help is greatly appreciated. Thank you all.

We assist    individual clients to find personalized solutions involving:

Finance
Visas

Marriage-Based Green Cards

Removal of Conditions

Naturalization & Citizenship

Adjustment of Status

Waivers

Consular Processing

Visas for Victims of Crimes

Special Immigrant Juveniles

Asylum

Investment
Visas

Deferred Action for Childhood Arrivals

Deferred Action for Parental Accountability

Removal & Deportation Defense

A: Create one-row slider with all of those and a div which is hidden. On click (one of the elements @slider) append data to the div with js.


text:
Q: WordPress multiple-submenu What's the best way to make multiply-page menu?
For example Category1 -> Article -> Full article text?
Not dropdown menu.
There's site example: http://fl.jetcode.lv/service.html
There are on page "Услуги" (Services), list with point's (Обслуживание windows, Подключение интернета, Сборка компьютеров, Чистка вирусов, ...)
When i click one of them (for example 'Обслуживание windows'('Maintenance windows')), i need to get page with points of that category like Установка Windows XP /Vista /7 /8 / W.S 2003,2008 (Installing Windows), Установка Linux (Installing Linux). And each Category have their own list of that text. So what's the best way to make that?
By steps:
1. I'm here: http://fl.jetcode.lv/index.html
 2. I click on 'Обслуживание windows', and go to that page http://fl.jetcode.lv/service.html
 3. Now i see a list with services on that category
 4. Click on 'Полное описание', under 'Установка Windows XP /Vista /7 /8 / W.S 2003,2008'
 5. And get to that page http://fl.jetcode.lv/service_inside.html
So how i can structure that's menu with WordPress ?
I've created a Posts with first categories (Category1), then i added it to Appearance->Menus, and get that list on page. Now i can manage their content in post, but it will be hard for end-user. So i trying to make list with second-category in post, and stucked. So can somebody please advice how it correctly/better to do ?
Thanks!

A: To put this simply,
You won't be needed to change anything to header but in category.php.
Instead of including the
 in the header put it on categories.php then to the usual get post contents and you are done.
The logic isn't in the menu but the flow of how you call each file/element.
This is the sample structure in category.php

<?php single_cat_title(); ?>

                <?php while(have_posts()): the_post(); ?>

<a href="<?php echo get_permalink() ?>"><?php the_title(); ?>

Posted on <?php the_time('F j, Y'); ?>

                    <?php
                        if ( has_post_thumbnail() ) {
                            the_post_thumbnail( add_image_size( 'post-thumbnail'), array( 'class' => "post-thumb" ) );
                        }
                        else {
                            echo '';
                        }
                    ?>

                        <?php the_excerpt();?>

                    <a class= "category-read" href="<?php echo get_permalink() ?>">Read

                 <?php endwhile; ?>

                    <?php next_posts_link('« Older Entries ') ?>
                     |
                    <?php previous_posts_link(' Newer Entries »') ?>


text:
Q: PhantomJS 'click' event works on link, but not button? I'm scraping dynamic content with PhantomJS. I want to load this website: https://www.instagram.com/explore/tags/fun/, and click the button at the bottom of the screen "load more" to load more pictures, and save the HAR content. This code works:
            var page require('webpage').create();

            page.open('http://www.milliondollarhomepage.com', function(status) {

            setTimeout(function(){
            page.sendEvent('click', 240, 210, button='left') }, 200);

            setTimeout(function(){
            page.render("screensho1.png");
                    phantom.exit();
                }, 5000);

            });

It clicks a --link-- on the screen. But when I use my URL of interest, https://www.instagram.com/explore/tags/fun/ the same code with the proper coordinates won't click the ---button---.
Any help would be much appreciated.

A: Positioning of elements is often relative, so I would recommend to avoid absolute click events; instead work with selectors and trigger a click event on the element:
var page = require('webpage').create();
var fs = require('fs');
var system = require('system');

var url = "https://www.instagram.com/explore/tags/fun/";

page.open(url, function(status) {
    console.log("Status: " + status);
    if(status === "success") {

    setTimeout(
        function(){
            page.evaluate(
                function(){document.querySelector("#react-root > section > main > article > div > div > a").click();}
            );
        }, 200);

    setTimeout(
        function(){
            path = 'hardcoded.png';
            page.render(path, {format: 'png', quality: '100'});
            phantom.exit();
        }, 1000);

    }else{
        phantom.exit();
    }
});


text:
Q: TCPDF como redirecionar a pagina caso o código seja inválido? estou fazendo um relatório para impressão com o TCPDF porém estou enfrentando algumas dificuldades no redirecionamento caso o código seja invalido.
vejam o seguinte código:
if(isset($_GET['CODIGO']) AND $_GET['CODIGO'] != ''){

        $html   = '';
        $item   = 1;
        $dados = filter_var($_GET['CODIGO'], FILTER_SANITIZE_NUMBER_INT);

        $sql    = "SELECT * FROM TESTE_TABELA WHERE CODIGO = $dados";
        $query  = sqlsrv_query($conexion,$sql);

        while($row = sqlsrv_fetch_array($query)){
            $cod = 0;
            $manufacturero = $row['NOME'];
            $imagen = $row['IMG'];

            if($row['CODIGO']){

                $pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
                $pdf->SetTitle('Imprimir Imagem'); //Titlo del pdf
                $pdf->setPrintHeader(false); //No se imprime cabecera
                $pdf->setPrintFooter(false); //No se imprime pie de pagina
                $pdf->SetMargins(20, 20, 20, false); //Se define margenes izquierdo, alto, derecho
                $pdf->Cell(200, 30, 'Relatório', 1, '', 'center', '', '', '', '');
                $pdf->SetAutoPageBreak(true, 20); //Se define un salto de pagina con un limite de pie de pagina
                $pdf->addPage();

                //$barcode = '';
                //$barcode = $pdf->serializeTCPDFtagParameters(array($barcode, 'C128', '', '', 72, 25, 0.5, array('position'=>'S', 'border'=>false, 'padding'=>2, 'fgcolor'=>array(0,0,0), 'bgcolor'=>array(255,255,255), 'text'=>true, 'font'=>'helvetica', 'fontsize'=>7, 'stretchtext'=>6), 'N'));

                $html .= '

Nome: '.$manufacturero.'

';

                $item = $item+1;

                $pdf->SetFont('Helvetica', '', 10);
                $pdf->writeHTML($html, true, 0, true, 0);

                $pdf->lastPage();
                $pdf->output('Reporte.pdf', 'I');

            }else if(!$row['CODIGO']){
                echo "";
            }
        }
    }else{
        echo "";
    }

O primeiro if esta funcionando de boa, se não existir o get, e se o código da url for igual a 0 ele redireciona. O grande problema é quando ele entra no while, ai ele entra no if faz a comparação mas caso o código não exista ele não redireciona.
Exemplo:
tenho um relatório com o código 7, caso eu digite na url 6 é um relatório que não exite, ele deveria entrar no primeiro if mas ser barrado no segundo, porém ele não faz nada, não redireciona, a pagina fica em branco, alguém tem alguma ideia do que seja? Desde já obrigado.

A: if(isset($_GET['CODIGO']) AND $_GET['CODIGO'] != ''){
        $dados = filter_var($_GET['CODIGO'], FILTER_SANITIZE_NUMBER_INT);

        $sql    = "SELECT CODIGO FROM TESTE_TABELA WHERE CODIGO = $dados";
        $query  = sqlsrv_query($conexion,$sql);

        if($row = sqlsrv_fetch_array($query) > 0){

        }else{
             echo "";
        }
}

Depois de muito tempo consegui, fiz essa condição se o if($row = sqlsrv_fetch_array($query) > 0) for verdadeiro ou seja maior que 0 ele executa o código e abre o pdf, se for false menor ou igual 0 ele redireciona. Todo o restante do código que postei antes vai dentro do if($row = sqlsrv_fetch_array($query) > 0


text:
Q: Scrollpane destroy element on hide I have a bit complicated scenario with jscrollpane, and a problem with the scrolled element disappearing...
I call jscrollpane with this in js root
var $scrollfix = $('.sidebar nav').jScrollPane().data('jsp');

Then have in doc ready
$scrollfix;

And in window resize
$scrollfix.reinitialise();

And then I need to remove the jscrollpane when the menu (where the scroll is placed) is closed with a button, and then restore the function when it is opened
$(".close").on('click', function(e){
    // Close menu
    // jScrollpane
    $scrollfix.destroy();
    e.preventDefault();
});

$(".open").on('click', function(e){
    // Open menu
    // jScrollpane
    $scrollfix;
    e.preventDefault();
});

But, it doesn't work at the second open after close, I believe because the $scrollfix.destroy(); removes completely the jscrollpane.
How can I get it back or not remove it completely, just disable it on the closed menu?


text:
Q: I want to stream video from my webserver, but I only want it to stream when there is a viewer This might seam like a really stupid question.  I'm trying to set up a webcam to watch my fish while I'm away, and I want it to be on all the time, however, I have a bandwidth cap, so I can't have it streaming all the time.  I was hoping to develop some sort of application where it will start streaming whenever a user connects and cease streaming whenever the user disconnects.  Is this possible?

A: Try Page Visibility API.
Supported Browsers : http://caniuse.com/#feat=pagevisibility


text:
Q: HTML Counter that starts at 15 minutes and goes until button press? I'm trying to make a little HTML page with 2 buttons on it and 1 drop down (Eventually I will multiply this by 5).
The first button activates a small timer that starts at 15 minutes and goes into the negatives until the button is pressed again.
The second button does the exact same thing, but starts at 30 minutes and goes down into the negatives until the button is pressed again.
The drop down just has a list of all employees.
I have found many different timers, but none of them go into the negatives. and if I remove the if statement that checks for negatives, it just doesn't work. Can anyone help me with this negative counter?
$(document).ready(function () {
    var secs = 0;
    var id = setInterval(function () {
        secs++; console.log(secs);
        if (secs > 5) {
            clearInterval(id);
            alert('Total Time: ' + secs + ' seconds');
        }
    }, 1000);
});

######Javascript:

window.onload = function () {
    var secs = 0;
    var id = setInterval(function () {
        secs++; console.log(secs);
        if (secs > 5) {
            clearInterval(id);
            alert('Total Time: ' + secs + ' seconds');
        }
    }, 1000);
};

A: This is how I would do it:
var myTimer;
var started = false
var count = 15 * 60; //15 mins x 60 secs

$("button").click(function() {
  if (!started) {
    started = true;
    $(this).text("Stop");
    myTimer = setInterval(function() {
      $(".timer").text(--count);
    }, 1000);
  } else {
    started = false;
    clearInterval(myTimer);
    $(this).text("Start");
  }
});

Here is the JSFiddle demo
Please note that I implemented only the 15 mins timer. You can replicate the code for the 30 mins one.

A: You could try this

(function (javascript) {
    // An Array with the doms and their cancellation functions
    var buttonList = [];

    /**
     * Toggles each button's timer
     * @param {HTMLElement} dom
     * @param {number} timer
     * @returns {void}
     */
    function toggleButton(dom, timer) {
        // find the object for the dom in the list
        var result = buttonList.find(function (item) {
            return item.dom === dom;
        });
        // if it is found
        if (result) {
            // stop the timer
            result.cancel();
            // reset the text to default
            print(timerFormat(timer));
            // remove the object from the list
            var index = buttonList.indexOf(result);
            buttonList.splice(index, 1);
        } else {
            // if it isn't found then start the timer and add the object to the list
            buttonList.push({
                cancel: startTimer(timer, print),
                dom: dom
            });
        }
        /**
         * Changes the text of the element
         * @param {string} text
         * @returns {void}
         */
        function print(text) {
            dom.innerText = text;
        }
    }

    /**
     * Creates a timer and returns a cancelation function
     * @param {number} timer
     * @param {function(string): void} print
     * @returns {function(): void}
     */
    function startTimer(timer, print) {
        var intervalId = setInterval(onTick, 1000);
        return cancel;
        function onTick() {
            var result = timerFormat(timer--);
            if (typeof print === "function") print(result);
            else console.log(result);
        }
        function cancel() {
            if (intervalId) {
                clearInterval(intervalId);
                intervalId = undefined;
            }
        }
    }

    /**
     * Converts the seconds into [mm:ss] format
     * @param {number} timer
     * @returns {string}
     */
    function timerFormat(timer) {
        var negative = false;
        if (timer < 0) {
            timer = timer * -1;
            negative = true;
        }
        var minutes = Math.floor(timer / 60);
        var seconds = String(timer % 60);
        var symbol = negative ? "- " : "";
        return symbol + minutes + ":" + "0".repeat(2 - seconds.length) + seconds;
    }

    javascript.toggleButton = toggleButton;
})(window);
<button onclick="toggleButton(this, 900)">15:00</button>
<button onclick="toggleButton(this, 1800)">30:00</button>


text:
Q: Gulp - add contents of one file to end of multiple files I'm fairly new to Gulp so, hopefully this is a simple question.  My project comprises many files (more than shown in the example below), and the magic of Gulp lets me combine, minify, babel, etc.  All good - I've used Grunt for years so I understand the basic concepts, but this project requires Gulp for ((reasons)), so here I am.
The project results in several output scripts. Each one is, basically, the same core application compiled with different configuration options.  The config is substantial, so not appropriate to pass in at instantiation.  Anyway, all good there, just some background.
The problem I'm having is the project is dependent on one vendor script.  I don't want to run that script though all the processing, rather I need to prepend (preferably) or append it to each output script after all processing has happened on the app codebase.
Here's what I've tried to do, but it's failing.  I also tried the commented out stuff (without the extra task in the series) but the files aren't output to dist until the entire routine is complete (which makes sense, but you know... ever hopeful).  Note:  I 'anonymized' the script a bit, so hopefully I didn't put any weird syntax errors in...  my build script runs fine, I just can't figure out how to get the vendor script prepended without a bunch of ugly hardcoded tasks for each instance (there's several instances, so I'd rather not do it that way).
Thanks in advance!
    function instance1(cb) {
    return gulp.src([
            'src/app/data/data_en-us.js',
            'src/app/data/data_pt-br.js',
            'src/app/data/data.js',
            'src/app/instances/_global/global_config.js',
            'src/app/instances/_global/report_config.js',
            'src/app/instances/1/config.js',
            'src/app/instances/1/report_config.js',
            'src/app/core/calculator.js',
            'src/app/core/report.js',
            'src/app/instances/_global/global.js',
            'src/app/instances/1/instance.js',
        ])
        .pipe(sourcemaps.init())
        .pipe(babel({
            presets: ['@babel/env']
        }))
        .pipe(concat('app.js'))
        .pipe(sourcemaps.write('maps'))
        .pipe(gulp.dest('dist'))
        .pipe(minify({preserveComments:'some'}))
        .pipe(gulp.dest('dist'))
        //.pipe(src(['src/vendor/script.js','dist/app.js']))
        //.pipe(concat('dist/app.js'))
        //.pipe(src(['src/vendor/script.js','dist/app-min.js']))
        //.pipe(concat('dist/app-min.js'))
        //.pipe(gulp.dest('dist'));
    cb();

}

function appendVendorScript(cb) {
    return gulp.src(['src/vendor/script.js','dist/*.js'])
        .pipe(concat())
        .pipe(gulp.dest('dist'));

    cb();
}

exports.build = series(
    cleanup,
    parallel(
        series(instance1,appendVendorScript)
        //more items here for each instance
        )
);

A: I found a solution that also lets me minimize redundancy.  Turns our, the sourcemap plugin was responsible, so I just removed it.  Talking with some other colleagues, I learned that they too had issues with that plugin.  I guess it's just poorly done, or old, or otherwise not well maintained.  Such is life in open source :)
Here's what I came up with.  Works well, but when I run build to do them all at once, it somehow breaks the code.  Works perfectly when I build them one at a time... so far, haven't been able to explain that one, but one problem at a time!
const coreFilesList = [
    //list of codebase files here
];

const vendorFilesList = [
        //list of vendor files here
];

const outputFileData = {
    prefix: 'app',
    seperator: '_',
    ext: '.js'
}

function instance1(cb) {
    const token = 'instance1';
    process(coreFilesList,token);
    cb();
}
function instance2(cb) {
    const token = 'instance2';
    process(coreFilesList,token);
    cb();
}

function process(srclist,token){
    let outputFileName = outputFileData.prefix + outputFileData.seperator + token + outputFileData.ext;

    for (let i = 0; i < srclist.length; i++){
        if(srclist[i].match(/_TOKEN_/)){
            srclist[i] = srclist[i].replace(/_TOKEN_/g,token);
        }
    }

    return src(srclist)
    .pipe(concat(outputFileName))
    .pipe(babel({
        presets: ['@babel/env']
    }))
    .pipe(src(vendorFilesList))
    .pipe(concat(outputFileName))
    .pipe(minify({preserveComments:'some'}))
    .pipe(dest('dist'));
}

exports.instance1 = series(cleanup, instance1);
exports.instance2 = series(cleanup, instance2);
//more here

exports.build = series(
    cleanup,
    parallel(
        instance1,
        instance2
//more here
    )
);


text:
Q: Sudden jump in sin function frequency I'm writing signal source for digital signal processing and found strange behaviour. Here is the code:
    float complex *output = malloc(sizeof(float complex) * 48000);
    FILE *f = fopen("test_signal.cf32", "wb");
    int64_t freq = -3355;
    float phase_increment = 2 * (float) M_PI * (float) freq / 48000;
    float phase = 0.0F;
    for (int i = 0; i < 150 * 5; i++) {
        for (int j = 0; j < 9600; j++) {
            output[j] = cosf(phase) + sinf(phase) * I;
            phase += phase_increment;
        }
        fwrite(output, sizeof(float complex), 9600, f);
    }
    fclose(f);

It will create a file with complex signal shifted by -3355hz from the centre. So when I run FFT over this file I expect a signal at -3355hz. With some minor frequency distribution around that number due to quantisation. But in reality I'm getting the following:

There is a quite significant frequency jump (~2000hz) around 50 seconds.
Anyone knows why?
My experiments showed:

*

*using double for the phase helps

*doing argument reduction from -2pi to 2pi helps

*Apple M1 and raspberry pi have the same jump

*there seems to be no overflow in the phase argument

*Fun reading https://randomascii.wordpress.com/2014/10/09/intel-underestimates-error-bounds-by-1-3-quintillion/ but unlikely causing sudden jump of a frequency

A: Once phase gets large enough, increments to it are quantized by floating-point rounding, maybe enough that rounding to nearest with tie-break of rounding to even mantissa doesn't balance out, and instead means you consistently advance the phase less.  See wikipedia's article on single-precision IEEE float
A base-10 analogy with values limited to 4 significant figures would be 101.2 + 0.111 only going up to 101.3, not 101.311.  (Computers use binary floats, so actually stuff like 101.125 is exactly representable where 101.1 isn't.)
I suspect that's what's happening.  You won't overflow to +Inf, but given the limited relative precision of a float, adding a small number to a huge number will eventually not move it at all: the closest representable float to phase + phase_increment will be the original phase.
A quick way to test this hypothesis would be to use double phase (without making any other changes), and see if that moves the point at which you get frequency steps.  (To be vastly greater, probably past the end of what you're generating).
(Oh, just noticed you already did that, and it did help.  If you mean it completely removed the problem, then that's probably it.)
You can still keep the single-precision sinf and cosf, although changing them would be the other thing to try: as @Weather Vane points out, some sin implementations lose significant precision in range-reduction.  But you'd expect that to be a noisier signal, not a consistent change in frequency (which would take a scale factor for the phase.)
You could also let it run longer with float and see if you get another step down in frequency, or a change all the way to DC (constant phase, frequency = 0).
Or with float, manually unroll so you have two counters offset by phase_increment and you increment each one by 2*phase_increment.  So the relative magnitude of phase vs. what's being added doesn't get so extreme.  They'll still get to the same absolute magnitude, though, large relative to the original phase_increment, so there will still be some rounding.

I don't know if there are better strategies for generating complex sine waves, I'm just trying to explain the behaviour you're seeing.
For performance of this method, you probably want sincosf to compute both values at the same time, if your compiler doesn't optimize your calls into that.  (And hopefully auto-vectorize by calling a SIMD sincosf.)

A: What you observing is floating point precision issues. Precision of floats degrades with magnitude.
Fortunately, for phases or similar angular values there's an easy workaround, wrap the value around 2π so the magnitude is never too large.
Add the following code after your phase += phase_increment; and see if that helps.
if( phase < (float)( 2.0 * M_PI ) )
    continue;
phase -= (float)( 2.0 * M_PI );


text:
Q: Explain the usage of 'some_list[0:0] = new_list' I encountered this code that is giving a long list of file paths but I am curious what the significance of the [0:0] part of the code is but I can't seem to find any references to this specific syntax usage.
Would sys.path[0] = mean the same thing as sys.path[0:0]? Is that even a thing?
Since I can't seem to find reference to this kind of code, does that mean there is a better way to do this in newer versions of Python? I ask because I suspect the application using this code was build on Python 2.4.
import sys
sys.path[0:0] = [
  '/home/nac/eggs/Pillow-2.7.0-py2.7-linux-x86_64.egg',
...
...
...
 '/home/nac/eggs/pycparser-2.14-py2.7.egg',
]

A: It is equivalent to an update/insert:
>>> numbers = [1, 2, 3]
>>> numbers[0:0] = [4, 5, 6]
>>> numbers
[4, 5, 6, 1, 2, 3]

Another example:
numbers = [1, 2, 3]
>>> numbers[0:2] = [4, 5, 6]
>>> numbers
[4, 5, 6, 3]


text:
Q: What can OLS with a Box-Cox transformed dependent variable tell me? Just to ellaborate: I'm doing an OLS-test to determine the following things:

*

*Do my independent variables have a significant effect on the dependent variable?

*What's the direction of the effect of my significant independent variables (positive/negative)?

*What's the order of my independent variables by strength of effect? (e.g.: Which independent variable has the strongest effect, and which one has the weakest effect?)

Now, I know that there are other statistical models that could come into play, but for all other reasons, I decided to make OLS work if possible.
Since my residuals are definitely not normal (but I would like to interpret p-values, etc. from my model), I'm thinking of using a Box-Cox transformation. However, I'm a bit confused about whether I can interpret the coefficients of the significant independent variables after doing a Box-Cox transformation on the dependent variable to answer my research questions. Again, I'm not looking to build a predictive model with precise predictive power – I'm just looking to:

*

*Establish whether an independent variable has a statistically significant effect on the dependent variable

*Establish the direction of this effect

*Establish whether one independent variable has a stronger effect than another one (without saying anything about 'how much stronger" that effect is)
Thanks!

Since the question has been closed until I provide more details, I'll do that now:
My dependent variable is a percentage (the percentage of a certain bacteria in various stool-samples). I'm curious about how to interpret the OLS results if I decide to do a Box-Cox transformation on this dependent variable (with a lambda value around 0.2 - 0.5).
My independent variables are things like age, gender (dummy), weekly average amount of milk consumed, BMI-score, and a few others. After the Box-Cox transformation of my dependent variable, I'm curious if I can make statements like the following (based on the OLS results):

*

*"BMI and age have a significant effect on the percentage of X-bacteria"

*"Based on their standardized coefficients (or should I look at something else??), BMI is negatively associated with the percentage of X-bacteria, while age is positively associated with this percentage"

*"Based on the absolute value of their standardized coefficients (again: am I looking in the wrong direction?), the effect of BMI on the percentage of X-bacteria is stronger than the effect of age"

As you can see, I'm looking to make broad statements (so NOT predictions) about my original dependent variable, despite having transformed it using the Box-Cox method. Also, I'm planning on using the various standardized coefficients of my independent variables to make these broad statements.
To summarize:

*

*I want to determine which independent variables have a significant effect. Since the residuals of my dependent variable are non-normal, I assume that I can't trust the p-values I get from that regression. But my question is: can I trust the p-values after the Box-Cox transformation IF the residuals look normal?

*I want to know the direction of the effect of my various independent variables. Can I make this assessment by looking at their standardized coefficients in the regression with the Box-Cox transformed dependent variable (whether the coefficients are positive or negative)? Or is there any other way to determine this?

*I want to know which of the significant independent variables has a "stronger" effect on the dependent variable. Can I do this by looking at the standardized coefficients (the absolute value) of the independent variable?

I don't know how to be any more clear than this. Please note, that I'm kind of a newbie, but I'm trying my best!
Thank you for all of the answers and your patience!


text:
Q: How to rerun the process if it dies - Linux Can any one let me know how to re-run the process automatically again if it gets dies. Below is my code which i have tired but it is giving me an  error :
Edited Code :
commandpid=`$busyboxValue pidof command`
echo ${commandpid} > /sdcard/CommandProcess.txt
if [ $commandpid -gt 0 ]
then
    echo -16 > /proc/$commandpid/oom_adj
    echo -1000 > /proc/$commandpid/oom_score_adj
fi

while [ true ]
do
    echo "PID $commandpid"
    if [ ps -p $commandpid > /dev/null ]
    then
        echo "[$(date)] :Process is already running with PID $commandpid"
    else
        echo "[$(date)] :Process is not running"
        /data/local/command 1200 &
        commandpid=`$busyboxValue pidof command`
        echo ${commandpid} > /sdcard/CommandProcess.txt
    fi
    sleep 10
done

I have updated the code but still with the above code multiple process id i am getting. Dose it mean my else part code is keep executing? If yes the what changes i need to do to stop it?
Can please any one help me ?

A: To repeatedly run a command, regardless of exit status:
while :; do command; done

To repeatedly run a command until a successful exit:
until command; do :; done


text:
Q: Nokogiri can't install native extensions issue When trying to install nokogiri, I get:
± gem install nokogiri -v '1.6.0'
Building native extensions.  This could take a while...
/Users/Chintan/.rvm/rubies/ruby-1.9.3-p327/lib/ruby/1.9.1/rubygems/ext/builder.rb:48: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777
ERROR:  Error installing nokogiri:
    ERROR: Failed to build gem native extension.

        /Users/Chintan/.rvm/rubies/ruby-1.9.3-p327/bin/ruby extconf.rb
/Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:199: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777
Extracting libxml2-2.8.0.tar.gz into tmp/x86_64-apple-darwin11.4.0/ports/libxml2/2.8.0... OK
Running 'configure' for libxml2 2.8.0... ERROR, review 'tmp/x86_64-apple-darwin11.4.0/ports/libxml2/2.8.0/configure.log' to see what happened.
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/Users/Chintan/.rvm/rubies/ruby-1.9.3-p327/bin/ruby
/Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:235:in `block in execute': Failed to complete configure task (RuntimeError)
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:227:in `chdir'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:227:in `execute'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:57:in `configure'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/mini_portile-0.5.0/lib/mini_portile.rb:100:in `cook'
    from extconf.rb:101:in `block in <main>'
    from extconf.rb:119:in `call'
    from extconf.rb:119:in `block in <main>'
    from extconf.rb:109:in `tap'
    from extconf.rb:109:in `<main>'

Gem files will remain installed in /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/nokogiri-1.6.0 for inspection.
Results logged to /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/nokogiri-1.6.0/ext/nokogiri/gem_make.out

Looks like the issue is with the C compiler, here's the contents of configure.log:
checking build system type... x86_64-apple-darwin12.2.1
checking host system type... x86_64-apple-darwin12.2.1
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... ./install-sh -c -d
checking for gawk... no
checking for mawk... no
checking for nawk... no
checking for awk... awk
checking whether make sets $(MAKE)... yes
checking for gcc... gcc
checking whether the C compiler works... no
configure: error: in `/Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/nokogiri-1.6.0/ext/nokogiri/tmp/x86_64-apple-darwin11.4.0/ports/libxml2/2.8.0/libxml2-2.8.0':
configure: error: C compiler cannot create executables
See `config.log' for more details

Update:
Re-installing my compiler lets me install nokogiri, but I can't start rails server:
/Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require': dlopen(/Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rmagick-2.13.2/lib/RMagick2.bundle, 9): Library not loaded: /usr/local/lib/libMagickCore-Q16.7.dylib (LoadError)
  Referenced from: /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rmagick-2.13.2/lib/RMagick2.bundle
  Reason: image not found - /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rmagick-2.13.2/lib/RMagick2.bundle
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rmagick-2.13.2/lib/RMagick.rb:11:in `<top (required)>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
    from /Users/Chintan/Documents/Work/Aidin/config/initializers/imagemagick.rb:1:in `<top (required)>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/zeus-0.13.3/lib/zeus/load_tracking.rb:50:in `load'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/zeus-0.13.3/lib/zeus/load_tracking.rb:50:in `load'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/zeus-0.13.3/lib/zeus/load_tracking.rb:43:in `load'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/engine.rb:587:in `each'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/engine.rb:587:in `block in <class:Engine>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in `method_missing'
    from /Users/Chintan/Documents/Work/Aidin/config/environment.rb:5:in `<top (required)>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `block in require'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:251:in `require'
    from /Users/Chintan/Documents/Work/Aidin/config.ru:3:in `block in <main>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/builder.rb:51:in `instance_eval'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/builder.rb:51:in `initialize'
    from /Users/Chintan/Documents/Work/Aidin/config.ru:in `new'
    from /Users/Chintan/Documents/Work/Aidin/config.ru:in `<main>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/builder.rb:40:in `eval'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/builder.rb:40:in `parse_file'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/server.rb:200:in `app'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/commands/server.rb:46:in `app'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/server.rb:304:in `wrapped_app'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/rack-1.4.5/lib/rack/server.rb:254:in `start'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/commands/server.rb:70:in `start'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/commands.rb:55:in `block in <top (required)>'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/commands.rb:50:in `tap'
    from /Users/Chintan/.rvm/gems/ruby-1.9.3-p327@aidin_development/gems/railties-3.2.13/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

Last time I had this issue, the fix was to just re-install apple-gcc42, but that that doesn't seem to be the issue right now. Any ideas?

A: Looks like this issue has been already addressed: nokogiri will not install - ERROR: Failed to build gem native extension
Try
sudo apt-get install libxslt-dev libxml2-dev

A: You need libxslt and libxml2 to build nokogiri. And since you're on MacOS X, you need to install via MacPorts or Homebrew. For Homebrew, try:
brew install libxslt libxml2

A: homebrew 0.9
Apparently some people have had problems getting libiconv to install under homebrew 0.9 (see issue #442). Here's what reportedly works:
brew install libxml2 libxslt
brew link libxml2 libxslt

Then install libiconv from source:
wget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-1.13.1.tar.gz
tar xvfz libiconv-1.13.1.tar.gz
cd libiconv-1.13.1
./configure --prefix=/usr/local/Cellar/libiconv/1.13.1
make
sudo make install

Then (finally) install nokogiri:
gem install nokogiri -- --with-xml2-include=/usr/local/Cellar/libxml2/2.7.8/include/libxml2 \
                        --with-xml2-lib=/usr/local/Cellar/libxml2/2.7.8/lib \
                        --with-xslt-dir=/usr/local/Cellar/libxslt/1.1.26 \
                        --with-iconv-include=/usr/local/Cellar/libiconv/1.13.1/include \
                        --with-iconv-lib=/usr/local/Cellar/libiconv/1.13.1/lib

A: This workaround worked for me: https://github.com/opscode-cookbooks/xml/issues/19
1) Add liblzma-dev and z-lib1g-dev
sudo apt-get install liblzma-dev zlib1g-dev

2) Install using those
sudo /opt/chef/embedded/bin/gem install nokogiri -q --no-rdoc --no-ri -v "1.6.5" -- --use-system-libraries --with-xml2-include=/usr/include/libxml2

A: Following this worked for me http://jasdeep.ca/2013/10/installing-nokogiri-fails-os-x-mavericks/
It was a Mavericks issue involving developer tools.

A: A more comprehensive cases are detailed on nokogiri website
For me, on MacOs, it worked like as it is sugested here:
brew install libxml2
# If installing directly
gem install nokogiri -- --use-system-libraries \
  --with-xml2-include=$(brew --prefix libxml2)/include/libxml2
# If using Bundle
bundle config build.nokogiri --use-system-libraries \
  --with-xml2-include=$(brew --prefix libxml2)/include/libxml2
bundle install

When working with this, be certain to use $(brew --prefix libxml2)
because it will use the correct location for your Homebrew install.


text:
Q: Post multiple lines with PHP When someone presses the submit button a line is added with this code:

    <form method ="POST" action="" name ="formpje">

        A line<input type="text" name="name">

        <input type="submit" name="submit">

    </form>

<?php
$post = $_POST['name'];
echo $post;
?>

The result:

When i add a new line the current one gets changed to the newest one. I want it to stay as i add a new one.
Heres what it would look like:

A: Try this, each time you submit the form it will place the name into a session and print it out bellow.
<?php
    session_start();
    if( isset( $_POST[ 'submit' ] ) )
    {
        $_SESSION[ 'submissions' ][] = $_POST[ 'name' ];
    }
?>
<form method ="POST" action="" name ="formpje">
    A line<input type="text" name="name">

    <input type="submit" name="submit">

</form>

<?php
    foreach( $_SESSION[ 'submissions'] as $line )
    {
        echo $line."\n";  <------ May need to replace this with "
" instead of "\n" for the html.
    }
?>


text:
Q: Illuminate \ Broadcasting \ BroadcastException 404 NOT FOUND I'am using Laravel 5.8 with pusher to make an broadcast , after i submit the form im getting this 404 not found i have been searching the google for the answer but no luck.
PostPublished.php
 <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class PostPublished implements ShouldBroadcast {
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $data;

    public function __construct($data) {
      $this->data = $data;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn() {
      return new Channel('my-channel');
    }

    public function broadcastAs()
    {
      return 'Post-Published';
    }

  }

AdminAnnounceController
public function store(Request $request)
{
    $data = request()->validate([
    'department' => ['required', 'string', 'max:255'],
    'title' => ['required', 'string', 'max:255'],
    'content' => ['required', 'string', 'max:255'],
    'status' => ['required'],

    ]);

    $data = Announcement::create([

        'department' => $data['department'],
        'title' => $data['title'],
        'content' => $data['content'],
        'status' => $data['status'],

    ]);

     event(new PostPublished($data));

    return redirect('admin_announce')->with('success', 'the Annonucement  has been send');

}


text:
Q: A better function to perform multiple replaces in a text, specified by arrays? I have 2 text arrays, the first contains the string set that I am looking for, and the second is the string that I need to be replaced when found. PostgreSQL offers the string function replace(text,text,text)....
Is there a simple implentation or library that offers an optimized version of replace(text,text[],text[]) function? PS: or similar thing.

NOTES

*

*this question about character-replace is similar bot not a duplicate.

*answering the "use case" that @Bergi asked: the replace is the main piece in any user-defined template system engine (imagine for example an pure-SQL mustache implementation). Imagine that you need massive "on the fly" (real time) string replaces to use it in an REST API like PostgREST or PostGraphile.

*I need optimized version (in C or something with better performance) of the "not optimized example" below.
-- not optimized implentation:
CREATE FUNCTION agg_replace_fn(
  oldtxt text, txt text, fnd text, rpl text
) RETURNS text AS $f$
  SELECT CASE
   WHEN oldtxt>'' AND txt>'' AND fnd>'' THEN replace( oldtxt, fnd, rpl )
   WHEN (oldtxt IS NULL OR oldtxt='') AND txt>'' AND fnd>'' THEN replace( txt, fnd, rpl )
   ELSE COALESCE(txt,'')
   END
$f$ LANGUAGE SQL IMMUTABLE;
CREATE AGGREGATE agg_replace(text,text,text) (
  sfunc = agg_replace_fn,
  stype = text,
  initcond = ''
);

CREATE FUNCTION replace(txt text, fnd text[], rpl text[]) RETURNS text AS $f$
  SELECT agg_replace(txt,f,r)
  FROM unnest(fnd) WITH ORDINALITY t1(f,idx)
       NATURAL JOIN  unnest(rpl) WITH ORDINALITY t2(r,idx)
$f$ LANGUAGE SQL IMMUTABLE;
-- to test:
SELECT
  replace('axbcde abxcdefg etc', array['ax','bx','e'], array['a!','b0','@'])
  =
  'a!bcd@ ab0cd@fg @tc'
;

As @Bergi suggested, showing the performance problem:
-- Benchmark:
EXPLAIN ANALYSE SELECT
  replace('axbcde abxcdefg etc', array['ax','bx','e'], array['a!',i::text,'@'])
FROM generate_series(1,10000) t(i); -- 3 replaces per row, total 30000
--  Execution Time: 804.722 ms

EXPLAIN ANALYSE SELECT
  replace('axbcde abxcdefg etc', i::text, 'b0')
FROM generate_series(1,10000*3) t(i); -- one replace per row, total 30000
-- Execution Time: 12.616 ms

So the "optimized" is ~60 times faster.


text:
Q: Converting timezone specific time into UTC using MomentJS When converting Casablanca time into UTC, MomentJS is using the wrong hour:
moment.tz.add("Africa/Casablanca|LMT WET WEST CET|u.k 0 -10 -10|0121212121212121213121212121212121212121212121212121212121212121212121212121212121212121212121212121|-2gMnt.E 130Lt.E rb0 Dd0 dVb0 b6p0 TX0 EoB0 LL0 gnd0 rz0 43d0 AL0 1Nd0 XX0 1Cp0 pz0 dEp0 4mn0 SyN0 AL0 1Nd0 wn0 1FB0 Db0 1zd0 Lz0 1Nf0 wM0 co0 go0 1o00 s00 dA0 vc0 11A0 A00 e00 y00 11A0 uM0 e00 Dc0 11A0 s00 e00 IM0 WM0 mo0 gM0 LA0 WM0 jA0 e00 Rc0 11A0 e00 e00 U00 11A0 8o0 e00 11A0 11A0 5A0 e00 17c0 1fA0 1a00 1a00 1fA0 17c0 1io0 14o0 1lc0 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1lc0 14o0 1fA0|32e5");

alert(moment.tz({ year: 2016, month: 6, date: 13, hour: 20 }, "Africa/Casablanca")._d.toUTCString());

This is showing 20:13, but it should show 19:13 (UTC), shouldn't it?
JSFIDDLE

A: AFAIK, using internals like _d can cause unexpected results. Try using the public API:
moment.tz(...).toDate().toUTCString()


text:
Q: Sort By Descending Date Django models.py
class Record(models.Model):
    date = models.DateTimeField()
    ....

class Balance(models.Model):
    record = models.ForeignKey(Record)
    ....

views.py
balances = Balance.objects.filter(record__date__week=current_week).order_by("-record")

this will order the balance entries based on when the records were created not on the date from Record. How can I sort these queries for Balance based on Record Date.

A: Just add the date field of the record to ordering:
balances = Balance.objects.filter(record__date__week=current_week).order_by("-record__date")


text:
Q: Why am I getting an assert Error When trying to Delete a section in a tableview ios I have a tableView with some sections, which all have a footer, and then I have a tableViewFooter on the Tableview itself.
If I scroll down to the bottom of my tableview and delete the last item(therefore deleting the section altogether) in any sections above the last section (second last and up) it gives me this error
2014-02-21 13:19:55.066 xxxx[5436:60b] *** Assertion failure in -[UIViewAnimation initWithView:indexPath:endRect:endAlpha:startFraction:endFraction:curve:animateFromCurrentPosition:shouldDeleteAfterAnimation:editing:], /SourceCache/UIKit/UIKit-2903.23/UITableViewSupport.m:2661
Uncaught exception: Cell animation stop fraction must be greater than start fraction

at endUpdates
this is my code
[self.tableView beginUpdates];
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if(indexPath != nil){
        TableSection * sec = [self.sections objectAtIndex:indexPath.section];
        NSMutableDictionary *dic =[sec.items objectAtIndex:indexPath.row];

        Product* product = [dic valueForKey:PRODUCT];

        //removing the item in the section
        [sec.items removeObject:dic];

        //deleting item from products
        NSMutableArray *temp = [NSMutableArray array];
        for (Product *p in self.dataCon.listPersister.products) {
            if ([p.product.objId isEqualToString: product.product.objId]) {
                [temp addObject:p];
            }
        }

        for (Product *p in temp) {
            [self.dataCon.listPersister.products removeObject:p];
        }

        //if it was the last object in section, delete the section else just delete the single row

        if(sec.items.count == 0)
        {

            [self.sections removeObject:sec];
            [self.footers removeObjectAtIndex:indexPath.section];
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]  withRowAnimation:UITableViewRowAnimationFade];

        } else
        {

            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            USFooterView *footer = [self.footers objectAtIndex:indexPath.section];
            footer.totalLabel.text = [self.dataCon.listPersister getTotalForShopId:sec.title];
            self.footerView.totalLabel.text = [self.dataCon.listPersister getTotalForAllProducts];
        }

    }

    [self.tableView endUpdates];

I had the same code earlier, just without my tableView and table sections having footers, where it worked, so I think they might be the problem, but I'm not entirely sure that's the reason it's acting up.
I have seen this post
UITableView tableFooterView may cause crash?
And the post that it links to, but that didn't help me.
Any help is appreciated :)

A: In the else statement you delete row from table view:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

But not from data source. Delete row from array which you use as data source and it should works.

A: I found a "fix", but I'm avoiding the use of sectionFooter, because that seems to be bugged.
I created an extra cell at the end of each section, with the same setup I had for my footer View before, and made that last cell not editable with
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    TableSection * sec = [self.sections objectAtIndex:indexPath.section];
    if (sec.items.count != indexPath.row) {
        return YES;
    } else
        return NO;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

        return [sec.items count] +1 ;

}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"normalcell";
static NSString *CellIdentifier1 = @"footercell";

TableSection * sec = [self.sections objectAtIndex:indexPath.section];

if (indexPath.row != sec.items.count) {
    //use normal type of cell

    return cell;
} else{
    //use footer type of cell

    return cell;
}

}

So the last cell Imitates a "footer", but it's not stuck to the bottom of the frame, but I'll have to live with that. It's better than crashes.

A: Try using UITableViewRowAnimationLeft or UITableViewRowAnimationRight as the delete row animation(deleteRowsAtIndexPaths:withRowAnimation:).
It crashed for me when using UITableViewRowAnimationAutomatic, but not with the other two. I have not tried all of them but it seems to be a bug with the animation code for some of the options.


text:
Q: How do I parse ndjson file using Golang? I have a ndjson (newline delimited JSON) file, I need to parse it and get the data for some logical operation. Is there any good method for parsing ndjson files using golang. A sample ndjson is given below
{"a":"1","b":"2","c":[{"d":"100","e":"10"}]}
{"a":"2","b":"2","c":[{"d":"101","e":"11"}]}
{"a":"3","b":"2","c":[{"d":"102","e":"12"}]}

A: The encoding/json Decoder parses sequential JSON documents with optional or required whitespace depending on the value type. Because newlines are whitespace, the decoder handles ndjson.
d := json.NewDecoder(strings.NewReader(stream))
for {
    // Decode one JSON document.
    var v interface{}
    err := d.Decode(&v)

    if err != nil {
        // io.EOF is expected at end of stream.
        if err != io.EOF {
            log.Fatal(err)
        }
        break
    }

    // Do something with the value.
    fmt.Println(v)
}

Run it on the playground.


text:
Q: issues with jQuery accept Firstly apologises if this already on stack overflow.  I have 3 blocks, one of these blocks need to be dragged into the target segment. unfortunately when I drag any of the 3 blocks I the code executes. If the user drags the incorrect block I simply want it to do nothing. I am new to coding, but from what I've read the following:
accept: "#Proof";

should work, however it seems not. Help is greatly appreciated. Please note I must do this in jQuery as it's for an education project.
Many thanks
  $(".drop").draggable();

  $("#Proof").draggable();

  $("#target").droppable({
      accept: "#Proof";
    drop: function (event, ui){
      $("#Proof").html("Success!!<br> Please now press submit");
      $("#target").css("background-color", "#00cc00");
      $(".falseTarget").css("background-color", "#00cc00");
      $(".drop").hide();
      $("#Proof").draggable('disable');
    }
  });

A: There is a typo issue in your code.
$("#target").droppable({
    accept: "#Proof"; // <-- replace ';' by ','
    drop: function (event, ui) {...}
});


text:
Q: MVC 3 Razor - show modal based on an EF query At work I have been tasked with adding additional functionality to an existing MVC 3/Razor project.  I haven't used MVC before, but am quite versed with Web Forms.
However, I am not quite sure where to place everything I need.
When the app is first loaded, a login page appears.  When the user logs in successfully, the user sees a dashboard type page.
The new functionality is to detect whether the user has FollowUpItems with a Due Date < Now. If Count > 0 then display a Modal popup with some text and a link to 'View Followup Items'.
There is already a controller and action made for viewing Followup items.  I need to display the modal, and I would like to make the modal a reuseable type of object - I am assuming/thinking a PartialView where I can pass in the name of the Controller, Action, Params for a possible ActionLink that I would display in the modal popup, and the message text, etc.
I need a little guidance on how to open the modal since it isn't attached to a click, but rather to whether an expression evaluates true or false, and where the best place for the pieces are.
Thanks in advance for the guidance

A: I would detect if the user has FollowUpItems in the Action that loads the dashboard page, and store that information in the ViewBag. For example,
public ActionResult Dashboard()
{
    ViewBag.HasFollowupItems = UserHasFollowupItems();
    return View();
}

In this example, UserHasFollowupItems() returns a string, something like 'true' or false'.
In the dashboard view, add an empty div into which the modal data will be loaded

then add a document.ready() in the same view which defines the modal and determines if the modal should be loaded:
$(document).ready(function ()
{
    // define modal
    $("#followup_items").dialog({
        autoOpen: false,
        height: 'auto',
        width: 825,
        title: 'Followup Items',
        position: [75, 75],
        modal: true,
        draggable: true,
        closeOnEscape: true,
        buttons: {
            'Close': function ()
            {
                $(this).dialog('close');
            }
        },
        close: function ()
        {
            $('.ui-widget-content').removeClass('ui-state-error');
        },
    });

    if(@ViewBag.HasFollowupItems == 'true')
    {
        $('#followup_items').load("/FollowupItems/Load", function (data, txtStatus, XMLHttpRequest)
        {
            $('#followup_items').dialog('open');
        }
    });
});

In this example /FollowupItems/Load is the URL to the proper controller/action that generates the data for the view. You are correct, the view for this would be a partial view, loaded into the empty followup_items div on the page.
So you can use the @ViewBag object anywhere in the view, in this case passing in your boolean indicating if the modal should be loaded/opened. I have not found a way to use ViewBag in an external javascript file, so I typically use embedded script tags in my views so I can use the ViewBag.
You could also add in the user id in the same way (/FollowupItems/Load/@ViewBag.Userid), or any other data the followup action needs.


text:
Q: App with most logic on the serverside (web api design) I have a mobile application that allows managers in companies to record when employees fall ill and contact them at certain points after their sick leave has started (so they know the status of the employee).
The app is pretty dumb. It relies heavily on a web api. From the web api, the app gets info about who to contact when. The app is also able to register that an employee has fallen ill, that an ill employee is no longer ill and that a manager has contacted an employee. All the logic for these actions is located in the web api.
There are two classes, Employee and SickLeave. Employee contains name and phonenumber of an actual employee. SickLeave contains two employees (1 ill, 1 manager) and a boolean to determine if it is still active.
With all the logic residing in the web api, all the POST requests (creating, changing sick leave entries) are super simple. Basically all the web api needs to know is the action to be performed and the relevant id's involved. So I end up with:
POST request to api/sickleave/new containing the id of the employee and the id of the manager.
POST request to api/register/healthy containing the id of the sickleave.
POST request to api/register/contact containing the id of the sickleave.
etc.
This is confusingly simple and leads me to believe that I'm doing something wrong? It can't be right, that all a POST request contains is an id?

A: According to the design principles of REST, a POST should be used when creating a new entity. PUT is for updating an entire entity and PATCH is for partially updating an entity.
Generally speaking, your API structure should be based on the structure of your entities so you should have /api/sickleave/ and /api/employee/. I see from your example that you have not really followed this pattern, instead you have API actions for different statuses. This means your API is not fully RESTful.
If you were to fully implement a REST structure, to record a new sick leave, you can POST to /api/sickleave/ with the ID of the employee (as you are already doing). I think it is fine if the API figures out the manager ID internally.
To update the status of the sickleave, you should PUT or PATCH to /api/sickleave/{id}/ modifying the relevant details. You should also delete sick leave by sending a DELETE request to /api/sickleave/{id}.
REST is just a pattern and you can really overcomplicate things by strictly following every minute detail of the pattern. However on the flip-side, not following patterns and best practices makes your code hard to understand for other developers.
Hope this helps. I'd probably need to see your full data structure to give you lower level details.


text:
Q: How to fix FileNotFoundError [WinError 2]? I'm trying to port the Proton-VPN Linux CLI (https://github.com/ProtonVPN/linux-cli) to Windows and have had decent success so far, but I'm running into an issue with [subprocess.Popen()]. I've tried many fixes but none have worked so far. I've tried converting this:
    with open(os.path.join(CONFIG_DIR, "ovpn.log"), "w+") as f:
        subprocess.Popen(
            [
                "openvpn",
                "--config", OVPN_FILE,
                "--auth-user-pass", PASSFILE,
                "--dev", "proton0",
                "--dev-type", "tun"
            ],
            stdout=f, stderr=f
        )

which is from the original module, to this:
    file_name = os.path.join(CONFIG_DIR, "ovpn.log")
    print(file_name)
    with open(file_name, "w+") as f:
        subprocess.Popen([
            "openvpn",
            "--config", OVPN_FILE,
            "--auth-user-pass", PASSFILE,
            "--dev", "proton0",
            "--dev-type", "tun"
        ], stdout=f, stderr=f)

which both yield the same error:
Traceback (most recent call last):
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\runpy.py", line 87, in _run_code
    exec(code, run_globals)
  File "C:\Users\<user>\AppData\Local\Programs\Python\Python39\Scripts\protonvpn.exe\__main__.py", line 7, in <module>
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\site-packages\protonvpn_cli\cli.py", line 73, in main
    cli()
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\site-packages\protonvpn_cli\cli.py", line 114, in cli
    connection.fastest(protocol)
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\site-packages\protonvpn_cli\connection.py", line 163, in fastest
    openvpn_connect(fastest_server, protocol)
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\site-packages\protonvpn_cli\connection.py", line 463, in openvpn_connect
    subprocess.Popen([
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\subprocess.py", line 947, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "c:\users\<user>\appdata\local\programs\python\python39\lib\subprocess.py", line 1416, in _execute_child
    hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

Anyone able to help me? I've been struggling all day with this and have been unable to find a fix. (by the way, I'm very new to python)
Edit: Upon trying to print "f" from the original module it returns this - "<_io.TextIOWrapper name='C:\Users\\.pvpn-cli\ovpn.log' mode='w+' encoding='cp1252'>". I tried inputting the name into an explorer tab and I received an error, but upon removing the double slashes I was taken to the file. I'm quite certain the double slashes are supposed to be there but could this be the problem?


text:
Q: How to force restart NodeJS process in Heroku in case of unrecoverable error? One of the 3rd party libraries rarely behaves oddly and gets application into some weird state that's not possible to recover from. So I made an escape hatch to catch the error and then I call process.exit(0) in hopes the Heroku would restart it.
Today was the first occurrence of this and unfortunately, it took Heroku about 10 minutes before it decided to restart the dyno. It kept spamming with error code=H10 desc="App crashed" along the way.
What could a better way to handle this so Heroku restarts immediately? I would like to avoid calling Heroku API, that's odd workaround.

A: First of all, I think your "escape hatch" is not a good practice to handle a "weird state" of your node application. You should tackle the problem heads-on, maybe remove that 3rd party library and make sure that your application works as expected, all the time.
That being said, the fact that "it took Heroku about 10 minutes" is because you are probably using their 'Common Runtime'. If you want your services to reboot immediately on failure, you will have to look at running them in their 'Private Spaces Runtime'.
From the docs:

The Common Runtime implements an incremental backoff policy for
crashing dynos
The Private Spaces Runtime does not have a backoff policy. When a dyno
crashes it will be continuously restarted with no cool-off period.

A: You can use Heroku api, this way you won't get this "App crashed" error:
https://devcenter.heroku.com/articles/platform-api-reference#dyno-restart
Don't forget to use Authorization header:
https://devcenter.heroku.com/articles/platform-api-reference#authentication


text:
Q: Rewriting Git history by untaring archives I'm currently converting a CVS repository to multiple git repositories.
The cvs2git process is fine, but then I have problems running the filter-branch commands. I test the commands with simple scripts because the main repository size is 4Go with more than 14k commits.
During the process, I want to replace some archives by their content in the history of the git repo.
Here is the script I use to test my filter-branch --tree-filter command:
#!/bin/bash

BASEDIR=/tmp/migration_git
if test ! -d $BASEDIR; then
 mkdir $BASEDIR
fi

script_tree_filter='\
archives=`find . -name "archive.tgz"`; \
CURDIR=`pwd`; \
for archive in $archives; do \
cd `dirname $archive`; \
tar xzf archive.tgz ; \
rm -f archive.tgz ; \
cd $CURDIR;\
done'

cd $BASEDIR
if test -d repo.server.git; then
  rm -rf repo.server.git;
fi
mkdir repo.server.git && cd repo.server.git && git init
touch a toto && tar czf archive.tgz a && rm a && git add . && git commit -am "1st commit" && git tag commit1
touch b a && rm archive.tgz &&  tar czf archive.tgz a b && rm a b && git commit -am "2nd commit" && git tag commit2
touch a b c && rm archive.tgz &&  tar czf archive.tgz a b c && rm a b c && git commit -am "3rd commit" && git tag commit3
# git rm archive.tgz && mkdir rep1 rep2
mkdir rep1 rep2
cd rep1 && touch a b c d && tar czf archive.tgz a b c d && rm a b c d && cd ..
cd rep2 && touch a b c d && tar czf archive.tgz a b c d && rm a b c d && cd ..
git add . && git commit -am "4th commit" && git tag commit4

cd $BASEDIR
if test -d repo.client.git; then
  rm -rf repo.client.git;
fi
git clone repo.server.git repo.client.git
cd $BASEDIR/repo.client.git

git filter-branch -f -d /tmp/test_git --tag-name-filter cat --prune-empty --tree-filter "$script_tree_filter" -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
git reflog expire --expire=now --all
git gc --prune=now

I have 2 questions:

*

*At the end the script shows an error during the process:

error: Untracked working tree file 'a' would be overwritten by merge.

If the client clone is done using --mirror:

git clone --mirror repo.server.git repo.client.git

the error won't appear. I don't understand why.

*When I cd to repo.client.git, the repository has local modifications: the archives are present and the files I wanted to keep are git removed. I don't understand neither.
Edit: either the files a, b, c, d are empty or not does not change the result.

A: After the remark of DomQ, I upgraded my version of Git (1.8.0 => 1.8.3) and the problem does not appear anymore.


text:
Q: Image Magick - complex character in Kannada (indic language) not being rendered properly I'm trying to use imagemagick to generate some images of Kannada text. The problem is that complex characters are being rendered separately (not together as they should be... imagine that "ku" should be one character, but it is rendered first as "k-" and then as "-u")
Concretely, ಗ್ರಾಮ ಕೋಡ್ gets rendered as this:

The command I am using is:
convert -background lightblue -fill blue -pointsize 48 -font '/Library/Fonts/Kannada Sangam MN.ttf' label:@Kannada_test.txt label_utf8.gif

On another program, TextEdit, the same font renders the text fine:
Any hints as to how I can get imagemagick to display these complex characters properly?

A: I'm afraid you can't, because ImageMagick seems to be incapable of handling combining marks. That is, it cannot combine them with preceding characters to produce proper graphic presentation but render a spacing glyph for the mark.


text:
Q: Does the "Bearer" Authorization header have any special meaning? Is there a difference between using a "Bearer" Authorization header and using a custom header? For example, the "Basic" Authorization header is different from a custom header because browsers treat "Basic" Authorization headers as a special case (some browsers cache the "Basic" Authorization header). In other words, is "Bearer" just an arbitrary string or do browsers know about it?
If I don't want future browsers to cache my bearer token, should I be safe and use a custom header?
For example, is there a difference between these (assuming my server can handle both):
header('Authorization: Bearer 12345');
header('Mysite-Bearer-Token: 12345');

A: Bearer token is defined by OAuth 2.0. You can get more details from https://www.rfc-editor.org/rfc/rfc6750.