Sunday 30 September 2018

Expo Push Notifications not popping in Android phones (Floating Notifications)

EDIT: I discovered these are known as FLOATING NOTIFICATIONS. Anyone knows how to enable them by default from the app (through a permission etc) on an Android device?

I am currently testing push notifications on an Android device and noticed that although I get the push notifications, they are not popped up on the screen but stay in the background (I need to drag down the top status bar as per picture). I see this as rather useless as the user is not really notified if he's using the phone:

enter image description here

On iPhone, the pop up displays correctly with no issues whatsoever.



from Expo Push Notifications not popping in Android phones (Floating Notifications)

Add frontend pagination on dynamicall created div elements

I created 20 Divs dynamically. Now i am trying to add frontend pagination to my div's, But It is not working. I am following this link to add pagination to my webpage. Below is my code in which i created div's and apply pagination.

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width">
  <link type="text/css" href="pagination/simplePagination.css"/>
  <script type="text/javascript" src="pagination/jquery.min.js"></script>
  <script type="text/javascript" src="pagination/jquery.simplePagination.js"></script>  
  <style>
    .containerdiv{
        width: 50%;
        position:absolute;
        top: 50%;
        left:50%;
        transform: translate(-50%,-50%);
        margin-top: 30px;
    }
    .image{
        background-image: url('3332.jpg');
        height:150px;
        width: 100%;
    }
    .name{
        text-align: center;
        font-weight: bold;
        margin-top:10px;
    }
    .description{
        text-align: center;
        margin-top:20px;
    }
    a{
      text-decoration: none;    
      font-size: 20px;
      margin-left: 20px;
    }
    a:visited{
      color:blue;
    }
    a.current {
      color: red;
      font-size: 25px;
      font-weight: bold;
    }
   #pagin li {
     display: inline-block;
   }
</style>
</head>
<body>
 <h3 style="text-align: center;font-family: arial">Dynamically Created Div</h3>
 <div id="main-content" class="slider" style="width: 50%;"></div>
 <ul id="pagin"></ul>
 <script>
    var dataLength = 0; 
    var names = ['rajat','kunal','naman','divyank','krishna'];
    var description = ['Rajat is a very good guy','Kunal is a very good guy','Naman is a very good guy','Divyank is a very good guy','Krishna is a very good guy'];
    for(var i=0;i<5;i++){
        dataLength++;
        var mainContent = document.getElementById('main-content');

        var container = document.createElement('div');
        var imageDiv = document.createElement('div');
        var vendorInfoDiv = document.createElement('div');
        var vendorNameDiv = document.createElement('div');
        var vendorDescriptionDiv = document.createElement('div');

        vendorNameDiv.setAttribute('class','name');
        vendorNameDiv.innerHTML = names[i];     

        vendorDescriptionDiv.setAttribute('class','description');
        vendorDescriptionDiv.innerHTML = description[i];

        vendorInfoDiv.appendChild(vendorNameDiv);
        vendorInfoDiv.appendChild(vendorDescriptionDiv);

        imageDiv.setAttribute("class","image");
        imageDiv.setAttribute("style","background-image:url('3332.jpg')");

        container.setAttribute("style","height:300px;width:250px;border: 1px solid red;background-image: (100%,100%);margin-left:12px;margin-top:10px;float:left");

        container.appendChild(imageDiv);
        container.appendChild(vendorInfoDiv);

        mainContent.appendChild(container);         
        mainContent.setAttribute('class','card-container');
    }
    pageSize = 2;
    var totalPaginate = Math.round(dataLength/pageSize);

    for(var i=1;i<=totalPaginate;i++){
        var ulist = document.getElementById('pagin');
        var list = document.createElement('li');
        var anchor = document.createElement('a');
        anchor.setAttribute('href','#');
        anchor.innerHTML = i;
        list.appendChild(anchor);
        ulist.appendChild(list);
    }

    showPage = function(page) {
        $(".paginate").hide();
        $(".paginate").each(function(n) {
            console.log(n);
            if (n >= pageSize * (page - 1) && n < pageSize * page)
                $(this).show();
        });        
    }

    $("#pagin li a").click(function() {
        $("#pagin li a").removeClass("current");
        $(this).addClass("current");
        showPage(parseInt($(this).text())) 
    });
    showPage(1);
 </script>

Can anyone please help me to solve this issue or please suggest me any other pagination plugin.

Thanks.



from Add frontend pagination on dynamicall created div elements

Unable to determine possible causes of EXC_BAD_ACCESS (which occurs during app startup)

I'm seeing a lot of crashes in an app in the app store which I'm totally unable to reproduce or speculate from code review what the cause could be. What is particularly confusing is that this is occurring at app launch while there is low memory - confusing because if there was insufficient memory for the app to launch I might expect to see other types of crash reports as opposed to an EXC_BAD_ACCESS - i.e. if the EXC_BAD_ACCESS is being caused by accessing deleted memory, there's nowhere in the code where anything gets the chance to be deleted, as the crash is occurring as objects are in the process of being created.

I've tried many thing to recreate this - running in the simulator and sending low memory warning messages, deliberately failing the initialization of various objects in the app creation process, calling calloc during app launch to consume vast amounts of memory, running the app numerous times on a handset whose RAM is totally maxed out. I can't recreate, or see from code inspection what might be going wrong.

Here is a crash report:

Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000000 many also at 0x0000000000000008) hread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 The_Name_Of_MyApp
0x000000010268ca94 SearchViewController.init(coder:) + 838292 (SearchViewController.swift:67) 1 The_Name_Of_MyApp
0x000000010268ca88 SearchViewController.init(coder:) + 838280 (SearchViewController.swift:67) 2 The_Name_Of_MyApp
0x000000010268cd4c @objc SearchViewController.init(coder:) + 838988 (SearchViewController.swift:0) 3 UIKitCore
0x00000001bca63d64 -[UIClassSwapper initWithCoder:] + 248 4
UIFoundation 0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744 5 UIFoundation
0x000000019a7800cc UINibDecoderDecodeObjectForValue + 1324 6
UIFoundation 0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320 7 UIKitCore
0x00000001bd0a1288 -[UIViewController initWithCoder:] + 1420 8
UIKitCore 0x00000001bceb5dcc -[UITabBarController initWithCoder:] + 80 9 The_Name_Of_MyApp
0x000000010283f658 TabBarViewController.init(coder:) + 2618968 (TabBarViewController.swift:0) 10 The_Name_Of_MyApp
0x000000010283f70c @objc TabBarViewController.init(coder:) + 2619148 (TabBarViewController.swift:0) 11 UIKitCore
0x00000001bca63d64 -[UIClassSwapper initWithCoder:] + 248 12 UIFoundation 0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744 13 UIFoundation
0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320 14 UIKitCore 0x00000001bcd9dcbc -[UIRuntimeConnection initWithCoder:] + 188 15 UIFoundation 0x000000019a77fe88 UINibDecoderDecodeObjectForValue + 744 16 UIFoundation 0x000000019a7800cc UINibDecoderDecodeObjectForValue + 1324 17 UIFoundation
0x000000019a71eb3c -[UINibDecoder decodeObjectForKey:] + 320 18 UIKitCore 0x00000001bccc4a1c -[UINib instantiateWithOwner:options:] + 1124 19 UIKitCore
0x00000001bce92f18 -[UIStoryboard instantiateViewControllerWithIdentifier:] + 196 20 The_Name_Of_MyApp 0x000000010266b4dc InitialViewController.start() + 701660 (InitialViewController.swift:118) 21 The_Name_Of_MyApp
0x000000010266bba4 @objc InitialViewController.start() + 703396 (InitialViewController.swift:0) 22 Foundation
0x0000000190bff6d0 NSFireDelayedPerform + 404 23 CoreFoundation
0x00000001900f2bf0 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION
+ 28 24 CoreFoundation 0x00000001900f2920 __CFRunLoopDoTimer + 864 25 CoreFoundation 0x00000001900f2154 __CFRunLoopDoTimers + 248 26 CoreFoundation 0x00000001900ed030 __CFRunLoopRun + 1880 27 CoreFoundation
0x00000001900ec5b8 CFRunLoopRunSpecific + 436 28 GraphicsServices
0x0000000192360584 GSEventRunModal + 100 29 UIKitCore
0x00000001bc9e3558 UIApplicationMain + 212 30 The_Name_Of_MyApp
0x00000001026ea6b0 main + 1222320 (AppDelegate.swift:20) 31 libdyld.dylib 0x000000018fbacb94 start + 4

Thread 1: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 2 name: Dispatch queue: com.myQueue.backgroundSerialQueue Thread 2: 0 libsystem_c.dylib 0x000000018fc60ae4 __v2printf + 616 1 libsystem_c.dylib 0x000000018fc60a00 __v2printf + 388 2 libsystem_c.dylib 0x000000018fc46ac0 _vsnprintf + 264 3 libsystem_c.dylib 0x000000018fc3b9c0 snprintf_l + 28 4 CoreFoundation 0x000000019010fa88 __CFStringAppendFormatCore + 8548 5 CoreFoundation 0x00000001901111b8 _CFStringCreateWithFormatAndArgumentsAux2 + 136 6 Foundation 0x0000000190afd3ec -[NSString initWithFormat:locale:] + 36 7 Foundation
0x0000000190afd364 -[NSNumber descriptionWithLocale:] + 1044 8
CoreFoundation 0x000000019004d9a8 -[__NSCFNumber descriptionWithLocale:] + 72 9 CoreFoundation
0x0000000190053268 -[__NSCFNumber stringValue] + 64 10 The_Name_Of_MyApp 0x00000001025f6494 -[RobocallerManager readCityAndStateData] + 222356 (RobocallerManager.m:596) 11 The_Name_Of_MyApp 0x00000001025f343c __25-[RobocallerManager init]_block_invoke + 209980 (RobocallerManager.m:148) 12 libdispatch.dylib
0x000000018fb9b6c8 _dispatch_call_block_and_release + 24 13 libdispatch.dylib 0x000000018fb9c484 _dispatch_client_callout + 16 14 libdispatch.dylib 0x000000018fb43c18 _dispatch_lane_serial_drain$VARIANT$mp + 592 15 libdispatch.dylib 0x000000018fb44760 _dispatch_lane_invoke$VARIANT$mp + 432 16 libdispatch.dylib 0x000000018fb4cf00 _dispatch_workloop_worker_thread + 600 17 libsystem_pthread.dylib 0x000000018fd7e0f0 _pthread_wqthread + 312 18 libsystem_pthread.dylib 0x000000018fd80d00 start_wqthread + 4

Thread 3: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 4 name: com.apple.uikit.eventfetch-thread Thread 4: 0
libsystem_kernel.dylib 0x000000018fceded0 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x000000018fced3a8 mach_msg + 72 2
CoreFoundation 0x00000001900f1fb0 CFRunLoopServiceMachPort + 236 3 CoreFoundation 0x00000001900ece4c __CFRunLoopRun + 1396 4 CoreFoundation
0x00000001900ec5b8 CFRunLoopRunSpecific + 436 5 Foundation
0x0000000190ae06a4 -[NSRunLoop+ 34468 (NSRunLoop) runMode:beforeDate:] + 300 6 Foundation
0x0000000190ae0514 -[NSRunLoop+ 34068 (NSRunLoop) runUntilDate:] + 88 7 UIKitCore 0x00000001bc940ac0 -[UIEventFetcher threadMain] + 136 8 Foundation
0x0000000190c133b0 __NSThread__start
+ 1040 9
libsystem_pthread.dylib 0x000000018fd7d2fc _pthread_body + 128 10 libsystem_pthread.dylib 0x000000018fd7d25c _pthread_start + 48 11 libsystem_pthread.dylib 0x000000018fd80d08 thread_start + 4

Thread 5 name: com.twitter.crashlytics.ios.MachExceptionServer Thread 5: 0 libsystem_kernel.dylib 0x000000018fceded0 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x000000018fced3a8 mach_msg + 72 2 The_Name_Of_MyApp 0x000000010288d08c CLSMachExceptionServer + 1180 3 libsystem_pthread.dylib
0x000000018fd7d2fc _pthread_body + 128 4 libsystem_pthread.dylib
0x000000018fd7d25c _pthread_start + 48 5 libsystem_pthread.dylib
0x000000018fd80d08 thread_start + 4

Thread 6: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 7: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 8: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 9: 0 libsystem_pthread.dylib 0x000000018fd80cfc start_wqthread + 0

Thread 10 name: com.apple.NSURLConnectionLoader Thread 10: 0
libsystem_kernel.dylib 0x000000018fceded0 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x000000018fced3a8 mach_msg + 72 2
CoreFoundation 0x00000001900f1fb0 CFRunLoopServiceMachPort + 236 3 CoreFoundation 0x00000001900ece4c __CFRunLoopRun + 1396 4 CoreFoundation
0x00000001900ec5b8 CFRunLoopRunSpecific + 436 5 CFNetwork
0x000000019070ce18 -[__CoreSchedulingSetRunnable runForever] + 212 6 Foundation 0x0000000190c133b0 __NSThread__start
+ 1040 7 libsystem_pthread.dylib 0x000000018fd7d2fc _pthread_body + 128 8 libsystem_pthread.dylib 0x000000018fd7d25c _pthread_start + 48 9 libsystem_pthread.dylib
0x000000018fd80d08 thread_start + 4

Thread 0 crashed with ARM Thread State (64-bit): x0: 0x0000000000000000 x1: 0x0000000000000000 x2: 0x0000000282718580 x3: 0x0000000000000000 x4: 0x0000000104870680 x5: 0x0000000000000000 x6: 0x0000000000000072 x7: 0x00000000000000a0 x8: 0x0000000103f03650 x9: 0x0000000000000000 x10: 0x000000000000001f x11: 0x0000000000000005 x12: 0x0000000000000005 x13: 0x0000000000000000 x14: 0x0000000000000068 x15: 0x00000001ae696425 x16: 0x000000018f34b858 x17: 0x0000000102601328 x18: 0x0000000000000000 x19: 0x0000000104853200 x20: 0x00000001048709c8 x21: 0x0000000280b73880 x22: 0x00000001c92684c0 x23: 0x0000000104870600 x24: 0x0000000281e51ec0 x25: 0x00000001c73e2000 x26: 0x0000000000000002 x27: 0x00000001c73e2000
x28: 0x0000000000000171 fp: 0x000000016d83c0b0 lr: 0x000000010268ca88 sp: 0x000000016d83bcc0 pc: 0x000000010268ca94 cpsr: 0x60000000

Here's a diagram outlining the relationship between the objects shown in the crash report. Basically at app launch the AppDelegate causes a LicenceManger object to be instantiated, which in turn causes a DatabaseManager and Database objects to be created, all of which are model type classes. Meanwhile the GUI is launching with InitialVC being a root VC which instantiates a TabBar VC which causes the instantiation of the SearchVC. The SearchVC accesses the DatabaseModel object and that is where the crash occurs.

enter image description here

And here is the code (reduced to just relevant portions, note the code is Swift except the DataBaseManager is Ojb-C)

////////////////// InitialViewController ////////////////////////////
class InitialViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        self.perform(#selector(InitialViewController.start), with: nil, afterDelay: 1.5)
    }
}

@objc func start() {
    let tbvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "TabBarViewControllerID") as! TabBarViewController
navigationController.pushViewController(tbvc, animated: true)
}



SearchViewController gets created as a consequence of there being a relationship segue between it and TabBarViewControllerSp


///////////////////////// SearchViewController ///////////////////////////////
class SearchViewController: UITableViewController, UISearchBarDelegate {
    var searchResultsList   = DatabaseManager.instance().database.emptyList()  line 67




////////////////////// App Delegate ///////////////////////////
AppDelegate:didFinishLaunchingWithOptions() {
    let _ = LicenseManager.instance
}



//////////////////////// LicenseManager ////////////////////////
@objc class LicenseManager : NSObject {
    @objc open static let instance = LicenseManager()
    private let databaseManager = DatabaseManager.instance()
}

override private init() {
    super.init()
}



///////////////////// DatabaseManager ////////////////////////
+ (DatabaseManager*) instance {
    static DatabaseManager *theInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^ {
        theInstance = [[DatabaseManager alloc] init];
    });
    return theInstance;
}

@interface DatabaseManager()
@property (strong, nonatomic)   Database*  _Nonnull database;
@end


@implementation DatabaseManager
- (id) init {
    self = [super init];
    if (self)
    {
        _database   = Database.instance;
        [_database openOrCreateDatabase];


        dispatch_async(robocallerQueue(), ^{
            [self readCityAndStateData];
        });
    }
}

- (void) readCityAndStateData {
     Populates a very large dictionary > 100K entries
}



////////////////////// Database //////////////////////
@objcMembers class Database : NSObject {
    open static let instance = Database()
    fileprivate var configuration:Realm.Configuration?    = nil

    override init()
    {
    }
}


@objc func openOrCreateDatabase() {
       configuration = Realm.Configuration(encryptionKey: Database.getKey() as Data)
}

class func getKey() -> NSData {
    let string = "AED16D8B-7762-4CBF-A313-48FDCAD51B9C23456754635498123450ka&9dB6t"
    let data = string.data(using: String.Encoding.utf8)
    return data! as NSData
}

func emptyList() -> Results<Caller> {        
    let realm = try! Realm(configuration: configuration!)
    let mdn = "DoesNotExist"
    let searchTerm = "number ==  " + "\"" + mdn + "\""
    let results = realm.objects(Caller.self).filter(searchTerm)
    return results
 }





//////////////// Caller ///////////
@objc public class Caller : Object {
    @objc dynamic var name:String? = nil
    // More simple types, strings, dates, ints etc.
}



from Unable to determine possible causes of EXC_BAD_ACCESS (which occurs during app startup)

In iOS, how can I distinguish a Haptic Touch from a long press?

Apple's recent iPhone XR announcement replaces 3D Touch with Haptic Touch, letting you access 3D Touch features by just long-pressing a view.

I'm curious how that will interact with existing UILongPressGestureRecognizer interfaces. There are items in my app that currently have different 3D Touch and long-press functionality.

Since the iPhone XR hardware isn't yet available, I was wondering if anything had been published about how the two features will work together.



from In iOS, how can I distinguish a Haptic Touch from a long press?

Can end user contact SQL DB if he can write his own Javascript?

I have a website on which i let the user edit the frontend of the website. The user only has access to an editor, not to the server its hosted on.

The user asked me to also allow javascript. This means the user can create his own scripts on the frontend.

What i was worrying was that the user may be use this to do malicious stuff. i'm afraid that if the user knows stuff well enough he might screw over the site.

My questions: - Let's say the user has the connection string of the SQL DB, can he manage to perform queries on that server ? Normally this should be NO as javascript is client side right?

I found the following snippet:

var connection = new ActiveXObject("ADODB.Connection") ;

var connectionstring="Data Source=<server>;Initial Catalog=<catalog>;User ID=<user>;Password=<password>;Provider=SQLOLEDB";

connection.Open(connectionstring);
var rs = new ActiveXObject("ADODB.Recordset");

rs.Open("SELECT * FROM table", connection);
rs.MoveFirst
while(!rs.eof)
{
   document.write(rs.fields(1));
   rs.movenext;
}

rs.close;
connection.close; 

Let's say my connection string looks like

Data Source=(local);Initial Catalog=TestDB;Application Name=TestDB;Integrated Security=True

I have tried to make the script run ,but luckily it showed a blank page. but is this since I'm maybe doing something wrong? or is it indeed cause javascript is client sided and will not allowing doing that sort of stuff?

Other question: - what examples of other risks did i take allowing him to use javascript on the front end? if it's true that javascript is an entirely client side- language, it means that he couldn't do anything else risky right?



from Can end user contact SQL DB if he can write his own Javascript?

sendfile() failed (32: Broken pipe) while sending request to upstream, request: "POST

I'm having issue when uploading file on production using meteor with nginx + passenger. I'm also using meteor files for uploading files. it worked great in development but i can't upload files in production. i got and error in browser console:

POST http://my-url/ net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)

i found error in my passenger log file saying Not keep-aliving application session connection because application did not allow it here is the log:

[ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/HttpChunkedBodyParser.h:183 ]: [Client 63] ChunkedBodyParser: parsing new chunk [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/HttpChunkedBodyParser.h:123 ]: [Client 63] ChunkedBodyParser: chunk size determined: 982 bytes [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/HttpChunkedBodyParser.h:162 ]: [Client 63] ChunkedBodyParser: parsing 982 of 982 bytesof remaining chunk data; 0 now remaining [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:1416 ]: [FBC 0x7f71e801b670] Feeding 982 bytes [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:486 ]: [FBC 0x7f71e801b670] pushBuffer() completed: nbuffers = 1, bytesBuffered = 982 [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:554 ]: [FBC 0x7f71e801b670] Reader: reading next [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:586 ]: [FBC 0x7f71e801b670] Reader: found buffer, 982 bytes [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:493 ]: [FBC 0x7f71e801b670] popBuffer() completed: nbuffers = 0,bytesBuffered = 0 [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:594 ]: [FBC 0x7f71e801b670] Reader: feeding buffer, 982 bytes [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:554 ]: [FBC 0x7f71e801b670] Reader: reading next [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:561 ]: [FBC 0x7f71e801b670] Reader: no more buffers. Transitioning to RS_INACTIVE [ D3 2018-09-27 16:53:44.2194 2500/Ta Ser/FileBufferedChannel.h:539 ]: [FBC 0x7f71e801b670] Calling dataFlushedCallback [ D3 2018-09-27 16:53:44.2194 2500/Ta age/Cor/Con/ForwardResponse.cpp:64 ]: [Client 2-63] Event: onAppSourceData [ D3 2018-09-27 16:53:44.2194 2500/Ta age/Cor/Con/ForwardResponse.cpp:206 ]: [Client 2-63] Processing 7 bytes of application data: "\r\n0\r\n\r\n" [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:248 ]: [Client 63] ChunkedBodyParser: done parsing a chunk [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:183 ]: [Client 63] ChunkedBodyParser: parsing new chunk [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:123 ]: [Client 63] ChunkedBodyParser: chunk size determined: 0bytes [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:162 ]: [Client 63] ChunkedBodyParser: parsing 0 of 0 bytes of remaining chunk data; 0 now remaining [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:164 ]: [Client 63] ChunkedBodyParser: end chunk detected [ D3 2018-09-27 16:53:44.2195 2500/Ta Ser/HttpChunkedBodyParser.h:267 ]: [Client 63] ChunkedBodyParser: end chunk reached [ D2 2018-09-27 16:53:44.2195 2500/Ta age/Cor/Con/ForwardResponse.cpp:224 ]: [Client 2-63] End of application response body reached [ D2 2018-09-27 16:53:44.2195 2500/Ta age/Cor/Con/ForwardResponse.cpp:1077 ]: [Client 2-63] Not keep-aliving application sessionconnection because application did not allow it [ D3 2018-09-27 16:53:44.2195 2500/Ta age/Cor/App/Socket.h:201 ]: Socket unix:/tmp/passenger.toEIX2t/apps.s/node.1si9u5: connection not checked back into connection pool. There are now 2 connections in total [ D2 2018-09-27 16:53:44.2195 2500/Ta age/Cor/App/Gro/SessionManagement.cpp:150 ]: Session closed for process (pid=2519, group=/var/www/hmn/bundle (production))

  • Meteor 1.6.1
  • Meteor-Files 1.9.11
  • Ubuntu 16.04
  • nginx 1.14.0
  • passenger 5.3.5
  • AWS

anybody know how to fix it and explain what is wrong? thank you!



from sendfile() failed (32: Broken pipe) while sending request to upstream, request: "POST

Change host dynamically with SuperAgent

I'm trying to write a test where SuperAgent calls multiple (sub)domains, where cookies should be shared between them. Therefore, I want to swtich the agent dynamically, ie I can't create a new agent because I want the agent to retain cookies throughout.

  agent = request.agent("https://example1.com")
  agent.get('/path')
  agent.changeHost("https://example2.com") // Fake. How to actually do this?
  agent.get('/path') // Now we are retrieving same path from a different host

(syntax based on agency.js example)

I've also tried absolute URLs, ie agent.get('https://example1.com/path'), but that apparently isn't supported (Uncaught TypeError: Cannot read property 'address' of undefined`).



from Change host dynamically with SuperAgent

Change host dynamically with SuperAgent

I'm trying to write a test where SuperAgent calls multiple (sub)domains, where cookies should be shared between them. Therefore, I want to swtich the agent dynamically, ie I can't create a new agent because I want the agent to retain cookies throughout.

  agent = request.agent("https://example1.com")
  agent.get('/path')
  agent.changeHost("https://example2.com") // Fake. How to actually do this?
  agent.get('/path') // Now we are retrieving same path from a different host

(syntax based on agency.js example)

I've also tried absolute URLs, ie agent.get('https://example1.com/path'), but that apparently isn't supported (Uncaught TypeError: Cannot read property 'address' of undefined`).



from Change host dynamically with SuperAgent

why jquery position() method does not have a setter version

I'm currently studying jquery and have noticed most of the method in jquery have a setting and getter version. i.e. the method is used as a setter or as a getter, depending on the type/number of arguments passed to the method.

A example would be the jquery offset() method.

But I have also noticed that the jquery position() method only have a getter version, and its setter version is missing.

Does anyone have any idea why the position() method does not have a setter version? I'm not exactly sure but I think a setter version would be useful in certain situations.



from why jquery position() method does not have a setter version

why jquery position() method does not have a setter version

I'm currently studying jquery and have noticed most of the method in jquery have a setting and getter version. i.e. the method is used as a setter or as a getter, depending on the type/number of arguments passed to the method.

A example would be the jquery offset() method.

But I have also noticed that the jquery position() method only have a getter version, and its setter version is missing.

Does anyone have any idea why the position() method does not have a setter version? I'm not exactly sure but I think a setter version would be useful in certain situations.



from why jquery position() method does not have a setter version

Python flask saml throwing saml2.sigver.SigverError Error Message

Has anyone succesfully implemented flask-saml using Windows as dev environment, Python 3.6 and Flask 1.0.2?

I was given the link to the SAML METADATA XML file by our organisation and had it configured on my flask app.

app.config.update({
    'SECRET_KEY': 'changethiskeylaterthisisoursecretkey',
    'SAML_METADATA_URL': 'https://<url>/FederationMetadata.xml',
})

flask_saml.FlaskSAML(app)

According to the documentation this extension will setup the following routes:

  • /saml/logout/: Log out from the application. This is where users go if they click on a “Logout” button.

  • /saml/sso/: Log in through SAML.

  • /saml/acs/: After /saml/sso/ has sent you to your IdP it sends you back to this path. Also your IdP might provide direct login without needing the /saml/sso/ route.

When I go to one of the routes http://localhost:5000/saml/sso/ I get the error below

saml2.sigver.SigverError saml2.sigver.SigverError: Cannot find ['xmlsec.exe', 'xmlsec1.exe']

I then went to this site https://github.com/mehcode/python-xmlsec/releases/tag/1.3.5 to get xmlsec and install it. However, I'm still getting the same issue.

Here is a screenshot of how I installed xmlsec

where does not seem to find the xmlsec.exe

enter image description here



from Python flask saml throwing saml2.sigver.SigverError Error Message

angular schema-form modal....problems with $scope

Plunker

This plunker allows you to edit rows in a grid. I have created a new method based on RowEditCtrl to insert a new row but am having trouble with the validation.

When I insert a new row, the form is "pristine and valid". In the insert method, I need to call $scope.$broadcast('schemaFormValidate') which will validate the form and form.$valid will be false. Ideally, I would like to call this check from ng-show on the save button so the button does not appear until the form is ok.

The problem is, I don't understand or know how to get the schema-form $scope in this RowEditCtrl method and cannot get the form to be invalid before the user has typed anything.

function RowEditCtrl($modalInstance, PersonSchema, grid, row) {
  var vm = this;
  
  vm.schema = PersonSchema;
  vm.entity = angular.copy(row.entity);
  vm.form = [
    'name',
    'company',
    'phone',
    {
      'key': 'address.city',
      'title': 'City'
    },
  ];
  
  vm.save = save;
  
  function save() {
    // Copy row values over
    row.entity = angular.extend(row.entity, vm.entity);
    $modalInstance.close(row.entity);
  }
}


from angular schema-form modal....problems with $scope

angular schema-form modal....problems with $scope

Plunker

This plunker allows you to edit rows in a grid. I have created a new method based on RowEditCtrl to insert a new row but am having trouble with the validation.

When I insert a new row, the form is "pristine and valid". In the insert method, I need to call $scope.$broadcast('schemaFormValidate') which will validate the form and form.$valid will be false. Ideally, I would like to call this check from ng-show on the save button so the button does not appear until the form is ok.

The problem is, I don't understand or know how to get the schema-form $scope in this RowEditCtrl method and cannot get the form to be invalid before the user has typed anything.

function RowEditCtrl($modalInstance, PersonSchema, grid, row) {
  var vm = this;
  
  vm.schema = PersonSchema;
  vm.entity = angular.copy(row.entity);
  vm.form = [
    'name',
    'company',
    'phone',
    {
      'key': 'address.city',
      'title': 'City'
    },
  ];
  
  vm.save = save;
  
  function save() {
    // Copy row values over
    row.entity = angular.extend(row.entity, vm.entity);
    $modalInstance.close(row.entity);
  }
}


from angular schema-form modal....problems with $scope

Android ndk not bundle v8 .a file symbols

I have a project which similar too J2V8 which bundle v8 to android. But after compile J2V8 has all v8 symbols but similar project lose all v8 symbols. You can check the original J2V8.so here by using nm -D libj2v8.so | grep "GetIsolate", you can get something like 003530fc T _ZN2v815SnapshotCreator10GetIsolateEv 003613c4 T _ZN2v86Object10GetIsolateEv 0035f78c T _ZN2v87Context10GetIsolateEv 0038c354 W _ZNK2v88internal10HeapObject10GetIsolateEv 00503a78 T _ZNK2v88internal11MessageImpl10GetIsolateEv 00503b4c T _ZNK2v88internal16EventDetailsImpl10GetIsolateEv But after compile sample project, the related output is none.



from Android ndk not bundle v8 .a file symbols

Why I can not debug Proxy.newProxyInstance method?

I am using Retrofit on Android.

I define a service GitHubService.

public interface GithubService {

    @GET("users/{user}")
    Call<ResponseBody> fetchUserInfo(@Path("user") String user);

}

Then I create service.

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://api.github.com")
        .build();

GithubService service = retrofit.create(GithubService.class);
Call<ResponseBody> call = service.fetchUserInfo("coxier");
call.enqueue(...);

As you see, I use above code to get user info of github. And above code works well for me. Now I want to know how Retofit works so I read source code.The code below is Retrofit#create. After reading, I still don't know its magic then I decide to debug Retroft.

public <T> T create(final Class<T> service) {
  ...
  return (T) Proxy.newProxyInstance(...,
      new InvocationHandler() {
        ...
        @Override public Object invoke(..)
            throws Throwable {

          if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args);
          }
          ...
          return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
        }
      });
}

I debug at if(method.getDeclaringClass() == Object.class) line ,however it crashes. I don't know why it crashes.

EDIT

I tested several devices.

  • Nexus 6P Android 8.0 : crash when debug
  • Xiaomi 6 Android 8.1: crash when debug
  • OnePlus 3 Android 8.0: crash when debug
  • Nexus 6P Android 7.0:works well when debug
  • Oppo Android 6.0: works well when debug
  • Samsung S4 Android 5.0: works well when debug

It may crash above Android 8.0.



from Why I can not debug Proxy.newProxyInstance method?

iOS crash in testFlight on open

When running the app in test fight it crashes upon opening. The app runs well if tested directly in the simulator or on the device.

I did clean, archive and upload the app again and there was no difference. The Valid Architecture is set only to arm64

This is the error in the console

Attempt to add an app with insufficient id, info {
BKSApplicationStateAppIsFrontmost = 1;
BKSApplicationStateExtensionKey = 0;
SBApplicationStateDisplayIDKey = "org.mydomain.name";
SBApplicationStateKey = 8;
SBApplicationStateProcessIDKey = 677;
SBMostElevatedStateForProcessID = 8;
}

The app is build in react-native

React Native Environment Info:

System:
  OS: macOS High Sierra 10.13.6
  CPU: x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
  Memory: 3.59 GB / 16.00 GB
  Shell: 3.2.57 - /bin/bash
Binaries:
  Node: 8.9.3 - /usr/local/bin/node
  npm: 6.1.0 - /usr/local/bin/npm
  Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
  iOS SDK:
    Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
  Android SDK:
    Build Tools: 23.0.1, 25.0.2, 25.0.3, 26.0.2, 27.0.3
    API Levels: 16, 19, 22, 23, 25, 26, 27
IDEs:
  Android Studio: 3.0 AI-171.4443003
  Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
  react: 16.3.1 => 16.3.1
  react-native: ^0.56.0 => 0.56.0
npmGlobalPackages:
  create-react-native-app: 1.0.0
  react-native-cli: 2.0.1
  react-native-rename: 2.2.2

I have fallowed the guid for release from here https://facebook.github.io/react-native/docs/running-on-device

Any thoughts on how to fix this?



from iOS crash in testFlight on open

iOS crash in testFlight on open

When running the app in test fight it crashes upon opening. The app runs well if tested directly in the simulator or on the device.

I did clean, archive and upload the app again and there was no difference. The Valid Architecture is set only to arm64

This is the error in the console

Attempt to add an app with insufficient id, info {
BKSApplicationStateAppIsFrontmost = 1;
BKSApplicationStateExtensionKey = 0;
SBApplicationStateDisplayIDKey = "org.mydomain.name";
SBApplicationStateKey = 8;
SBApplicationStateProcessIDKey = 677;
SBMostElevatedStateForProcessID = 8;
}

The app is build in react-native

React Native Environment Info:

System:
  OS: macOS High Sierra 10.13.6
  CPU: x64 Intel(R) Core(TM) i7-4770HQ CPU @ 2.20GHz
  Memory: 3.59 GB / 16.00 GB
  Shell: 3.2.57 - /bin/bash
Binaries:
  Node: 8.9.3 - /usr/local/bin/node
  npm: 6.1.0 - /usr/local/bin/npm
  Watchman: 4.9.0 - /usr/local/bin/watchman
SDKs:
  iOS SDK:
    Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
  Android SDK:
    Build Tools: 23.0.1, 25.0.2, 25.0.3, 26.0.2, 27.0.3
    API Levels: 16, 19, 22, 23, 25, 26, 27
IDEs:
  Android Studio: 3.0 AI-171.4443003
  Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
  react: 16.3.1 => 16.3.1
  react-native: ^0.56.0 => 0.56.0
npmGlobalPackages:
  create-react-native-app: 1.0.0
  react-native-cli: 2.0.1
  react-native-rename: 2.2.2

I have fallowed the guid for release from here https://facebook.github.io/react-native/docs/running-on-device

Any thoughts on how to fix this?



from iOS crash in testFlight on open

Unable to load dynamic library 'C:\php\ext\php_pthreads.dll'

I'm trying to have threads in my php code, but I can't get my head around pthreads library and every time I run my program I encounter this error:

Warning: PHP Startup: Unable to load dynamic library 'C:\php\ext\php_pthreads.dll' - The specified module could not be found.in Unknown on line 0

I followed every step needed:

I've added the file pthreadVC2.dll in my "C:\php" folder
I've added the file php_pthreads.dll in my "C:\php\ext"folder
I've modified the file php.ini, enabling the extension: extension=php_pthreads.dll
I've also added pthreadVC2.dll to system32 folder.

Here is my phpinfo():

PHP Version => 5.6.38
Compiler => MSVC11 (Visual C++ 2012)
Architecture => x64

And here is the version of pthreads I used:

php_pthreads-2.0.9-5.6-ts-vc11-x64

I have read similar topics on the issue, even did try everything step by step according to a video tutorial but nothing works. What am I doing wrong?



from Unable to load dynamic library 'C:\php\ext\php_pthreads.dll'

Codeigniter search engine BUG: results pagination items display ALL the posts

I am working on a basic blog application with Codeigniter 3.1.8. and Bootstrap 4. The application has a search posts functionality.

The form in the header view:

<form method="get" action="<?php echo base_url('posts/search') ?>" id="search_form" class="w-100 py-1 px-2 px-md-3 px-lg-5" accept-charset="utf-8">
    <div class="input-group <?php if(form_error('search')) echo 'has-error';?>">
      <input class="form-control form-control-dark" type="text" name="search" placeholder="Search posts..." aria-label="Search">
      <?php if(form_error('search')) echo form_error('search'); ?> 
      <div class="input-group-append">
        <button class="btn btn-success" type="submit"><i class="fa fa-search"></i></button>
      </div>
    </div>
</form>

Since the posts are paginated, so should the search results. The index() and search() methods are both part of the same Posts controller, so I have tried to NOT repeat the pagination's code:

private function _initPagination($path, $totalRows, $query_string_segment = 'page') {
    //load and configure pagination 
    $this->load->library('pagination');
    $config['base_url'] = base_url($path);
    $config['query_string_segment'] = $query_string_segment; 
    $config['total_rows'] = $totalRows;
    $config['per_page'] = 12;
    if (!isset($_GET[$config['query_string_segment']]) || $_GET[$config['query_string_segment']] < 1) {
      $_GET[$config['query_string_segment']] = 1;
    }
    $this->pagination->initialize($config);

    $limit = $config['per_page'];
    $offset = ($this->input->get($config['query_string_segment']) - 1) * $limit;

    return ['limit' => $limit, 'offset' => $offset];
  }

  public function index() {
    //call initialization method
    $config = $this->_initPagination("/posts", $this->Posts_model->get_num_rows());

    $data = $this->Static_model->get_static_data();
    $data['categories'] = $this->Categories_model->get_categories();

    //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
    $this->load->view('partials/header', $data);
    $this->load->view('posts');
    $this->load->view('partials/footer');
  }

  public function search() {
   // Force validation since the form's method is GET
   $this->form_validation->set_data($this->input->get());
   $this->form_validation->set_rules('search', 'Search term', 'required|trim|min_length[3]');
   $this->form_validation->set_error_delimiters('<p class = "error search-error"> ', ' </p>
       ');
    // If search fails
   if ($this->form_validation->run() === FALSE) {
       return $this->index();
   } else {
       $expression = $this->input->get('search');
       $posts_count = $this->Posts_model->search_count($expression);
       $query_string_segment = 'search=' . $expression . '&page';
       $config = $this->_initPagination("/posts/search", $posts_count, $query_string_segment);
       $data = $this->Static_model->get_static_data();
       $data['categories'] = $this->Categories_model->get_categories();
       //use limit and offset returned by _initPaginator method
       $data['posts'] = $this->Posts_model->search($expression, $config['limit'], $config['offset']);
       $data['expression'] = $expression;
       $data['posts_count'] = $posts_count;
       $this->load->view('partials/header', $data);
       $this->load->view('search');
       $this->load->view('partials/footer');
   }
} 

The model:

public function search_count($expression) {
    $query = $this->db->like('title', $expression)
                      ->or_like('description', $expression)
                      ->or_like('content', $expression);
    $query = $this->db->get('posts');
    return $query->num_rows();  
}

public function search($expression, $limit, $offset) {
    $query = $this->db->like('title', $expression)
                        ->or_like('description', $expression)
                        ->or_like('content', $expression);
    $this->db->order_by('posts.id', 'DESC');
    $query = $this->db->get('posts', $limit, $offset);
    return $query->result();
}

The PROBLEM:

The first page of search results displays 12 items containing the search expression, as expected, but all the other pages, display all the posts again.

Since $config['query_string_segment'] is used by the pagination, the line $query_string_segment = 'search=' . $expression . '&page'; should help pass the search expression, via $_GET[], to the pages 1, 2 and so on.

But the page items link does not keep = and &:

<a href="http://localhost/ciblog/posts/search?search%3Dharum%26page=2" data-ci-pagination-page="2">2</a>

Why does that happen? Where is my mistake?



from Codeigniter search engine BUG: results pagination items display ALL the posts

2960x1440 stretching Android Camera Preview

I have a camera preview that works perfectly on almost all of the screens but when I tested my camera with 2960x1440 screen, which for example are on phones S8 and S9, the preview is really stretched.

I have included everything I have on setting the preview size for the Camera.

private static final int MAX_PREVIEW_WIDTH = 2960;
private static final int MAX_PREVIEW_HEIGHT = 1440;

/**
 * Given {@code choices} of {@code Size}s supported by a camera, choose the smallest one that
 * is at least as large as the respective texture view size, and that is at most as large as the
 * respective max size, and whose aspect ratio matches with the specified value. If such size
 * doesn't exist, choose the largest one that is at most as large as the respective max size,
 * and whose aspect ratio matches with the specified value.
 *
 * @param choices           The list of sizes that the camera supports for the intended output
 *                          class
 * @param textureViewWidth  The width of the texture view relative to sensor coordinate
 * @param textureViewHeight The height of the texture view relative to sensor coordinate
 * @param maxWidth          The maximum width that can be chosen
 * @param maxHeight         The maximum height that can be chosen
 * @param aspectRatio       The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int textureViewWidth, int textureViewHeight, int maxWidth, int maxHeight, Size aspectRatio)
{
    List<Size> bigEnough = new ArrayList<>();
    List<Size> notBigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getWidth() <= maxWidth && option.getHeight() <= maxHeight &&
                option.getHeight() == option.getWidth() * h / w) {
            if (option.getWidth() >= textureViewWidth &&
                    option.getHeight() >= textureViewHeight) {
                bigEnough.add(option);
            } else {
                notBigEnough.add(option);
            }
        }
    }
    if (bigEnough.size() > 0)
    {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else if (notBigEnough.size() > 0)
    {
        return Collections.max(notBigEnough, new CompareSizesByArea());
    } else
    {
        return choices[0];
    }
}

/**
 * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
 * width and height are at least as large as the respective requested values, and whose aspect
 * ratio matches with the specified value.
 *
 * @param choices     The list of sizes that the camera supports for the intended output class
 * @param width       The minimum desired width
 * @param height      The minimum desired height
 * @param aspectRatio The aspect ratio
 * @return The optimal {@code Size}, or an arbitrary one if none were big enough
 */
private static Size chooseOptimalSize(Size[] choices, int width, int height, Size aspectRatio) {
    List<Size> bigEnough = new ArrayList<>();
    int w = aspectRatio.getWidth();
    int h = aspectRatio.getHeight();
    for (Size option : choices) {
        if (option.getHeight() == option.getWidth() * h / w &&
                option.getWidth() >= width && option.getHeight() >= height) {
            bigEnough.add(option);
        }
    }
    if (bigEnough.size() > 0) {
        return Collections.min(bigEnough, new CompareSizesByArea());
    } else {
        return choices[0];
    }
}


/**
 * Sets up member variables related to camera.
 * @param width  The width of available size for camera preview
 * @param height The height of available size for camera preview
 */
private void setUpCameraOutputs(int width, int height) {

    System.out.println("Setup camera outputs.");
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);

        assert map != null;

        Size largest = Collections.max(
                Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)),
                new CompareSizesByArea());

        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class)); //640x480

        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                width, height, mVideoSize);
        mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(),
                ImageFormat.JPEG, /*maxImages*/2);
        mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);
        int displayRotation =parentactivity.getWindowManager().getDefaultDisplay().getRotation();
        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        boolean swappedDimensions = false;

        switch (displayRotation) {
            case Surface.ROTATION_0:
            case Surface.ROTATION_180:
                if (mSensorOrientation == 90 || mSensorOrientation == 270)
                {
                    swappedDimensions = true;
                }
                break;
            case Surface.ROTATION_90:
            case Surface.ROTATION_270:
                if (mSensorOrientation == 0 || mSensorOrientation == 180)
                {
                    swappedDimensions = true;
                }
                break;
            default:
        }

        Point displaySize = new Point();
        parentactivity.getWindowManager().getDefaultDisplay().getSize(displaySize);
        int rotatedPreviewWidth = width;
        int rotatedPreviewHeight = height;
        int maxPreviewWidth = displaySize.x;
        int maxPreviewHeight = displaySize.y;

        if (swappedDimensions) {
            rotatedPreviewWidth = height;
            rotatedPreviewHeight = width;
            maxPreviewWidth = displaySize.y;
            maxPreviewHeight = displaySize.x;
        }

        if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
            maxPreviewWidth = MAX_PREVIEW_WIDTH;
        }
        if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
            maxPreviewHeight = MAX_PREVIEW_HEIGHT;
        }

        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                maxPreviewHeight, mVideoSize);

        int orientation = getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        Boolean available = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE);
        mFlashSupported = available == null ? false : available;

    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    catch (CameraAccessException | NullPointerException e) {
        e.printStackTrace();
    }
}

 /**
 * Creates a new {@link CameraCaptureSession} for camera preview.
 */
private void createCameraPreviewSession()
{
    if (null == mCameraDevice || !mTextureView.isAvailable() || null == mPreviewSize) {
        return;
    }
    try
    {
        closePreviewSession();
        SurfaceTexture texture = mTextureView.getSurfaceTexture();
        assert texture != null;
        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Surface surface = new Surface(texture);
        mPreviewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);
        mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                new CameraCaptureSession.StateCallback() {

                    @Override
                    public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession)
                    {
                        if (null == mCameraDevice) {
                            return;
                        }
                        mCaptureSession = cameraCaptureSession;

                        try {
                            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                            mPreviewRequest = mPreviewRequestBuilder.build();
                            mCaptureSession.setRepeatingRequest(mPreviewRequest,
                                    mCaptureCallback, mBackgroundHandler);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onConfigureFailed(
                            @NonNull CameraCaptureSession cameraCaptureSession)
                    {
                        showToast("Failed to configure camera.");
                    }
                }, null
        );
    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * Configures the necessary {@link Matrix} transformation to `mTextureView`.
 * This method should be called after the camera preview size is determined in
 * setUpCameraOutputs and also the size of `mTextureView` is fixed.
 * @param viewWidth  The width of `mTextureView`
 * @param viewHeight The height of `mTextureView`
 */
private void configureTransform(int viewWidth, int viewHeight) {
    if (null == mTextureView || null == mPreviewSize || null == parentactivity) {
        return;
    }
    int rotation =parentactivity.getWindowManager().getDefaultDisplay().getRotation();
    Matrix matrix = new Matrix();
    RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
    RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
    float centerX = viewRect.centerX();
    float centerY = viewRect.centerY();
    if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
        bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
        matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
        float scale = Math.max(
                (float) viewHeight / mPreviewSize.getHeight(),
                (float) viewWidth / mPreviewSize.getWidth());
        matrix.postScale(scale, scale, centerX, centerY);
        matrix.postRotate(90 * (rotation - 2), centerX, centerY);
    } else if (Surface.ROTATION_180 == rotation) {
        matrix.postRotate(180, centerX, centerY);
    }
    mTextureView.setTransform(matrix);
}

Since I do not quite understand what is wrong here when scaling the preview size to 2960x1440, I would be really thankful if someone could help me with this.

Just in case I have added a link to the complete code Pastebin Link to Camera



from 2960x1440 stretching Android Camera Preview

slate.js based reactjs rich text editor reverse engineering

it all started from watching two slate.js demo videos in youtube

  1. https://www.youtube.com/watch?v=8K-qYdOPKT4
  2. https://www.youtube.com/watch?v=BMID1FbEZSk&t=3s

His name is Andrei Fiodorov and he showed in those demos how his rich text editor works using slate.js library. In the comment section he shared a snippet of code which is a glimpse of the overall code. I have started a sandbox pen here

https://codesandbox.io/s/rvp8j5q7n

looks like he used Materialize and npgrogress in his project. I a noob in React. I am interested about the beautiful UI Mr Andrei Fiodorov created successfully. But unfortunately couldn't render the page yet. I will be grateful if anybody could help me to render the UI.



from slate.js based reactjs rich text editor reverse engineering

Exclude some of the lazy modules from the build (Angular5)

I am working on a project, which runs at multiple customers. There are many lazy loaded modules, and most of them is used by all of the customers. But there are some modules, which are only needed in a few places, so I would like to exclude them from the build everywhere else.

Is it possible?



from Exclude some of the lazy modules from the build (Angular5)

Exclude some of the lazy modules from the build (Angular5)

I am working on a project, which runs at multiple customers. There are many lazy loaded modules, and most of them is used by all of the customers. But there are some modules, which are only needed in a few places, so I would like to exclude them from the build everywhere else.

Is it possible?



from Exclude some of the lazy modules from the build (Angular5)

Retrieving owner information on Samsung Galaxy S9

I am trying to programmatically obtain the user's profile information in an Android application. This works fine on a Pixel phone but doesn't return any results on a Samsung phone. For example:

String contactId = null;

// getting contacts ID
Cursor cursorID = getContentResolver().query(ContactsContract.Profile.CONTENT_URI,
            new String[]{ContactsContract.Contacts._ID},
            null, null, null);

if (cursorID.moveToFirst()) {
    contactId = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}

On the Pixel this returns the contact id of the phone's owner. On the Galaxy the cursor is empty. I'm assuming this is because Samsung is using some proprietary version of contacts that is not exposed through the standard Android API. Can anyone confirm? Is there an alternative for Samsung devices?



from Retrieving owner information on Samsung Galaxy S9

how to configure swagger UI to allow user to entry multiple values for query string parameter

I am using django-rest-swagger==2.1.2 and djangorestframework==3.7.7 and I have a view that looks like this:

class PendingRequests(generics.GenericAPIView):
    ...
    filter_backends = (PendingRequestsFilter,)

    def get(self, request):
        ...
        request_status = request.GET.getlist('status')
        request_start_date = request.GET.get('start_date')
        request_end_date = request.GET.get('end_date')
        ...

and I have defined a filter like so:

class PendingRequestsFilter(BaseFilterBackend):
    def get_schema_fields(self, view):
        fields = [
            coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='active'),
            coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='pending'),
            coreapi.Field(name="status", description="Statuses of the Requests", required=False, location='query', example='inactive'),
            coreapi.Field(name="start_date", description="Start Date of the Request (YYYY-MM-DD)", required=False, location='query', example='2525-12-25'),
            coreapi.Field(name="end_date", description="End Date of the Request (YYYY-MM-DD)", required=False, location='query', example='2525-12-26'),
        ]
        return fields

This results in my swagger UI for this view looking like this:

enter image description here

But when I enter different status like so ...

enter image description here

... and click 'try it out' I get a Request URL that looks like this:

http://myserver:4800/api/v1/sudorequests/requests/?status=pending&status=pending&status=pending

Note that status=pending is repeated three times. I wanted to get a Request URL that looks more like this:

http://myserver:4800/api/v1/sudorequests/requests/?status=inactive&status=active&status=pending



from how to configure swagger UI to allow user to entry multiple values for query string parameter

Import vendored dependencies in Python package without modifying sys.path or 3rd party packages

Summary

I am working on a series of add-ons for Anki, an open-source flashcard program. Anki add-ons are shipped as Python packages, with the basic folder structure looking as follows:

anki_addons/
    addon_name_1/
        __init__.py
    addon_name_2/
        __init__.py

anki_addons is appended to sys.path by the base app, which then imports each add_on with import <addon_name>.

The problem I have been trying to solve is to find a reliable way to ship packages and their dependencies with my add-ons while not polluting global state or falling back to manual edits of the vendored packages.

Specifics

Specifically, given an add-on structure like this...

addon_name_1/
    __init__.py
    _vendor/
        __init__.py
        library1
        library2
        dependency_of_library2
        ...

...I would like to be able to import any arbitrary package that is included in the _vendor directory, e.g.:

from ._vendor import library1

The main difficulty with relative imports like this is that they do not work for packages that also depend on other packages imported through absolute references (e.g. import dependency_of_library2 in the source code of library2)

Solution attempts

So far I have explored the following options:

  1. Manually updating the third-party packages, so that their import statements point to the fully qualified module path within my python package (e.g. import addon_name_1._vendor.dependency_of_library2). But this is tedious work that is not scalable to larger dependency trees and not portable to other packages.
  2. Adding _vendor to sys.path via sys.path.insert(1, <path_to_vendor_dir>) in my package init file. This works, but it introduces a global change to the module look-up path which will affect other add-ons and even the base app itself. It just seems like a hack that could result in a pandora's box of issues later down the line (e.g. conflicts between different versions of the same package, etc.).
  3. Temporarily modifying sys.path for my imports; but this fails to work for third-party modules with method-level imports.
  4. Writing a PEP302-style custom importer based off an example I found in setuptools, but I just couldn't make head nor tail of that.

I've been stuck on this for quite a few hours now and I'm beginning to think that I'm either completely missing an easy way to do this, or that there is something fundamentally wrong with my entire approach.

Is there no way I can ship a dependency tree of third-party packages with my code, without having to resort to sys.path hacks or modifying the packages in question?



from Import vendored dependencies in Python package without modifying sys.path or 3rd party packages

Setting up PHP-FPM, Nginx, Mariadb on CentOs using docker

I'm trying to move from from using VirtualBox as my development environment to docker.

With VirtualBox, I mainly install PHP-FPM, Nginx and Mariadb but in Docker, I can't replicate the same stack despite trying for some days.

Out of all the LEMP/LAMP stack docker guides, only this one chentex/docker-nginx-centos works for me:

Here is the code from the Dockerfile

FROM centos:centos7
LABEL maintainer="Vicente Zepeda <chente.z.m@gmail.com>"

ENV nginxversion="1.12.2-1" \
    os="centos" \
    osversion="7" \
    elversion="7_4"

RUN yum install -y wget openssl sed &&\
    yum -y autoremove &&\
    yum clean all &&\
    wget http://nginx.org/packages/$os/$osversion/x86_64/RPMS/nginx-$nginxversion.el$elversion.ngx.x86_64.rpm &&\
    rpm -iv nginx-$nginxversion.el$elversion.ngx.x86_64.rpm &&\
    sed -i '1i\
    daemon off;\
    ' /etc/nginx/nginx.conf

CMD ["nginx"]

This works right out of the box, and I can see a default page on http://localhost

The only problem is that, it does not contain PHP-FPM and Mariadb.

I tried to alter the file and add PHP-FPM and Mariadb, but I found out on reddit that each container should have on service, as in one container for nginx, and another for php ... and I'm lost on how to make that



from Setting up PHP-FPM, Nginx, Mariadb on CentOs using docker

Is there a way to add badge notifications using progressive web apps (PWA)?

I'm developing a progressive web application (PWA) that will eventually send notifications to users.

I already know that I'm able to send push notifications (like in any regular app), as explained in the following blog post: https://developers.google.com/web/fundamentals/getting-started/codelabs/push-notifications/?hl=en-us.

I also know that I can add a PWA to the home screen, by creating a simple manifest file (https://developers.google.com/web/updates/2014/11/Support-for-installable-web-apps-with-webapp-manifest-in-chrome-38-for-Android).

However, after having the app in home screen, I would like to add a "hint" to user, letting him know that he has to access the application. A great way to do that is doing something like a "badge notification" (as showed in Facebook icon on the image below).

Image showing a badge notification example on the Facebook icon

Is it possible to add this kind of behavior using progressive web applications?


Update - September, 28th, 2018

Relevant Links

As Josh Lee pointed out in Is there a way to add badge notifications using progressive web apps (PWA)?, there are some discussions about the subject on the chromium team.

Looking at the discussion:

FYI, the notification indicators are being pushed to M-71.

and

Thanks for the heads up. That's fine for us because while we hope to have this testable behind a flag in M70, there's no way we'll be launching the API before (at least) M71.

So, maybe, at least for now, it seems that it's not possible to add badge notifications for PWAs, but maybe in the future we'll be able to do that.



from Is there a way to add badge notifications using progressive web apps (PWA)?

Saturday 29 September 2018

d3.event is null in modular d3 project

I am doing a project with the following structure:

root
|
|____js
|     |__index.js
|
|__node_modules
|             |__d3-*
|             
|
|__index.html
|__package.json

index.html:

<head>
    <script src="https://unpkg.com/getlibs"></script>
</head>

<body>
<div id="detail"></div>
</div>
<!--script type="module" src="./js/index.js"></script> Also tried this method -->

<script>
    System.import('./js/index.js');
</script>
</body>

index.js:

import {select} from "d3-selection";
import {event as currentEvent} from "d3-selection";
let svg = select('#detail')
        .append('svg')
        .attr('width', 500)
        .attr('height', 500);
        svg.on('click', function() {
            console.log(window.event);
            console.log(currentEvent);
         });

And the output is:

MouseEvent {isTrusted: true, screenX: 266, screenY: 247, clientX: 266, clientY: 175, …}
null

If I use d3 globally through a script tag, referring to it inside the module via window.d3, then d3.event correctly catches the mouse event. I want to create a modular project and avoid having a global d3 object.

Is that achievable, and if so, how?



from d3.event is null in modular d3 project

Possible Combination of Parentheses in a Matrix Chain Application

I have studied matrix chain multiplication, wherein given a sequence of matrices, the goal is to find the most efficient way to multiply matrices. The problem is not actually to perform the multiplications, but merely to decide the sequence of the matrix multiplications involved. That is the reason why I am tasked to make a program that outputs all possible combinations of matrices in a matrix multiplication given n as the number of matrices as an input. For example

 n == 1     (A)

 n == 2     (AB)

 n == 3     (AB)C ,  A(BC)

 n== 4      ((AB)C)D,   (A(BC))D, A((BC)D), A(B(CD)), (AB)(CD)

My intial code was below, called by

 possible_groupings(4) #4 matrices

def possible_groupings(n):
    print("Possible Groupings : ")
    total  = 0
    if(n==1):
        print('A')
        total = total + 1
    elif(n==2):
       print('(AB)')
       total = total + 1
    else:
       a = 2
       while(a <= n-1):
           b = 0
           while((b+a) <= (n )):
               c = b

               d = 0
               substr = ''
               while (d < c):                    
                   substr = substr + chr(65 + d)                    
                   d = d + 1

               if substr != '':
                   if len(substr) == 1:
                      print( substr, end = '')
                   else:
                      print('(' + substr + ')', end = '')

            print('(', end = '')
            while (c < (b +a)):                    
                print(chr(65 + c), end = '');
                c = c + 1
            print(')', end = '')

            e = b+a

            substr = ''
            while (e < n):
                substr = substr + chr(65 + e) 
                e = e + 1
            if substr != '':
                if len(substr) == 1:
                    print( substr, end = '')
                else:
                    print('(' + substr + ')', end = '')
            print('')

            total = total + 1

            b = b + 1
        a = a + 1
print('Total : ' + str(total))

The output of the code above when my inout is 4 matrices is:

(AB)(CD)
A(BC)D
(AB)(CD)
(ABC)D
A(BCD)

How can I revise my code. The number of matrices must be in the range 1-26. My head now is aching. Please help.



from Possible Combination of Parentheses in a Matrix Chain Application

How to save requests (python) cookies to a file?

How to use the library requests (in python) after a request

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
bot = requests.session()
bot.get('http://google.com')

to keep all the cookies in a file and then restore the cookies from a file.



from How to save requests (python) cookies to a file?

Displaying Depth Map from PHAsset

I am trying to read the depth map and overlay it over the UIImageView of a PHAsset.

So far I have this:

PHImageManager.default().requestImageData(for: self.asset!, options: nil, resultHandler:{ (data, responseString, orientation, info) -> Void in
    if let imageData: Data = data {
        if let imageSource = CGImageSourceCreateWithData(imageData as CFData, nil) {

            let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)! as NSDictionary

            let auxDataType = kCGImageAuxiliaryDataTypeDisparity
            let auxDataInfo = CGImageSourceCopyAuxiliaryDataInfoAtIndex(imageSource, 0, auxDataType)
            if auxDataInfo == nil {
                print ("NO DEPTH")
            } else {
                do {
                    var depthData = try AVDepthData(fromDictionaryRepresentation: auxDataInfo as! [AnyHashable : Any])
                    if depthData.depthDataType != kCVPixelFormatType_DisparityFloat16 {
                        depthData = depthData.converting(toDepthDataType: kCVPixelFormatType_DisparityFloat16)
                    }
                    let depthMap : CVPixelBuffer = depthData.depthDataMap
                    var ciImage = CIImage(cvPixelBuffer: depthMap)
                    ciImage = ciImage.applyingFilter("CIDisparityToDepth", parameters: [:])
                    DispatchQueue.main.async {
                        self.imageView.image = UIImage(ciImage: ciImage)
                    }
                }
                catch { }

            }
        }

    }
})

Issues:

  1. Depth map is incorrect and seems to be vague.
  2. Orientation of depth map is incorrect
  3. Depth map color is red for some reason


from Displaying Depth Map from PHAsset

How can I host an Android APK file for every pull-request, so QA can test them before merging?

In order to improve our QA workflow, we want to automatically build an APK file for each pull-request on Github so we can test it BEFORE the branch is merged. We already figured out how to build the file, but we are now wondering how to integrate this in our workflow.

It seems like most available Beta programs (e.g. Crashlytics Beta, Google Play) mostly focus on creating one beta version shortly before the release, but don't allow hosting multiple APKs in parallel.

Here's an example for our ideal workflow:

  1. Developer finishes coding and creates a pull-request
  2. Tests run
  3. If tests are successful, an APK is built automatically and uploaded somewhere (that's the part we're trying to figure out)
  4. QA takes a look at the pull-request and should be able to easily download the correct APK on their testing device
  5. If there are no issues during QA, the pull-request is merged
  6. The APK file is automatically deleted

We specifically don't want to test the APK after the pull-request has been merged, but instead test before so less bugs pop up in our develop branch.



from How can I host an Android APK file for every pull-request, so QA can test them before merging?

Equivalent of jQuery.active in javascript Selenium Web Driver

I am using selenium webdirver to interact with some website.
If the website is using jQuery we can get the pending ajax request by using jQuery.active.

 JavascriptExecutor jsx = (JavascriptExecutor) driver;

Int totAjaxRequest = (Int)jsx.executeScript("jQuery.active");

Int totAjaxRequest = (Int)jsx.executeScript("return jQuery.active");

In case if the website is not using jQuery how can we count the number of XMLHttpRequest request.



from Equivalent of jQuery.active in javascript Selenium Web Driver

Equivalent of jQuery.active in javascript Selenium Web Driver

I am using selenium webdirver to interact with some website.
If the website is using jQuery we can get the pending ajax request by using jQuery.active.

 JavascriptExecutor jsx = (JavascriptExecutor) driver;

Int totAjaxRequest = (Int)jsx.executeScript("jQuery.active");

Int totAjaxRequest = (Int)jsx.executeScript("return jQuery.active");

In case if the website is not using jQuery how can we count the number of XMLHttpRequest request.



from Equivalent of jQuery.active in javascript Selenium Web Driver

Xcode iOS Notability "zoom box"

Notability and other note taking apps have this 'zoom box' feature where you can draw in the magnified box at the bottom. Users can also drag the box at the top to change what they want magnified at the bottom. I have tried literally everything I can think of to add this feature in my app. I have added the same document in two views but then I run into many memory issues, I've duplicated the file but again memory issues. Does anyone know a simple way to do this? Is there anyway I can just have a view that is a magnification of another view?

enter image description here



from Xcode iOS Notability "zoom box"

PyInstaller ImportError DLL not found when testing EXE on other computer

I built an EXE file from a Python script using PyInstaller, using

pyinstaller --onefile myscript.py

Packages I used:

pandas, numpy, imutils, opencv, logging, os, random, json, string, csv, datetime, uuid

The EXE runs fine on my PC. However, when I try it on another PC I get the error shown in this screenshot: https://www.screencast.com/t/msZrURL4v

Any idea what the problem is?



from PyInstaller ImportError DLL not found when testing EXE on other computer

AutoFill username and password in iOS 12

I implemented AutoFill for stored username and password suggestion successfully in iOS 11.
I have two text fields in my login view controller, one for email, one for password. The content types are defined as follows:

email / username text field configuration
email / username text field configuration

password text field configuration password text field configuration

This used to work just fine in iOS 11, but after upgrading my development iPad to iOS 12, the app suggests emails for the username field and the following happens when editing the password field:

actual result


In my create account view controller, I have 3 text fields: email, password, repeat password. Their content modes are setup as follows:

  • email → email address
  • password → new password, rule: minlength:8;
  • repeat password → new password, rule: minlength:8;

When editing the email address field, it properly suggests an email address. For the password and repeat password fields, however, it suggests stored passwords, instead of suggesting a new password.


What I tried

  • (illogically) flip the content mode setup, so the login password field is set to new password and the create account password fields are set to password
    • no success; in fact, no change of behavior at all
  • set content mode to none for login and create account fields so AutoFill can try to handle it automatically
    • no success; in fact, no change of behavior at all

Note

  • AutoFill is properly setup on the server. The stored passwords being suggested in the create account fields prove that
  • The functionality is still working on iOS 11 iPads
  • When logging in with a new username, the app will ask the user to add this username and password to Keychain, even on iOS 12

Any idea what I need to change so that stored username & password suggestion works in iOS 12 again?

Thanks!



Edit

As requested by @kralex below, here's my view hierarchy for the login view controller in the storyboard:

view hierarchy in storyboard

...and on the device:

view hierarchy on device



from AutoFill username and password in iOS 12

'This socket is closed' when stdout is listened in Mocha test

This test

it.only('should not throw', () => {
    var output = '';

    function callback(data) {
        output += data.toString();
    }

    process.stdout.on('data', callback); // error is thrown at this line
    // ...
    process.stdout.removeListener('data', callback);
})

throws an error:

Error: This socket is closed                                                                           
    at WriteStream.Socket._writeGeneric (net.js:679:19)                                                
    at WriteStream.Socket._write (net.js:730:8)                                                        
    at doWrite (_stream_writable.js:331:12)                                                            
    at writeOrBuffer (_stream_writable.js:317:5)                                                       
    at WriteStream.Writable.write (_stream_writable.js:243:11)                                         
    at WriteStream.Socket.write (net.js:657:40)                                                        
    at Console.log (console.js:43:16)                                                                  
    at Runner.<anonymous> (node_modules\mocha\lib\reporters\spec.js:80:13)
    at emitTwo (events.js:111:20)                                                                      
    at Runner.emit (events.js:191:7)                                                                   
    at Runner.fail (node_modules\mocha\lib\runner.js:251:8)               
    at Runner.uncaught (node_modules\mocha\lib\runner.js:757:8)           
    at process.uncaught (node_modules\mocha\lib\runner.js:839:10)         
    at emitOne (events.js:96:13)                                                                       
    at process.emit (events.js:188:7)                                                                  
    at process._fatalException (bootstrap_node.js:297:26)                                              

Where node_modules\mocha\lib\reporters\spec.js:80:13 are these Mocha lines:

  runner.on('fail', function(test) {
    console.log(indent() + color('fail', '  %d) %s'), ++n, test.title);
  });

It's supposed to test code that outputs to process.stdout with spawn, but I wasn't able to get to this part; the error is thrown instantly on process.stdout.on('data', ...) call.

The problem persists with latest Mocha (5.2.0) and default configuration, a reporter in use doesn't affect the result.

What is going on and how can process.stdout be listened? If this is impossible, how can stdout from spawned process be tested in Mocha otherwise?



from 'This socket is closed' when stdout is listened in Mocha test

Extend Array methods

I have a custom array class that extends the base array class. I have a custom method for ease of use

export class ExampleArray extends Array {
    includesThing(thing) {
        ...

        return false
    }
}

However the existing methods of filter, map etc return an instance of an array. I would like to return an instance of ExampleArray with these methods.

I can find the interface for these methods, but not their implementation. How do I call the parent method and return my custom EampleArray instead? Something like the following

export class ExampleArray extends Array {
    filter() {

    result = Array.filter()
    array = new ExampleArray()
    array.push(...result)

    return array
}

Or is this even the correct way to extend an Array to make a custom array?



from Extend Array methods

Running Instrumented Test with arguments using command prompt

I've an InstrumentedTest

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
    @Test
    public void useAppContext(String groupName) {
Context appContext = InstrumentationRegistry.getTargetContext();
        UiDevice device=UiDevice.getInstance(getInstrumentation());
...
...
  }
}

And I want to execute it using adb shell command. But I've to pass value of groupName parameter for the method useAppContext(String groupName)

I was using command

adb shell am instrument -w -r   -e debug false -e class 'com.<package_name>.ExampleInstrumentedTest' com.<package_name>.test/android.support.test.runner.AndroidJUnitRunner  

But how can I pass method parameters as arguments to the command running over command prompt?



from Running Instrumented Test with arguments using command prompt

Removing [ts] errors from JS files In VS Code

I get these TypeScript errors VS Code while I'm working in JS files. Is there anything I can do to disable this? I have put this in my settings and did not solve the issue:

"typescript.validate.enable": false

The error can been seen here

enter image description here



from Removing [ts] errors from JS files In VS Code

Cannot properly set RequestOptionsArgs of POST, in service

I use angular 6 and I was following along a video tutorial to submit images.

I would like to observe the progress of the form submission, so I can get the percentage of the uploaded file.

I have this in my component

this.http.post('http://localhost:3000/cms/upload',myFormData,{reportProgress:true,observe:'events'}).subscribe(
  event=>{
    console.log('event - ', event);       
});

This works fine and I get the event in console.log.

I try to "split" this now in two parts. Turn the post and its headers and its parameters to a function in my service, and just subscribe and get the results in the component. I try to do this:

myapp.component.ts

this.myService.uploadImage(form).subscribe(
  e=>{
    console.log('e- ',e);
  }
);

and in my service myapp.service.ts

  uploadImage(data) {
    let formData = new FormData(data);
    let headers = new Headers();    
    headers.append('Authorization',this.token);
    return this.http.post('http://localhost:3000/cms/upload',formData,{reportProgress:true, observe:'events', headers:headers});
  }

VScode says Argument of type {reportProgress:boolean;observe:string;headers:Headers} is not assingable to parameter of type RequestOptionsArgs

During compile I get Object literal may only specify known properties, and 'reportProgress' does not exist in type 'RequestOptionsArgs'. and when I try to use the form I get just the final response object back, with no event info in between.

So, how can I properly set my RequestOptionsArgs ?

Thanks



from Cannot properly set RequestOptionsArgs of POST, in service

JobScheduler JobService is startet without Application

We converted our main Application class to Kotlin recently.
Since then we are experiencing crashes, especially during the night (when our application was probably killed by the system), when our JobService is startet.

We are accessing the Application Context in a static way for some dependencies which worked pretty well before we converted the class to Kotlin. Since then the static getter is a lateinit var which is initialised in the applications onCreate function.

After the release Google Play reported these crashes:

Caused by: kotlin.UninitializedPropertyAccessException: 
  at x.y.z.application.App.access$getAppContext$cp 
  [...]
  at x.y.z.jobs.JobSchedulerService.onCreate (JobSchedulerService.java:27)  

Which leads to the question, is our Application.onCreate() not executed yet?

We refactored the JobService a little bit to reduce the amount of static context access until a major refactoring would be necessary. After that, we received these crashes from our users in Google Play Console:

Caused by: kotlin.UninitializedPropertyAccessException: 
  at org.koin.standalone.StandAloneContext.getKoinContext (StandAloneContext.java:45)
  at org.koin.java.standalone.KoinJavaComponent.get (KoinJavaComponent.java:66)
  at org.koin.java.standalone.KoinJavaComponent.get$default (KoinJavaComponent.java:64)
  at org.koin.java.standalone.KoinJavaComponent.get (KoinJavaComponent.java)
  at x.y.z.SearchState.<init> (SearchState.java:21)
  [...]
  at x.y.z.jobs.JobSchedulerService.onStartJob (JobSchedulerService.java:54)

These crashed tell us the same thing: Application.onCreate() was not executed yet because Koin is not initialised.

So my question? Why would the execution time of Application.onCreate() change when converting to Kotlin or why is our Application not created anymore before the JobService is startet?

I mean, sure, we could refactored the whole application dependencies to use the context provided by the JobService itself, but what if the application is created afterwards and we still want to use Koin? Our app will probably crash again with an AlreadyStartetException. And if our Application is not "there" yet, what context would the service have?

Sources (simplified):

Application

abstract class App : MultiDexApplication() {

    companion object {
        @JvmStatic
        lateinit var appContext: Context
        @JvmStatic
        val isDevelopment: Boolean = BuildConfig.DEBUG
    //  @JvmStatic
    //  val isDevelopment: Boolean by lazy { 
    //      appContext.resources.getBoolean(R.bool.isDevelopment) 
    //  }
    }

    override fun onCreate() {
        super.onCreate()

        appContext = applicationContext
        startKoin(
                applicationContext,
                listOf(
                        coreModule,
                        sharedPrefsModule
                )
        )

    }
}

JobService

public class JobSchedulerService extends JobService implements OnFinishListener {

    @Override
    public boolean onStartJob(JobParameters params) {

        if (App.isDevelopment()) { //First crash cause `isDevelopment` relied on App.appContext
            ...
        }
        this.mJobParameters = params;

        this.mStateMachine = StateContext.getInstance(getApplication());
        mStateMachine.setOnFinishListener(this);
        mStateMachine.execute("" + params.getJobId()); //Second crash is in the first executed state auf this state Machine

        return true;
    }
}

SearchState

public class SearchState extends State {

    //Koin Crash in SearchState.<init>
    private PlacemarkRepository placemarkRepository = get(PlacemarkRepository.class);

    ...
}



from JobScheduler JobService is startet without Application