Thursday 31 May 2018

Audio recording issue in Oreo using Bluetooth headset

Does anybody experiencing Audio recording issue in Android Oreo using Bluetooth headset ?.

In my application audio recorded in a Foreground service. I start recording after Bluetooth SCO is connected. Its working fine form Android KitKat to Nougat. But when I tried with Huawei Honor 8 (Android Oreo), audio is recording from phone microphone instead of Bluetooth headset microphone. When I tried on Google pixel 2, the recording not works at all.



from Audio recording issue in Oreo using Bluetooth headset

How to prevent click event triggering base on life an element?

In fact, I've done a project that creates tab dynamically. For example, when you each time click on email button, it creates a new tab and also in the new tab there is ('x') symbol to remove that. Indeed, I want to prevent click event triggering multiple tabs. If a user clicks on 'x' symbol .so, I can create a new tab.

http://jsfiddle.net/v6awanwn/1/

#mainTab li span {
    position: relative;
    top: -31px;
    left: 5px;
}


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link href="common.css" rel="stylesheet" />
</head>
<body>
    <div>
        <ul>
            <li class="gtab">
                <a><span title="Email">Email</span></a>
            </li>
            <li class="gtab">
                <a><span title="system">system</span></a>
            </li>
        </ul>
    </div>
    <div class="tabbable" id="tabpanel">
        <ul id="mainTab" class="nav nav-tabs"></ul>
        <div class="tab-content">
        </div>
    </div>
   <script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <script src="common.js"></script>
</body>
</html>


$("#mainTab").on("click", "a", function (e) {


    $(this).tab('show');

})
    .on("click", "span", function () {
        var anchor = $(this).siblings('a');
        $(anchor.attr('href')).remove();
        $(this).parent().remove();
        $(".nav-tabs li").children('a').first().click();
    });

$('.gtab').click(function (e) {

   var id = $("#mainTab").children().length + 1; 
    var tabId = 'contact_' + id;
    var tabtitle = $(this).find('span').html();

    $('#mainTab').closest('li').before('<li><a href="#contact_' + id + '">New Tab</a> <span> x </span></li>');
    $('<li><a href="#contact_' + id + '">' + tabtitle + '</a> <span> x </span></li>').appendTo('#mainTab');
    $('#tabpanel .tab-content').append('<div style="height:400px;" class="tab-pane" id="' + tabId + '">' + tabtitle + '</div>');

    $('#mainTab li:nth-child(' + id + ') a').click();
});



from How to prevent click event triggering base on life an element?

Incoming call listener sleeps after couple of hours

since couple of weeks facing issue with telephony manager api in Android, having listener for incoming call based on listener starting Recording and on end call stopping recording (The process working smoth)

ISSUE
What i am facing issue is that in some mobiles its working all the time, in some of mobile Broadcast listener of telephony manager stops working after few hour, after few research i found solution that use wake-lock for preventing the cpu to sleeps, tried this also but all is vain same issue.

   @Override
public void onReceive(Context context, Intent intent) {
//We listen to two intents.  The new outgoing call only tells us of an 
 //outgoing  call.  We use it to get the number.
    roPlantPrefs = RoPlantPrefs.getInstance(context);
    databaseHelper = new DatabaseHelper(context);
     //lastState = roPlantPrefs.getLastState();

    if (roPlantPrefs.getLogin()) {


        if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
            savedNumber = intent.getExtras().getString("android.intent.extra.PHONE_NUMBER");
        } else {

            roPlantPrefs = RoPlantPrefs.getInstance(context);
 //            if (!roPlantPrefs.getIsOnCall()) {

            String stateStr = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);
            String number = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);

            int state = 0;
            if (stateStr.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                state = TelephonyManager.CALL_STATE_IDLE;
            } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                state = TelephonyManager.CALL_STATE_OFFHOOK;
            } else if (stateStr.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                state = TelephonyManager.CALL_STATE_RINGING;
            }


            onCallStateChanged(context, state, number);
        }
    }


   //        }
}      

Also used timer and alarm manger but its work maximum 2 to 3 hours than listener stop working, Any help could be appreciated.



from Incoming call listener sleeps after couple of hours

Geting CPU usage per Process of Chrome

I developed a Chrome-Extension and want to know if it is possible to get CPU usage of any tab in Chrome (please see the image)? I saw a few questions which are very old. Maybe there is some new techniques to get the CPU usage for each tab.

enter image description here



from Geting CPU usage per Process of Chrome

PHP - Compare multidimensional sub-arrays to each other and merge on similarity threshold

Introduction - This question has been updated the 27th May 2018:

I have 1 PHP multidimensional-array, containing 6 sub-arrays, each containing 20 sub-sub-arrays, which in turn, each contain 2 sub-sub-arrays, one being a string (header), the other being an unspecified number of keywords (keywords).

I am looking to compare each of the 120 sub-sub-arrays to the 100 other sub-sub-arrays contained in the remainint 5 sub-arrays. So that sub-sub-array1 in sub-array1 is compared to sub-array1 to and including sub-array20 in sub-array2 to and including sub-array6, and so forth.

If enough keywords in two sub-sub-arrays are deemed identical and headers are as well, both using Levenshtein distance, the sub-sub-arrays will be merged.


Example script

I have written a script doing exactly this, but for two separate arrays to demonstrate my goal:

<?php
// Variable deciding maximum Levenshtein distance between two words. Can be changed to lower / increase threshhold for whether two keywords are deemed identical.
$lev_point_value = 3;

// Variable deciding minimum amount of identical (passed the $lev_point_value variable) keywords needed to merge arrays. Can be changed to lower / increase threshhold for how many keywords two arrays must have in common to be merged.
$merge_tag_value = 4;

// Variable deciding minimum Levenshtein distance between two headers needed to merge arrays. Can be changed to lower / increase threshhold for whether two titles are deemed identical.
$merge_head_value = 22;

// Array1 - A story about a monkey, includes at header and keywords.
$array1 = array (
        "header" => "This is a story about a monkey.",
        'keywords' => array( "Trees", "Monkey", "Flying", "Drink", "Vacation", "Coconut", "Big", "Bonobo", "Climbing"
    ));

// Array1 - Another, but slightly different story about a monkey, includes at header and keywords.
$array2 = array (
        "header" => "This is another, but different story, about a monkey.",
        'keywords' => array( "Monkey", "Big", "Trees", "Bonobo", "Fun", "Dance", "Cow", "Coconuts"
    ));

// Function comparing keywords between two arrays. Uses levenshtein distance lesser than $lev_point_value. Each pass increases $merged_tag, which is then returned.
function sim_tag_index($array1, $array2, $lev_point_value) {
    $merged_tag = 0;
    foreach ($array1['keywords'] as $item1){
        foreach ($array2["keywords"] as $item2){
            if (levenshtein($item1, $item2) <= $lev_point_value) {
            $merged_tag++;
            };
         }
    };
    return $merged_tag;
}

// Function comparing headers between two arrays using levenshtein distance, which is then returned as $merged_head.
function sim_header_index($array1, $array2) {
    $merged_head = (levenshtein($array1['header'], $array2['header']));
    return $merged_head;
}

// Function running sim_tag_index against $merge_tag_value, if it passes, then running sim_tag_index against $merge_head_value, if this passes aswell, merge arrays.
function merge_on_sim($array1, $array2, $merge_tag_value, $merge_head_value, $lev_point_value) {
    $group = array();
    if (sim_tag_index($array1, $array2, $lev_point_value) >= $merge_tag_value) {
        if (sim_header_index($array1, $array2) >= $merge_head_value) {
            $group = (array_unique(array_merge($array1["keywords"],$array2["keywords"])));
        }
    }
    return $group;
}

// Printing function merge_on_sim.
print_r (merge_on_sim($array1, $array2, $merge_tag_value, $merge_head_value, $lev_point_value));
?>


Question:

How can I expand or rewrite my script to go through multiple sub-sub-arrays, comparing them to all other sub-sub-arrays, found in other sub-arrays, and then merge sub-sub-arrays that are deemed identical enough?


Multidimensional Array Structure

$array = array (
    // Sub-array 1
    array (
        // Story 'Monkey 1' - Has identical sub-sub-arrays 'Monkey 2' and 'Monkey 3' and will be merged with them.
        array (
            "header" => "This is a story about a monkey.",
            'keywords' => array( "Trees", "Monkey", "Flying", "Drink", "Vacation", "Coconut", "Big", "Bonobo", "Climbing")
        ),
        // Story 'Cat 1' - Has identical sub-sub-array 'Cat 2' and will be merged with it.
        array (
            "header" => "Here's a catarific story about a cat",
            'keywords' => array( "meauw", "raaaw", "kitty", "growup", "Fun", "claws", "fish", "salmon")
        )
    ),
    // Sub-array 2
    array ( 
        // Story 'Monkey 2' - Has identical sub-sub-arrays 'Monkey 1' and 'Monkey 3' and will be merged with them.
        array (
            "header" => "This is another, but different story, about a monkey.",
            'keywords' => array( "Monkey", "Big", "Trees", "Bonobo", "Fun", "Dance", "Cow", "Coconuts")
        ),
        // Story 'Cat 2' - Has identical sub-sub-array 'Cat 1' and will be merged with it.
        array (
            "header" => "Here's a different story about a cat",
            'keywords' => array( "meauwe", "ball", "cat", "kitten", "claws", "sleep", "fish", "purr")
        )
    ),
    // Sub-array 3
    array ( 
        // Story 'Monkey 3' - Has identical sub-sub-arrays 'Monkey 1' and 'Monkey 2' and will be merged with them.
        array (
            "header" => "This is a third story about a monkey.",
            'keywords' => array( "Jungle", "tree", "monkey", "Bonobo", "Fun", "Dance", "climbing", "Coconut", "pretty")
        ),
        // Story 'Fireman 1' - Has no identical sub-sub-arrays and will not be merged.
        array (
            "header" => "This is a story about a fireman",
            'keywords' => array( "fire", "explosion", "burning", "rescue", "happy", "help", "water", "car")
        )
    )
);


Wanted Multidimensional Array

$array = array (
    // Story 'Monkey 1', 'Monkey 2' and 'Monkey 3' merged.
    array (
        "header" => array( "This is a story about a monkey.", "This is another, but different story, about a monkey.", "This is a third story about a monkey."),
        'keywords' => array( "Trees", "Monkey", "Flying", "Drink", "Vacation", "Coconut", "Big", "Bonobo", "Climbing", "Fun", "Dance", "Cow", "Coconuts", "Jungle", "tree", "pretty")
    ),
    // Story 'Cat 1' and 'Cat 2' merged.
    array (
        "header" => array( "Here's a catarific story about a cat", "Here's a different story about a cat"),
        'keywords' => array( "meauw", "raaaw", "kitty", "growup", "Fun", "claws", "fish", "salmon", "ball", "cat", "kitten", "sleep", "fish", "purr")
    )
);



from PHP - Compare multidimensional sub-arrays to each other and merge on similarity threshold

Get annotated methods from gradle plugin

I'm developing a gradle plugin for android projects in kotlin and I need to scan the project source files in order to get all tests' names. I have implemented a directory scanner and I got an Arraylist<File> with all test classes.

I tried to apply reflection to this files but I got always a no class found exception. I suppose that the gradle plug in is trying to find the class inside the same gradle plugin the project instead of the Android project where the plugin is used.

Is there any way to scan each File object in my ArrayList and get all methods with the annotation @test?



from Get annotated methods from gradle plugin

Google Analytics V4 to Firebase

Am using google analytics version v4 in android mobile application from past few years, am planning to move firebase analytics now.

If i move to firebase analytics is it i will loose all data which is present in google analytics console.?

If not how do i get the all data which is present in google analytics console to firebase console.?



from Google Analytics V4 to Firebase

API Data Returning Unicode Characters in Console

I am facing a rather confusing problem since the last two days. I am working on a document management system, that uses an API that pulls in data from SOLR. The data is in tune of around ~15Mbs, and pulls records of more than 4000+ documents. The API has response in this format -

{
    "documents" :[
                {
                   id: 123,
                   some_field : "abcd",
                   some_other_field : "abcdef"
} ,
                 {
                    id: 124,
                   some_field : "abcd1",
                   some_other_field : "abcdef1"
}
]
}

Everything works fine in browser. If I hit the endpoint in Chrome or Firefox browser, it gives me the correct output and I am able to see the JSON output.

However, if I try hitting the same API endpoint with a Java or JS code - the response code is 200, but the output in console (Terminal or Eclipse) shows unicode characters like \u0089 \u0078 U+0080 - all the output comes in this way, and since there are around 4000+ records being fetched by the API, the console kinda fills with all of these unicode characters.

The only difference that I see between the requests made from browser and the code is that in browser I can see Content-Encoding : gzip, while I cannot find this header from the code that I written . For eg - in JS code, through Chakram framework, I can check

expect(response).to.be.encoded.with.gzip

mentioned here. However, this returns a failure stating expected undefined to match gzip

What am I missing here? Is this something related to encoding/decoding or something entirely different?

Edit 1 : The Response Headers as seen in Network tab of Chrome :

cache-control: max-age=0, private, must-revalidate, max-age=315360000
content-encoding: gzip
content-type: application/json; charset=utf-8
date: Tue, 22 May 2018 06:07:26 GMT
etag: "a07eb7c1eef4ab97699afc8d61fb9c5d"
expires: Fri, 19 May 2028 06:07:26 GMT
p3p: CP="NON CUR OTPi OUR NOR UNI"
server: Apache
Set-Cookie : some_cookie
status: 200 OK
strict-transport-security: 
transfer-encoding: chunked
vary: Accept-Encoding
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-request-id: abceefr4-1234-acds-100b-d2bef2413r47
x-runtime: 3.213943
x-ua-compatible: chrome=1
x-xss-protection: 1; mode=block

The Request Headers as seen in Network tab of Chrome

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Cookie: some_cookie
Host: abcd.bcd.com
IV_USER: demouser123
IV_USER_L: demouser123
MAIL: demouser@f.com
PERSON_ID: 123
Referer: http://abcd.bcd.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36
X-CSRF-TOKEN: some_csrf_token

Edit 2 : The tests that I am using

describe('Hits required API',()=>{

    before(()=>{
        return chakram.wait(api_response = chakram.get(url,options));
    });

    it('displayes response',()=>{
        return api_response.then((t_resp)=>{
            console.log(JSON.stringify(t_resp));
            expect(t_resp).to.have.header('Content-Encoding','gzip');
        });
    });



from API Data Returning Unicode Characters in Console

Global code coverage in multi-module Android project: merge code coverage reports (Unit & UI tests)

I have an Android app which is made up of 2 modules:

  • App - UI

  • Submodule - has most of the business logic

For each of them I have a gradle task to validate code coverage:

  • App: UI Code coverage (Espresso)

  • Submodule: Unit tests code coverage

As a requirement for the client, I need to merge those two reports to get the overall/global code coverage of the app.

Note: I'm using Gradle version 3.1.2.


App Gradle file:

apply plugin: 'jacoco'

android {

   testBuildType "uiTest"

    ...

  buildTypes {
    debug {
        applicationIdSuffix ".debug"
        versionNameSuffix "-debug"
        debuggable true

        minifyEnabled false
        shrinkResources false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'


        matchingFallbacks = ['debug']
    }

    // TESTS

    // unitTest will be used to run unit tests.
    unitTest.initWith(buildTypes.debug) //Beware the buildType this depends on MUST be above on the gradle file
    unitTest {
        applicationIdSuffix ".unitTest"
        versionNameSuffix "-unitTest"

        testCoverageEnabled = true
        matchingFallbacks = ['unitTest', 'debug']
    }

    // uiTest will be used to run ui tests.
    uiTest.initWith(buildTypes.debug) //Beware the buildType this depends on MUST be above on the gradle file
    uiTest {
        applicationIdSuffix ".uiTest"
        versionNameSuffix "-uiTest"

        testCoverageEnabled = true
        matchingFallbacks = ['uiTest', 'debug']
    }

    ...

SubModule Gradle file:

apply plugin: 'jacoco'

android {

   testBuildType "uiTest"

   buildTypes {
    debug {
    }

    unitTest {
        initWith(buildTypes.debug)
        testCoverageEnabled = true
    }

    uiTest {
        initWith(buildTypes.debug)
        testCoverageEnabled = true
    }

  ...
}

I've tried several ways, this one below indeed merges the tests.. but the coverage is not appearing correctly:

The task for creating UI Test coverage in the app:

//UI Test Coverage filtered (we need to run unit tests of App to be able to use Jacoco to filter)

task createTestReport(type: JacocoReport, dependsOn: [':app:testUnitTestUnitTest', ':app:createUiTestAndroidTestCoverageReport']) {

reports {
    html.enabled = true
}

def fileFilter = [
        //Android stuff
        '**/R.class',
        '**/BR.class',
        '**/R$*.class',
        '**/BR$*.class',
        '**/BuildConfig.*',
        'android/**/*.*',
        //Data Binding
        '**/*databinding',
        '**/*binders',
        '**/*layouts',
        '**/Manifest*.*',
        '**/*Test*.*',
        "**/services/**/model/**",
        //Utils
        '**/utils/*.*',
        '**/utils/**/*.*'
]

//To support Java coverage on Unit tests
def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/unitTest", excludes: fileFilter)
//To support Kotlin coverage on Unit tests
def kotlinDebugTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/unitTest", excludes: fileFilter)

def mainSrc = "${project.projectDir}/src/main/java"
def debugSrc = "${project.projectDir}/src/debug/java"

sourceDirectories = files([mainSrc, debugSrc])


def appAndroidTests = fileTree(dir: "${buildDir}/outputs/code-coverage/connected/", includes: ["**/*.ec"])
def appOtherAndroidTests = fileTree(dir: "${buildDir}/outputs/androidTest-results/connected/", includes: ["**/*.ec"])

classDirectories = files([debugTree], [kotlinDebugTree])
executionData = files("${buildDir}/jacoco/testUnitTestUnitTest.exec", appAndroidTests, appOtherAndroidTests)

}

The task for creating Unit test coverage in the sub-module:

//Unit Test Coverage filtered

task createTestReport(type: JacocoReport, dependsOn: ['testUnitTestUnitTest']) {

reports {
    html.enabled = true
}

def fileFilter = ['**/R.class',
                  '**/BR.class',
                  '**/R$*.class',
                  '**/BR$*.class',
                  '**/BuildConfig.*',
                  '**/*databinding/**/*.*',
                  '**/Manifest*.*',
                  '**/*Test*.*',
                  "**/services/**/model/**",
                  'android/**/*.*',
                  '**/utils/*.*',
                  '**/utils/**/*.*']

//To support Java coverage on Unit tests
def debugTree = fileTree(dir: "${buildDir}/intermediates/classes/unitTest", excludes: fileFilter)
//To support Kotlin coverage on Unit tests
def kotlinDebugTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/unitTest", excludes: fileFilter)

def mainSrc = "${project.projectDir}/src/main/java"
def debugSrc = "${project.projectDir}/src/debug/java"

sourceDirectories = files([mainSrc, debugSrc])


classDirectories = files([debugTree], [kotlinDebugTree])
executionData = files("${buildDir}/jacoco/testUnitTestUnitTest.exec")

}

The task for creating Global coverage in the app:

//Global Test Coverage

task createGlobalTestReport(type: JacocoReport, dependsOn: [':app:testUnitTestUnitTest', ':app:createTestReport', ':submodule:testUnitTestUnitTest']) {

reports {
    html.enabled = true
}

def fileFilter = [
        //Android stuff
        '**/R.class',
        '**/BR.class',
        '**/R$*.class',
        '**/BR$*.class',
        '**/BuildConfig.*',
        'android/**/*.*',
        //Data Binding
        '**/*databinding',
        '**/*binders',
        '**/*layouts',
        '**/Manifest*.*',
        '**/*Test*.*',
        "**/services/**/model/**",
        //Utils
        '**/utils/*.*',
        '**/utils/**/*.*'
]

// Note: **/reviews/ReviewService*.* was added as BazaarVoice cannot be mocked

//To support Java coverage on Unit tests
def debugAppTree = fileTree(dir: "${buildDir}/intermediates/classes/unitTest", excludes: fileFilter)
//To support Kotlin coverage on Unit tests
def debugKotlinAppTree = fileTree(dir: "${buildDir}/tmp/kotlin-classes/unitTest", excludes: fileFilter)

def debugSdkTree = fileTree(dir: "..//build/intermediates/classes/unitTest", excludes: fileFilter)
def debugKotlinSdkTree = fileTree(dir: "../submodule/build/tmp/kotlin-classes/unitTest", excludes: fileFilter)


def mainAppSrc = "${project.projectDir}/src/main/java"
def debugAppSrc = "${project.projectDir}/src/debug/java"

def mainSdkSrc = "../submodule/src/main/java"
def debugSdkSrc = "../submodule/src/debug/java"


sourceDirectories = files([mainAppSrc, debugAppSrc,
                           mainSdkSrc, debugSdkSrc])


def appAndroidTests = fileTree(dir: "${buildDir}/outputs/code-coverage/connected/", includes: ["**/*.ec"])
def sdkAndroidTests = fileTree(dir: "../submodule/build/outputs/code-coverage/connected/", includes: ["**/*.ec"])

classDirectories = files([debugAppTree, debugSdkTree,
                          debugKotlinAppTree, debugKotlinSdkTree])
executionData = files("${buildDir}/jacoco/testUnitTestUnitTest.exec"
        , "../submodule/build/jacoco/testUnitTestUnitTest.exec"
        , appAndroidTests
        , sdkAndroidTests
)

}

Any help would be much appreciated



from Global code coverage in multi-module Android project: merge code coverage reports (Unit & UI tests)

Youtube Analytics API returns 403 forbidden even if token is valid

I have an issue with access to Youtube Analytics API for random youtube channels.

After a successful authorization with following scopes:

I'm saving the token and refresh token in the database. Everything works well for some time. After a while (eg. three months) when my app makes a request, Google returns 403:

{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "forbidden",
        "message": "Forbidden"
      }
    ],
    "code": 403,
    "message": "Forbidden"
  }
}

but only for Youtube Analytics API, other endpoints in Youtube Data API works fine with this token. That happen for random accounts (channels). Owners of this channels didn't revoke access to my app, didn't change account password etc.

This issue affects about 40% of all channels in my application (the time when Youtube Analytics API stops working is different, from 1 to 6 months after obtaining OAuth2 token). Then I have to send them periodically a new authorization url.

Where is the problem?

This is how I generate an auth url and make requests:

  • Auth URL:

    flow = client.flow_from_clientsecrets(
        secret_file_path,
        scope=["https://www.googleapis.com/auth/youtube.readonly",
               "https://www.googleapis.com/auth/yt-analytics.readonly"],
        redirect_uri=redirect_url,
        prompt="consent"
    )
    flow.params["access_type"] = "offline"
    url = flow.step1_get_authorize_url(state=state)
    
    
  • Stats request:

    auth = client.OAuth2Credentials.from_json(credentials_from_db)
    http_auth = auth.authorize(httplib2.Http())
    api = discovery.build("youtubeAnalytics", "v1", http=http_auth,
                       cache_discovery=False)
    api.reports().query(
        ids="channel==%s" % channel_id,
        metrics="estimatedMinutesWatched",
        dimensions="video",
        start_date=start_date,
        end_date=end_date,
        max_results=20,
        filters="video=={}".format(",".join(video_ids))
    ).execute(http=http)
    
    

I'm using google-api-python-client 1.6.5



from Youtube Analytics API returns 403 forbidden even if token is valid

Could not parse for GALX or gxf token - Google Voice [PHP]

This script https://github.com/aaronpk/Google-Voice-PHP-API was working earlier but stopped.. It throws this error now.

An uncaught Exception was encountered
Type: Exception

Message: Could not parse for GALX or gxf token. Inputs from page: array ( )

Filename: /usr/share/nginx/html/application/libraries/Gv_lib.php

Line Number: 55

Backtrace:

File: /usr/share/nginx/html/application/libraries/Gv_lib.php
Line: 159
Function: _logIn

File: /usr/share/nginx/html/application/controllers/Notification.php
Line: 42
Function: sendSMS

File: /usr/share/nginx/html/index.php
Line: 292
Function: require_once

..It might have something to do with this:

curl https://accounts.google.com/signin/challenge/sl/password
<HTML>
<HEAD>
<TITLE>Moved Temporarily</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Moved Temporarily</H1>
The document has moved <A HREF="https://accounts.google.com/ServiceLogin">here</A>.
</BODY>
</HTML>

I've tried setting the post sign-in $URL to be: https://accounts.google.com/signin/v1/lookup to no avail.



from Could not parse for GALX or gxf token - Google Voice [PHP]

Reducing the size of a video exported with AVAssetExportSession - iOS Swift

I'm currently exporting a video in the following way:

   let exporter = AVAssetExportSession.init(asset: mixComposition, presetName: AVAssetExportPreset1280x720)
   exporter?.outputURL = outputPath
   exporter?.outputFileType = AVFileType.mp4
   exporter?.shouldOptimizeForNetworkUse = true
   exporter?.videoComposition = mainCompositionInst

A 15s video consumes about 20MB in data. Comparing this to Snapchat's 2MB videos, this number seems totally unacceptable.

I already reduced the quality of the export- and capture session (1280x720).

The video is filmed on a custom camera. UIImagePickerController is not used.

Is there any way I can reduce the size of my videos? Thanks a lot!



from Reducing the size of a video exported with AVAssetExportSession - iOS Swift

How restore smooth scolling after format text in "ios contenteditable element"?

I want edit content inside "contenteditable element" on #ios. In that element is more text.

Steps

  1. I scroll smoothly to the selected text
  2. I touch into element and that open keyboard
  3. I touch and select multi lines of text and format it to bold
  4. I want scroll content now but it's not smoothly anymore

Here is playable code:
https://console.webcloud.io/profile/bruno.onlyme@gmail.com/_playwithcode/contenteditable-scroll-after-format/index.html

<html>

<head>
    
    <meta name="viewport" content="width=device-width,minimum-scale=1,maximum-scale=1,user-scalable=no">
    
    <style>
        
        body {
            font-size: 24px;
        }
        
    </style>

</head>

<body>
    
    <button>button</button> | <a onclick="console.log();">anchor</a><br>
    <br>
    
    <div contenteditable>
        What is Lorem Ipsum?
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        
        Why do we use it?
        It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
    </div>
    <br>
    
    <button>button</button> | <a onclick="console.log();">anchor</a>
    
</body>

</html>

After a huge investigation I figure out that this issue is in S CH FF, Opera somehow solve it but not work another things correctly. This issue is in every known editor #ckeditor5 #medium #alloyeditor too.

"Smooth scroll" is restored only on 2conditions

  1. if keyboard is hidden and repeatedly opened by touch into any "contenteditable element"
  2. if I touch any other "clickable element"

Q does anyone have any idea how to keep "smooth scrolling"?



from How restore smooth scolling after format text in "ios contenteditable element"?

How to add max_length to allauth username

I'm using Django allauth as my user account framework for my django site. The docs show there is an ACCOUNT_USERNAME_MIN_LENGTH however there is no ACCOUNT_USERNAME_MAX_LENGTH for some reason.

Is there any way to create a max length for username?

Here's my custom allauth signup form - maybe I can do something here?:

class AllauthSignupForm(forms.Form):

    captcha = ReCaptchaField(
        public_key=config("RECAPTCHA_PUBLIC_KEY"),
        private_key=config("RECAPTCHA_PRIVATE_KEY"),
    )

    class Meta:
        model = User

    def signup(self, request, user):
        """ Required, or else it throws deprecation warnings """
        pass



from How to add max_length to allauth username

Activity Recognition continues services in Oreo

I am breaking my head around it with no solution's so far. I seen many guides how to accomplish this (Documentation, Tutorial) and successfully made it happen in android 7. What I managed to do is successfully get notification with service running at background when user activity changed. My app works perfectly. The problem is with android 8 and google battery management. My service is always killed. So... What I already tried to overcome this problem:

  1. Explain the user how to disable battery optimization for my app so it will not kill my service. The problem is its too comlicated for cummon user.

  2. Add

    uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"
    
    

and check it with code:

Intent intent = new Intent();
            String packageName = context.getPackageName();
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (pm.isIgnoringBatteryOptimizations(packageName)){
                    intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);

                }
                else {
                    intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + packageName));
                }
            }
            context.startActivity(intent);

But I undersood my app can be banned from play store, and this is big problem.

  1. Use foreground service with persistent notification. The problem is its very anoin to user to see this ongoing and sometimes irrelevant notification.

So how can I use ActivityRecognitionClient and always receive notification when activity changed even when my app is in background in android 8? Maybe connecting directly google service for this somehow?



from Activity Recognition continues services in Oreo

How do I guarantee that my Android SurfaceView is transparent instead of black?

I have a custom view that extends SurfaceView overlaying the rest of my interface, it works on emulators and when the debugger is connected on my phone, but but when the phone is running on battery the view never clears.

public class CustomView extends SurfaceView {

    private final Paint paint;
    private final SurfaceHolder holder;
    private final Context context;

    private float strokeWidth = 4;

    private boolean canvasAlreadyLocked = false;

    public CustomView(Context viewContext, AttributeSet attrs)
    {
        super(viewContext, attrs);
        Log.i("CustomView", "CustomView create context & attrs");
        holder = getHolder();
        context = viewContext;
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(strokeWidth);
        drawLine();
        setZOrderOnTop(true);
        holder.setFormat(PixelFormat.TRANSPARENT);
    }

    public void resume() {
        Log.i("CustomView", "Resume the customview display.");
        setZOrderOnTop(true);
        holder.setFormat(PixelFormat.TRANSPARENT);
    }

    @Override
    public void onAttachedToWindow(){
        super.onAttachedToWindow();
        setZOrderOnTop(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    protected void drawLine() {
        if (!canvasAlreadyLocked) {
            invalidate();
            if (holder.getSurface().isValid()) {
                try {
                    final Canvas canvas = holder.lockCanvas();
                    canvasAlreadyLocked = true;
                    if (canvas != null) {
                        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
                        paint.setColor(Color.BLACK);
                        paint.setStrokeWidth(strokeWidth * 2);
                        canvas.drawLine(0, getY(), getWidth(), getY(), paint);
                        paint.setColor(Color.WHITE);
                        paint.setStrokeWidth(strokeWidth);
                        canvas.drawLine(0, getY(), getWidth(), getY(), paint);
                        holder.unlockCanvasAndPost(canvas);
                        canvasAlreadyLocked = false;
                    }
                }
                catch (IllegalArgumentException iae)
                {
                    Log.w("CustomView", "Exception trying to lock canvas: "+iae.getMessage());
                    Log.getStackTraceString(iae);

                }
            }
        }
    } 

    private float getY() {
        getHeight()/2;
    }

}

I'm aware that some of the calls here are redundant - that is mostly the legacy of trying lots of different things to try to make it work. You will notice that I have already done everything recommended in this answer.

The layout works like this:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.custom.CustomViewApp">

    <FrameLayout
        android:id="@+id/control"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true">

        <com.custom.AutoFitTextureView
            android:id="@+id/texture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true" />

        <ImageButton
            android:id="@+id/gpsNotification"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/gps_unfixed"
            android:layout_gravity="right"
            android:tint="@color/gps_unfixed"
            android:background="@null" />

        <ProgressBar
            android:id="@+id/camera_spinner"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|center_vertical"
            android:gravity="center"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="invisible"
            />

        <com.custom.CustomView
            android:id="@+id/custom_view"
            android:background="@color/transparent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true" />

    </FrameLayout>
</FrameLayout>

This is pulled in from a ViewFragment:

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    mTextureView = (AutoFitTextureView) view.findViewById(R.id.texture);
    gpsNotification = (ImageButton) view.findViewById(R.id.gpsNotification);
    customView = (CustomView) view.findViewById(R.id.custom_view);
    spinner = (ProgressBar) view.findViewById(R.id.camera_spinner);
    spinner.setVisibility(VISIBLE);
}

I have tried to simplify this as far as I can and obviously there is a lot more happening in this scenario, but hopefully this is enough to indicate where the problem might be coming from.

The AutoFitTextureView is displaying the view from the camera.

  • When I run it in an emulator, everything displays as expected, regardless of the battery settings.
  • When I run it on my phone connected by USB everything displays as expected.
  • When I run it on my phone disconnected, the view will usually, but not always, show as plain black - the AutoFitTextureView is completely obscured, but the line on the CustomView is drawn. The other components are visible, which leads me to suspect there is a problem with when or how I call setZOrderOnTop().
  • If I hit a breakpoint in the fragment and set the visibility of the CustomView to INVISIBLE I can immediately see everything else, but as you might expect I lose the overlay. Manually calling setZOrderOnTop at that point doesn't seem to change anything.
  • When it is running correctly, I can examine the structure with the Layout Inspector tool, but when the SurfaceView is opaque the Layout Inspector raises an Unexpected Error: Empty View Hierarchy message. I haven't been able to locate a corresponding error message in Logcat.

How do I ensure my SurfaceView-derived View is always transparent? If I can't guarantee that, is there any way I can test whether it currently is transparent so that I can intercede if it is not?



from How do I guarantee that my Android SurfaceView is transparent instead of black?

How to debug with this Android Native crash log (perhaps multiple webview issue)?

I got a crash that I couldn't find linked directly to my code, then I found that it is a native crash. The backtrace is like this

Abort message: '[FATAL:jni_android.cc(259)] Please include Java exception stack in crash report
    '
        r0 00000000  r1 00003c12  r2 00000006  r3 00000008
        r4 7cb80978  r5 00000006  r6 7cb80920  r7 0000010c
        r8 7cb7ffad  r9 7cb7ffac  sl 7cb80408  fp 7cb80404
        ip 0000000b  sp 7cb7ff38  lr b3eab4b7  pc b3eadd20  cpsr 600f0010

A/DEBUG: backtrace:
        #00 pc 0004ad20  /system/lib/libc.so (tgkill+12)
        #01 pc 000484b3  /system/lib/libc.so (pthread_kill+34)
        #02 pc 0001dd89  /system/lib/libc.so (raise+10)
        #03 pc 00019511  /system/lib/libc.so (__libc_android_abort+34)
        #04 pc 00017150  /system/lib/libc.so (abort+4)
        #05 pc 0079a29b  /data/app/com.android.chrome-1/base.apk (offset 0xfa5000)

I'm wondering how can I utilize this to help me locate my problem. I know this is too broad, difficult to locate the problem in my code. So I'm wondering if anyone can give any instruction or direction to utilize this log? To give more information, I have multiple webviews when it crashes, is it possible of memory fragmentation error? If so, what should I do? Recreate webview? Seems there are something before this

System.err: java.lang.IllegalStateException: get field slot from row 25 col 46 failed
        at net.sqlcipher.CursorWindow.getLong_native(Native Method)
05-29 15:38:24.016 22757-23608/com.boxer.email W/System.err:     at net.sqlcipher.CursorWindow.getLong(CursorWindow.java:450)
        at net.sqlcipher.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:110)
        at net.sqlcipher.AbstractCursor.moveToPosition(AbstractCursor.java:201)
        at net.sqlcipher.AbstractCursor.moveToNext(AbstractCursor.java:230)
05-29 15:38:24.017 22757-23608/com.boxer.email W/System.err:     at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)
        at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)
        at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)
        at android.database.CursorWrapper.moveToNext(CursorWrapper.java:202)



from How to debug with this Android Native crash log (perhaps multiple webview issue)?

RecyclerView Endless Scrolling with RxJava

I want to implement Endless Scrolling functionality on RecyclerView using RxJava.

What I want: I want to fetch first 10 data from API call and display it in RecyclerView. After user scrolled down these 10 data, I want to make another API call and pull another 10 data. Again when user scrolls down after these latest 10 data, I have to make API call for another 10 data. This will continues until API call gives all the data.

I tried with take operator but not getting desired result. I searched for different operators but not getting single operator or any combination of operator to achieve this. Any help will be appreciated.

My code is like below.

SalesDashboardActivity.java

    public class SalesDashboardActivity2 extends BaseActivity implements SalesDashboardView {

    List<DashboardStatusBean> inProgressList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sales_dashboard2);
        ButterKnife.bind(this);
        setSupportActionBar(mToolbar);
        mSalesDashboardPresenter.attachView(this);
        getDashboardData();
    }

    private void getDashboardData() {

        SearchLoansInput searchLoansInput = new SearchLoansInput();
        searchLoansInput.setUserName(sessionManager.getMobileNumber());

        if (Util.isInternetConnection(this)) {
            mSalesDashboardPresenter.handleSalesInquiryRequest(searchLoansInput);
        } else {
            displayToastMessage("Internet is not available! Check your internet connection.");
        }
    }

    @Override
    public void handleSalesInquiryResponse(SearchLoansOutput searchLoansOutputData) {

        if (searchLoansOutputData.isSuccess()) {

            Util.SALES_IN_PROGRESS_LIST.clear();

            for (int i = 0; i < searchLoansOutputData.getLoanDetailList().size(); i++) {
                DashboardStatusBean dashboardStatusBean = new DashboardStatusBean();
                SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy");
                String approveDate = null;
                String createdDate = null;

                if (searchLoansOutputData.getLoanDetailList().get(i).getCreatedDate() != null) {
                    createdDate = String.valueOf(sdf.format(searchLoansOutputData.getLoanDetailList().get(i).getCreatedDate()));
                }
                if (searchLoansOutputData.getLoanDetailList().get(i).getApprovedDate() != null) {
                    approveDate = String.valueOf(sdf.format(searchLoansOutputData.getLoanDetailList().get(i).getApprovedDate()));
                }

                String loanNumber = searchLoansOutputData.getLoanDetailList().get(i).getLoanNumber();
                String firstName = searchLoansOutputData.getLoanDetailList().get(i).getFirstName();
                String lastName = searchLoansOutputData.getLoanDetailList().get(i).getLastName();
                String mobileNumber = searchLoansOutputData.getLoanDetailList().get(i).getMobileNumber();
                String status = searchLoansOutputData.getLoanDetailList().get(i).getStatus().getDisplayName();
                String loanAmount = String.valueOf(searchLoansOutputData.getLoanDetailList().get(i).getLoanAmount().setScale(0, BigDecimal.ROUND_UP));
                String loanAppId = searchLoansOutputData.getLoanDetailList().get(i).getId();
                BigDecimal productAmount = searchLoansOutputData.getLoanDetailList().get(i).getTotalProductAmount();
                BigDecimal downPayment = searchLoansOutputData.getLoanDetailList().get(i).getDownPayment();
                BigDecimal processingFee = searchLoansOutputData.getLoanDetailList().get(i).getProcessingFee();
                String tenure = searchLoansOutputData.getLoanDetailList().get(i).getDesiredItemPaybackTenure();
                String sourceAcquisition = searchLoansOutputData.getLoanDetailList().get(i).getSourceAcquisition();
                List<SingleDocumentOuput> documentUpdatedList = searchLoansOutputData.getLoanDetailList().get(i).getDocOutputList();

                dashboardStatusBean.setCreatedDate(createdDate);
                dashboardStatusBean.setApproveDate(approveDate);
                dashboardStatusBean.setLoanNumber(loanNumber);
                dashboardStatusBean.setFirstName(firstName);
                dashboardStatusBean.setLastName(lastName);
                dashboardStatusBean.setMobileNumber(mobileNumber);
                dashboardStatusBean.setStatus(status);
                dashboardStatusBean.setLoanAppId(loanAppId);
                dashboardStatusBean.setProductAmount(productAmount);
                dashboardStatusBean.setDownPayment(downPayment);
                dashboardStatusBean.setProcessingFee(processingFee);
                dashboardStatusBean.setTenure(tenure);
                dashboardStatusBean.setLoanAmount(loanAmount);
                dashboardStatusBean.setDocumentUpdatedList(documentUpdatedList);

                if (status.equals(LoanApplicationStatus.STILL_FILLING.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.ONBOARDIN_IN_PROG.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.INITIATED.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.ADDITIONAL_DATA_REQ.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.UPLOAD_IN_PROG.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.VERIFIED.getDisplayName()) ||
                        status.equals(LoanApplicationStatus.LEAD.getDisplayName())) {
                    inProgressList.add(dashboardStatusBean);
                }

                Util.SALES_IN_PROGRESS_LIST = inProgressList;
            }

        } else {
            displayMessage(searchLoansOutputData.getErrorCode(), searchLoansOutputData.getErrorMessage());
        }
    }
}

SalesLoginDashboardPresenter.java

    public class SalesLoginDashboardPresenter implements Presenter {

    private SalesDashboardView mView;
    private final SalesLoginInquiryUseCase mSalesInquiryUseCase;

    @Inject
    public SalesLoginDashboardPresenter(SalesLoginInquiryUseCase salesLoginInquiryUseCase) {
        mSalesInquiryUseCase = salesLoginInquiryUseCase;
    }

    @Override
    public void attachView(View v) {
        mView = (SalesDashboardView) v;
    }

    public void handleSalesInquiryRequest(SearchLoansInput searchLoansInput) {
        mView.displayLoadingScreen();
        mSalesInquiryUseCase.setSalesLoginInquiryBody(searchLoansInput);
        mSalesInquiryUseCase.execute()
                .subscribe(this::onSalesInquiryReceived, this::onSalesInquiryError);
    }

    private void onSalesInquiryError(Throwable throwable) {
        mView.hideLoadingScreen();
        mView.displayErrorMessage("Error fetching data");
        throwable.printStackTrace();
    }

    private void onSalesInquiryReceived(SearchLoansOutput searchLoansOutput) {
        mView.hideLoadingScreen();
        mView.handleSalesInquiryResponse(searchLoansOutput);
    }
}

SalesLoginInquiryUseCase.java

    public class SalesLoginInquiryUseCase extends Usecase<SearchLoansOutput> {

    private final MerchantRepository mRepository;
    private final Scheduler mUiThread;
    private final Scheduler mExecutorThread;
    private SearchLoansInput mSearchLoansInput;
    private String mCookie;

    @Inject
    public SalesLoginInquiryUseCase(
            MerchantRepository repository,
            @Named("ui_thread") Scheduler uiThread,
            @Named("executor_thread") Scheduler executorThread) {

        mRepository = repository;
        mUiThread = uiThread;
        mExecutorThread = executorThread;
    }

    public void setSalesLoginInquiryBody(SearchLoansInput searchLoansInput){
        mSearchLoansInput = searchLoansInput;
    }

    @Override
    public Observable<SearchLoansOutput> buildObservable() {
        return mRepository.postSalesLoginDetailsInquiryBody(mSearchLoansInput)
                .observeOn(mUiThread)
                .subscribeOn(mExecutorThread);
    }
}



from RecyclerView Endless Scrolling with RxJava

Sort string with integers and words without any change in their positions

Say I have a string a.

a = "12 I have car 8 200 a"

I need to sort this string in such a way that the output should be

8 a car have 12 200 I

ie, Sort the string in such a way that all words are in alphabetical order and all integers are in numerical order. Furthermore, if the nth element in the string is an integer it must remain an integer, and if it is a word it must remain a word.

This is what I tried.

a = "12 I have car 8 200 a"


def is_digit(element_):
    """
    Function to check the item is a number. We can make using of default isdigit function
    but it will not work with negative numbers.
    :param element_:
    :return: is_digit_
    """
    try:
        int(element_)
        is_digit_ = True
    except ValueError:
        is_digit_ = False

    return is_digit_



space_separated = a.split()

integers = [int(i) for i in space_separated if is_digit(i)]
strings = [i for i in space_separated if i.isalpha()]

# sort list in place
integers.sort()
strings.sort(key=str.lower)

# This conversion to iter is to make use of next method.
int_iter = iter(integers)
st_iter = iter(strings)

final = [next(int_iter) if is_digit(element) else next(st_iter) if element.isalpha() else element for element in
         space_separated]

print " ".join(map(str, final))
# 8 a car have 12 200 I

I am getting the right output. But I am using two separate sorting function for sorting integers and the words(which I think is expensive).

Is it possible to do the entire sorting using a single sort function?.



from Sort string with integers and words without any change in their positions

How can we include php files without specifying the subfolder path

Normally we use the following code to include php files inside each other:

<?php 

include_once 'include/config.php';
// OR
include 'include/config.php'; 
// OR 
include_once $_SERVER['DOCUMENT_ROOT'].'include/config.php';
// ect...
?>

But the above codes only apply if the php files are in the root file. I mean, if we move our files into a subfolder. We need to make a change to the code we included in the php files. For example like this:

<?php 
    include_once 'subfolder/include/config.php';
    // OR
    include 'subfolder/include/config.php'; 
    // OR 
    include_once $_SERVER['DOCUMENT_ROOT'].'/subfolder/include/config.php';
    // ect...
?>

What I'm saying is that when we move our php files into the subfolder, then include_once want to see subfolder name like (include_once 'subfolder/include/config.php';). This is a challenging situation because we need to do this for the included page in many files.

For example i include the include_once $_SERVER['DOCUMENT_ROOT'].'/functions/includes.php'; from the index.php and also included this includes.php file from all php files like header.php, posts.php, and ajax_post.php . It is working fine from the root folder but if we move the files in the subfolder then include.php file not including without subfolder name.

Maybe it is also possible to do this with .htaccess.

I have made this htaccess code maybe you have a solution with htaccess. I must be say i have tryed to use RewriteBase /subfoldername/ but include files didn't worked.

Options +FollowSymLinks -MultiViews
RewriteEngine On 
RewriteBase /

RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=302,NE,L]

RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} /index\.php [NC]
RewriteRule ^(.*)index\.php$ /$1 [L,R=302,NC,NE]

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^group/([\w-]+)/?$ sources/group.php?group_username=$1 [L,QSA]  
RewriteRule ^profile/([\w-]+)/?$ sources/user_profile.php?username=$1 [L,QSA]
RewriteRule ^profile/(followers|friends|photos|videos|locations|musics)/([\w-]+)/?$ sources/$1.php?username=$2 [L,QSA]     

RewriteRule ^admin/(.*)$ admin/index.php?page=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]  

RewriteRule ^(.+?)/?$ index.php?pages=$1 [L,QSA]

. My responsibility is, how can we include php files without subfolder name?



from How can we include php files without specifying the subfolder path

Renderscript fails on GPU enabled driver if USAGE_SHARED

We are using renderscript for audio dsp processing. It is simple and improves performance significantly for our use-case. But we run into an annoying issue with USAGE_SHARED on devices that have custom driver with GPU execution enabled.

As you may know, USAGE_SHARED flag makes the renderscript allocation to reuse the given memory without having to create a copy of it. As a consequence, it not only saves memory, in our case, improves performance to desired level.

The following code with USAGE_SHARED works fine on default renderscript driver (libRSDriver.so). With custom driver (libRSDriver_adreno.so) USAGE_SHARED does not reuse given memory and thus data.

This is the code that makes use of USAGE_SHARED and calls renderscript kernel

void process(float* in1, float* in2, float* out, size_t size) {
  sp<RS> rs = new RS();
  rs->init(app_cache_dir);

  sp<const Element> e = Element::F32(rs);
  sp<const Type> t = Type::create(rs, e, size, 0, 0);

  sp<Allocation> in1Alloc = Allocation::createTyped(
                rs, t,
                RS_ALLOCATION_MIPMAP_NONE, 
                RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_SHARED,
                in1);

  sp<Allocation> in2Alloc = Allocation::createTyped(
                rs, t,
                RS_ALLOCATION_MIPMAP_NONE, 
                RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_SHARED,
                in2);

  sp<Allocation> outAlloc = Allocation::createTyped(
                rs, t,
                RS_ALLOCATION_MIPMAP_NONE, 
                RS_ALLOCATION_USAGE_SCRIPT | RS_ALLOCATION_USAGE_SHARED,
                out);

  ScriptC_x* rsX = new ScriptC_x(rs);
  rsX->set_in1Alloc(in1Alloc);
  rsX->set_in2Alloc(in2Alloc);
  rsX->set_size(size);

  rsX->forEach_compute(in1Alloc, outAlloc);
}

NOTE: This variation of Allocation::createTyped() is not mentioned in the documentation, but code rsCppStructs.h has it. This is the allocation factory method that allows providing backing pointer and respects USAGE_SHARED flag. This is how it is declared:

/**
 * Creates an Allocation for use by scripts with a given Type and a backing pointer. For use
 * with RS_ALLOCATION_USAGE_SHARED.
 * @param[in] rs Context to which the Allocation will belong
 * @param[in] type Type of the Allocation
 * @param[in] mipmaps desired mipmap behavior for the Allocation
 * @param[in] usage usage for the Allocation
 * @param[in] pointer existing backing store to use for this Allocation if possible
 * @return new Allocation
 */
static sp<Allocation> createTyped(
            const sp<RS>& rs, const sp<const Type>& type,
            RsAllocationMipmapControl mipmaps, 
            uint32_t usage, 
            void * pointer);

This is the renderscript kernel

rs_allocation in1Alloc, in2Alloc;
uint32_t size;

// JUST AN EXAMPLE KERNEL
// Not using reduction kernel since it is only available in later API levels.
// Not sure if support library helps here. Anyways, unrelated to the current problem

float compute(float ignored, uint32_t x) {
  float result = 0.0f;
  for (uint32_t i=0; i<size; i++) {
    result += rsGetElementAt_float(in1Alloc, x) * rsGetElementAt_float(in2Alloc, size-i-1); // just an example computation
  }

  return result;
}

As mentioned, out doesn't have any of the result of the calculation. syncAll(RS_ALLOCATION_USAGE_SHARED) also didn't help.

The following works though (but much slower)

void process(float* in1, float* in2, float* out, size_t size) {
  sp<RS> rs = new RS();
  rs->init(app_cache_dir);

  sp<const Element> e = Element::F32(rs);
  sp<const Type> t = Type::create(rs, e, size, 0, 0);

  sp<Allocation> in1Alloc = Allocation::createTyped(rs, t);
  in1Alloc->copy1DFrom(in1);

  sp<Allocation> in2Alloc = Allocation::createTyped(rs, t);
  in2Alloc->copy1DFrom(in2);

  sp<Allocation> outAlloc = Allocation::createTyped(rs, t);

  ScriptC_x* rsX = new ScriptC_x(rs);
  rsX->set_in1Alloc(in1Alloc);
  rsX->set_in2Alloc(in2Alloc);
  rsX->set_size(size);

  rsX->forEach_compute(in1Alloc, outAlloc);
  outAlloc->copy1DTo(out);
}

Copying makes it to work, but in our testing, copying back and forth significantly degrades performance.

If we switch off GPU execution through debug.rs.default-CPU-driver system property, we could see that custom driver works well with desired performance.

Aligning memory given to renderscript to 16,32,.., or 1024, etc did not help to make the custom driver respect USAGE_SHARED.

Question

So, our question is this: How to make this kernel work for devices that use custom renderscript driver that enables GPU execution?



from Renderscript fails on GPU enabled driver if USAGE_SHARED

How to get WatchOS4 heartRateVariabilitySDNN and it's use?

I am trying to use heartRateVariabilitySDNN. I successfully get heartRate by query and i use following code for get heartRateVariabilitySDNN but have no idea how its works. also there is no any proper documentation about their query or sample code from apple side.
func createheartRateVariabilitySDNNStreamingQuery(_ workoutStartDate: Date) -> HKQuery? {

    let typeHeart = HKQuantityType.quantityType(forIdentifier: .heartRateVariabilitySDNN)
    let predicate: NSPredicate? = HKQuery.predicateForSamples(withStart: workoutStartDate, end: nil,
 options: HKQueryOptions.strictEndDate)

    let squery = HKStatisticsQuery(quantityType: typeHeart!, quantitySamplePredicate: predicate,
 options: .discreteAverage, completionHandler: {(query: HKStatisticsQuery,result: HKStatistics?, 
error: Error?) -> Void in
        DispatchQueue.main.async(execute: {() -> Void in

            print("got: \(String(describing: result))")
        })
    })

    return squery
}



from How to get WatchOS4 heartRateVariabilitySDNN and it's use?

Wednesday 30 May 2018

checkbox animation on multiple labels for one input

How do I get the label for .select-label to fire it's css animation when the label for .pick-select is selected?

Instead of having only one label effected by the input change, I want a second label to also react to a change in input and run the same animation for the .pick-select label as it does for the .select-label label.

$(document).ready(function() {
  $(".select-all").on("click", function() {
    $(this).is(":checked") ?
      $(".select-input")
      .prop("checked", true)
      .change() :
      $(".select-input")
      .prop("checked", false)
      .change();
  });
  $("input[name='select-check']:checkbox").change(function() {
    if ($(this).is(":checked")) {
      if ($("input[name='select-check']:checkbox:not(:checked)").length == 0) {
        $(".select-all").prop("checked", true);
      }
      $(this)
        .closest(".shrink")
        .addClass("active");
    } else {
      $(".select-all").prop("checked", false);
      $(this)
        .closest(".shrink")
        .removeClass("active");
    }
  });
});
.pick-select {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
}
.shrink {
  height: 50px;
  width: 50px;
  border: 3px solid;
  position: relative;
  -webkit-transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  -o-transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
}
.shrink.active {
  -webkit-transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  -o-transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  transition: all 600ms cubic-bezier(0.19, 1, 0.22, 1);
  -webkit-transform: scale(0.8);
  -ms-transform: scale(0.8);
  transform: scale(0.8);
  border: 2px solid red;
}
.select-label {
  display: inline-block;
  cursor: pointer;
  position: relative;
}
.select-label span {
  display: inline-block;
  position: relative;
  background-color: transparent;
  width: 15px;
  height: 15px;
  transform-origin: center;
  border: 2px solid silver;
  border-radius: 50%;
  vertical-align: -6px;
  margin-right: 10px;
  transition: background-color 150ms,
    transform 350ms cubic-bezier(0.78, -1.22, 0.17, 1.89);
}
input[name="select-check"] {
  display: none;
}
input[name="select-check"]:checked + label span {
  background-color: blue;
  border-color: blue;
  transform: scale(1.25);
}
input[name="select-check"]:checked + label span:after {
  width: 10px;
  background: #fff;
  transition: width 150ms ease 100ms;
}
input[name="select-check"]:checked + label span:before {
  width: 5px;
  background: #fff;
  transition: width 150ms ease 100ms;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="selectall-btn">
  <input type="checkbox" id="selectall" class="select-all" name="select-check" />
  <label class="select-label" for="selectall"><span></span>Select All
</label>
</div>
<div class="post-list">
  <div class="item">
    <div class="selectall-btn">
      <label class="select-label" for="post-select1"><span></span>
</label>
    </div>
    <div class="shrink">
      <div class="select-block">
        <label class="pick-select hidden">
<input id="post-select1" type="checkbox" class="select-input" name="select-check">
</label> 1
      </div>
    </div>
  </div>
  <div class="item">
    <div class="selectall-btn">
      <label class="select-label" for="post-select2"><span></span>
</label>
    </div>
    <div class="shrink">
      <div class="select-block">
        <label class="pick-select hidden">
<input id="post-select2" type="checkbox" class="select-input" name="select-check">
</label> 2
      </div>
    </div>
  </div>
</div>


from checkbox animation on multiple labels for one input

Fabric Crashlytics Welcome window won't go away

I was trying to accept the new terms and service of Fabric, so I logged in to Fabric. I get this window that won't go away! enter image description here
I figured that it is mandatory to install crashlytics, so I started installing it, which pointed me to this page: https://fabric.io/kits/ios/crashlytics/install
I reached this step to install my keys
"${PODS_ROOT}/Fabric/run" <FABRIC_API_KEY> <BUILD_SECRET>

per this picture enter image description here
I clicked on the login link next to it but was faced with the 1st picture from above.
I can't go around that window, what should I do to get rid of that screen!?


from Fabric Crashlytics Welcome window won't go away

W/IInputConnectionWrapper(1066): showStatusIcon on inactive InputConnection

Here is my class:

public class Insert extends Activity 
{

    EditText name,surname,age;
    Button insert;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
     {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.insert);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);
        name =(EditText)findViewById(R.id.name);
        surname =(EditText)findViewById(R.id.surname);
        age =(EditText)findViewById(R.id.age);
        insert=(Button)findViewById(R.id.click);
        insert.setOnClickListener(new OnClickListener()
        {
              public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                String nm = name.getText().toString();
                String ct = surname.getText().toString();
                String emailid = age.getText().toString();
                 insertRecords(nm, ct, emailid);
              }
            private void insertRecords(String nm,String ct,String emailid)
            {
                 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
                    nameValuePairs.add(new BasicNameValuePair("name", nm));
                    nameValuePairs.add(new BasicNameValuePair("surname",ct));
                    nameValuePairs.add(new BasicNameValuePair("age",emailid));
                    sendData(nameValuePairs);
            }
            private void sendData(ArrayList<NameValuePair> data)
            {
                try 
                {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("http://10.0.2.2:81/new/insert.php");
                    httppost.setEntity(new UrlEncodedFormEntity(data));
                    HttpResponse response = httpclient.execute(httppost);

                }
                catch (Exception e) {
                    // TODO: handle exception
                    Log.e("log_tag", "Error:  "+e.toString());
                }
            }
        });
    }
    ...
}

In LogCat

04-23 12:12:10.263: W/IInputConnectionWrapper(1066): showStatusIcon on inactive InputConnection



from W/IInputConnectionWrapper(1066): showStatusIcon on inactive InputConnection

CircleCI 2.0: Build directory for scp deployment

Re: CircleCI 2.0: Build directory for scp deployment

I’m confused as to the source folder to use for deploying to another server over SSH (scp, rsync, etc). I’ve tried the working_directory from my build, I’ve tried ~/repo_name and several other variations but without any luck.

I am just attempting to build the circleci-demo-php-laravel demo as a test.

https://github.com/dmgig/circleci-demo-php-laravel/blob/circleci-2.0/.circleci/config.yml

Thanks for any help.

Here’s the deploy step I’m hung up on. I've tried about everything - setting the working_directory in the build and deploy, using the CIRCLE_WORKING_DIRECTORY env variable that is created when the deploy machine spins up. I'm at a total loss.

run:
name: Deploy Over SSH
command: scp -r {WHAT_IS_THE_BUILD_DIR} serveradmin%mydomain.org@mydomain.org:~/domains/circleci.mydomain.org/html/



from CircleCI 2.0: Build directory for scp deployment

Using JQuery Server side datatables in ruby app and pagination shows blank page after 1st page

I am using Jquery Server side datatables and am not able to get the pagination to work on pages 2+.
I have 200 records. The first page shows 50. When I click the pagination numbers at the bottom of the page it navigates to page 2, but page 2 is empty.
I am using non-serverside datatables in the same app (but another table) and it works fine.
In addition pagination, the select menu that chooses #of records to display per page is not working and column sorting is not working.
Search is working
I'm using: "1.12.4" Rails 5 DataTables 1.10.16
index.json.jbuilder
json.draw params[:draw]
json.recordsTotal @cooks.length
json.recordsFiltered @cooks.length
json.data do
  json.array! @paginated do |cook|
    json.DT_RowClass "js-cook-row js-cook-row-#{donor.id}"
    if browser.device.mobile?
      json.partial! 'cooks/mobile_data', cook: cook, project: @project
    else
      json.partial! 'cooks/desktop_data', cook: cook, project: @project
    end
  end
end

Page with table (slim)
table.table.table-striped.table-bordered.table-hover.js-cook-table.cooks-table.
dataTables-example.small-font.kitchen-table id="#{table_id}" 
data-toggle="table" width="100%"
  thead
    tr
      - if source == RouteSourceConsts::WIZARD
        th.updated-th data-field="cook-checkbox"
      th.cook-category data-field="given" data-sortable="true" = t('cooks.table_title.given')
      th.cook-vendor data-field="cook_name" data-sortable="true" = t('cooks.table_title.name')
      th data-field="recipes" = t('cooks.table_title.recipes')
      th data-field="helper" data-sortable="true" = t('cooks.table_title.helper')
      th.status-info-th data-field="status" data-sortable="true" = t('cooks.table_title.status')
      - if source == RouteSourceConsts::WIZARD
        th data-field="contact_info" data-sortable="false" Info
        th.updated-th  data-field="updated" data-sortable="true" = t('cooks.table_title.updated')

  tbody.js-assignable-table-body

javascript:
  $(document).ready(function () {

    var default_columns = [
      {data: "given", className: "cook-value-received"},
      {data: "cook_name", className: "cook-name"},
      {data: "recipes", className: "recipes-list", orderable: false},
      {data: "helper", className: "assignment-info.doer-info", orderable: true},
      {data: "status", className: "cook-status"}



    ];
    if (#{source == RouteSourceConsts::WIZARD}) {
      var columns = default_columns.concat([ {data: "contact_info", className: "cook-info"}, {data: "updated", className: "updated-at"}]);
      columns.unshift({data: "cook_checkbox"})

    } else {
      var columns = default_columns
    }
    if (#{source == RouteSourceConsts::WIZARD}) {
      var custom_options = {
        lengthMenu: [50, 100, 150],

      };
    } else {
      var custom_options = {lengthMenu: [50, 100, 150]};
    }
    var default_table_options = {
      autoWidth: false,
      serverSide: true,
      searching: true,
      searchDelay: 1000,
      paging: true,
      responsive: true,
      dom: '<"pull-left"l><"pull-right"f>t<"bottom"p><"clear">',
      pagingType: "full_numbers",
      language: {emptyTable: '', zeroRecords: ''},
      ajax: {
        url: "#{project_cooks_path(project, source: source, type: type)}",
        type: 'GET',
        data: function (data) {
          data.type_filter = $('select.js-cook-type-filter').val()
        }
      },
      drawCallback: function (_settings) {
        initializecookStatusSelect();
        var pagination = $(this).closest('.js-donation-tabs, .js-cooks-main-container').find('.dataTables_paginate');
        pagination.toggle(this.api().page.info().pages > 1);
      },
      headerCallback: function (_thead, _data, _start, _end, _display) {
        cells = $('##{table_id} th');
        $(cells[0]).removeClass('cook-value-received');
        $(cells[1]).removeClass('cook-name');
        $(cells[2]).removeClass('recipes-list');
        $(cells[3]).removeClass('assignment-info.doer-info');
        $(cells[4]).removeClass('cook-status');
        $(cells[5]).removeClass('cook-info');
        $(cells[6]).removeClass('updated-at');
      },
      columns: columns,
      order: []
    };
    $("##{table_id}").dataTable($.extend({}, default_table_options, custom_options));

    channel = pusher.subscribe('cooks-#{project.id}');
    channel.bind('update', function (_data) {
      $('##{table_id}').DataTable().rows().invalidate('data').draw(false);
    });

    channel = pusher.subscribe('cooks-#{project.id}');
    channel.bind('imported', function (_data) {
      $('##{table_id}').DataTable().rows().invalidate('data').draw(false);
    });
  });



from Using JQuery Server side datatables in ruby app and pagination shows blank page after 1st page

Android Canvas change color of intersection of shapes and texts

I'm trying to change color of intersection of shapes and text using Canvas. As you can see in the imagei have 2 shapes and 1 text with different paints.
This is without any PorterDuffXfermode, and PorterDuffColorFilter mode added to any paint. I want intersection of shapes to be particular color, for example white, and text red or white like the images below.
In my example, text is at the bottom, circle middle and rectangle above but it's insignificant, i'm just trying to figure out how it works and how should intersection can be set to particular color.
As you can see in this imageimage background is black, circles are white and text is black. When circles overlap intersection of circles turns to black and overlapping section of text turns to white.
I can achieve this with
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));

if circle and rectangle are both white and background is black. When i change background color to any other color, text is not visible, shapes are black.
I also wonder how can i get similar results like in this imageon the image Can overlapping sections for circle, rectangle and text can be set to specific color?


from Android Canvas change color of intersection of shapes and texts

How to disable google tag manager and google analytics

Hi I used following code for disable google analytics and google tag manager but its not worked.

<script>
var gaoop_property    = 'UA-xxxxxxxx-x';
var gaoop_disable_str = 'ga-disable-' + gaoop_property;
function gtmOptOut() {
    document.cookie = gaoop_disable_str + '=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/';       
    window[gaoop_disable_str] = true;        
    window.location.reload();
}
</script>

Does anyone know how I can fix this? Thank you.



from How to disable google tag manager and google analytics

/lib64/libc.so.6: version `GLIBC_2.14' not found. Why am I getting this error?

I am working in node js. I have installed hummus package. It installed properly. I am using this package for modifying the pdf files. While downloading the pdf I am calling hummus. Onclick of download I am getting this error.

Error: /lib64/libc.so.6: version `GLIBC_2.14' not found (required by /var/www/html/node_modules/hummus/binding/hummus.node)
    at Object.Module._extensions..node (module.js:681:18)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/www/html/node_modules/hummus/hummus.js:5:31)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at /var/www/html/app/routes.js:2250:18
    at Layer.handle [as handle_request] (/var/www/html/node_modules/express/lib/router/layer.js:95:5)

With the help of this link I have updated glibc. But still I am getting the same error. Please help me to find out the issue. I am using CentOs 6.9



from /lib64/libc.so.6: version `GLIBC_2.14' not found. Why am I getting this error?

Image passed from an API not displaying in a pageview container swift

I am working on an iOS application which interacts with an API using alamofire and swiftyJSON. In this api I get a bunch of values returned and one of them is images. the Images returned comes in form of an array but i am able to iterate through the array and display a single image. To make the application more advanced, I decided to implement UIPageViewController class in my application. I called the API function and tried to pass my images into view controllers.
List of things in my storyboard
  1. A UIPageView
  2. A UiViewController with a UIImage embeded into it.
I have my codes fine to the best of my knowledge but when I run the application nothing happens on in the console. Below is my codes.
protocol ProductImagesPageViewControllerDelegate: class {
    func setupPageController(numberOfPages: Int)
    func turnPageController(to index: Int)
}

class ProductPageVC: UIPageViewController {

    weak var  pageViewControllerDelegate: ProductImagesPageViewControllerDelegate?

    override func viewDidLoad() {
        super.viewDidLoad()

        automaticallyAdjustsScrollViewInsets = false
        dataSource = self
        delegate = self

    }


    func configureImg() {
        let productId = ProductServices.instance.selectedProduct?.id
        ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

            if success {
                ProductServices.instance.productDetails.forEach({ (productDetail) in

                    let images = productDetail.productImg.count

                    if images > 0 {

                        for image in 0..<(images) {

                            let imageVC = self.storyboard?.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                            self.controllers.append(imageVC!)

                        }
                    }

                })
            }
        })
    }

    lazy var controllers: [UIViewController] = {

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        var controllers = [UIViewController]()


        let productId = ProductServices.instance.selectedProduct?.id
        ProductServices.instance.findIndividualProducts(id: productId!, completion: { (success) in

            if success {
                ProductServices.instance.productDetails.forEach({ (productDetail) in

                    let images = productDetail.productImg.count

                    if images > 0 {

                        for image in 0..<(images) {

                            let imageVC = storyboard.instantiateViewController(withIdentifier: PRODUCT_IMAGE_VC)
                            controllers.append(imageVC)

                        }
                    }

                })
            }
        })



        self.pageViewControllerDelegate?.setupPageController(numberOfPages: controllers.count)

        return controllers
    }()



    func turnToPage(index: Int)
    {
        let controller = controllers[index]
        var direction = UIPageViewControllerNavigationDirection.forward

        if let currentVC = viewControllers?.first {
            let currentIndex = controllers.index(of: currentVC)!
            if currentIndex > index {
                direction = .reverse
            }
        }

        self.configureDisplaying(viewController: controller)

        setViewControllers([controller], direction: direction, animated: true, completion: nil)
    }

    func configureDisplaying(viewController: UIViewController)
    {
        for (index, vc) in controllers.enumerated() {
            if viewController === vc {
                if let imageVC = viewController as? ImagesVC {

                    imageVC.configureImage(productIndex: index)

                    self.pageViewControllerDelegate?.turnPageController(to: index)
                }
            }
        }
    }
}
// MARK: - UIPageViewControllerDataSource

extension ProductPageVC : UIPageViewControllerDataSource
{
    func pageViewController(_ pageViewController: UIPageViewController, 
viewControllerBefore viewController: UIViewController) -> UIViewController?
    {
        if let index = controllers.index(of: viewController) {
            if index > 0 {
                return controllers[index-1]
            }
        }

        return controllers.last
    }

    func pageViewController(_ pageViewController: UIPageViewController, 
viewControllerAfter viewController: UIViewController) -> UIViewController? {

        if let index = controllers.index(of: viewController) {
            if index < controllers.count - 1 {
                return controllers[index + 1]
            }
        }

        return controllers.first
    }
}

extension ProductPageVC : UIPageViewControllerDelegate {

    func pageViewController(_ pageViewController: UIPageViewController, 
willTransitionTo pendingViewControllers: [UIViewController])
    {
        self.configureDisplaying(viewController: pendingViewControllers.first as! ImagesVC)
    }

    func pageViewController(_ pageViewController: UIPageViewController, 
didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], 
transitionCompleted completed: Bool)
    {
        if !completed {
            self.configureDisplaying(viewController: previousViewControllers.first as! 
ImagesVC)
        }
    }
}

This is my ImageVC code
class ImagesVC: UIViewController {

    @IBOutlet weak var imageView: UIImageView!


    func configureImage(productIndex : Int) -> Void {

        ProductServices.instance.productDetails.forEach { (productImg) in

            if productImg.productImg.count > 0 {
                imageView.sd_setImage(with: URL(string: productImg.productImg[productIndex]!) )
            } else {
                imageView.image = UIImage(named: "image_not_found")
            }
        }

    }}

This is my HeaderImageView code
class HeaderImageVC: UIView {

    @IBOutlet weak var pageControl: UIPageControl!
}

extension HeaderImageVC : ProductImagesPageViewControllerDelegate {
    func setupPageController(numberOfPages: Int)
    {
        pageControl.numberOfPages = numberOfPages
    }

    func turnPageController(to index: Int)
    {
        pageControl.currentPage = index
    }
}

I have no idea why the code is not working buth further codes would be supplied on request. Thanks.


from Image passed from an API not displaying in a pageview container swift

Documenting class attributes with type annotations

I want to autogenerate documentation to my code from docstrings. I have some basic class meant to store some data:

class DataHolder:
    """
    Class to hold some data

    Attributes:
        batch: Run without GUI
        debug (bool): Show debug messages
    """
    batch: bool = False
    debug: bool = False
    name: str = 'default'
    """Object name"""
    version: int = 0
    """int: Object version"""

My rst file:

DataHolder
==========

.. autoclass:: data_holder.DataHolder
   :members:

I have documented each attribute in a different way to show the difference, here is the output:
enter image description here

It seems like Sphinx cannot connect the Attributes section with the real attributes, that's why it cannot display their default value.

The final output I would like to achieve is the outcome as for the version field with the docstring defined as for batch. I want to display the attribute name with default value and type, but taken from type annotations. Looks like Sphinx is ignoring the type annotations in this case.

My sphinx extensions:

extensions = [
    'sphinx.ext.viewcode',
    'sphinx.ext.autodoc',
    'sphinxcontrib.napoleon',
]

What can I do to achieve such behavior? I can't find any good examples for such use case.



from Documenting class attributes with type annotations

Wrong order of execution in Resolution Center crash report

My app got rejected from the app store because there is a button that causes it to crash when pressed on an iPad. I don't have an iPad, and the bug is unreproducible on any of the iPad simulators. Here's the crash report the Resolution Center sent me:

{"app_name":"xxx","timestamp":"2018-05-23 14:18:37.70 -0700","app_version":"0.4.5","slice_uuid":"f7e0571c-a2a9-313c-ab7b-9a9109670ff2","adam_id":1387669409,"build_version":"1","bundleID":"com.b.xxx","share_with_app_devs":false,"is_first_party":false,"bug_type":"109","os_version":"iPhone OS 11.3.1 (15E302)","incident_id":"D5ADA937-9FAF-479B-A925-7B127B5E0C44","name":"xxx"}
Incident Identifier: D5ADA937-9FAF-479B-A925-7B127B5E0C44
CrashReporter Key:   cac3035154ad4b589b77fd30cfea229fc2cfaf20
Hardware Model:      xxx
Process:             xxx [1949]
Path:                /private/var/containers/Bundle/Application/FD86FF84-2DDF-4DFA-B23D-703D4A08316B/xxx.app/xxx
Identifier:          com.b.xxx
Version:             1 (0.4.5)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.b.xxx [1153]


Date/Time:           2018-05-23 14:18:37.5753 -0700
Launch Time:         2018-05-23 14:18:31.9754 -0700
OS Version:          iPhone OS 11.3.1 (15E302)
Baseband Version:    6.55.00
Report Version:      104

Exception Type:  EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x0000000180b03644
Termination Signal: Trace/BPT trap: 5
Termination Reason: Namespace SIGNAL, Code 0x5
Terminating Process: exc handler [0]
Triggered by Thread:  0

Application Specific Information:
BUG IN CLIENT OF LIBDISPATCH: trying to lock recursively

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libdispatch.dylib               0x0000000180b03644 _dispatch_gate_wait_slow$VARIANT$mp + 180
1   libdispatch.dylib               0x0000000180b04334 dispatch_once_f$VARIANT$mp + 132
2   libdispatch.dylib               0x0000000180b04334 dispatch_once_f$VARIANT$mp + 132
3   xxx                             0x00000001006cc6ec specialized static TextFieldFactory.manufacture(for:with:) + 2868972 (TextFieldFactory.swift:13)
4   xxx                             0x00000001006535ac _T09xxx22GRADEDISPLAY_MAX_WIDTH12CoreGraphics7CGFloatVvpfiAEycfU_ + 2373036 (DimensionConstants.swift:0)
5   xxx                             0x00000001006532b8 globalinit_33_D344213E1027291683078D92DF0D6E22_func214 + 2372280 (DimensionConstants.swift:220)
6   libdispatch.dylib               0x0000000180b00ae4 _dispatch_client_callout + 16
7   libdispatch.dylib               0x0000000180b042ec dispatch_once_f$VARIANT$mp + 60
8   xxx                             0x00000001006cc6ec specialized static TextFieldFactory.manufacture(for:with:) + 2868972 (TextFieldFactory.swift:13)
9   xxx                             0x00000001006cac10 static TextFieldFactory.manufacture(for:with:) + 2862096 (TextFieldFactory.swift:0)
10  xxx                             0x0000000100614f2c _T09xxx04EditA4ViewC5titleAA9TextFieldCvgAFycfU_ + 2117420 (EditClassView.swift:26)
11  xxx                             0x000000010060ff90 EditClassView.beginInit() + 2097040 (EditClassView.swift:24)
12  xxx                             0x00000001006bc970 MView.init(sizeConstraint:) + 2804080 (MView.swift:0)
13  xxx                             0x0000000100614934 EditClassView.init(cCreateSemester:clss:sizeConstraint:) + 2115892 (EditClassView.swift:237)
14  xxx                             0x00000001007184f8 specialized CCreateSemester.createCreateCourseView(_:) + 3179768 (CCreateSemester.swift:667)
15  xxx                             0x000000010071393c CCreateSemester.setupNewSemester() + 3160380 (CCreateSemester.swift:594)
16  xxx                             0x000000010071030c CCreateSemester.viewDidLoad() + 3146508 (CCreateSemester.swift:0)
17  xxx                             0x0000000100711674 @objc CCreateSemester.viewDidLoad+ 3151476 () + 28
18  UIKit                           0x000000018adeaee0 -[UIViewController loadViewIfRequired] + 1020
19  UIKit                           0x000000018ae98e98 -[UINavigationController _updateScrollViewFromViewController:toViewController:] + 76
20  UIKit                           0x000000018ae98354 -[UINavigationController _startTransition:fromViewController:toViewController:] + 172
21  UIKit                           0x000000018ae97c90 -[UINavigationController _startDeferredTransitionIfNeeded:] + 1164
22  UIKit                           0x000000018ae97720 -[UINavigationController __viewWillLayoutSubviews] + 164
23  UIKit                           0x000000018ae8b424 -[UILayoutContainerView layoutSubviews] + 188
24  UIKit                           0x000000018ade3770 -[UIView+ 309104 (CALayerDelegate) layoutSublayersOfLayer:] + 1420
25  QuartzCore                      0x000000018538525c -[CALayer layoutSublayers] + 184
26  QuartzCore                      0x00000001853893ec CA::Layer::layout_if_needed+ 1209324 (CA::Transaction*) + 324
27  QuartzCore                      0x00000001852f5aa0 CA::Context::commit_transaction+ 604832 (CA::Transaction*) + 320
28  QuartzCore                      0x000000018531d5d0 CA::Transaction::commit+ 767440 () + 580
29  QuartzCore                      0x000000018531e450 CA::Transaction::observer_callback+ 771152 (__CFRunLoopObserver*, unsigned long, void*) + 92
30  CoreFoundation                  0x00000001811b6910 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 32
31  CoreFoundation                  0x00000001811b4238 __CFRunLoopDoObservers + 412
32  CoreFoundation                  0x00000001811b4884 __CFRunLoopRun + 1436
33  CoreFoundation                  0x00000001810d4da8 CFRunLoopRunSpecific + 552
34  GraphicsServices                0x00000001830b7020 GSEventRunModal + 100
35  UIKit                           0x000000018b0b578c UIApplicationMain + 236
36  xxx                             0x00000001004179b8 main + 31160 (PercentBasedUnequalField.swift:12)
37  libdyld.dylib                   0x0000000180b65fc0 start + 4

Thread 1:
0   libsystem_kernel.dylib          0x0000000180c95d84 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x0000000180e33eb4 _pthread_wqthread + 928
2   libsystem_pthread.dylib         0x0000000180e33b08 start_wqthread + 4

Thread 2:
0   libsystem_kernel.dylib          0x0000000180c95d84 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x0000000180e33eb4 _pthread_wqthread + 928
2   libsystem_pthread.dylib         0x0000000180e33b08 start_wqthread + 4

Thread 3:
0   libsystem_kernel.dylib          0x0000000180c95d84 __workq_kernreturn + 8
1   libsystem_pthread.dylib         0x0000000180e340a0 _pthread_wqthread + 1420
2   libsystem_pthread.dylib         0x0000000180e33b08 start_wqthread + 4

Thread 4:
0   libsystem_pthread.dylib         0x0000000180e33b04 start_wqthread + 0

Thread 5 name:  com.apple.uikit.eventfetch-thread
Thread 5:
0   libsystem_kernel.dylib          0x0000000180c73e08 mach_msg_trap + 8
1   libsystem_kernel.dylib          0x0000000180c73c80 mach_msg + 72
2   CoreFoundation                  0x00000001811b6e40 __CFRunLoopServiceMachPort + 196
3   CoreFoundation                  0x00000001811b4908 __CFRunLoopRun + 1568
4   CoreFoundation                  0x00000001810d4da8 CFRunLoopRunSpecific + 552
5   Foundation                      0x0000000181b49674 -[NSRunLoop+ 34420 (NSRunLoop) runMode:beforeDate:] + 304
6   Foundation                      0x0000000181b4951c -[NSRunLoop+ 34076 (NSRunLoop) runUntilDate:] + 148
7   UIKit                           0x000000018ad9a7e4 -[UIEventFetcher threadMain] + 136
8   Foundation                      0x0000000181c59efc __NSThread__start__ + 1040
9   libsystem_pthread.dylib         0x0000000180e35220 _pthread_body + 272
10  libsystem_pthread.dylib         0x0000000180e35110 _pthread_body + 0
11  libsystem_pthread.dylib         0x0000000180e33b10 thread_start + 4

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

Thread 7 name:  RLMRealm notification listener
Thread 7:
0   libsystem_kernel.dylib          0x0000000180c7834c kevent + 8
1   Realm                           0x0000000100a05a80 realm::_impl::ExternalCommitHelper::listen() + 88704 (external_commit_helper.cpp:203)
2   Realm                           0x0000000100a063ec std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0>::operator()() + 91116 (future:2323)
3   Realm                           0x0000000100a06374 std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >::__execute() + 90996 (future:1041)
4   Realm                           0x0000000100a06524 std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >*> >(void*, void*) + 91428 (thread:354)
5   libsystem_pthread.dylib         0x0000000180e35220 _pthread_body + 272
6   libsystem_pthread.dylib         0x0000000180e35110 _pthread_body + 0
7   libsystem_pthread.dylib         0x0000000180e33b10 thread_start + 4

Thread 8 name:  RLMRealm notification listener
Thread 8:
0   libsystem_kernel.dylib          0x0000000180c7834c kevent + 8
1   Realm                           0x0000000100a05a80 realm::_impl::ExternalCommitHelper::listen() + 88704 (external_commit_helper.cpp:203)
2   Realm                           0x0000000100a063ec std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0>::operator()() + 91116 (future:2323)
3   Realm                           0x0000000100a06374 std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >::__execute() + 90996 (future:1041)
4   Realm                           0x0000000100a06524 std::__1::__thread_proxy<std::__1::tuple<std::__1::unique_ptr<std::__1::__thread_struct, std::__1::default_delete<std::__1::__thread_struct> >, void (std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >::*)(), std::__1::__async_assoc_state<void, std::__1::__async_func<realm::_impl::ExternalCommitHelper::ExternalCommitHelper(realm::_impl::RealmCoordinator&)::$_0> >*> >(void*, void*) + 91428 (thread:354)
5   libsystem_pthread.dylib         0x0000000180e35220 _pthread_body + 272
6   libsystem_pthread.dylib         0x0000000180e35110 _pthread_body + 0
7   libsystem_pthread.dylib         0x0000000180e33b10 thread_start + 4

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x00000001007cdd68   x1: 0x0000000000000301   x2: 0x0000000000000000   x3: 0x0000000000000000
    x4: 0x00000001007654a0   x5: 0x0000000000000011   x6: 0x0000000000000000   x7: 0x00000001c8041ce0
    x8: 0x0000000000000003   x9: 0x0000000000000301  x10: 0x0000000000000000  x11: 0x0000000000000000
   x12: 0x0000000000000001  x13: 0x0000000000000000  x14: 0x0000000000000000  x15: 0x0000000000000001
   x16: 0x0000000180b042b0  x17: 0x0000000000000000  x18: 0x0000000000000000  x19: 0x0000000000000000
   x20: 0x00000000ffffffff  x21: 0x00000001007cdd68  x22: 0x0000000000000303  x23: 0x0000000000000001
   x24: 0x0000000000000001  x25: 0x0000000101534280  x26: 0x0000000000000000  x27: 0x0000000000000001
   x28: 0x0000000000000001   fp: 0x000000016f9eb140   lr: 0x0000000180b04334
    sp: 0x000000016f9eb120   pc: 0x0000000180b03644 cpsr: 0x60000000

Moving up from Line 11 Thread 0 here is the code execution:

Line 11: EditClassView.beginInit()

class EditClassView: MStackView {

    // Parent implementation does nothing
    override func beginInit() {

        // First time `title` is referenced. It's lazy, so it's initialized here
        title.text = clss.getTitle()

        // Crashes before here
        ...
    }
}

Line 10: Initialization of local title property in EditClassView.title's lazy initializer:

lazy private(set) var title: TextField = {

    let title = TF.manufacture(for: .allPurpose, with: TParams(textSize: 21, inputView: nil, placeholder: "Class Title"))

    // Crashes before here
    ...
}()

Line 9: I think this is just referring to the TextFieldFactory.manufacture(for:with:) reference, and not the actual execution of the function itself:

Line 8: I'm not sure what this is referring to. It appears to just be the TextFieldFactory.TextFieldParams typealias because that's what's on TextFieldFactory.swift:13:

typealias TParams = TextFieldFactory.TextFieldParams

// Here is the definition    
class TextFieldParams {

    static let DEFAULT_TEXT: String? = nil
    static let DEFAULT_FONT_NAME = "poiretone-regular"
    static let DEFAULT_TEXT_SIZE = MEDIUM_TEXT_SIZE
    static let DEFAULT_TEXT_COLOR = UIColor.black
    static let DEFAULT_TINT_COLOR = UIColor.black
    static let DEFAULT_TEXT_ALIGNMENT = NSTextAlignment.center
    static let DEFAULT_USES_AUTORESIZING_MASK = true
    static let DEFAULT_INPUT_VIEW = TextFieldFactory.EMPTY_INPUT_VIEW
    static let DEFAULT_PLACEHOLDER: String? = nil
    static let DEFAULT_ADJUST_WIDTH_WITH_TEXT = false
    static let DEFAULT_MIN_WIDTH: CGFloat? = nil
    static let DEFAULT_MAX_WIDTH: CGFloat? = nil
    static let DEFAULT_EMPTY_WIDTH: CGFloat? = nil

    let text: String?
    let fontName: String
    let textSize: CGFloat
    let textColor: UIColor
    let tintColor: UIColor
    let textAlignment: NSTextAlignment
    let translatesAutoresizingMaskIntoConstraints: Bool
    let inputView: UIView?
    let placeholder: String?
    let adjustWidthWithText: Bool
    let minWidth: CGFloat?
    let maxWidth: CGFloat?
    let emptyWidth: CGFloat?

    var font: UIFont {   return UIFont(name: fontName, size: textSize)!   }

    init(text: String? = DEFAULT_TEXT,
         fontName: String = DEFAULT_FONT_NAME,
         textSize: CGFloat = DEFAULT_TEXT_SIZE,
         textColor: UIColor = DEFAULT_TEXT_COLOR,
         tintColor: UIColor = DEFAULT_TINT_COLOR,
         textAlignment: NSTextAlignment = DEFAULT_TEXT_ALIGNMENT,
         translatesAutoresizingMaskIntoConstraints: Bool = DEFAULT_USES_AUTORESIZING_MASK,
         inputView: UIView? = DEFAULT_INPUT_VIEW,
         placeholder: String? = DEFAULT_PLACEHOLDER,
         adjustWidthWithText: Bool = DEFAULT_ADJUST_WIDTH_WITH_TEXT,
         minWidth: CGFloat? = DEFAULT_MIN_WIDTH,
         maxWidth: CGFloat? = DEFAULT_MAX_WIDTH,
         emptyWidth: CGFloat? = DEFAULT_EMPTY_WIDTH
        ) {

        self.text = text
        self.fontName = fontName
        self.textSize = textSize
        self.textColor = textColor
        self.tintColor = tintColor
        self.textAlignment = textAlignment
        self.translatesAutoresizingMaskIntoConstraints = translatesAutoresizingMaskIntoConstraints
        self.inputView = inputView
        self.placeholder = placeholder
        self.adjustWidthWithText = adjustWidthWithText
        self.minWidth = minWidth
        self.maxWidth = maxWidth
        self.emptyWidth = emptyWidth
    }
}

Now here's where I get lost. Line 7 and 6 don't refer to my code at all, so I'm not sure what it's doing but next thing you know one of my global constants --GRADEDISPLAY_MAX_WIDTH -- is getting initialized on Line 5. And bear in mind that it has nothing to do with EditClassView at all let alone EditClassView.title.

But before I show its initialization, there is a link. GRADEDISPLAY_MAX_WIDTH is referenced in TF.manufacture(for:with:), but you'll see that the function is just one big switch block, and GRADEDISPLAY_MAX_WIDTH is not referenced in the case we should be executing in which is odd. If you look back to Line 10, you'll see the relevant case is .allPurpose, all the way at the end of the function:

static func manufacture(for textFieldPurpose: TextFieldPurpose, with params: TextFieldParams = TextFieldParams()) -> TextField {

    switch textFieldPurpose {

    case .notifyingTimeField:

        var ntf = makeNotifyingFocusableTimeField(with: params as! NotifyingFocusableTimeFieldParams)
        ntf.frame.size.width = CGFloat.timeFieldWidth
        ntf.underline()

        return ntf

    case .timeField:

        var ftf = makeFocusableTimeField(with: params as! FocusableTimeFieldParams)
        ftf.frame.size.width = CGFloat.timeFieldWidth
        ftf.underline()

        return ftf

    case .gradingCategoryTitle:

        var tf = makeUnderlineTextField(with: UnderlineTextFieldParams(edgeInsets: UIEdgeInsetsMake(0, AC_TITLE_DEFAULT_SIDE_INSET, UnderlineLabel.DEFAULT_BOTTOM_INSET, AC_TITLE_DEFAULT_SIDE_INSET),
                                                                       text: params.text,
                                                                       textSize: LARGE_TEXT_SIZE,
                                                                       inputView: nil,
                                                                       adjustWidthWithText: true,
                                                                       maxWidth: params.maxWidth)
        )
        tf.underline()

        return tf

    case .whereTextField:

        var tf = makeUnderlineTextField(with: UnderlineTextFieldParams(inputView: nil,
                                                                       adjustWidthWithText: true,
                                                                       minWidth: WHERE_TEXTFIELD_MIN_WIDTH,
                                                                       maxWidth: params.maxWidth)
        )
        tf.underline()

        return tf

    case .notifyingDateField:

        var ndf = makeNotifyingFocusableDateField(with: params as! ContextualFocusableParams)
        ndf.frame.size.width = CGFloat.timeFieldWidth
        ndf.underline()

        return ndf

    case .percentTotalField, .percentEachField, .percentUnequalField, .pointsTotalField, .pointsEachField, .pointsUnequalField, .percentExamTotalField, .percentEachExamField, .percentFinalField, .pointsExamTotalField, .pointsEachExamField, .pointsFinalField:

        guard let params = params as? ContextualFocusableParams else {

            fatalError("A ContextualFocusableParams must be passed in order to manufacture a FocusableWeightField")
        }

        var f = makeFocusableWeightField(for: textFieldPurpose, with: ContextualFocusableParams(context: params.context,
                                                                                                adjustWidthWithText: true,
                                                                                                minWidth: CGFloat.timeFieldWidth)
        )
        f.underline()

        return f

    case .customTitleField:

        let edgeInsets = UIEdgeInsetsMake(0, CUSTOM_TITLE_SIDE_INSET, UnderlineLabel.DEFAULT_BOTTOM_INSET, CUSTOM_TITLE_SIDE_INSET)
        var tf = makeUnderlineTextField(with: UnderlineTextFieldParams(edgeInsets: edgeInsets,
                                                                       inputView: nil,
                                                                       placeholder: params.placeholder,
                                                                       adjustWidthWithText: true,
                                                                       minWidth: params.minWidth,
                                                                       maxWidth: params.maxWidth,
                                                                       emptyWidth: params.emptyWidth)
        )
        tf.underline()

        return tf

    case .gradeField:

        let tf = initializedTextField(textField: PercentSuffixedTextField(),
                                      params: TParams(text: params.text,
                                                      textSize: AV_GRADE_TEXT_SIZE,
                                                      textColor: UIColor.defaultTextColor,
                                                      inputView: nil)
        )
        tf.frame.size = CGSize(width: GRADEDISPLAY_MAX_WIDTH, height: GV_HEIGHT)
        tf.isEnabled = false
        tf.keyboardType = .numberPad

        return tf

    case .fractionField:

        let tf = makeTextField(with: TParams(text: params.text,
                                             textSize: AV_GRADE_TEXT_SIZE,
                                             textColor: UIColor.defaultTextColor,
                                             inputView: nil)
        )
        tf.frame.size.width = GRADEDISPLAY_MAX_WIDTH
        tf.isEnabled = false
        tf.keyboardType = .numberPad

        return tf

    case .assessmentTitle:

        let tf = makeTextField(with: TParams(text: params.text,
                                             textSize: AV_TITLE_TEXT_SIZE,
                                             textColor: UIColor.defaultTextColor,
                                             placeholder: String.classTitlePlaceholder,
                                             adjustWidthWithText: true)
        )
        tf.isEnabled = false

        return tf

    case .weightField:

        let tf = initializedTextField(textField: PercentSuffixedTextField(adjustWidthWithText: true, minWidth: params.minWidth),
                                      params: TParams(text: params.text,
                                                      textSize: params.textSize,
                                                      textAlignment: .right,
                                                      inputView: nil)
        )
        tf.keyboardType = .decimalPad
        tf.performableActions = []

        return tf

    // `GRADEDISPLAY_MAX_WIDTH` is referenced in the `.gradeField` 
    // and `.fractionField` cases just above here
    case .allPurpose: return makeTextField(with: params)

    case .allPurposeInsetting: return makeInsetTextField(with: params as! ITParams)
    }
}

Line 5: I think this is the initialization of GRADEDISPLAY_MAX_WIDTH because DimensionConstants.swift:220 is where its property definition begins

let GRADEDISPLAY_MAX_WIDTH: CGFloat = {

    let gradeField = TF.manufacture(for: .allPurpose, with: TParams(text: "100%", textSize: 17))

    // From the look of the crash report, it doesn't look 
    // like execution makes it this far
    let trailingMargin: CGFloat = 4

    return proportionedWidth(gradeField.frame.size.width + trailingMargin)
}()

I'm not sure what Line 4 is referring to. Could it be GRADEDISPLAY_MAX_WIDTH itself?

And finally the last reference to my code in the crash report.

Line 3: Which just appears to be the same as Line 8...

The priority here is fixing the crash, and I think it has something to do with what's going on on Lines 6 and 7 of the stack trace. I could get into my code base, but take my word for it that GRADEDISPLAY_MAX_WIDTH is not referenced anywhere in EditClassView or any code that is related to it, so there's no reason it should be seen anywhere remotely near EditClassView in any stack trace.

Can anyone shed some light on what's going on on Lines 6 and 7?

This may be another clue:

On Line 36 in Thread 0 PercentBasedUnequalField is referenced; specifically line 12 in it. PercentBasedUnequalField is actually not used anywhere within the executing code of the app. It's part of a new feature I'm working on. I left the file in the bundle because it would have been a hassle to remove it because the current source branch branched off that incomplete feature.

The similarity here is that like GRADEDISPLAY_MAX_WIDTH, PercentBasedUnequalField is also referenced in an unrelated switch case in TF.manufacture(for:with:).



from Wrong order of execution in Resolution Center crash report