text:
Q: NSFetchResultsController iOS4 I'm only getting this error in my app since upgrading to ios4.
newsDetailController.news = (News *)[self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"\n Indexpath of details news before pass = %@", [self.fetchedResultsController indexPathForObject:newsDetailController.news]);

Basically, this:
[self.fetchedResultsController indexPathForObject:newsDetailController.news])

returns NULL.
Why would this be?
newsDetailController.news isn't NULL.
Edit:
To highlight this:
NSLog(@"\n Indexpath of detailssss news before pass = %@", [self.fetchedResultsController indexPathForObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]);

... returns NULL, even though:
[self.fetchedResultsController objectAtIndexPath:indexPath]

...returns an object.

A: Are you positive that the news property (I am guessing it is a property on your detail view controller) is not nil?  Are you confirming your assumptions that both newsDetailController and newsDetailController.news are not nil?
iOS4 has brought with it proper non-fragile iVars.  If you were doing something incorrect in your @property declarations before that "worked" then the changes to iOS4 may now be catching that mistake.
Step one, walk the code in the debugger and make sure everything has a value that you expect to have a value.

A: Usually when something goes wonky with the indexes of a fetched results controller, it's because a mistake as been made with the section info e.g. adding a section key when you don't have sections. You should also not use the cache until you resolve the problem.
In this case, you also want to make sure that news is an object that represents a complete entity. If you use a keypath as the object to return at the indexpath, it has to be an object at the other end of a relationship, it can't be an object (such as an NSString) that holds the data of an attribute.
If news is a relationship, the FRC walks the object graph and returns the indexPath. However, if news is just an attribute, then it has no indexPath because indexPaths only describe the route to an entity in the object graph.


text:
Q: SSL error using curl/wget Recently, I started seeing this problem on my Mac.  I am able to download files or visit any https web page from Chrome, but I am not able to do that anymore with either curl or wget.
$ curl --verbose https://www.google.com/
*   Trying 2607:f8b0:4007:803::2004...
* TCP_NODELAY set
* Connected to www.google.com (::1) port 443 (#0)
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /Users/tomkwong/anaconda3/ssl/cacert.pem
  CApath: none
* TLSv1.2 (OUT), TLS header, Certificate Status (22):
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to www.google.com:443
* Closing connection 0
curl: (35) OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to www.google.com:443

Here's the wget error:
$ wget --verbose https://www.google.com/
--2018-03-27 23:53:32--  https://www.google.com/
Resolving www.google.com (www.google.com)... 2607:f8b0:4007:803::2004, 172.217.14.68
Connecting to www.google.com (www.google.com)|2607:f8b0:4007:803::2004|:443... connected.
GnuTLS: The TLS connection was non-properly terminated.
Unable to establish SSL connection.

More information by using openssl command as requested.  I'm unsure what to make sense out of it... looks like errno=54 means "Connection reset by peer".
$ openssl s_client -debug -connect www.google.com:443 -prexit
CONNECTED(00000003)
write to 0x7feb37558870 [0x7feb3800ca00] (307 bytes => 307 (0x133))
0000 - 16 03 01 01 2e 01 00 01-2a 03 03 73 60 8a 49 d5   ........*..s`.I.
0010 - ad 36 db 41 da 14 20 c9-85 7b f8 5b 2b b3 2b c0   .6.A.. ..{.[+.+.
0020 - b6 47 e1 c5 b9 75 b9 c2-9d d9 1c 00 00 ac c0 30   .G...u.........0
0030 - c0 2c c0 28 c0 24 c0 14-c0 0a 00 a5 00 a3 00 a1   .,.(.$..........
0040 - 00 9f 00 6b 00 6a 00 69-00 68 00 39 00 38 00 37   ...k.j.i.h.9.8.7
0050 - 00 36 00 88 00 87 00 86-00 85 c0 32 c0 2e c0 2a   .6.........2...*
0060 - c0 26 c0 0f c0 05 00 9d-00 3d 00 35 00 84 c0 2f   .&.......=.5.../
0070 - c0 2b c0 27 c0 23 c0 13-c0 09 00 a4 00 a2 00 a0   .+.'.#..........
0080 - 00 9e 00 67 00 40 00 3f-00 3e 00 33 00 32 00 31   ...g.@.?.>.3.2.1
0090 - 00 30 00 9a 00 99 00 98-00 97 00 45 00 44 00 43   .0.........E.D.C
00a0 - 00 42 c0 31 c0 2d c0 29-c0 25 c0 0e c0 04 00 9c   .B.1.-.).%......
00b0 - 00 3c 00 2f 00 96 00 41-00 07 c0 11 c0 07 c0 0c   .<./...A........
00c0 - c0 02 00 05 00 04 c0 12-c0 08 00 16 00 13 00 10   ................
00d0 - 00 0d c0 0d c0 03 00 0a-00 ff 01 00 00 55 00 0b   .............U..
00e0 - 00 04 03 00 01 02 00 0a-00 1c 00 1a 00 17 00 19   ................
00f0 - 00 1c 00 1b 00 18 00 1a-00 16 00 0e 00 0d 00 0b   ................
0100 - 00 0c 00 09 00 0a 00 23-00 00 00 0d 00 20 00 1e   .......#..... ..
0110 - 06 01 06 02 06 03 05 01-05 02 05 03 04 01 04 02   ................
0120 - 04 03 03 01 03 02 03 03-02 01 02 02 02 03 00 0f   ................
0130 - 00 01 01                                          ...
read from 0x7feb37558870 [0x7feb38012000] (7 bytes => -1 (0xFFFFFFFFFFFFFFFF))
write:errno=54
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 307 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1522221838
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---
---
no peer certificate available
---
No client certificate CA names sent
---
SSL handshake has read 0 bytes and written 307 bytes
---
New, (NONE), Cipher is (NONE)
Secure Renegotiation IS NOT supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1.2
    Cipher    : 0000
    Session-ID:
    Session-ID-ctx:
    Master-Key:
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    Start Time: 1522221838
    Timeout   : 300 (sec)
    Verify return code: 0 (ok)
---

A: Rebooting the computer fixes the problem!
I should have thought about that earlier :-)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to avoid multiple for loops I am new in JavaScript data structure. I am working on linked list in JavaScript. I want to create a function which can find the distance between nodes. I have created a function which work perfectly what i want. But i think this is not the way of writing time efficient code. Is there any way to replace those for loops in distance function to any other code that can give the same result with the time efficiency. Here is the distance function code.
linkList.prototype.distance = function (val1, val2) {
let node1 = this.search(val1);
let node2 = this.search(val2);
let info = {};
let node1Values = [...Object.keys(node1)];
let node2Values = [...Object.keys(node2)];
for (let i = 0; i < node1Values.length; i++){
    for (let j = 0; j < node2Values.length; j++){
        info[`Distance From ${node1Values[i]} To ${node2Values[j]} is:`] =
Math.abs(node1[node1Values[i]].Index - node2[node2Values[j]].Index);
    }
}
return info;
};

Here is the search function code which is used by distance function.
linkList.prototype.search = function (value) {
let info = {};
let curNode = this.head;
let c = 0;
let duplicate = 1;
while (curNode) {
    if (curNode.value === value) {
        let info_arr = {};
        let val = curNode.value;
        let next = null;
        if (curNode.next) {
            next = curNode.next.value;
        }
        let prev = null;
        if (curNode.prev) {
            prev = curNode.prev.value;
        }
        let index = c;
        info_arr["Value"] = val;
        info_arr["Index"] = index;
        info_arr["Next"] = next;
        info_arr["Prev"] = prev;
        if (info[curNode.value]) {
            info[curNode.value + ":" + duplicate] = info_arr;
            duplicate++;
        } else {
            info[curNode.value] = info_arr;
        }

        }
        curNode = curNode.next;
        c++;
        }
        return info;
        };

Here is the output of distance function when i console log it.


text:
Q: r markdown could not find function "%>%" error I am working on the google data analytics certificate and kind of just messing around. But I was trying to create a markdown in r with some code chunks. Everything is working except one chunk. When I run that chunk in r console it works just fine, but when I run knitr I get an error.
The code chunk is as follows:

average_mass<-penguins %>% select(species,body_mass_g) %>% drop_na() %>% group_by(species) %>% summarize(avg_body_mass=mean(body_mass_g))

ggplot(average_mass,aes(species,avg_body_mass,fill=species))+geom_col()+
  labs(title="Penguins: Average Body Mass By species",caption="Gentoo is the Largest")

but when I run knitr the result is this:
Error in penguins %>% select(species, body_mass_g) %>% drop_na() %>% group_by(species) %>% : could not find function "%>%"
Error in ggplot(average_mass, aes(species, avg_body_mass, fill = species)): object 'average_mass' not found
Obviously since I'm just messing around its not a big deal but was kind of curious if there was a way to resolve this issue??


text:
Q: Convert signed to unsigned int column How can I convert a signed int column to unsigned in MySQL?
I set a column to signed in CREATE TABLE and need to set it to UNSIGNED now.

A: Syntax:
ALTER TABLE tbl_name MODIFY [COLUMN] col_name column_definition [FIRST | AFTER col_name]

Example:
ALTER TABLE tbl_name MODIFY col_name bigint(20) unsigned NOT NULL default '0';

Reference

A: You can use ALTER TABLE to change the datatype of your table column. It can be done as follows -
ALTER TABLE table_name MODIFY column_name UNSIGNED INT;

Read more about ALTER TABLE here


text:
Q: Probablity/Statistical Inference Important Questions (problems) Collection for Interviews and Understanding of Concept This might be irrelevant here! But I would really appreciate your help! It would definitely help lot of us preparing for Interviews in Data Science domain.
I am looking for a book/github/ any resource where I can find Probablity & STatistical Inference questions/puzzles (just like leetcode has programming) to prepare for interviews.
Any suggestions on books/resources which has probablity problems I can solve to get thorough on all sort of probablity and statistical inference questions.
Thank you

A: Unfortunately there are no resources yet for data science/machine learning interviews that are on par with Cracking the Coding Interview, Heard on the Street or LeetCode.
There are various websites that collect interview questions, but they usually do not provide detailed answers. Here are some examples:
100+ Data Science and Machine Learning Interview Questions
Curated list of 70 data science interview questions
How to Prepare for a Machine Learning Interview
Acing AI Interviews
100+ Basic Deep Learning Interview Questions and Answers
This Stats.SE thread is also relevant.
For probability questions you can rely on quantitative finance books such as Heard on the Street and the likes.


text:
Q: Unable to connect to my aws elasticache cluster I am not able to connect to my aws elasticache cluster from my local machine.
Is it possible to connect to the cluster from my local machine?

A: You cannot connect to Elastic cluster through your local instance . You can connect only through EC2 instances .


text:
Q: Access files from a location in Android I am trying to access(only read) the list of files available in a location in android device using below code but I am getting null as a response. Please correct me if I am missing something. I tried the below code in Android 11 and I am expecting it should work from Android 9 onwards.
File[] files = new File("/storage/emulated/0/Android/data/MyApp/files/").listFiles();

I am getting null for the above code. Also I add the below permissions in my AndroidManifest.xml file.
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Also having the permission granting request in code as well and added the below attribute in the application tag in AndroidManifest.
android:requestLegacyExternalStorage="true"

After adding all the above still I am facing the issue to get the files from the given location.
Am I doing it in a right way? My objective is to access the files after the application is launched and these files will be added manually into the location by user using ADB commands.

A: please try this way
for internal files (/data/data)
File[] files = getApplicationContext().getFilesDir().listFiles();

for external files (/sdcard)
File[] files =  getApplicationContext().getExternalFilesDirs("your path");


text:
Q: How can i use additional fields to get jwt token i use https://django-rest-framework-simplejwt.readthedocs.io/en/latest/
i have such code
User = get_user_model()

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField()
    ROLE_CHOICES = [
        ('U', 'User'),
        ('M', 'Moderator'),
        ('A', 'Admin'),
    ]
    role = models.CharField(max_length=1, choices=ROLE_CHOICES, default='U')
    confirmation_code = models.CharField(max_length=30)

And i want to get JWT token, here is my urls
path("v1/token/", views.EmailTokenObtainPairView.as_view(), name="token_obtain_pair")

i need send such POST query
http://127.0.0.1:8000/api/v1/token/

with data :
{ 'email': email, 'confirmation_code': confirmation_code }

but by default in simple-jwt i need to send data :
{'username' : username, 'password':password }

in my serializer.py
class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
    username_field = User.EMAIL_FIELD

in my views.py
class EmailTokenObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenObtainPairSerializer

i have done to chane username on email, bun i can not chane password on confirmation_code
how can i change default way ?

A: You can override TokenObtainSerializer to customize.
For your case, you need to custom method validate(). Refer to this link https://django-rest-framework-simplejwt.readthedocs.io/en/latest/customizing_token_claims.html and https://github.com/SimpleJWT/django-rest-framework-simplejwt/blob/c684e8396f8446cc289ed73a0740ca222c85470d/rest_framework_simplejwt/serializers.py#L20 for detail.


text:
Q: How to insert widget areas specific to certain pages (or posts, etc.)? I am developing a theme the pages of which (as well as posts) are so different from the home page that I want different widgets on their sidebars.Is there a way to do it?
I'm calling the sidebar on single.php this way, exactly as it's on index.php:
<?php get_sidebar(); ?>

The sidebar.php is this way:
<?php
/**
 * The Sidebar containing the primary and secondary widget areas.
 ?>

<?php
    /* When we call the dynamic_sidebar() function, it'll spit out
     * the widgets for that widget area. If it instead returns false,
     * then the sidebar simply doesn't exist, so we'll hard-code in
     * some default sidebar stuff just in case.
 */
if ( ! dynamic_sidebar( 'primary-widget-area' ) ) : ?>

    <?php endif; // end primary widget area ?>

<?php
    // A second sidebar for widgets, just because.
    if ( is_active_sidebar( 'secondary-widget-area' ) ) : ?>

                <?php dynamic_sidebar( 'secondary-widget-area' ); ?>

<?php endif; ?>

A: Use Conditional Tags to show content only if a certain condition is met.
In your case, you're probably looking to use is_front_page().

    <?php
        if ( function_exists( 'dynamic_sidebar' ) ) {
             if ( is_front_page() ) {
                 if ( ! dynamic_sidebar( 'frontpage-widget-area' ) ) {
                     echo '
No sidebars for the frontpage.
'; // some default output
                 }
             } else {
                 if ( ! dynamic_sidebar( 'primary-widget-area' ) ) {
                     echo '
No sidebars for posts/pages.
'; // some default output
                 }
             }
        } else {
            echo '
Sidebars disabled.
'; // some default output
        }
    ?>

That's assuming, the two widget areas have been properly registered via register_sidebar() beforehand.


text:
Q: How to create a Paypal Buy Now button for a mobile checkout from a mobile website? I have a mobile web page with a Paypal Buy Now button and I want it to send users to a mobile friendly Paypal checkout. I'm getting really confused with documentation about for checkouts in mobile apps, but all I want is a mobile browser checkout. Can I just add an extra param to a buy now button? I've been looking at this but I think perhaps this is for mobile apps. http://code.google.com/p/paypalmobile/
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="xxxxxxxxxxx">
<input type="image" src="https://www.paypalobjects.com/en_US/GB/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online.">
<img alt="" border="0" src="https://www.paypalobjects.com/en_GB/i/scr/pixel.gif" width="1" height="1">
</form>

A: I've not found a way to use a Buy It Now button but have managed to get it working by utilising the Paypal SetExpressCheckout method in the Express Checkout API (https://api-3t.paypal.com/nvp). This returns a Token which you use to redirect to Paypal
https://www.paypal.com/webscr?cmd=_express-checkout&token=RETURNED_TOKEN
If you use Express Checkout Paypal automatically uses mobile checked when accessed by a mobile.
https://cms.paypal.com/cms_content/US/en_US/files/developer/PP_ExpressCheckout_IntegrationGuide.pdf

A: for mobile billing please change the url  with cmd hidden

header('location:https://mobile.paypal.com/wc?t='.$querystring);
it is device recognize URL when u are open in dektop it differnt look and mobile showing like express checkout on top showing it's amount


text:
Q: [resolved]instanceDoesNotExist after upgrading cloudsql-proxy to v1.31.0 I'm using Mac m1 machine and I wanted to upgrade to v 1.31.0 which make cloud-proxy ARM friendly. Here is a sample of my proxy file(which was working fine with the previous cloudsql-proxy versions)
    apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: db-proxy
  name: db-proxy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: db-proxy
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 0
    type: RollingUpdate
  template:
    metadata:
      labels:
        app: db-proxy
      name: db-proxy
    spec:
      containers:
      - command:
        - /cloud_sql_proxy
        - --dir=/cloudsql
        - -instances= ...some instances here
        - -credential_file=...file path
        image: gcr.io/cloudsql-docker/gce-proxy:1.31.0
        imagePullPolicy: IfNotPresent
        name: cloudsql-proxy
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /credentials
          name: db-proxy-credentials
          readOnly: true
        - mountPath: /etc/ssl/certs
          name: ssl-certs
        - mountPath: /cloudsql
          name: cloudsql
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      volumes:
      - name: db-proxy-credentials
        hostPath:
          path: ...
          type: Directory
      - hostPath:
          path: /etc/ssl/certs
          type: ""
        name: ssl-certs
      - emptyDir: {}
        name: cloudsql

And this is the error that i'm getting while starting the pod
googleapi: Error 404: The Cloud SQL instance does not exist., instanceDoesNotExist

Update :
As per first comment the problem was wrong naming of some instances.
the old version doesn't crash the pod if instance is not there, but the latest version does.

A: 404 error appears because of the wrong naming of the Cloud SQL instances or if the instance doesn't exist. The older version of Cloud SQL Auth proxy doesn't crash the pod if the instance is not there, but the latest version does and hence the error.  @Omar Ahmed confirmed the  issue was solved by reviewing the instance names.


text:
Q: Why require only R >= 3.3.0? I'm building a R model in Azure machine learning with a zipped xgboost package attached to the 'execute R script'.
Azure machine learning uses R 3.2.2.
The model returns with an error saying "This is R 3.2.2, package 'xgboost' needs >= 3.3.0".
Is there any reason it insists on >= 3.3.0. If not, can I get it down to run with R 3.2.2?


text:
Q: how to setup "Get started" button in facebook messenger bot I m trying to use postman
link:https://graph.facebook.com/v6.0/me/messages?access_token=my_token
{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}

in raw JSON body
but getting this response
{
    "error": {
        "message": "(#100) Tried accessing nonexisting field (messages) on node type (Page)",
        "type": "OAuthException",
        "code": 100,
        "fbtrace_id": "AtFh2_fJ2sxkeU8k-2aNJGl"
    }
}

A: Here is the little rundown how to put get started button , I hope its help:
Using postman:

*

*Start by changing the type by choosing a POST request: (one of the
problems that solve my issue thanks to @misorude

*Define a Post request to this URL:

https://graph.facebook.com/v6.0/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>

As @misorude notice my another problem check endpoint from here https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api

*In the BODY section:

.
Paste this code:
{
  "get_started":{
    "payload": "Hi, I am bot"
  }
}

P.S.
Thank you again


text:
Q: Trigger one async call after another is resolved I am trying to learn something about async controller in asp.net
so i created one controller:
[Route("api/[controller]")]
public class SummonerController : Controller
{
    [HttpGet("[action]/{name}")]
    public async Task<SummonerDTO> GetSummonerData(string name)
    {
        SummonerEndPoint endPoint = new SummonerEndPoint();
        Task<SummonerDTO> data =  endPoint.GetSummonerData(name);
        var readed = await data;
        MatchesEndPoint endPoint2 = new MatchesEndPoint();
        var data2 = endPoint2.GetMatches(data.Result.accountId.ToString());
        var readed2 = await data2;
        return await endPoint.GetSummonerData(name);
    }
}

As you can see in second request i use data i receive from first one.
I am aware of that there is a chance that second request will be resolved before first one.
So my question is is there a way  to make sure that second call is triggered after first one ended?
combining both results into one dto is another thing but i wont put it to this question

A: If you await the Task, which you're already doing, you're fine. They would only overlap if you call the async method and don't await it.
As a side note,
var result = await task;

waits for a task to complete asynchronously and gets the result.
var result = task.Result;

waits for a task synchronously (blocking the thread).
You can change your code to
var summonerEndPoint = new SummonerEndPoint();
var summonerData =  await summonerEndPoint.GetSummonerData(name);
var matchesEndPoint = new MatchesEndPoint();
var matches = await matchesEndPoint.GetMatches(summonerData.accountId.ToString());
return summonerData;


text:
Q: jQuery: $.append and $.html are not working This should straightforward but I have no idea what is wrong.
I am making an ajax call when there is onblur event on a text field. Ajax request goes to backend and gets the response. Then I have to append that response next to the text field. But it's not working.
HTML
<input type="text" required="" id="123456" onblur="validateWithDB(this)"></input>

Javascript
function validateWithDB(field)
            {
                $.ajax({
                    type:"POST",
                    url:"validate",
                    data: "fieldValue="+field.value,
                    success: function(response) {
                        alert(response);// this is correct
                        alert($(field).val());// this is correct
                        var result = ''+response+''
                        alert(result) // this is correct
                        $(field).html(result);// Does not show up.
                    },
                    error:function (xhRequest, ErrorText, thrownError) {
                        alert('Error: '  + '  ' + xhRequest);
                    }
                });
            }

I tried both $(field).html(result); and $(field).append(result); but no luck.

A: If you want the span NEXT to the input, use .after()
$(field).after(result);

A: Try this:
$(field).val(result);

If you want to append span after input use this:
$(field).after(result)

A: As tymeJV asid in the comment, you can't put HTML inside the input tag.
You can either set it as the value using $(field).val(result) but this doesn't make much sense.
Or you can insert it after using .after:
$(field).after(result);

This will display the HTML in result directly after the input.


text:
Q: Looking for a library for encoding/decoding MPEG-2 Can someone recommend to me a good .NET library that can encode and decode MPEG-2 files? If the library can make VOBs for DVD movies, that'd be a plus. I'm looking for something C# specifically.

A: You could consider the library at the following link:
http://nolovelust.com/post/Another-Simple-C-Wrapper-For-FFmpeg.aspx
Open FFMPEG is a library that has been around for quite some time.
The project at the link mentioned seems to have done what you seek.
You can download the source files from:
http://www.mediafire.com/?z7t7uqztp871xm7
I checked the download link. It works.


text:
Q: redirect subdirectory to subdomain issue I have .htaccess file like:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
RewriteRule ^/?market/(.*)$ http://market.example.com/$1 [L,R=301]
RewriteRule ^/?buddies/(.*)$ http://buddies.example.com/$1 [L,R=301]
RewriteRule ^/?bazaar/(.*)$ http://bazaar.example.com/$1 [L,R=301]

It works fine in market subdirectory. It redirects to the subdomain. But, There is a problem with other 2 subdirectories.
ERROR FOR OTHER 2 sub-domains:
The page isn't redirecting properly

What should I do to overcome this problem?

A: It is because RewriteCond is only applicable to the very next RewriteRule. Your last 2 rules execute for all the hosts including buddies and bazaar and causes redirection loop.
You need these rules:
RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
RewriteRule ^/?market/(.*)$ http://market.example.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
RewriteRule ^/?buddies/(.*)$ http://buddies.example.com/$1 [L,R=301]

RewriteCond %{HTTP_HOST} ^(www\.)?example.com$ [NC]
RewriteRule ^/?bazaar/(.*)$ http://bazaar.example.com/$1 [L,R=301]


text:
Q: How to distinguish git ignored files and directories in NERDTree I want the NERDTree to show files and directories ignored by Git in light color (i.e., dimmed) to distinguish them from tracked files and directories. How can this be done?
Thanks.

A: Modified from nerdtree-git-plugin, this snippet will auto highlight ignored files using Commment for new version NERDTree without |- similar prefix (which cause sync match failure?).
function! GitDimIgnoredFiles()
    let gitcmd = 'git -c color.status=false status -s --ignored'
    if exists('b:NERDTree')
        let root = b:NERDTree.root.path.str()
    else
        let root = './'
    endif
    let files = split(system(gitcmd.' '.root), '\n')

    call GitFindIgnoredFiles(files)
endfunction

function! GitFindIgnoredFiles(files)
    for file in a:files
        let pre = file[0:1]
        if pre == '!!'
            let ignored = split(file[3:], '/')[-1]
            exec 'syn match Comment #\<'.escape(ignored, '~').'\(\.\)\@!\># containedin=NERDTreeFile'
        endif
    endfor
endfunction

autocmd FileType nerdtree       :call GitDimIgnoredFiles()


text:
Q: Prefix all requests in JSON Server with middleware I'm using the JSON Server package (json-server) from https://github.com/typicode/json-server. I'd like to make the server prefix all requests with /api/v2. The documentation even gives an example how to do this with the following:
server.use('/api', router)
However I don't want to setup my own server instance but extend the default when running json-server.
Can I somehow use the above statement in a middleware?

A: Since the router that json-server returns to you is an Express router.
First define all of your /v1, /v2, etc in its own routes file as show below:
// api-routes.js
const express = require('express')
const jsonServer = require('json-server')

const router = express.Router()
const server = jsonServer.create()
const middlewares = jsonServer.defaults()
const v1Router = jsonServer.router('db-v1.json')
const v2Router = jsonServer.router('db-v2.json')

router.use('/v1', v1Router)
router.use('/v2', v2Router)

module.exports = router

Then mount your API router onto /api like so:
const express = require('express')
const apiRoutes = require('./api-routes')

const app = express()
app.use('/api', apiRoutes)

// ...

Should now have /api/v1 and /api/v2. Untested code above, but should give an idea what you need to do.


text:
Q: pointer changes unexpectedly despite not being changed out of scope I am writing code here to try and replicate virtual memory in C. For some reason, a pointer I create and maintain within main get changed unexpectedly after being passed into a function. Here is my code in main
int main(){

    void * a = a_malloc(sizeof(int)*2);
    printf("1 a:%p\n",a);//1 a:0x1
    int x = 9;
    int y = 0;
    put_value(a,(void*)&x,sizeof(int));
    printf("2 a:%p\n",a);//2 a:0x1
    get_value(a,(void*)&y,sizeof(int));
    printf("3 a:%p\n",a);//3 a:0x8049050
    printf("y:%d\n",y);//y:9
    printf("4 a:%p\n",a);//4 a:0x8049050
    a_free(a,sizeof(int));

}

The code works as expected (y correctly holds the value 9), however, the pointer 'a' gets changed from its initial value (0x1) to a new value (0x8049050) after a call to get_value. Whats interesting though is that it was not changed after put_value, which does an extremely similar thing to get_value, and neither should be able to change the pointer 'a' which is local to main. The code for those two functions is
/* The function copies data pointed by "val" to physical
* memory pages using virtual address (va)
*/
void put_value(void *va, void *val, int size) {

   int pages = (int)(ceil((double)size/PGSIZE));
   int c=0;
   for(c=0;c<pages;c++){

       unsigned int addr = (unsigned int)va + (c*PGSIZE);
       void * pa = translate((void*)addr);
       addr = (unsigned int)val + (c*PGSIZE);
       memcpy(pa,(void*)addr,PGSIZE);
       c++;

   }
}

/*Given a virtual address, this function copies the contents of the page to val*/
void get_value(void *va, void *val, int size) {

   int pages = (int)(ceil((double)size/PGSIZE));
   int c=0;
   for(c=0;c<pages;c++){

       unsigned int addr = (unsigned int)va + (c*PGSIZE);
       void * pa = translate((void*)addr);
       addr = (unsigned int)val + (c*PGSIZE);
       memcpy((void*)addr,pa,PGSIZE);
       c++;

   }
}

PGSIZE is a header defined value, which is defined in my testing as 4096. translate really is irrelevant here, but just in case
/*
The function takes a virtual address and page directories starting address and
performs translation to return the physical address
*/
void *translate(void *va) {

    translation =((page_directory[get_top_bits((unsigned)va)]).pagetable[get_mid_bits((unsigned)va)]).paddr;

    return translation;

}

I have stepped through the code multiple times using GDB and I can't find exactly where 'a' is being reset, or even how its being reset. Because it is being reset, the call to a_free segfaults (as it calls translate, which uses the wrong address in trying to access our defined page directory and page tables) Any advice would be helpful. Thanks.


text:
Q: Should I backup my older questions because they could be deleted? A few of my older questions have been deleted. I know they existed but I don't remember their titles. Maybe some of them were closed but with very useful answers.
Is there an authority who can do this without notifying me? If not, why I haven't been notified?
Are my deleted questions backed up for some time period (e.g. a year) or should I make the backup myself immediately I have a useful answer?
EDIT (little off topic): This is another question that has been deleted. This is not my question, but has many interesting answers and I have it in my bookmarks if Firefox. I can't read it anymore. Though I found a copy on stackprinter website which saved it.
EDIT another interesting question that has dead link.

A: You should make a backup of anything you give to a third-party provider.  If a dragon destroyed Stack Exchange tomorrow and your questions/answers went away what would you do? What would you DO??

A: David's already given you some good background information here, but I'd like to provide you with a bit of a sanity-check lest you think your questions might be getting deleted out from under you without warning...

*

*You have 34 deleted questions.

*Of these, 27 were deleted... By you.

*Of those remaining, 3 were deleted automatically after being migrated.

*Of the last 4, all but one were deleted by moderators after you flagged to ask that they be deleted.

*The last one was deleted because you cross-posted it on another site.
This is pretty typical. If a moderator needs to go in and delete your posts without your permission, and your account is in good standing otherwise, they'll usually post a comment detailing why first (assuming no one else has already done so). When no reason is given, you can usually assume it's one of the standard reasons listed in the FAQ.

A:
A few of my older questions have been deleted. I know they existed but I don't remember their titles. Maybe some of them were closed but with very useful answers.

If a question has useful answers, it may be closed, but it's not likely to be deleted. Deletion is for content which really contributes nothing useful to the site.

Is there an authority who can do this without notifying me? If not, why I haven't been notified?

Yes, you are not notified when a question of yours is deleted (as far as I know).

Are my deleted questions backed up for some time period (e.g. a year) or should I make the backup myself immediately I have a useful answer?

Deletion on Stack Exchange is a "soft deletion" which means the content is really just made invisible to most users, not really deleted. Accordingly there is no need for it to be backed up (beyond the backups that are already done for the whole SE network). Any deleted content can still be seen by moderators and users with over 10000 reputation.
If you need to get access to your deleted content, you might be able to ask a moderator to copy it into a meta post for you.


text:
Q: Nginx rewrite address does not automatically add parameters Original request address:
www.example.com/index.php?r=mobile/receive/index

Rewritten request address:
www.example2.com/newindex.php?r=mobile2/receive2/index2

Here is my own configuration:
if ($args ~* "^r=mobile/receive/index") {
    rewrite ^ "http://www.example2.com/newindex.php?r=mobile2/receive2/index2";
}

But the end of the rewritten address is like this:
http://www.example2.com/index.php?r=mobile2/receive2/index2&r=mobile/receive/index

Do you see my problem? The rewritten address is automatically added, but this is not what I want. The same parameter keys will result in the back cover front.

A: In order to prevent the original query string being appended to the target URL you need to include an additional question mark (?) at the end of the rewritten URL. For example:
rewrite ^ http://www.example2.com/newindex.php?r=mobile2/receive2/index2?;

Reference:
http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite


text:
Q: I keep getting a NaN when calculating numbers Whenever I put the following into a program it always comes back with NaN. Does anybody know why? Is there a way I can fix this?
double test = -1.17425 * (pow(10, 3)) / (5.75 * (pow(10, 6)));
System.out.print(test);

A: Works just fine on my computer. I get:
-2.0421739130434784E-4
Which math library are you using? Try this:
double test = -1.17425*(Math.pow(10,3))/(5.75*(Math.pow(10,6)));


text:
Q: Scrapy Spider not writing to Postgres in the correct format I'm scraping the Science of Us website for articles related to mental health and trying to dump it to a postgres database I'm running locally. The scrapy output is stored in a dictionary that looks like articles = {'title': [], 'teaser': [], 'link': [], 'date': [], 'author': [], 'source': []}
On running my code, it dumps the entire list of values for each key into the column with name == key. Instead, I would like each article to be one row in the database e.g. Article 1 would have its own row with its title, teaser, link, date, author and source in each of the columns.
Here is the relevant code:
1) spider.py
from scrapy.spiders import Spider
from scrapy import Request
from mhnewsbot_app.items import SOUItem
import string

mh_search_terms = ["DEPRESS", "MENTAL HEALTH", "EMOTIONAL HEALTH", "MENTAL DISORDER", "DIGITAL MEDICINE", "ANXI", "PSYCH", "THERAPY", "THERAPIST"]
tbl = string.maketrans('-', ' ') #To protect against cases where the article has hyphens or other special characters

articles = {'title': [], 'teaser': [], 'link': [], 'date': [], 'author': [], 'source': []}

def url_lister():
  url_list = []
  article_count = 0
  while article_count < 150:
    url = 'http://nymag.com/scienceofus/?start=%s' %article_count
    url_list.append(url)
    article_count += 50
  return url_list

class SOUSpider(Spider):
  name = 'scienceofus'
  start_urls = url_lister()

def parse(self, response):
    for article in response.xpath('//ul[@class="newsfeed-article-list"]'):
        title = article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/a[@class="headline-link"]/h3[@class="headline"]').extract()
        for i in title:
            for search_term in mh_search_terms:
                if search_term in i.upper().strip():
                    articles['title'].append(article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/a[@class="headline-link"]/h3[@class="headline"]/text()').extract()[title.index(i)])
                    articles['teaser'].append(article.xpath('.//li[contains(@class, "newsfeed-article")]/p[@class = "teaser"]/text()').extract()[title.index(i)])
                    articles['link'].append(article.xpath('.//li[contains(@class, "newsfeed-article")]/a[@class = "read-more"]/@href').extract()[title.index(i)])
                    articles['date'].append(article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/div[@class="headline-above"]/time/text()').extract()[title.index(i)])
                    articles['author'].append(article.xpath('.//li[contains(@class, "newsfeed-article")]/span[@class="by-authors"]/span/span[@class="author"]/text()').extract()[title.index(i)])
                    articles['source'].append('Science Of Us')
    return articles

2) pipelines.py
from sqlalchemy.orm import sessionmaker
from models import Articles, db_connect, create_articles_table

class ArticlesPipeline(object):
  def __init__(self):
      engine = db_connect()
      create_articles_table(engine)
      self.Session = sessionmaker(bind=engine)

def process_item(self, item, spider):
  session = self.Session()
    article = Articles(**item)

    try:
        session.add(article)
        session.commit()
    except :
        session.rollback()
        raise
    finally:
        session.close()

    return item

A: you are outputting 1 item, with multiple values on their fields, better output one item per value, because that's how your database seems to accept it:
 def parse(self, response):
for article in response.xpath('//ul[@class="newsfeed-article-list"]'):
    title = article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/a[@class="headline-link"]/h3[@class="headline"]').extract()
    for i in title:
        for search_term in mh_search_terms:
            if search_term in i.upper().strip():
                article_item = {}
                article_item['title'] = article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/a[@class="headline-link"]/h3[@class="headline"]/text()').extract()[title.index(i)]
                article_item['teaser'] = article.xpath('.//li[contains(@class, "newsfeed-article")]/p[@class = "teaser"]/text()').extract()[title.index(i)]
                article_item['link'] = article.xpath('.//li[contains(@class, "newsfeed-article")]/a[@class = "read-more"]/@href').extract()[title.index(i)]
                article_item['date'] = article.xpath('.//li[contains(@class, "newsfeed-article")]/div[@class="headline-wrapper"]/div[@class="headline-above"]/time/text()').extract()[title.index(i)]
                article_item['author'] = article.xpath('.//li[contains(@class, "newsfeed-article")]/span[@class="by-authors"]/span/span[@class="author"]/text()').extract()[title.index(i)]
                article_item['source'] = 'Science Of Us'
                yield article_item


text:
Q: WCF Web Service Authentication based on AD groups I have a WCF Web Service which is being consumed by a C# client application, and I also have 4 groups stored in Active Directory. Client application should connect this web service by passing login credentials.
Requirement:

*

*Restrict web service functionality based on windows user credential's group stored in AD (Active Directory)

*Pass specific user credentials from the client application to this web service

Question:
How to authenticate or validate logged in user on connecting to this web service, which event handler function will be invoked to validate logged in user credentials.
If anybody knows about this then please do let me know

A: You need to two keep concepts apart:

*

*AUTHENTICATION is the process of determining who it is that's calling you, and making sure he really is who he claims to be; this can be done using username/password, Windows credentials (he had already authenticated himself to his Windows box through logging on), or by requiring the caller to have some information (certificate)

*AUTHORIZATION is the process - once you know who is calling you, to determine what that caller can do (or what he cannot do)
In order to use Active Directory groups, you need to use a security mode in WCF that supports Windows credentials. The easiest is to use Windows credentials from the beginning, which is the default for wsHttpBinding and netTcpBinding - in this case, the caller will always pass along his Windows credentials with every call, and you can inspect those on the server side by looking at the ServiceSecurityContext.Current.WindowsIdentity:
WindowsIdentity caller = ServiceSecurityContext.Current.WindowsIdentity;

This works well in an Intranet scenario - everyone is behind a corporate firewall and authenticated on their machines anyway. In order to enable this, just use wsHttp or netTcp binding (I'd recommend netTcp in this case).
The other slightly more complicated case is when you have your client present a X.509 certificate, and you then map that on the server side to an existing AD user in your network. That's rather advanced, however.
Once your caller is authenticated, e.g. you know who is calling, you can use the regular role-based security model to limit privileges. Just add [PrincipalPermission(....)] attributes to your methods that you want to protect, and if the user doesn't match any of those requirements, a security exception will the thrown and the method will not be executed.
    [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
    [PrincipalPermission(SecurityAction.Demand, Name = "JohnDoe")]
    public string SayHello(string caller)
    {
     ......
    }

You can have multiple of those "PrincipalPermission" attributes, and they're matched together in an "OR"-fashion - if any one of them matches the current caller, he'll be allowed to make the call.
Check out page 4 of this article Fundamentals of WCF Security for more details on how to use role-based security.
Marc


text:
Q: C# update custom config section programmatically I can easily update the app settings dynamically like
System.Configuration.Configuration configDefault = null;
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                        fileMap.ExeConfigFilename = configFileName;
                        configDefault = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);

configDefault.AppSettings.Settings[key].Value = "some value";

How can I replace the existing config section values in memory, I don't want to update the app.config itself? Current app.config looks like:
 <SomeCustomSection>
    <group name="mygroup" isenabled ="true">
      <subscriber name="customer" log="true" isenabled="false"/>
      <subscriber name="order" log="true" isenabled="false"/>
    </group>
  </SomeCustomSection>

I am overriding the config values from another config file.
SomeConfiguration sectionClient = (SomeConfiguration)configClient.GetSection("SomeCustomSection");
SomeConfiguration sectionDefault = (SomeConfiguration)configDefault.GetSection("SomeCustomSection");
foreach (var groupClient in sectionClient.Groups)
{
    var groupDefault = sectionDefault.Groups[groupClient.Name];
    groupDefault.IsEnabled = groupClient.IsEnabled;
    foreach(var sub in groupClient.Subscribers)
    {
        var subDefault = groupDefault.Subscribers[sub.Name];
        subDefault.Log = sub.Log;
        subDefault.IsEnabled = sub.IsEnabled;
    }
}

How should i update the Configuration object configDefault with the updated section? Something like:
configDefault.Sections["SomeCustomSection"] = sectionDefault;

A: I don't know of a way to do it in memory.  Even the AppSettings update code you include doesn't update config in memory in the sense that if the ConfigurationManager.AppSettings is checked after changing a setting in a loaded mapped config, it still reflects what's in the file <app>.exe.config.  At least that's how it behaves when I try the code you have because the config you're changing is not the config loaded by ConfigurationManager.
If changing only the configuration loaded by ConfigurationManager.OpenMappedExeConfiguration is what you need then the code you show is already changing the config sections.  There's nothing to set.
If you need the changed configuration to be available elsewhere without passing the modified configuration around, you'll have to save, refresh and then later restore the <app>.exe.config file to its previous state:
 configDefault.Save();
 ConfigurationManager.RefreshSection(SomeCustomSection);


text:
Q: Inverse Fourier Transform of a half-integer Bessel function Is there an analytical solution for the following inverse Fourier transform?
$$f(x)=\frac{1}{\sqrt{2\pi}}\,\mathrm{j}^n \int_{-\infty}^\infty\frac{1}{\sqrt{k}\,(k^4-\lambda^4)}\mathrm{J}_{n+\frac{1}{2}}(k)\, \mathrm{e}^{-\mathrm{j}\,k\,x}\,\mathrm{d}k$$
with $n \in \mathbb{N_0}$, $\mathrm{Re}(\lambda)>0$, $\mathrm{Im}(\lambda)<0$, $x \in \mathbb{R}$ and $\mathrm{J}_\bullet$ is the Bessel function of the first kind.
Edit: I found out (through a completely different approach) that
$$f(x)=-\frac{1}{4\,\lambda^3}\left(\mathrm{e}^{-\lambda\,x}\,\mathrm{j}^n\,\sqrt{\frac{2\pi\mathrm{j}}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}\!\!\left(\frac{\lambda}{\mathrm{j}}\right)+\mathrm{e}^{-\mathrm{j}\,\lambda\,x}\,\mathrm{j}^{n+1}\,\sqrt{\frac{2\pi}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}\!\!\left(\lambda\right)\right)\quad\text{for}\quad x\geq1$$
and
$$f(x)=-\frac{1}{4\,\lambda^3}\left(\mathrm{e}^{\lambda\,x}\,\mathrm{j}^n\,\sqrt{-\frac{2\pi\mathrm{j}}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}\!\!\left(-\frac{\lambda}{\mathrm{j}}\right)+\mathrm{e}^{\,\mathrm{j}\,\lambda\,x}\,\mathrm{j}^{n+1}\,\sqrt{-\frac{2\pi}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}\!\!\left(-\lambda\right)\right)\quad\text{for}\quad x\leq-1$$
Now the question remains, how to solve it for $-1\leq x \leq1$. I am accually surprised that the integral even changes. Any idea, how to get the solution for $x\geq1$ and $x\leq-1$ directly from the integral above?
Edit2: Thanks to Mathematica I got the solution for $x=0$
$$f(0)=\frac{\sqrt{\pi}\,(-1)^{n+1}}{8\,\lambda^{7/2}}\left((2+2\,\mathrm{j})\, \mathrm{I}_{n+\frac{1}{2}}\!\!\left(\mathrm{j}\,\lambda\right)+2\,\sqrt{2}\, \mathrm{I}_{n+\frac{1}{2}}\!\!\left(\lambda\right)+\lambda^{3/2}\left(_1\tilde{F}_2\left(1;\frac{3}{2}-\frac{n}{2},2+\frac{n}{2};-\frac{\lambda^2}{4}\right)-\,_1\tilde{F}_2\left(1;\frac{3}{2}-\frac{n}{2},2+\frac{n}{2};\frac{\lambda^2}{4}\right)\right)\right)$$
with $\mathrm{I}_\bullet$ is the modified Bessel function of the first kind and $_1\tilde{F}_2\left(\cdots;\cdots;\bullet\right)$ the regularized hypergeometric function. The solution for $x=0$ vanishes for odd $n$.

A: Not an answer
Residue theorem can be used to calculate the integral
\begin{equation}
f(x)=\frac{1}{\sqrt{2\pi}}\,\mathrm{j}^n \int_{-\infty}^\infty\frac{1}{\sqrt{k}\,(k^4-\lambda^4)}\mathrm{J}_{n+\frac{1}{2}}(k)\, \mathrm{e}^{-\mathrm{j}\,k\,x}\,\mathrm{d}k
\end{equation}
When $\Re x\le -1$, we close the contour by the large upper half-circle. This additionnal contribution vanishes owing to Jordan lemma ($\left|J(it)\right|\sim e^{\left|t\right|}/\sqrt t$), we have then
\begin{equation}
f(x)=\sqrt{2\pi}\mathrm{j}^{n+1}\sum_{k_p/\Im k_p>0}\operatorname{Res}\left( \phi(k),k=k_p \right)
\end{equation}
where $k_p$ are the 4 poles of
\begin{equation}
\phi(k)=\frac{\mathrm{J}_{n+\frac{1}{2}}(k)\, \mathrm{e}^{-\mathrm{j}\,k\,x}}{\sqrt{k}\,(k^4-\lambda^4)}
\end{equation}
defined on the complex plane cut along the negative real axis. The poles are $\lambda,\mathrm{j}\lambda,-\lambda,-\mathrm{j}\lambda$.
As $-\pi/2<\operatorname{Arg}(\lambda)<0$, only $\mathrm{j}\lambda$ and $-\lambda$ have to be taken into account in the summation. Their residues are
\begin{align}
\operatorname{Res}\left( \phi(k),k=\mathrm{j}\lambda\right)&=\frac{\mathrm{J}_{n+\frac{1}{2}}(\mathrm{j}\lambda)\, \mathrm{e}^{\lambda\,x}}{4\sqrt{\mathrm{j}\lambda}\,\mathrm{j}^3\lambda^3}\\
&=-\frac{1}{4\mathrm{j}\lambda^3}\sqrt{\frac{-\mathrm{j}}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}(\mathrm{j}\lambda)\, \mathrm{e}^{\lambda\,x}\\
\operatorname{Res}\left( \phi(k),k=-\lambda\right)&=\frac{\mathrm{J}_{n+\frac{1}{2}}(-\lambda)\, \mathrm{e}^{\mathrm{j}\lambda\,x}}{4\sqrt{-\lambda}\,(-\lambda)^3}\\
&=-\frac{1}{4\lambda^3}\sqrt{\frac{1}{-\lambda}}\mathrm{J}_{n+\frac{1}{2}}(-\lambda)\, \mathrm{e}^{\mathrm{j}\lambda\,x}
\end{align}
and thus
\begin{equation}
f(x)=-\frac{\sqrt{2\pi}\mathrm{j}^{n}}{4\lambda^3}\left[\sqrt{\frac{-\mathrm{j}}{\lambda}}\mathrm{J}_{n+\frac{1}{2}}(\mathrm{j}\lambda)\, \mathrm{e}^{\lambda\,x}
+\mathrm{j}\sqrt{\frac{1}{-\lambda}}\mathrm{J}_{n+\frac{1}{2}}(-\lambda)\, \mathrm{e}^{\mathrm{j}\lambda\,x}
\right]
\end{equation}
which is identical to the quoted result for $x\le-1$.
For $\Re x\ge1$, the same calculation can be made by closing the contour downwards. It can be easier to calculate the complex conjugate and use the previous result. Using the symmetry property
\begin{equation}
J_{n+1/2}\left(ze^{\mathrm{j}\pi }\right)=e^{\mathrm{j}(n+1/2)\pi }J_{n+1/2}\left(z\right)
\end{equation}
we obtain the proposed result.

A: It seems that the solution for $-1<x<1$ is given by
$$f(x)=-\frac{1}{4\,\lambda^3}\left(-\sqrt{\frac{2}{\lambda\,\pi}}\left((-1)^n\,\mathrm{e}^{-x\lambda}+\mathrm{e}^{x\lambda}\right) \mathrm{K}_{n+1/2}(\lambda)+\\\sum_{k=0}^n\frac{(k+n)!\,(1+(-1)^k)}{2^k\,\lambda^{k+1}\,k!\,(n-k)!}\,\, {_2\mathrm{F}_1}\left(k-n;k+n+1;k+1;\frac{1-x}{2}\right)\right)-\frac{\mathrm{j}}{4\,\lambda^3}\left(-\sqrt{\frac{2}{\mathrm{j}\,\lambda\,\pi}}\left((-1)^n\,\mathrm{e}^{-x\,\mathrm{j}\,\lambda}+\mathrm{e}^{x\,\mathrm{j}\,\lambda}\right) \mathrm{K}_{n+1/2}(\mathrm{j}\,\lambda)+\\\sum_{k=0}^n\frac{(k+n)!\,(1+(-1)^k)}{2^k\,(\mathrm{j}\,\lambda)^{k+1}\,k!\,(n-k)!}\,\, {_2\mathrm{F}_1}\left(k-n;k+n+1;k+1;\frac{1-x}{2}\right)\right)$$
which I reconstructed from results given in here.
This is not very useful though, since I can not use this result for large $n$ (the fraction in the sum takes very large values) even though the total value of $f(x)$ remains nicely bounded for large $n$. Any ideas how to resolve this?


text:
Q: Multiple jQuery functions & Autocomplete I found that using declaring jQuery Autocomplete as the first function in your script prevents other functions from being executed.
The second and third functions below will not work:
<script>
$(function() {
    $("#ent_input").autocomplete('get_suggestions',
        {autoFill: true, scroll: false});
});

    // Freebase Suggest
$(function() {
    $("#ent_input_fb").suggest({type:'/film/director'});
});

$(function() {
    $("#ent_input_fb2").suggest({type:'/film/actor'});
});
</script>

However, if I move autocomplete to the bottom, the other script works, but autocomplete doesn't.
<script>
    // Freebase Suggest
$(function() {
    $("#ent_input_fb").suggest({type:'/film/director'});
});

$(function() {
    $("#ent_input_fb2").suggest({type:'/film/actor'});
});

    $(function() {
    $("#ent_input").autocomplete('get_suggestions',
        {autoFill: true, scroll: false});
});
</script>

Has anyone run into any similar issues with jQuery Autocomplete?

A: jQuery should execute all of your $(function()...) handlers in the order they have been declared without issue.  It looks like your calls to autocomplete and suggest are the culprits.
jQuery is extremely cautious about event handlers, and if you tried to do something similar to the above with click handlers you'll notice that they too execute in sequence (rather than overwrite each other).  Try it:
Assume someElement is marked up as follows:
<span id="someElement" onclick="alert('Me First!');" />

...and the JavaScript
$("#someElement").click
(
  function()
  {
    alert("1");
  }
);

$("#someElement").click
(
  function()
  {
    alert("2");
  }
);

You will see three alert boxes shown in the following order: "Me First!," "1," and "2."
jQuery goes the extra mile to retain your marked up onclick handlers as the first function to click when the event occurs.  This makes it very safe to use this library with server-side technology like ASP.NET, which sprinkles onclick handlers all over the place.
To remove all jQuery-assigned click event handlers from an element, do the following:
$("#someElement").unbind("click");

Bear in mind that this does not remove a click handler assigned some other way (i.e., the onclick attribute in markup).


text:
Q: MonetDB install with Java 1.8 Error - Unsupported major.minor version 52.0 I am following the MonetDB install procedure described by Hannes Mühleisen by running commands 1 to 6 described below.
how do I install MonetDB on Centos 6.5?

*

*sudo yum install openssl-devel pcre-devel

*tar xvf MonetDB-.tar.

*cd MonetDB-*

*./configure

*make

*sudo make install ---> Fails in this Step

The machines Java Home is /usr/lib/java/jdk1.8.0_25. Apparently, the install is trying to find a 1.7 version somewhere else
Here is the error text
make[4]: Entering directory `/usr/local/MonetDB-11.15.19/java/tests'
make  all-am
make[5]: Entering directory `/usr/local/MonetDB-11.15.19/java/tests'
"/usr/local/ant/bin/ant" -f "`readlink -f ./build.xml`" -Dbuilddir="`readlink -f /usr/local/MonetDB-11.15.19/java/tests/jar_jdbctests`" -Djardir="`readlink -f /usr/local/MonetDB-11.15.19/java/tests`" -Dbasedir="`readlink -f .`" jar_jdbctests
Unable to locate tools.jar. Expected to find it in /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/lib/tools.jar
Buildfile: /usr/local/MonetDB-11.15.19/java/tests/build.xml

prepare:

find_driver:

BUILD FAILED
/usr/local/MonetDB-11.15.19/java/tests/build.xml:87: java.lang.UnsupportedClassVersionError: nl/cwi/monetdb/jdbc/MonetDriver : Unsupported major.minor version 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
    at org.apache.tools.ant.AntClassLoader.defineClassFromData(AntClassLoader.java:1136)
    at org.apache.tools.ant.AntClassLoader.getClassFromStream(AntClassLoader.java:1307)
    at org.apache.tools.ant.AntClassLoader.findClassInComponents(AntClassLoader.java:1362)
    at org.apache.tools.ant.AntClassLoader.findClass(AntClassLoader.java:1323)
    at org.apache.tools.ant.AntClassLoader.loadClass(AntClassLoader.java:1076)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at org.apache.tools.ant.taskdefs.Available.checkClass(Available.java:454)
    at org.apache.tools.ant.taskdefs.Available.eval(Available.java:285)
    at org.apache.tools.ant.taskdefs.condition.And.eval(And.java:42)
    at org.apache.tools.ant.taskdefs.ConditionTask.execute(ConditionTask.java:120)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.TaskAdapter.execute(TaskAdapter.java:154)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:435)
    at org.apache.tools.ant.Target.performTasks(Target.java:456)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1393)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1364)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1248)
    at org.apache.tools.ant.Main.runBuild(Main.java:851)
    at org.apache.tools.ant.Main.startAnt(Main.java:235)
    at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
    at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)

A: I think there are two different Java VMs installed on this machine, and for some reason (suspect per-user setting of $JAVA_HOME and/or $PATH) lead to the make using 1.8 and sudo make install using 1.7. The UnsupportedClassVersionError at least suggests this. I suggest you make sure only one version is used.
For CentOS, this should do it:
sudo /usr/sbin/alternatives --config java
sudo /usr/sbin/alternatives --config javac

Update: Turns out MonetDB now provides CentOS rpms: https://www.monetdb.org/downloads/epel/


text:
Q: Unable to run tensorflow multi-gpu with adam-optimizer I am running Tensorflow locally with the following code:
    distribution = tf.contrib.distribute.OneDeviceStrategy(device='/cpu:0')
    config = tf.estimator.RunConfig(train_distribute=distribution)
    estimator_model_fn = create_model_fn()
    estimator = tf.estimator.Estimator(estimator_model_fn, config=config)
    estimator.train(self.train_input_fn,steps=1000)

The model function uses tf.train.AdamOptimizer as the optimizer.
The call to train fails because of the following:
    File "/usr/local/lib/python2.7/site-
    packages/tensorflow/python/framework/op_def_library.py", line 641,
    in _apply_op_helper
    "(e.g.: a tf.Variable)") % (op_type_name, input_name))
    TypeError: 'ApplyAdam' Op requires that input 'm' be a mutable
    tensor
    (e.g.: a tf.Variable)
    Traceback (most recent call last):

If I change the optimizer to sgd the program runs without any problems.
Any ideas on how to solve this?


text:
Q: Using several key aliases with Android Maven Plugin and Jarsigner I'm newbie on Maven and I would need to set up a testing project for a complete Android device using Robotium, Android Maven plugin & Jarsigner.
In order to successfully deploy, install & run the tests on device, they would need to be signed using the same private keys the native apps (Eg. Contacts, Messaging, Camera...) on the device are using. Since there are several different keys, and it seems that the key aliases are defined in pom.xml-files (only one in each file in jarsigner configuration?), do I need to have multiple pom's defined in my project, or can they be defined elsewhere? The approach using multiple poms sounds hard to maintain.

A: Look at the morseflash example on how to set up signing. I am not sure I understand your question in terms of multiple keys and the native apps. You have to use your own key for your own app. And that is completely independent of any other app.


text:
Q: Translate variable value with ngx-translate Need help with ngx-translate
In component html there is
{{data.value | translate}}

In ts
data = {value: 'foo.bar'}

In i18n en.json
"foo": {
    "bar": "hello"
}

Instead of "hello" I'm getting "foo.bar" in the view.

A: If you want to use directly in Html then do as below
{{'foo.bar' | translate}}

refer below link and see how  <h2>{{ 'HOME.TITLE' | translate }}</h2> is translated
https://stackblitz.com/github/ngx-translate/example?file=src%2Fapp%2Fapp.component.ts
If you want to have translations for variables in TS then use can use translate.get and translate.stream methods as below
in TS:
let value = translate.get('foo.bar').subscribe((res: string) => {
    return res;
});

in Html
{{value}}


text:
Q: Web.py NameError When Importing Module in Module I am creating a web app using web.py on python 2.7.3.
I have the following folder structure:
start_app.py
/app
   __init__.py
   /models
      __init__.py
      ActionModel.py
      AreaModel.py
   /controllers
      __init__.py
      world.py
   /views

Whenever I freshly start the app using python start_app.py, and visit world/surrounding I get the following error
<type 'exceptions.ImportError'> at /world/surrounding
cannot import name AreaModel
Python  /home/dev/app/models/ActionModel.py in <module>, line 13
Web     GET http://localhost:5000/world/surrounding

Line 13 is simply: from app.models import AreaModel but I don't see why python is complaining here.
If I comment this importing line, it runs fine. However, if I call a different URL, e.g. world/view, I get an error that AreaModel is not defined. Once I uncomment the line, it works fine again for all cases (i.e. /surrounding and /view).
I am suspecting that this has something to do with the fact that I am "importing in circles", i.e. world.py imports AreaModel, AreaModel imports ActionModel and ActionModel imports AreaModel.
I doubt that this is 'the pythonic way' to do things or even the 'MVC way', so I would very much appreciate your enlightening me how to do this properly.
Note: app is not in my PYTHONPATH, but I don't think it is needed here, since start_app.py is in the top-level directory and according to this all modules should be available.
Basically, what it comes down to is:
I need the models' functionalities in both the controllers and the models. Is it good practice to "import in circles"? Or is there a nicer approach to do this?
Also, is this problem related to python in general or just web.py?
Update:
Added init.py files, I had them, but did not include in original question. Sorry for that.
Update:
ActionModel.py includes (among others) a class named BaseAction and a few functions, which return instances or subclasses of BaseAction depending on what type of Action we are dealing with. They are called using e.g. ActionModel.get_by_id()
@matthew-trevor : Are you suggesting in a) that I should move those functions get_by_id() into a class ActionModel?
#actionmodel.py
class ActionModel(object):
    def __init__(arg1, arg2, area_class):
        self.area = area_class()

    def get_by_id(self, id):
        return BaseAction(id)

class BaseAction(object):
    def __init__(id):
        pass

I don't see how this should remedy my import problems though.

A: The Immediate Problem
You cannot import from folders, but you can import from packages. You can turn any folder into a package by adding an __init__.py file to it:
start_app.py
/app
   __init__.py
   /models
      __init__.py
      ActionModel.py
      AreaModel.py
   /controllers
      __init__.py
      world.py
   /views
      __init__.py

I'm guessing that ActionModel.py includes a class of the same name. If so, I recommend renaming the file to actionmodel.py to distinguish it from the class.
Circular imports

Is it good practice to "import in circles"? Or is there a nicer
  approach to do this?

It's not only bad practice, it just won't work. There are a couple of ways to get around this, which will mostly depend on what you're trying to do:
a. In AreaModel, import the ActionModel module and then reference anything you want to use in it via attribute lookup and vice versa:
# areamodel.py
import actionmodel

def foo():
    action = actionmodel.ActionModel(...)

As long as the references are inside class or function definitions, it will only occur at run time and not during importing, so the circular reference is avoided.
b. Turn models into a module and put both ActionModel and AreaModel code inside it.
c. Move the shared code/functionality for ActionModel and AreaModel into a base module they both import from.
d. Make your ActionModel class (or whatever) accept a class as an input, then pass AreaModel into it in world.py (ditto for AreaModel). This way, ActionModel doesn't need to contain a reference to AreaModel, it just has to know what to do with it:
# actionmodel.py
class ActionModel(object):
    def __init__(arg1, arg2, area_class):
        self.area = area_class()

# areamodel.py
class AreaModel(object):
    def __init__(action_class):
        self.action = action_class()

# world.py
from actionmodel import ActionModel
from areamodel import AreaModel

action = ActionModel('foo', 'bar', AreaModel)
area = AreaModel(ActionModel)

This is known as object composition.


text:
Q: How to track events from a parent widget My goal is that when I hover my mouse over the thumbnail image, a popup image of the original image will display to the right of the mouse; and if my mouse leaves the thumbnail, the popup destroys itself.
The issue I have is that the leaveEvent from the thumbnail does not trigger, because the popup takes control of the application main loop (or that is what I think is happening - I am not actually sure).
Here is my code:
class UI_ImagePopup(QLabel):
    def __init__(self):
        QLabel.__init__(self)
        movie = QMovie("C:/Users/Zelly/Desktop/thumbnail/1vgb1al.jpg", QByteArray(), self)
        movie_screen = QLabel()
        # Make label fit the gif
        movie_screen.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        movie_screen.setAlignment(Qt.AlignCenter)
        # Create the layout
        main_layout = QVBoxLayout()
        main_layout.addWidget(movie_screen)
        self.setLayout(main_layout)
        # center the zoomed image on the thumb
        position = self.cursor().pos()
        position.setX(position.x() +50)
        position.setY(position.y())
        self.move(position)
        # The following is blackmagic copy pasted from the internet
        # FramelessWindowHint may not work on some window managers on Linux
        # so I force also the flag X11BypassWindowManagerHint
        self.setWindowFlags(Qt.Popup | Qt.WindowStaysOnTopHint
                            | Qt.FramelessWindowHint
                            | Qt.X11BypassWindowManagerHint)
        movie.setCacheMode(QMovie.CacheAll)
        movie.setSpeed(100)
        movie_screen.setMovie(movie)
        movie.start()

    def mousePressEvent(self, event):
        self.close()

class Ui_ImageLabel(QLabel):
    def __init__(self):
        QLabel.__init__(self)
        self.setPixmap(QPixmap("C:/Users/Zelly/Desktop/thumbnail/1vgb1al.jpg"))
        self.p = None

    def enterEvent(self, event):
        print("Enter event")
        self.p = UI_ImagePopup()
        self.p.show()
        event.accept()

    def leaveEvent(self, event): # not triggered
        print("Leave event")
        self.p.destroy()

class Ui_MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.setMinimumSize(1024, 512) #TODO: Resizable
        self.setMaximumSize(1024, 800)
        self.gridlayout = QGridLayout(self)
        self.setLayout(self.gridlayout)
        for i in range(6):
            pic = Ui_ImageLabel()
            self.gridlayout.addWidget(pic,0,i)
        self.show()

if __name__ == '__main__':
    app = QApplication(sys_argv)
    ex = Ui_MainWindow()
    sys_exit(app.exec_())


text:
Q: Convergence in moments implies weak distribution in a special case? I know this is definitely not true in general. Consider this special case: $(X_n, X)$ are all random variables that map to $[0,1]$ that is a bounded interval. Given that $$\lim_{n\to +\infty}E[X_n^k] = E[X^k]$$ for all $k\in\mathbb{Z}^+$ (i.e. every moment converges). It seems to me that the following is true $$X_n \Rightarrow^d X$$ (i.e. weak convergence), but I have no idea on how to start. Any suggestions?

A: There is a direct elementary proof. Let $f \in C[0,1]$. Given $\epsilon>0$, the Weierstrass approximation theorem ensures that there is a polynomial $g$ such that $\displaystyle \max_{x \in [0,1]} |g(x)-f(x)| <\epsilon$.
Writing $g$ as a sum of monomials (and the hypothesis on moment convergence) imply that $Eg(X_n) \to Eg(X)$ as $n \to \infty.$
Therefore the triangle inequality yields
$$\limsup_n |E (f(X_n) -f(X))| \le 2\epsilon+ \limsup_n |E (g(X_n) -g(X))|=2\epsilon \,,$$
so the limsup on the LHS must equal $0$. This proves weak convergence.

A: It is true but it requires a few theorems. First of all, any sequence of probability measures on a compact set is relatively compact. All weak limit points of $P\circ X_n^{-1}$ are the same because on $[0,1]$, moments determine the distribution uniquely. Combining these we get the result.


text:
Q: compiling someone else's vs c++ app - inconsistent linkage hi
I am not a c++ developer and I'm trying to compile someone else's app.  Build succeeds, but I get 5 'inconsistent dll linkage' warnings.
the dll builds but does not work in the same scenario in which the existing dll does.  there have been no code changes.
after some googling, I assume it has to do with this, found in the header file:
#ifdef CPLAPPLET_PROGRAM_EXPORTS
#define CPLAPPLET_PROGRAM_API __declspec(dllexport)
#else
#define CPLAPPLET_PROGRAM_API __declspec(dllimport)
#endif

and there's a comment in the code that says CPLAPPLET_PROGRAM_EXPORTS is defined on the command line.
The warnings happen on the exported functions, like this:
HRESULT _stdcall CCplApplet_PROGRAM::DllUnregisterServer()
{
// our code added here
    return 0;
}

can someone point me in the right direction here?
thank you.
EDIT to address comments:
I have created a c++ win32 dll project in vs 2008, and I've added their .cpp, .h, and .def files to this project, but that's all.  Instead of just clicking 'build' I'm wondering if I need to do something specifically with the .def file or something?
the header file defines the methods like so:
class CPLAPPLET_LNK_PROGRAM CCplApplet_PROGRAM {
public:
static LONG APIENTRY CPlApplet(HWND hWnd, UINT uMsg, LONG lParam1, LONG lParam2);

private:
...
HRESULT _stdcall DllUnregisterServer(void);
 ...
   };

the .def file:
LIBRARY "CplApplet_PROGRAM"

EXPORTS DllUnregisterServer PRIVATE

A: Right-click the project in the Solution Explorer window, Properties.  Configuration Properties, C/C++, Preprocessor, Preprocessor Definitions setting.  Verify that you see CPLAPPLET_PROGRAM_EXPORTS there.  If you don't then add it.
It is also very likely that you'll need a .def file so that the export gets renamed.  Make sure it is present in your project's list of files.  After building, use Dumpbin.exe /exports on the generated DLL and ensure that the export is present and properly spelled "DllUnregisterServer" without any additional characters.  Needing the help from the author isn't very unlikely btw, the way the COM exports seem to be handled is pretty nonstandard.


text:
Q: UITableView scrolling hacks after some time I have several UITableView, UIScrollViews in my app. The tableview and scrollview scrolls smoothly on initial loading. But after the continuous usage of the app for some 7-10 minutes the scrolling really hacks. I implemented lazy loading for UITableView. I have also a NSTimer running in the background for polling.
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
pollTimer = [NSTimer timerWithTimeInterval:4 target:self selector:@selector(threadStarter) userInfo:nil repeats:YES];
[runloop addTimer:pollTimer forMode:NSRunLoopCommonModes];

Is this the reason for the stuck in the scrolling of UITableViews.
How can i solve this issue?

A: The one main reason for these kind of issues that cause the apps to respond slower over time is "Memory Leaks".
Check if you are releasing the cells and its contents properly. Please refer this post to know how to debug memory leaks, if you are new to this.


text:
Q: How to continue apt setup in shell if you choose to show the config update diff I have updated from shell as usual, but during the setup at 90% a package that has update the config file asked me to enter one of the following options
Yes(Y) No(N) Show the diff (D)

I have entered D to show the differences, the problem is that now the shell remained on the Diff  screen, and if I click enter on keyboard it goes to end of the diff screen and I don't know how to confirm and continue the installation.

What should I do?
Is there some special shortcut to continue in these situations?

A: q should quit the less process which displays the difference. Then you can know where are the differences and choose between the old version and the new. If you keep your own version, the new version is however available (with a .dpkg-dist suffix) and permit you to merge manually both files. (If you use the new file, a backup of the configuration is available with the .dpkg-old suffix).


text:
Q: Delete a variable in a newly inserted row my project is about calculating the working time of employees.
df:
   Door Name                Time Last Name First Name
0   RDC_IN-1 2019-08-05 15:00:00     STARK       ARYA
1  RDC_OUT-1 2019-08-05 12:55:00     STARK       ARYA
2  RDC_OUT-1 2019-08-05 11:11:00     STARK       ARYA
3   RDC_IN-1 2019-08-05 10:13:00     STARK       ARYA
4  RDC_OUT-1 2019-08-05 09:10:00     STARK       ARYA
5  RDC_OUT-1 2019-08-05 09:10:00     STARK       ARYA

First I need to sort it by time then I need to check if the Door Name is identical in two consecutive rows and if the time difference between these two consecutive rows is lower than 5min or not.
If these two conditions are verified then I've to remove the second row, else if the two rows have the same variable and the time difference is above 5min, then I should insert a new row with another variable, for example, if I have two RDC_IN-1 then I should insert between them a new line with the Door Name is RDC_OUT-1.
I've been able to do that, but the problem occurred when I tried to calculate the amount of time spent at work.
Code
import pandas as pd
import numpy as np
file_name='test.xlsx'
from datetime import timedelta
import datetime as dt

df= pd.DataFrame({'Time':[' 2019-08-05 15:00:00', ' 2019-08-05 12:55:00', ' 2019-08-05 11:11:00', ' 2019-08-05 10:13:00', ' 2019-08-05 09:10:00',' 2019-08-05 09:10:00'],
 'Door Name':[ 'RDC_IN-1,'RDC_OUT-1', ,'RDC_OUT-1','RDC_IN-1','RDC_OUT-1', ,'RDC_OUT-1'],
 'name':['alex','alex','alex','alex','alex','alex']})

print(df)
df= df.sort_values(by='Time')
df.reset_index(inplace = True)

Total='00:00:00'
idx=[]
l=len(df)
if l < 2:
    Total='00:00:00'

if l % 2 == 0:

    for i in range (len(df)):

        if i == 0:
            print ('index '+str(i)+' ok')
        elif (df['Door Name'][i] != df['Door Name'][i-1]):
            print('index '+str(i)+' ok')

        elif ((df['Door Name'][i] == df['Door Name'][i-1]) & ((df['Time'].iloc[i] - df['Time'].iloc[i-1]) > dt.timedelta(minutes=5))):
            df['Door Name']= df['Door Name'].map({'RDC_IN-1': 1, 'RDC_OUT-1': 0})
            # convert time stamp
            df['Time'] = pd.to_datetime(df['Time'], format="%H:%M:%S")

            # sort by time stamp
            df= df.sort_values(by='Time')

            # calculate difference to next row per column
            df_diff = df[['Time', 'Door Name']].diff(periods=-1)

            # select and copy relevant rows
            df_add = df[(df_diff.Time < dt.timedelta(minutes=-5)) & (df_diff['Door Name'] ==0)].copy()

            # change the time stamp of copied rows
            df_add.loc[df_add['Door Name'] == 0, 'Time'] =  pd.to_datetime('05/08/2019 12:00:00', format="%d/%m/%Y %H:%M:%S")
            df_add.loc[df_add['Door Name'] == 1, 'Time'] =  pd.to_datetime('05/08/2019 14:00:00', format="%d/%m/%Y %H:%M:%S")

            # switch the label of copied rows
            df_add['Door Name']= -(df['Door Name']-1)

            # change name to mark the new
            df_add['Last Name']= 'NEW_alex'
            df_add['First Name']= 'new_alex'
            df_add['name']= 'new_ALEX'

            # append existing data frame with new rows and sort by time stamp
            df = df.append(df_add ).sort_values(by='Time')

            # remap the door featuere
            df['Door Name']= df['Door Name'].map({1:'RDC_IN-1', 0:'RDC_OUT-1'})

        else:
            idx.append(i)

    df['Time Spent']=df['Time']
    df.drop(df.index[[idx]],inplace=True)

    for i in range (len(df)):
        df['diff'] = df['Time'].iloc[1::2].to_numpy() - df['Time'].iloc[::2]
#                print('\ndfff\n',df[['Time', 'Door Name', 'First Name', 'diff']])
        df['Time Spent']=df['Time']
        mydf=df
        Total = mydf['diff'].sum()
        print('Total: ',Total)
        mydf['WORK']=str(Total)
        mydf.drop_duplicates(subset='WORK', keep="first")
        mydf['WORK'] = mydf['WORK'].mask(mydf['WORK'].ne(mydf['WORK'].shift()).cumsum().duplicated(), '')

print('df3 \n',mydf[['Door Name', 'Time','First Name', 'diff']])

output:
    Door Name                Time First Name     diff
0  RDC_OUT-1 2019-08-05 09:10:00       ARYA 01:03:00
2   RDC_IN-1 2019-08-05 10:13:00       ARYA      NaT
3  RDC_OUT-1 2019-08-05 11:11:00       ARYA 00:49:00
3   RDC_IN-1 2019-08-05 12:00:00   new_alex 00:49:00
4  RDC_OUT-1 2019-08-05 12:55:00       ARYA 02:05:00
5   RDC_IN-1 2019-08-05 15:00:00       ARYA      NaT

desired output:
    Door Name                Time First Name     diff
0  RDC_OUT-1 2019-08-05 09:10:00       ARYA 01:03:00
2   RDC_IN-1 2019-08-05 10:13:00       ARYA      NaT
3  RDC_OUT-1 2019-08-05 11:11:00       ARYA 00:49:00
3   RDC_IN-1 2019-08-05 12:00:00   new_alex      NaT
4  RDC_OUT-1 2019-08-05 12:55:00       ARYA 02:05:00
5   RDC_IN-1 2019-08-05 15:00:00       ARYA      NaT

I don't know why it copied 00:49:00 in new_alex row or how to remove it.

A: just use the answer I gave you yesterday and add
df['diff'] = df['Time'].diff()
df.loc[df.door == 'RDC_IN-1','diff'] = np.nan

# calculate cumsum
df.loc[df.door == 'RDC_OUT-1','diff'] = df.loc[df.door == 'RDC_OUT-1','diff'].cumsum()

at the end.
Also don`t forget to provide a working example df. No one enjoys to create data frame from posted outputs ;)


text:
Q: homebrew cannot update and I cannot add a git repository Pretty much what the title says. I'm trying to update homebrew using
brew update

and I always get the error message
$ brew update
fatal: Not a git repository (or any of the parent directories): .git
fatal: Not a git repository (or any of the parent directories): .git
Error: Failure while executing: git checkout -q master

The brew doctor command output is as follows:
$ brew doctor
Warning: Missing git origin remote.

Without a correctly configured origin, Homebrew won't update
properly. You can solve this by adding the Homebrew remote:
  cd /usr/local
  git remote add origin https://github.com/Homebrew/homebrew.git
fatal: Not a git repository (or any of the parent directories): .git

When I run
cd /usr/local
git remote add origin https://github.com/Homebrew/homebrew.git

I get
$ cd /usr/local
$ git remote add origin https://github.com/Homebrew/homebrew.git
fatal: Not a git repository (or any of the parent directories): .git

What can I do to get rid of this problem? It seems git doesn't recognize homebrew's repository, put what should I use instead of this suggested one?

A: Indeed a correct answer but no need to go so far.
As mentioned in the comments also, removing the top .git directory present in /usr/local is enough. Run your brew update after only having removed the top .git directory will rebuild the tree!
Segmentation fault: 11 with your PHP installation is same issue it is still the pulled version from the Mavericks bottle so update and upgrade will correct this and also only needed for your main php55 or php56 and not for all your PHP dependencies installed using Homebrew.
GL!!!

A: I had the same problem, simply cloned the homebrew repository in a temporary location using
git clone https://github.com/Homebrew/homebrew.git

and moved the resulting .git directory to /usr/local, overwriting the one already there. After that, I had to checkout a few directories:
cd /usr/local
git checkout Library/Formula/
git checkout Library/Contributions/
git checkout Library/ENV/
git checkout Library/Homebrew/


text:
Q: Test for a particular file format This is a followup to Normal looking text file, detected by file as ASCII Pascal program text
It seems file can't be trusted all the time.
It seems possible that a particular file may be detected as having both encoding/format1 and encoding/format2. file tells me it's encoding/format1, but I need to check, whether it also satisfies the constraints of encoding/format2.

*

*Is there a way to do that?

*Is there a way I can ask "Check if this file follows the rules of
ASCII English Text (or some other encoding)" and the answer will be
"yes" or "no"?

A: Maybe you can use the --keep-going (-k) option of file. It writes out more matching formats.
Related man page description of this option:

Don't stop at the first match, keep going.  Subsequent matches will be have the string '\012- ' prepended.  (If you want a
  newline, see the -r option.)  The magic pattern
               with the highest strength (see the -l option) comes first.

A: Only answering your second question, as jofel has already answered the first.

*

*Is there a way I can ask "Check if this file follows the rules of ASCII English Text (or some other encoding)" and the answer will be "yes" or "no"?

See the -e/--exclude option.  From file(1):

-e, --exclude testname
Exclude the test named in testname from the list of tests made to determine the file type.
[...]

*

*soft    Consults magic files

Those magic files are responsible for the Pascal report, so -e soft should be enough.  You could try excluding other tests from that list too, as long as you leave ascii enabled.
For your "yes/no" test, combine with -b ("brief" ie. without the filename) and --mime-encoding, to output only the encoding.  Then it's a simple string comparison:
if [ "$(file -b --mime-encoding -e soft $file)" == "us-ascii" ] ; then
  echo yes
else
  echo no
fi


text:
Q: React Component changing from function to class - State and state hook I've got a question, because i can't find answer anywhere.
The problem is: what is the initial value of the following hook:
"Function" Example:
function Example() {
  const [settings, setSettings] = useState({});

  return (
     ...
  );
}

And here i'm writing this function "Example" as class, but i don't know how to initialize state
(is it empty string or empty list or 0 value?)
class Example extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
             settings: <-- and what here?
        };
    }

A: useState is passed the initial value as its only param - in your case {}.
You can accomplish the same in your second code snippet like so:
class Example extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
             settings: {}
        };
    }
}

Further reading:

*

*The React docs have an example almost identical to yours.

*useState source


text:
Q: Better way to iterate / get data from XML? I'm trying to get data from an XML file using python and BeautifulSoup.
I have managed to get the data out and formatted the way I want, but I'm trying to improve my knowledge.  My code is working but I keep thinking, there must be an easier way to do it.
My code is:
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen

url = 'http://localhost:8888/00612-Waoo-Weekly-2019-Mar-11-2019-Mar-18.xml'
url_result = urlopen(url)
raw_data = url_result.read()
xml_soup = soup(raw_data, 'xml')

entities = xml_soup.findAll('entities',{})
entities = entities[0]

channel_entities = entities.findAll('entity', {"name":"*Nord* Radio Nord"})

channel_check_PMT = []

for entity in channel_entities:
    channel_name = entity['name']
    channel_site = entity['site']
    channel_blade = entity['blade']
    channel_interface = entity['interface']

    channel_check_TS_Sync = entity.findAll('check', {"name": "TS sync"})
    channel_check_PAT = entity.findAll('check', {"name": "PAT"})
    channel_check_Continuity = entity.findAll('check', {"name": "Continuity"})
    channel_check_Sync_byte = entity.findAll('check', {"name": "Sync byte"})
    channel_check_Missing_PID = entity.findAll('check', {"name": "Missing PID"})
    channel_check_PMT = entity.findAll('check', {"name": "PMT"})

    channel_check_PMT = channel_check_PMT[0]
    channel_check_PMT = str(channel_check_PMT)
    channel_check_PMT = channel_check_PMT.replace("<data>","").replace("</data>","").replace('<check name="PMT" threshold="99.9500">','').replace("</check>","").replace("\n","")
    channel_check_PMT = channel_check_PMT.strip()
    channel_check_PMT = channel_check_PMT.split(",")
print(channel_check_PMT)

The XML file:
<entities>
    <entity name="*Nord*" site="" blade="" interface="QAM1" stream="" joinCount="1" entityType="2" serviceType="Digital Radio">
<check name="TS sync" threshold="99.9500">
        <data>090.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,2222.000,</data>
      </check>
      <check name="Sync byte" threshold="99.9500">
        <data>101.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
      </check>
      <check name="PAT" threshold="99.9500">
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
      </check>
      <check name="Continuity" threshold="99.9500">
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
      </check>
<check name="PMT" threshold="99.9500">
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
</check>
<check name="Missing PID" threshold="99.9500">
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
        <data>100.000,100.000,100.000,100.000,100.000,100.000,100.000,</data>
     </check>
    </entity>

If i print the result, it gives me this (What, i want)
['100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '100.000', '']

This result is expected.
The purpose of this script is to get data within each  and append them to 6 different arrays so it can be used later.
As of now, it's working as it should, but is there a better way to do this?

A: You should take a look at python-guide.org, they have a nice summary of some libraries aiming to make working with XML easier. I personally like xmltodict, but that's just a matter of preference.