Wednesday 31 October 2018

Drag and Drop not working between 2 activities on some devices

I use the following code to drag a view from an activity to another activity within my application. Knowing that the second activity (That receives drop event) is not created / alive when the drag starts.

It works good on

Samsung Note 3 Android 5 API 21, Samsung Note 4 Android 6.0.1 API 23

but not working on

ASUS ZenPad 8.0 Android 5.1.1 API 22, Le Max 2 Android 6.0 API 23

Your thoughts are appreciated.

Starting Drag operation:

public boolean onItemLongClick(AdapterView<?> aParent, View aView, int aPos, long aID) {

    View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(aView);

    Intent intent = prepDNDIntent();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        aView.startDragAndDrop(ClipData.newIntent(DRAG_N_DROP_DESCRIPTION, intent), shadowBuilder, null, 0);
    } else {
        aView.startDrag(ClipData.newIntent(DRAG_N_DROP_DESCRIPTION, intent), shadowBuilder, null, 0);
    }


    startMainActivity();

    finishThisActivity();

    return true;
}

Receiving Drop Operation

public boolean validDragNDropOperation(View aView, DragEvent aEvent){
    boolean status = false;

    ClipDescription clipDescription = aEvent.getClipDescription();
    if (clipDescription != null && clipDescription.getLabel().toString().equalsIgnoreCase(DRAG_N_DROP_DESCRIPTION)) {
        status = true;
    }

    return status;
}


public boolean onDrag(View aView, DragEvent aEvent) {

    switch (aEvent.getAction()) {
          case DragEvent.ACTION_DRAG_STARTED:

               This is not called on some devices

               return validDragNDropOperation(aView, aEvent, false);

          case DragEvent.ACTION_DROP:
                    ....
                    ....
                    ....
                    ....
                    ....
                 break;
    }

    return true;
}

Knowing that both Activities are set android:launchMode="standard"



from Drag and Drop not working between 2 activities on some devices

How to finish several SingleInstance Activities?

I have several activities with launchMode SingleInstance. On log out i want to finish all activities and open launchScreen.

val intent = Intent(context, LauncherActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
(context as AppCompatActivity).finishAffinity()
context.startActivity(intent)

However if i press back at Launcher activity i am forwarded to previously launched activities with singleInstance mode



from How to finish several SingleInstance Activities?

Angular 6 POST request sent out without Bearer token only with --prod?

I'm using Angular 6 with an HTTP Interceptor configured to apply bearer token to outgoing requests.

  • In the dev build (ng serve), the token is applied and everything works fine. :-)

  • In the production build (ng serve --prod) the request is sent out without bearer token. :-(

In the prod build, I have verified the header is being applied, by dumping the headers to the console after applying them.

I have no idea why they are excluded from the http request.

There are not differences in my environment files.

What else should I be looking at?

missing bearer token

What can I do to fix this?

At first I thought this was an issue between my local environment and my staging environment, but then I tried running ng serve --prod locally and saw the same results.

All that to say, everything is identical except one being a production build and one being a dev build.

Here's the Interceptor code:

import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // add authorization header with jwt token if available
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
            console.log('headers:', request.headers); // <---- I can see headers in console output
        }

        return next.handle(request);
    }
}



from Angular 6 POST request sent out without Bearer token only with --prod?

Cannot resolve symbol FirebaseVisionTextDetector

I get Cannot resolve symbol FirebaseVisionTextDetector error when I put in my module:

import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;

I can't understand why because in gradle I have the correct implementation:

implementation 'com.google.firebase:firebase-ml-vision:18.0.1'

SOLVED

I have solved by downgrading to 16.0.0. Still don't know the reason why.

implementation 'com.google.firebase:firebase-ml-vision:16.0.0'



from Cannot resolve symbol FirebaseVisionTextDetector

Electron TypeError: $(...).jstree is not a function when i try to use it

i'm using jstree i have downloaded code from here https://www.jstree.com/

found jstree.js from dist folder and put into my /js/jstree.js

imported jstree like this:

if(inElectron()){
    window.jQuery = require('./js/jquery.min.js');
    window.$ = window.jQuery;
    window.jstree = require('./js/jstree.js');
}

when i try to use it:

$('#jstree').jstree();// for just demo with minimal code (Actually i'm using full code from here http://jsfiddle.net/t4s7dz52/)

i'm getting below error:

"TypeError: $(...).jstree is not a function

Note: i'm able to use jQuery throughout project ,so no import error as both js are in same folder

Please help me thanks in advance!!!!



from Electron TypeError: $(...).jstree is not a function when i try to use it

Room: deleting a ForeignKey or setting the ForeignKey to a default value

I have the following entities:

@Entity(indices  = {@Index("address")},
    foreignKeys = @ForeignKey(
    entity = Address.class,
    parentColumns = "address",
    childColumns = "address",
    onUpdate = CASCADE,
    onDelete = SET_DEFAULT))
public class Human {
    @PrimaryKey(autoGenerate = true)
    public long id;

    @NonNull
    public String name;

    @NonNull
    public String address;
}

@Entity
public class Address {

    @PrimaryKey
    @NonNull
    public String address;

    public int someInt;
}

I add "humans" with different addresses which I later try to delete or edit using:

@Insert(onConflict = REPLACE)
void add(Human human);

Options that I see and problems with them:

  1. I have a list of addresses of which one is "default". When I delete an address, I would like the "Humans" residing at the deleted address to "move" to "default". I used:

    @Query("delete from Address where address = :address")
    void deleteAddress(String address);
    
    

so onDelete = SET_DEFAULT does not seem to work as I imagined if I set a default value to address in the Human Entity.

This currently fails with: NOT NULL constraint failed.

  1. An alternative to the deletion would be to edit an address and set it to "default" and thus merging with the existing "default" entry. I tried:

    @Query("update Address SET address = :address WHERE address = :addressToEdit")
    void editAddress(String addressToEdit, String newAddress);
    
    

This currently fails with: UNIQUE constraint failed. because there's already an address with the same name, obviously.

  1. Setting the address to @Nullable in both Entities. In this way, the "default" address is null. This adds extra complexity to my solution(would not prefer it) and it seems that I'm not able to query the Humans with a null address using the following code because it does not return anything.

    @Query("select * from Human where address = :address")
    LiveData<List<Human>> getHumans(String address);
    
    

How can I achieve this setting to default of a deleted address(foreign key)?



from Room: deleting a ForeignKey or setting the ForeignKey to a default value

Mousedown event sensitivity

I have a table grid that highlights cells/checkboxes with click and drag type of functionality.

When a user clicks on a cell and hovers for a while, then the cell / checkbox flickers a lot (firing off a lot of events).

Is there a way to make this less sensitive? i.e., some sort of timing event?

I tried adding .delay to the mouseover toggleclass, but it acts weird.

 $(function () {
        var isMouseDown = false,isHighlighted;

      $("#tablegrid").on('mousedown', 'td.nohighlight', function() {
            isMouseDown = true;
            $(this).toggleClass("highlighted");
            isHighlighted = $(this).hasClass("highlighted");
            var checkBoxes = $(this).find('.dosearchescheckbox :checkbox').trigger('click');
            return false; // prevent text selection
          })

      $("#tablegrid").on('mouseover', 'td.nohighlight', function() {
            if (isMouseDown) {
              $(this).toggleClass("highlighted");
              var checkBoxes = $(this).find('.dosearchescheckbox :checkbox').trigger('click');     
            }
          })
      $("#tablegrid").bind('selectstart', 'td.nohighlight', function() {    
            return false;
          })

      $(document)
        .mouseup(function () {
          isMouseDown = false;
        });
});



from Mousedown event sensitivity

Angular lags performance if multiple DOM elements inserted via dynamic component with binding

I have created n-level nested expand/collapse functionality using dynamic components of angular 5.

Functionally everything is working fine but when i load multiple dom elements browser either crashes or scroll stops working (Jerky Scroll)

Basically its advanced reporting feature with user selected filters and group by dimensions that we are offering.

Here is how my developed feature works

1) User visits report page on webapp. 2) User selects filters and groupby params according to which i generate div based table having multiple row.

Now i have kept condition checking that user can further expand/collapse row, based on object which i am maintaining using group by. Here group by indicates number of levels which user can utilize

For example Group by parameters are Country, OS, Appname and Campaign, I will render first level table displaying data for all countries available with expand button for every row, on click of expand button i render another table having Operating System (OS) data for that specific country and so on...

I have actually identified why performance issue occurs, it might be because of i am checking for that specific expand/collapsed button identified by next groupby object and isCollapsed parameter. Because of that specific conditon is checking multiple time periodically scroll either stops working or browser start performing slow

Here is video illustrating how it works and scroll bar performance

https://youtu.be/m1a2uxhoNqc

I can not upload code on plunker or any other online tool because its already integrated to platform that i am developing having actual data.

I am not able to add code here due to stackoverflow character limit but have created gist.

Here is url to access code:

https://drive.google.com/drive/folders/1ZxAS8yHd8iHJ6ds3mZhLR0bw6o0cnRL6?usp=sharing

I would like to make code more reusable will do it once performance issue is resolved.

Have look into this and let me know my mistakes to improve code quality and performance issues.

Thanks.



from Angular lags performance if multiple DOM elements inserted via dynamic component with binding

deploying the Tensorflow model in Python

Need help in implementing the Tensorflow model in real time. While I am training everything is working fine but when I move on for a realtime forecast or prediction, the output what I received flunked. I do not know why is this happening. I used the reference of teh code from here: https://www.kaggle.com/raoulma/ny-stock-price-prediction-rnn-lstm-gru/notebook And tried to implement or deploy using the same code with few changes.

See the following code:

import numpy as np
import pandas as pd
import sklearn
import sklearn.preprocessing
import datetime
import os
import tensorflow as tf

df = pd.read_csv("Realtime_Values.csv", index_col = 0)
df.info()
def load_data(stock,seq_len):

    data_raw = stock.as_matrix() # convert to numpy array
    data = []

    for index in range(len(data_raw) - seq_len): 
        data.append(data_raw[index: index + seq_len])
    #print(len(data))
    data = np.array(data);

    x_forecast = data[:,:-1,:]
    return x_forecast

def normalize_data(df):
    cols = list(df.columns.values)
    min_max_scaler = sklearn.preprocessing.MinMaxScaler()
    df = pd.DataFrame(min_max_scaler.fit_transform(df.values))
    df.columns = cols
    return df
model_path ="modelsOHLC"
seq_len = 9
# parameters
n_steps = seq_len-1 
n_inputs = 4
n_neurons = 100 
n_outputs = 4
n_layers = 4
learning_rate = 0.01
batch_size = 10
n_epochs = 1000
tf.reset_default_graph()

X = tf.placeholder(tf.float32, [None, n_steps, n_inputs])
y = tf.placeholder(tf.float32, [None, n_outputs])
layers = [tf.contrib.rnn.BasicRNNCell(num_units=n_neurons, activation=tf.nn.elu)
          for layer in range(n_layers)]
multi_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)
rnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)

stacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons]) 
stacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs)
outputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs])
outputs = outputs[:,n_steps-1,:] # keep only last output of sequence

loss = tf.reduce_mean(tf.square(outputs - y)) # loss function = mean squared error 
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) 
training_op = optimizer.minimize(loss)
saver = tf.train.Saver()
sess  =tf.Session()
sess.run(tf.global_variables_initializer())    
if(tf.train.checkpoint_exists(tf.train.latest_checkpoint(model_path))):
        saver.restore(sess, tf.train.latest_checkpoint(model_path))
df = normalize_data(df)
x_forecast = load_data(df,seq_len)
y_forecast_pred = sess.run(outputs, feed_dict={X: x_forecast})
print(y_forecast_pred)

Can anyone help me in getting the above code run in real time without any issues?



from deploying the Tensorflow model in Python

Perspective transform with Python PIL using src / target coordinates

I stumbled upon this question and am trying to perform perspective transformation with Python Pillow.

This is specifically what I am trying to do and what the result looks like:

enter image description here

And this is the code that I used to try it:

from PIL import Image
import numpy

# function copy-pasted from https://stackoverflow.com/a/14178717/744230
def find_coeffs(pa, pb):
    matrix = []
    for p1, p2 in zip(pa, pb):
        matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
        matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])

    A = numpy.matrix(matrix, dtype=numpy.float)
    B = numpy.array(pb).reshape(8)

    res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
    return numpy.array(res).reshape(8)

# test.png is a 256x256 white square
img = Image.open("./images/test.png")

coeffs = find_coeffs(
    [(0, 0), (256, 0), (256, 256), (0, 256)],
    [(15, 115), (140, 20), (140, 340), (15, 250)])

img.transform((300, 400), Image.PERSPECTIVE, coeffs,
              Image.BICUBIC).show()

I am not exactly sure how the transformation works, but it seems the points move quite into the opposite direction (e.g. I need to do (-15, 115) to make point A move to the right. However, it also won't move 15 pixels but 5).

How can I determine the exact coordinates of the target points to skew the image properly?



from Perspective transform with Python PIL using src / target coordinates

Faces indexed by iOS/Android app are not detected by Android/iOS App - AWS Rekognition

So I have been working on a product (Android First and then iOS) for a long time that index faces of people using AWS Rekognition and when they are again scanned later, it identifies them. It's working great when I index a face from an Android device and then try to search it with an Android device. But if I try to search it later on iOS app, it doesn't find it. Same is the result if I go other way round. Index with iOS, search with Android, not found. The collection ID is same while indexing and searching on both devices. I couldn't figure out how is it possible that a face indexed by one OS type, same region, same collection, couldn't be found while on other device.

If anyone here could try and help me with the issue, please do. I'll be really thankful.

Update 1: I have called "listCollections" function on both iOS and android apps. Both of them are showing different list of collections. This is the issue. But I can't figure our why it is happening. The identity pool and region is same on both of them.

Here is my Android Code to access Rekognition:

mCredentialsProvider = new CognitoCachingCredentialsProvider(
        mContext,
        "us-east-2:xbxfxexf-x5x5-xax7-x9xf-x5x0xexfx1xb", // Identity pool ID
        Regions.US_EAST_2 // Region
);

mUUID = UUID.randomUUID().toString().replace("-", "");

mAmazonS3Client = new AmazonS3Client(mCredentialsProvider);
mAmazonS3Client.setRegion(Region.getRegion(Regions.US_EAST_2));
mAmazonRekognitionClient = new AmazonRekognitionClient(mCredentialsProvider);

if(!mAmazonS3Client.doesBucketExist(mFacesBucket)) {
    mAmazonS3Client.createBucket(mFacesBucket);
}

Log.i(TAG, "Uploading image to S3 Bucket");
mAmazonS3Client.putObject(mFacesBucket, getS3ObjectName(), new File(data[0].toString()));
Log.i(TAG, "Image Uploaded");

Image image = new Image();
try {
    image.setBytes(ByteBuffer.wrap(Files.toByteArray(new File(data[0].toString()))));
} catch (IOException e) {
    e.printStackTrace();
}

Log.i(TAG, "Indexing image");
IndexFacesRequest indexFacesRequest =new IndexFacesRequest()
        .withCollectionId(mFacesCollection)
        .withImage(image)
        .withExternalImageId(mUUID)
        .withDetectionAttributes("ALL");

mAmazonRekognitionClient.indexFaces(indexFacesRequest);

Here is my iOS code to access Rekognition:

func uploadToCollection(img: UIImage)
    {
        let myIdentityPoolId="us-east-2:xbxfxexf-x5x5-xax7-x9xf-x5x0xexfx1xb"

        let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast2, identityPoolId: myIdentityPoolId)
        //store photo in s3()
        let configuration = AWSServiceConfiguration(region: .USEast2, credentialsProvider: credentialsProvider)

        AWSServiceManager.default().defaultServiceConfiguration = configuration
        rekognitionClient = AWSRekognition.default()

        guard let request = AWSRekognitionIndexFacesRequest() else
        {
            puts("Unable to initialize AWSRekognitionindexFaceRequest.")
            return
        }
        var go=false
        request.collectionId = "i_faces" + self.firebaseID.lowercased() //here iosCollection will be replaced by firebase Current UserID
        request.detectionAttributes = ["ALL", "DEFAULT"]
        request.externalImageId = self.UUID //this should be mUUID, passed as parameter to this function
        let sourceImage = img
        let image = AWSRekognitionImage()
        image!.bytes = sourceImage.jpegData(compressionQuality: 0.7)
        request.image = image
        self.rekognitionClient.indexFaces(request) { (response:AWSRekognitionIndexFacesResponse?, error:Error?) in
            if error == nil
            {
                print("Upload to Collection Complete")
            }
            go=true
            return
        }
        while(go==false){}
    }



from Faces indexed by iOS/Android app are not detected by Android/iOS App - AWS Rekognition

Running Apps Script on Android?

I am currently developing an Android app that requires the user to log into Google, and then get verified by running an Apps Script to figure out whether the user is part of a Google Group (I haven't been able to figure out how to do this outside of using Apps Scripts). I am able to get the user logged in using Firebase Authentication, but no matter what I try I am unable to run the Apps Script (the script itself works since it's able to run from the browser) since I can't seem to get the authorization right (I get 401 and 403 errors).

Here are some things I've tried:

  1. Using the Google Apps Script API

    Script service = new Script.Builder(new NetHttpTransport(), 
    JacksonFactory.getDefaultInstance(), credentials).setApplicationName(APPLICATION_NAME)
            .build();
    
    ExecutionRequest request = new ExecutionRequest()
            .setFunction("functionName");
    
    Operation op = service.scripts().run(MY_SCRIPT_ID, request).execute();
    
    if (op.getResponse() != null && op.getResponse().get("result") != null) {
         return op.getResponse().get("result");
    }
    
    

(https://developers.google.com/apps-script/api/how-tos/execute)

  1. Using a POST Request

    URL url = new URL("MY_SCRIPT_URL" + "?access_token=" + ACCESS_TOKEN);
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    
    HttpURLConnection urlConn = (HttpURLConnection) conn;
    urlConn.setRequestProperty("Authorization", "Bearer " + ACCESS_TOKEN);
    
    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream());
    wr.write("");
    wr.flush();
    wr.close();
    
    if(urlConn.getResponseCode() == 200){
        BufferedReader reader = new BufferedReader(urlConn.getOutputStream());
        //....AND HERE I READ FROM THE OUTPUT STREAM
    }
    
    

(Run Google Apps Script in Android, How to pass 'Authorization' header value in OAuth 2.0 with Google APIs, Add header to post request in string, https://developers.google.com/identity/protocols/OAuth2InstalledApp)

Where I've tried making credentials in the following ways:

  1. Using a Firebase Authentication Access Token

    GoogleCredential credentials = new GoogleCredential()
        .createScoped(Arrays.asList(ScriptScopes.GROUPS))
        .setAccessToken(FIREBASE_ACCESS_TOKEN);
    
    
  2. Using a Service Account

    InputStream in = activity.getAssets().open("SERVICE_INFO_FILE");
    
    GoogleCredential credentials = GoogleCredential.fromStream(new FileInputStream(in))
        .createScoped(Arrays.asList(ScriptScopes.GROUPS));
    
    credentials.refreshToken();
    
    
  3. Using a Client Secret

    GoogleCredential credentials = new GoogleCredential.Builder()
        .setClientSecrets("CLIENT_ID", "CLIENT_SECRET").build()
        .createScoped(Arrays.asList(ScriptScopes.GROUPS));
    
    

Some other things to note:

  • The Apps Script is linked to the same Google Cloud project as the service account and Firebase project.
  • The client secret was generated for the Apps Scripts API.

So, how do I authenticate properly to access the Apps Script as the user? And is there any other way of accessing what Google Groups the user is a part of?

Thanks in advance!

EDIT

While using the following code, I seem to have gotten it to authenticate properly;

GoogleAccountCredential credentials = GoogleAccountCredential.usingOAuth2(activity, Arrays.asList(ScriptScopes.GROUPS));

credentials.getSelectedAccountName(FirebaseAuth.getInstance().getCurrentUser().getEmail());

Script service = new Script.Builder(new NetHttpTransport(), 
    JacksonFactory.getDefaultInstance(), credentials).setApplicationName(APPLICATION_NAME)
            .build();

ExecutionRequest request = new ExecutionRequest()
            .setFunction("testGroup");

Operation op = service.scripts().run(MY_SCRIPT_ID, request).execute();

But when it reaches the last line, the whole app freezes and eventually stops working. I assume this is because the app is waiting for the Apps Script to return something? Any ideas on how to fix this?

Here is the Apps Script code btw:

function testGroup() {
  //return 0;
  var groups = GroupsApp.getGroups();
  for(var i = 0; i < groups.length; i++){
    //Logger.log(groups[i].getEmail());
    if(groups[i].getEmail().equals('group1')){
      return 0;
    }else if(groups[i].getEmail().equals('group2')){
      return 1;
    }
  }
  return -1;
}

(Even when I just return 0 it still doesn't work).



from Running Apps Script on Android?

PHP SoapClient doesn't work for my WebService. Basic Authentication problem?

I have to call a soap WebService that needs Basic Authentication. I tryed SoapUI with Basic Authentication and its working. WSDL page can be load from Browser correctly. There is no SSL releated problem.

I'm trying to do same call with SoapClient but not working. As I understand (with help of Burp Software) Authentication header isn't send with soapClient.

While I have this problem, I checked nearly all releated questions on StackOverflow and tryed everything that they suggest.

Here is my PHP code I'm working on it:

echo "<pre>";

$WSDL_URL='https://servis.turkiye.gov.tr/services/g2g/kdgm/test/uetds?wsdl';

$username='999999'; 
$password='999999testtest';

$params = array(
    'login' => $username,
    'password' => $password,
    'trace' => 0,
    'exceptions' => 0,
    'location' => $WSDL_URL,
    'uri' => $WSDL_URL
);

$soap = new SoapClient(null, $params);

$RESULT = $soap->servisTest( 'HELLO' );
echo "<h1>ServisTEST Result:</h1>";
print_r($RESULT);

Here is my error:

SoapFault Object
(
    [message:protected] => Client Error
    [string:Exception:private] => 
    [code:protected] => 0
    [file:protected] => /Applications/MAMP/htdocs/soap/test.php
    [line:protected] => 24
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => /Applications/MAMP/htdocs/soap/test.php
                    [line] => 24
                    [function] => __call
                    [class] => SoapClient
                    [type] => ->
                    [args] => Array
                        (
                            [0] => servisTest
                            [1] => Array
                                (
                                    [0] => HELLO
                                )
                        )
                )
        )
    [previous:Exception:private] => 
    [faultstring] => Client Error
    [faultcode] => s:Client
)



from PHP SoapClient doesn't work for my WebService. Basic Authentication problem?

Mousedown event sensitivity

I have a table grid that highlights cells/checkboxes with click and drag type of functionality.

When a user clicks on a cell and hovers for a while, then the cell / checkbox flickers a lot (firing off a lot of events).

Is there a way to make this less sensitive? i.e., some sort of timing event?

I tried adding .delay to the mouseover toggleclass, but it acts weird.

 $(function () {
        var isMouseDown = false,isHighlighted;

      $("#tablegrid").on('mousedown', 'td.nohighlight', function() {
            isMouseDown = true;
            $(this).toggleClass("highlighted");
            isHighlighted = $(this).hasClass("highlighted");
            var checkBoxes = $(this).find('.dosearchescheckbox :checkbox').trigger('click');
            return false; // prevent text selection
          })

      $("#tablegrid").on('mouseover', 'td.nohighlight', function() {
            if (isMouseDown) {
              $(this).toggleClass("highlighted");
              var checkBoxes = $(this).find('.dosearchescheckbox :checkbox').trigger('click');     
            }
          })
      $("#tablegrid").bind('selectstart', 'td.nohighlight', function() {    
            return false;
          })

      $(document)
        .mouseup(function () {
          isMouseDown = false;
        });
});



from Mousedown event sensitivity

How can you find the source for an "onevent" handler in HTML, without the event listeners panel?

I'm looking at an element that has several event handlers added to it the old-fashioned way--

<input onblur="doSomething()" onkeyup="doSomethingElse()">

When I check the event listeners panel in the inspector, it is entirely empty.

Is there a way to find the code for these in the page's source besides manually ctrl+f'ing for the function names?



from How can you find the source for an "onevent" handler in HTML, without the event listeners panel?

Luigi - Overriding Task requires/input

I am using luigi to execute a chain of tasks, like so:

class Task1(luigi.Task):
    stuff = luigi.Parameter()

    def output(self):
        return luigi.LocalTarget('test.json')

    def run(self):
        with self.output().open('w') as f:
            f.write(stuff)


class Task2(luigi.Task):
    stuff = luigi.Parameter()

    def requires(self):
        return Task1(stuff=self.stuff)

    def output(self):
        return luigi.LocalTarget('something-else.json')

    def run(self):
        with self.output().open('w') as f:
            f.write(stuff)

This works exactly as desired when I start the entire workflow like so:

luigi.build([Task2(stuff='stuff')])

When using luigi.build you can also run multiple tasks by explicitly passing arguments, as per this example in the documentation.

However, in my situation, I would also like to be able to run the business logic of Task2 completely independently of it's involvement in the workflow. This works fine for tasks that do not implement requires, as per this example.

My question is, how can I run this method both as part of the workflow, as well as on it's own? Obviously, I could just add a new private method like _my_custom_run, which takes the data and returns the result, and then use this method in run, but it just feels like something that should be baked into the framework, so it makes me feel like I am misunderstanding Luigi's best practices (still learning the framework). Any advice is appreciated, thanks!



from Luigi - Overriding Task requires/input

Record and process screen capture at high frame rate in NodeJS

As stated in the title, I would like to capture the screen 60 times a second and run it through a nodejs function.

Most libraries on npm only save to disk.

I tried taking screenshots with robotjs but only achieved 11fps.

I tried starting an RTMP server and using OBS but its delayed.

What in the world do I do?



from Record and process screen capture at high frame rate in NodeJS

Splash and infinite scrolling

I know about using /execute endpoint and passing LUA script to it which will load the page and scroll it via executing JavaScript code. However, this is "one and off" type of action, where I have no fine control about how or when to scroll the page within my Python program.

In other words, once Splash loads the page, additional actions on that page (e.g. executing JavaScript code) cannot be performed. I'd like to be able to interact with current page session within my Python program, Selenium-style. Is this possible in Splash, and how?

Alternative is to subclass QWebEnginePage and build a browser on top of it, but this is a whole new world of work which I'd like to avoid if possible.



from Splash and infinite scrolling

Chrome Back button issue after interaction with Iframe Angular

I have an Angular application. Below are the steps to follow:

  1. A customer goes through a flow and lands into one of the partial pages.

  2. From one of the partial page, I click a button to get an ID from a cross domain (done via service call, thus no CORS issue).

  3. Using this ID, I append on the cross domain url -- something like http://externalpahe.com?responseId=ID

  4. This url is executed a child component, inside an Iframe.

  5. In this Iframe cross domain's page, there are two button - 'Save' and 'Cancel'

  6. On Click of any of these buttons, the application is navigated back.

  7. ISSUE: After successful back navigation, on click of Chrome browser's back button, the application reloads.

Due to this, the flow of the application restarts again and the customer is required to go through the flow again. Though the data gets updated, on arriving back to the partial page, where the action has been performed previously, but it is not a good ease-of-use scenario.

I am making use of the below code to execute the cross domain's url in an iframe. I doubt that the DomSanitizer is causing the weird issue for Chrome. For others browsers', it works fine.

Angular Component:

constructor(private sanitizer: DomSanitizer) { }

ngOnInit() {
    this.targetUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.sourceUrl);
}

Angular Template:

<iframe #crossDomainIframe [src]="targetUrl" (load)="onPageLoad()">
</iframe>

In onPageLoad() I am doing simple business logic of emitting the response back to the parent component.

onPageLoad () {
    this.callbackResponse.emit(returnUrl);
}

Is there a way to handle the issue?

Or can the cross domain be executed on Iframe in a different way?



from Chrome Back button issue after interaction with Iframe Angular

Android NDK Linker failure for armeabi-v7a: "PLT offset too large, try linking with --long-plt"

When trying to build a signed APK, it fails with ~100 lines repeating:

Library/Android/sdk/ndk-bundle/toolchains/arm-linux-androideabi-4.9/prebuilt/darwin-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/../../../../arm-linux-androideabi/bin/ld: error: PLT offset too large, try linking with --long-plt

I've added --long-plt to the arguments:

externalNativeBuild {
    cmake {
        ...
        arguments '-DANDROID_STL=c++_static', '-Wl,--long-plt'
        cppFlags "-frtti -fexceptions", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_STL=c++_shared"
    }
}

But it doesn't seem to change anything.

It works with non-signed (debug) apk generation and works with arm64-v8a.

I'm dealing with >1GB of native code, so I'm guessing that's the main reason.

It seems there is almost no documentation or search result regarding this.

Does --long-plt need to be put somewhere else? If not, is there another setting that can be changed? Or would splitting the code into separate libraries help?

Here's the CMakeLists.txt for reference:

string(REPLACE "." "/" JAVA_GEN_SUBDIR ${JAVA_GEN_PACKAGE})
set(JAVA_GEN_DIR ${Project_SOURCE_DIR}/src/main/java/${JAVA_GEN_SUBDIR}/../../../../../generated)

# configure import libs
set(distribution_DIR ${PROJECT_SOURCE_DIR}/distribution)

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Note: One could use a 'GLOB' here, but newly added source files won't auto-regen build files
# After adding files, you'd need to 'touch' the CMakeLists.txt to re-gen

# SWIG required for build. Easy install is "brew install swig"
#Site: http://swig.org
find_package(SWIG REQUIRED)
include(${SWIG_USE_FILE})

# Remove old java files, in case we don't need to generate some of them anymore
#file(REMOVE_RECURSE ${JAVA_GEN_DIR})

# Ensure file recognized as C++ (otherwise, exported as C file)
set_property(SOURCE src/main/cpp/${LIBRARY_NAME}.i PROPERTY CPLUSPLUS ON)

# Setup SWIG flags and locations
set(CMAKE_SWIG_FLAGS -c++ -package ${JAVA_GEN_PACKAGE})
set(CMAKE_SWIG_OUTDIR ${JAVA_GEN_DIR})

# Export a wrapper file to Java, and link with the created C++ library
swig_add_module(${LIBRARY_NAME}_Wrapper java ${SWIG_I_FILE})
swig_link_libraries(${LIBRARY_NAME}_Wrapper ${LIBRARY_NAME})



# Include a location to the header files
include_directories(
    src/main/cpp
    ${NativeLibPath}
    ${LUAPATH}
    )

set(LUAPATH ${NativeLibPath}/lua)

    file(GLOB ALL_SOURCE_FILES
        "src/main/cpp/*.cpp"
        "${NativeLibPath}/*.cpp"
        "${LUAPATH}/*.c"
    )

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# You can define multiple libraries, and CMake builds them for you.
# Gradle automatically packages shared libraries with your APK.
add_library( # Sets the name of the library.
             ${LIBRARY_NAME}

             # Sets the library as a shared library.
             SHARED

             # Provides the list of files to compile.
             ${ALL_SOURCE_FILES} )

target_include_directories(${LIBRARY_NAME} PRIVATE)

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, you only need to specify the name of the public NDK library
# you want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )

# Specifies libraries CMake should link to your target library. You
# can link multiple libraries, such as libraries you define in this
# build script, prebuilt third-party libraries, or system libraries.
target_link_libraries(
                       # Specifies the target library.
                       ${LIBRARY_NAME}
                       android
                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib}
                     )



from Android NDK Linker failure for armeabi-v7a: "PLT offset too large, try linking with --long-plt"

Class inheritance in Python 3.7 dataclasses

I'm currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks like the order of the arguments are botched by my current approach such that the bool parameter in the child class is passed before the other parameters. This is causing a type error.

from dataclasses import dataclass

@dataclass
class Parent:
    name: str
    age: int
    ugly: bool = False

    def print_name(self):
        print(self.name)

    def print_age(self):
        print(self.age)

    def print_id(self):
        print(f'The Name is {self.name} and {self.name} is {self.age} year old')

@dataclass
class Child(Parent):
    school: str
    ugly: bool = True


jack = Parent('jack snr', 32, ugly=True)
jack_son = Child('jack jnr', 12, school = 'havard', ugly=True)

print(jack.print_id())
print(jack_son.print_id())

When I run this code I get this TypeError:

TypeError: non-default argument 'school' follows default argument

How do I fix this?



from Class inheritance in Python 3.7 dataclasses

How to create a nested menu using CSV file content

I need to use a CSV file for creating a webpage menu structure.

Can anyone please help me to create a nested menu in Jacascript using the given CSV structure?

The columns are: Level, Menu name, URL

0;"Service";
1;"Service 1";"http://some-url-1.com"
1;"Service 2";"http://some-url-2.com"
0;"Sales";
1;"Sales 1";"http://some-url-3.com"
1;"Sales 2";"http://some-url-4.com"
1;"Sales 3";
2;"Sales 3 Sub 1";"http://some-ulr-5.com";
0;"Development";"http://some-url-6.com"
0;"Internet";
1;"Internet 1";
2;"Internet 1 Sub 1";"http://some-url-7.com";

The first column shows the menu levels. 0- root level 1- first level 2- second level

Also the order of the menu items should be exactly as given in the CSV file.



from How to create a nested menu using CSV file content

Tuesday 30 October 2018

How to sign XML with xmlsec (or other more appropriate package)

I start with an XML like this one:

myXML="""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:mes="http://www.ercot.com/schema/2007-06/nodal/ews/message">
  <soapenv:Header> </soapenv:Header>
  <soapenv:Body>
  <RequestMessage xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message">
    <Header>
      <Verb>get</Verb>
      <Noun>BidSet</Noun>
      <ReplayDetection>
        <Nonce>177766768</Nonce>
        <Created>2018-10-22T09:03:33.169-05:00</Created>
      </ReplayDetection>
      <Revision>1</Revision>
      <Source>QSAMP</Source>
      <UserID>USER1</UserID>
      <MessageID>test</MessageID>
      <Comment>test</Comment>
    </Header>
    <Request>
      <ID>QSAMP.20181020.EB.AB_C.BID123</ID>
    </Request>
  </RequestMessage>
 </soapenv:Body>
</soapenv:Envelope>"""

I need to sign it with so it looks like this

<soapenv:Envelope xmlns:mes="http://www.ercot.com/schema/2007-06/nodal/ews/message" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header>
  <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" soapenv:mustUnderstand="1">
    <wsse:BinarySecurityToken EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="X509-411BAD9927582E29B715402172715641">MIIEHTCCAwWgAwIBAgIBdDANBgkqhkiG9w0BAQsFADATMREwDwYDVQQKEwhFUkNPVERFVjAeFw0xNTA1MDYxODA4MjJaFw0yNTA1MDMxODA4MjJaMIIBHDELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlRYMQ8wDQYDVQQHEwZUYXlsb3IxETAPBgNVBAoTCEVSQ09UREVWMRswGQYDVQQLExJFbXBsb3llZUlEIC0gVVNFUjExFzAVBgNVBAsTDk1QIC0gMDQzMjI2ODg1MSQwIgYDVQQLExtEVU5TIE51bWJlciAtIDA0MzIyNjg4NTIwMDAxGjAYBgNVBAsTEUVSQ09UIERldmVsb3BtZW50MQ4wDAYDVQQLEwVVU0VSMTEWMBQGA1UECxMNMDQzMjI2ODg1MjAwMDEcMBoGA1UEAxMTMDQzMjI2ODg1MjAwMCBVU0VSMTEeMBwGCSqGSIb3DQEJARYPdXNlcjFAZXJjb3QuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwBBaWstqWoqqJb+xAU6KGEMt+OkQY6ubbEEQml5SxkqDQRppo8U1kMHqKn4XhP3llZQGsMIBBMelb3nE9R3cDRmVcm3gJrj+pdeRh0ZGgPNwkASI/ev6SGGwWvDgAPNr8l+/UrrzgAMaYe9DrDEiFFZt+8Si3bbF4TEPM8F+6lJ2sNPU/5QBSv99v3QtZrqZvctSs9HCEfuoU9f2jHFCW46PWhH1dJUiyH24GPjaw+ZbVhrz1ccJH+JwZKybXgUdL5/fzcOfWveMXkTd6ai0/pSHiJRrT8oOXuaBsprDi0dKYbZTNx9d+8/HOugmP1J235Zg/mogP9h5lmjbw6lm7wIDAQABo3EwbzAdBgNVHQ4EFgQUCYkq9iXtxcS2GnQWwzBVQrefV3UwQwYDVR0jBDwwOoAUxY2QrudEPe3ldnlEenhuy/ehYUShF6QVMBMxETAPBgNVBAoTCEVSQ09UREVWggkA4jYWHOuW0D4wCQYDVR0TBAIwADANBgkqhkiG9w0BAQsFAAOCAQEAqVrVOfUbYotkL9Qmq5C8VYae+msJt4aG5SfXeWtND58DhDhx32PbWsFcQHPvJhHR+jV9dBg5yHkYMt712DJUsm2Fec+Cgc7yiJIFq1Pbs0cpe2NQqVJEaSzPyd6KB/nbJonIRtPFE+F4w4EHM+mbhdWecx7Tk8MH9235suZX50+uWPnnlYp9uJnqtJ13Mb6KObaCw/b8wXtFD1lu4B5p2W1vfgwhRR3Zh/f5AhuqaS+ZuMrwY7eM5LM278L5mzC+uYMT4fzzszDA3koXNTEqcCYCytj/sTO/UVqIO57/kU1l/ea+yj5E+Ak9yGBBu0sjua66bC5XwNFEOVrQLBkiUg==</wsse:BinarySecurityToken>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SIG-411BAD9927582E29B715402172716115">
    <ds:SignedInfo>
    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
    <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="mes soapenv"/>
    </ds:CanonicalizationMethod>
    <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
    <ds:Reference URI="#id-411BAD9927582E29B715402172716114">
    <ds:Transforms>
    <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#">
    <ec:InclusiveNamespaces xmlns:ec="http://www.w3.org/2001/10/xml-exc-c14n#" PrefixList="mes"/>
    </ds:Transform>
    </ds:Transforms>
    <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
    <ds:DigestValue>Vd6yUSv013P7ov8AzF2IbYv7yS4=</ds:DigestValue>
    </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>SnC9RHluvHxfg3zvfmoGHrfh6zfXSGUmGv9V351uhWgTn546tTU0/5LiaPsFEcfVxyWsoouVsBV9 VwCbw++6FmtehSCPH6CAO+1NngiE+miK6QThSqKJXj/5CbHwwfeQHqWRmf45AlCwvQiWhVqGi/tq
  YViFi5t0aIMrdhLJDRNUv17UNPKVjcowyIbKLKQxSqNxB/PED8tF0oHC7rRmsEr3x7NqO/VZBWZd OgCQggWiAdXiBy+SwoooAufMs6t+2+YOFQtWLOHuIx79X+hFi3Gqff1I5vfiHust7/rZdSzx1wB/
    T+aeNGIeIzQDNQoC55lhomgV0xp/3tZPHSzrqA==</ds:SignatureValue>
    <ds:KeyInfo Id="KI-411BAD9927582E29B715402172716112">
    <wsse:SecurityTokenReference wsu:Id="STR-411BAD9927582E29B715402172716113">
    <wsse:Reference URI="#X509-411BAD9927582E29B715402172715641" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"/>
    </wsse:SecurityTokenReference>
    </ds:KeyInfo>
    </ds:Signature>
    </wsse:Security>
    </soapenv:Header>
    <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-411BAD9927582E29B715402172716114">
    <RequestMessage xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Header>
    <Verb>get</Verb>
    <Noun>BidSet</Noun>
    <ReplayDetection>
    <Nonce>177766768</Nonce>
    <Created>2018-10-22T09:07:33.169-05:00</Created>
    </ReplayDetection>
    <Revision>1</Revision>
    <Source>QSAMP</Source>
    <UserID>USER1</UserID>
    <MessageID>test</MessageID>
    <Comment>test</Comment>
    </Header>
    <Request>
    <ID>QSAMP.20181020.EB.AB_C.BID123</ID>
    </Request>
    </RequestMessage>
    </soapenv:Body>
    </soapenv:Envelope>

As an aside, the certificate information in there isn't real so no worries there.

I looked at the example page from the doc but I don't know what their source xml looks like so it makes molding my use case to it pretty tricky.



from How to sign XML with xmlsec (or other more appropriate package)

Nodejs - Passport-saml implementation with One-login

I'm trying to run below passport-sample example with one login SSO. But I couldn't make it successful. I have given Onelogin HTTP-redirect url in the SAML entry point(config.js). It was redirecting to one login authentication page and redirecting back to application page but the application is not loading.

https://github.com/gbraad/passport-saml-example

Please advise what am I missing here.



from Nodejs - Passport-saml implementation with One-login

How do I get a refresh token from auth0 passwordless using lock v11?

I have an old-school angularJs app that has two pages. On both of the pages I include the auth0 lock script.

<script src="https://cdn.auth0.com/js/lock/11.9.0/lock.min.js"></script>

Of those two pages, one has the following js that specifies an auth0 lock to allow users to login:

new Auth0LockPasswordless(configuration.id,configuration.domain,
{
    allowedConnections: ['email'],
    passwordlessMethod: "link",
    auth: {
        redirectUrl: configuration.redirectUrl,
        responseType: 'token id_token',
        params: {
            scope: 'openid profile email offline_access'
        }
    }
}).show();

and the other page is responsible for the call-back after they've clicked the link in their email.

var lock = new Auth0LockPasswordless(configuration.id, configuration.domain);

lock.on('authorization_error',
    function(authResult) {
        console.log("DEBUG::AUTHRESULT::", authResult);
});

lock.on('authenticated',
    function(authResult) {
        console.log("DEBUG::AUTHRESULT::", authResult);
});

Now I've set offline_access in the scope of the request, and on my local environment been prompted for additional permissions when authenticating (so it's making it through). However when I check the log from the lock.on('authenticated', function(authResult).. refreshToken is always null.

There's some conflicting documentation around the web, with both suggestions that lock will and wont return a refresh token. Is anyone able to confirm if this code should result in a valid refreshToken?



from How do I get a refresh token from auth0 passwordless using lock v11?

JQuery Validation Form inside Bootstrap Modal won't submit after validation

UPDATE: To put the question into perspective I created another Fiddle that shows the same form outside of the modal.

When it meet the right conditions i.e you type an email address and hit the Get Started button it submits properly display the PHP page, in this case it shows a 404 error, but it does what is supposed to do, SUBMIT!

ORIGINAL PROBLEM: Now back to the problem: I would like to submit my form inside a bootstrap modal, but when I open the modal and type an email, and press the get started button: NOTHING HAPPENS

php won't submit

What am I doing wrong? Is there a JavaScript solution missing to submit the form correctly or are the validation errors interfering?

I'm a novice in JavaScript so I can't seem to figure out the coding solution if it's in fact js based.

Please help me figure this strange modal issue, thank you!

Fiddle: https://jsfiddle.net/o5vpt6ck/3/

HTML:

<form id="signup-form" class="cd-signin-modal__form" action="confirm.php" method="post">
                <h3 class="bigsentence black text-center font-weight-bold">Create</h3>
                <p class="cd-signin-modal__fieldset">
                    <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email">Enter your email address</label>
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border signupfield" id="email" type="email" name="email" placeholder="Enter your email address">
                </p>

                <p class="cd-signin-modal__fieldset">
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="submit" type="submit" value="GET STARTED">
                </p>
            </form>

JS:

$("#signup-form").validate ({

    // validation rules for registration formd
errorClass: "error-class",
validClass: "valid-class",
errorElement: 'div',
errorPlacement: function(error, element) {
    if(element.parent('.input-group').length) {
        error.insertAfter(element.parent());
    } else {
        error.insertAfter(element);
    }
},
onError : function(){
    $('.input-group.error-class').find('.help-block.form-error').each(function() {
      $(this).closest('.form-group').addClass('error-class').append($(this));
    });
},
        rules: {
    email: {email:true, required:true}
  },

    messages: {
        email: {
            required: "Please enter your email address",

        },


            highlight: function(element, errorClass) {
    $(element).removeClass(errorClass);
}    
    }

});



from JQuery Validation Form inside Bootstrap Modal won't submit after validation

Android 9 (Pie) Only: Context.startForegroundService() did not then call Service.startForeground() - Works fine on Oreo

We adjusted our ongoing notification for Oreo and it worked great. Now, on Pie only (not happening on Oreo devices), we're getting the titled error. Has something changed in foreground services in Pie that I'm missing?

Here's the onCreate code for the foreground service ->

override fun onCreate() {
    super.onCreate()

    val notification: Notification = NotificationCompat.Builder(this, packageName)
            .setSmallIcon(R.drawable.status_notification_icon)
            .setContentTitle(getString(R.string.ongoing_notify_temp_title))
            .setContentText(getString(R.string.ongoing_notify_temp_message))
            .setGroup(AppConstants.NOTIFICATION_GROUP_ONGOING)
            .setColor(ContextCompat.getColor(this, R.color.custom_blue))
            .build()

    startForeground(ONGOING_NOTIFY_ID, notification)

    appSettings = AppSettings(this)

    weatherLookUpHelper = WeatherLookUpHelper()
    MyRoomDatabase.getInstance().invalidationTracker.addObserver(onChange)

    retrieveCurrentLocation()
    createAlarmManager()
}

as you can see, we're just creating the notification and then calling startForeground. Any ideas on why this code would generate the titled error?

Side Note: Fabric Crashlytics shows this crash only happening on Pixel devices (pixel, pixel xl, pixel 2, pixel 2 xl) running Pie



from Android 9 (Pie) Only: Context.startForegroundService() did not then call Service.startForeground() - Works fine on Oreo

Android UI Tests with Storage Permissions in CI

I want to run UI tests and unit tests on a project in CI (Jenkins Pipeline). The UI tests requires images and video to be on the test device / emulator. In the UI tests I request permission for storage read/write access so I can dump a few assets into the downloads folder, then at the end of the test suite I remove them.

When I run my tests on Jenkins (mac) permissions are not granted, no media transfers over, and all of my tests fail.

The project contains an app module and two in-house library modules.

Pipeline steps

Build

sh "./gradlew clean assembleRelease"

Unit Test

sh "./gradlew testReleaseUnitTest"

UI Test

sh "$ANDROID_HOME/emulator/emulator @my_sweet_emulator_name -no-boot-anim & $ANDROID_HOME/platform-tools/adb wait-for-device"
sh './gradlew connectedAndroidTest'

Issues

1) The CI build hangs on the implicit assembleDebugAndroidTest task

2) If I run that task on the command line on my computer the tests will install however the permission is not granted to read/write storage so all tests fail.

Things I've Tried

  • I have attempted only testing a release build however this shows the same issue 2. testBuildType "release"
  • I have no other permissions I need to work with

How I'm granting permissions

@RunWith(AndroidJUnit4::class)
class MyMediaClassTest {

    @Rule
    @JvmField
    val activityRule = ActivityTestRule(MainActivity::class.java)

    @Rule
    @JvmField
    val grantPermissionRule: GrantPermissionRule = GrantPermissionRule
            .grant(android.Manifest.permission.READ_EXTERNAL_STORAGE,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
// tests and stuff
}

I have seen a potential solution to manually copy all of my media assets into the emulator image. But that doesn't seem right, this should be able to be automated.



from Android UI Tests with Storage Permissions in CI

library res/raw and res/xml resources are not included in the aar file

The res/raw and res/xml resources are not included to aar files, the raw folder contains keep.xml and the xml folder contains backup_rules.xml. None of them are included in aar files, the raw and xml folder is empty in extracted aar file. How should I include them into aar output?



from library res/raw and res/xml resources are not included in the aar file

Converting JSCAD / JS output to JSON (for three.js)

I'm looking for a way to convert the native output (parametric CAD?) of OpenJSCAD (jscad / js file) i.e.

function model() {
return polyhedron({points:[
[41.4780, -44.9832, 0.0000],
[41.8432, -43.0168, 0.0000],
[41.4780, -44.9832, 1.0579],
[41.8432, -43.0168, 1.0579],
...........................
[-41.7700, 35.8856, 1.2659]
],
triangles:[
[0, 2, 3],
[3, 1, 0],
[2, 6, 3],
[3, 6, 7],
[3, 7, 5],
..........
[298, 296, 297]
]});
}

function main() {
return model();
}

into json which can then be loaded into a three.js scene using the json object loader.

Is this possible?

EDIT: As digitial-pollution pointed out, this output is already a JSON string - and points and triangles are in seperate arrays.

The three.js json loader appears to accept json files that have been formatted with "Vertices" and "Faces" in seperate arrays. I've tried tweaking the output to match a working example - https://threejs.org/examples/webgl_loader_json_claraio.html replacing the values in the points array with "Vertices" and the faces with values in "triangles", also stripping out the brackets where neccessary - the three.js loader still fails to load the object.

Here's an example openjscad JS model: https://pastebin.com/BuSxNgg2

And here's an example working three.js JSON model: https://threejs.org/examples/models/json/teapot-claraio.json



from Converting JSCAD / JS output to JSON (for three.js)

Plotting lat/lon gridlines using Matplotlib-Basemap and Xarray

I have an xarray DataArray da containing a slice of data for Ireland which looks like this:

<xarray.DataArray 'co2' (lat: 733, lon: 720)>
array([[nan, nan, nan, ..., nan, nan, nan],
   [nan, nan, nan, ..., nan, nan, nan],
   [nan, nan, nan, ..., nan, nan, nan],
   ...,
   [nan, nan, nan, ..., nan, nan, nan],
   [nan, nan, nan, ..., nan, nan, nan],
   [nan, nan, nan, ..., nan, nan, nan]])
Coordinates:
  * lat      (lat) float32 49.9 49.908333 49.916664 49.924995 49.933327 ...
  * lon      (lon) float32 -11.0 -10.991667 -10.983334 -10.975 -10.966667 ...

I can map it like so:

import matplotlib.pyplot as plt
import xarray
import os
from mpl_toolkits.basemap import Basemap, cm

m= Basemap(projection='cyl',lat_0=ds.co2.lat[0],lon_0=ds.co2.lon[len(ds.co2.lon)/2])
m.drawcoastlines()
da.plot()

The problem is that lat/lon gridlines don't plot.

enter image description here

When I use the meridians command:

meridians = np.arange(10.,351.,20.)
m.drawmeridians(meridians,labels=[True,False,False,True])

I get the following error:

ValueError: dimensions () must have the same length as the number of data dimensions, ndim=1

I do not know what to try next.

EDIT: Full error trace:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-46-45a293c8bb99> in <module>()
  4 
  5 # draw grid plots
----> 6 m.drawmeridians(np.arange(-8.0,2.0,1.0),labels=[1,0,0,0]) #longitudes
      7 m.drawparallels(np.arange(51.0,59.0,1.0),labels=[0,0,0,1]) #latitudes
      8 

C:\Users\AppData\Local\Continuum\Anaconda\lib\site-    packages\mpl_toolkits\basemap\__init__.pyc in drawmeridians(self, meridians, color, linewidth, zorder, dashes, labels, labelstyle, fmt, xoffset, yoffset, ax, latmax, **kwargs)
   2593             # don't really know why, but this appears to be needed to
   2594             # or lines sometimes don't reach edge of plot.
-> 2595             testx = np.logical_and(x>=self.xmin-3*xdelta,x<=self.xmax+3*xdelta)
   2596             x = np.compress(testx, x)
   2597             y = np.compress(testx, y)

C:\Users\\AppData\Local\Continuum\Anaconda\lib\site-packages\xarray\core\dataarray.pyc in func(self, other)
   1550 
   1551             variable = (f(self.variable, other_variable)
-> 1552                         if not reflexive
   1553                         else f(other_variable, self.variable))
   1554             coords = self.coords._merge_raw(other_coords)

C:\Users\\AppData\Local\Continuum\Anaconda\lib\site-packages\xarray\core\variable.pyc in func(self, other)
   1164                         if not reflexive
   1165                         else f(other_data, self_data))
-> 1166             result = Variable(dims, new_data)
   1167             return result
   1168         return func

C:\Users\\AppData\Local\Continuum\Anaconda\lib\site-packages\xarray\core\variable.pyc in __init__(self, dims, data, attrs, encoding, fastpath)
    255         """
    256         self._data = as_compatible_data(data, fastpath=fastpath)
--> 257         self._dims = self._parse_dimensions(dims)
    258         self._attrs = None
    259         self._encoding = None

C:\Users\\AppData\Local\Continuum\Anaconda\lib\site-packages\xarray\core\variable.pyc in _parse_dimensions(self, dims)
    364             raise ValueError('dimensions %s must have the same length as the '
    365                              'number of data dimensions, ndim=%s'
--> 366                              % (dims, self.ndim))
    367         return dims
    368 

ValueError: dimensions () must have the same length as the number of data dimensions, ndim=1



from Plotting lat/lon gridlines using Matplotlib-Basemap and Xarray

Issue in SM-G950F(Samsung s8) for running OneoffTask

I am facing an issue, where my app users cannot get past a point.

When the user tries to login, it gets logged in, but after that I hit an API with "OneoffTask" using this code :

OneoffTask task = new OneoffTask.Builder()
        .setService(SyncService.class)
        .setTag(TaskConstants.UPLOAD_STREAK)
        .setExecutionWindow(0L, 200)
        .setRequiredNetwork(Task.NETWORK_STATE_CONNECTED)
        .setPersisted(true)
        .setUpdateCurrent(true)
        .build();

GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(MainApplication.getContext());
mGcmNetworkManager.schedule(task);

This code is executed, but the scheduled task does not execute. samsung s8 model : SM-G950F. It is working on all other devices. Why is this issue, I am also not getting an error. It is just stuck there.



from Issue in SM-G950F(Samsung s8) for running OneoffTask

Android: Parcelable exception

I am getting following exception in production environment. It is related with parcelable classes. But it is not showing which class is problematic. Below is detailed log trace:

Fatal Exception: java.lang.RuntimeException: Unable to start activity ComponentInfo{in.app/in.app.activity.MainActivity}: java.lang.RuntimeException: Parcel android.os.Parcel@ae3c90f: Unmarshalling unknown type code -15962911 at offset 816
   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
   at android.app.ActivityThread.-wrap11(Unknown Source)
   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
   at android.os.Handler.dispatchMessage(Handler.java:105)
   at android.os.Looper.loop(Looper.java:164)
   at android.app.ActivityThread.main(ActivityThread.java:6942)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

It is happening in onStart of Activity. I am not passing any parcelable object to the activity. It is launcher one. How can I find which parcelable is there at specifed
Unmarshalling unknown type code -15962911 at offset 816

Also as per Crashlytics, Device status is as follows:
100% Proximity on
3% App in background
It is happening on multiple OS versions.

MainActivity

public class MainActivity extends BaseActivity implements CleanUpDelegate,
    OnFilterAppliedListener,
    UpdatePhoneNoDialog.UpdatePhoneNoListener, GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, GenericDialogOperationListener,
    DAPopupFragment.DAPopupOperationsListener,
    OnLoginListener, HomeScreenFragmentV2.showECOOrderPopup, BottomNavigationRVAdapter.BottomNavigationItemClick

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        createBottomNavigation();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }
}



from Android: Parcelable exception

The provided registration token is not registered

I'm trying to send push notification for iOS via Google cloud functions but it returns error that The provided registration token is not registered. But I've checked it by debugging my app and the FCM registration token is correct. After that I've tried to send push notification via Firebase console to single device by providing FCM token but it failed due to Unregistered registration token. How this happens because there is no issue with device FCM token?



from The provided registration token is not registered

How to add bridging header to Flutter Plugin

I'm trying to create Flutter plugin, which uses Swift and has one pod dependency (NearbyMessages)

First of all, I've added it to .podspec

#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
  s.name             = 'flutter_nearby_messages'
  s.version          = '0.0.1'
  s.summary          = 'A new flutter plugin project.'
  s.description      = <<-DESC
A new flutter plugin project.
                       DESC
  s.homepage         = 'http://example.com'
  s.license          = { :file => '../LICENSE' }
  s.author           = { 'Your Company' => 'email@example.com' }
  s.source           = { :path => '.' }
  s.source_files = 'Classes/**/*'
  s.public_header_files = 'Classes/**/*.h'
  s.dependency 'Flutter'
  //************ I've added this lines ***************
  s.dependency 'NearbyMessages' 
  s.xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => 'Classes/bridging_header.h' }
  //********* ^^ I've added this lines ^^ ************
  s.static_framework = true
  s.ios.deployment_target = '8.0'
end

After pod install and initial empty project built, everything seems to be fine

I've tried using it in Objective-C:

#import "FlutterNearbyMessagesPlugin.h"
#import <NearbyMessages/GNSMessages.h>
#import <flutter_nearby_messages/flutter_nearby_messages-Swift.h>

@implementation FlutterNearbyMessagesPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {    
    GNSMessageManager *messageManager =
    [[GNSMessageManager alloc] initWithAPIKey:@"API_KEY"];
  [SwiftFlutterNearbyMessagesPlugin registerWithRegistrar:registrar];
}
@end

And it works, but when I try:

public class SwiftFlutterNearbyMessagesPlugin: NSObject, FlutterPlugin {
    private var client: GNSMessageManager? = nil

XCode says Use of undeclared type GNSMessageManager

I understand, that I need bridging header, and I've already tried to creating it, but it seems not to be linked at all

So my question is, how to add bridging header to flutter plugin?



from How to add bridging header to Flutter Plugin

How can I listen to which app has been chosen as Launcher Application?

I tried to implement a functionality that allows user to pick default Android's default Launcher Application. Also, I need to receive information which application has been chosen. But there is a problem with that approach.

To let user pick Launcher Application, we can simply start given intent:

val selector = Intent(Intent.ACTION_MAIN)
selector.addCategory(Intent.CATEGORY_HOME)
selector.flags = Intent.FLAG_ACTIVITY_NEW_TASK
startActivity(selector)

It results in such dialog:

enter image description here

What I observed, if I use startActivity, the Launcher Application is set nicely and works as intended, but if I use startActivityForResult, then I will get some callback, but the Launcher Application will not be set at all. Also, there was nothing interesting in intent received in onActivityResult.

Then, I tried using IntentSender instead.

The code looks as follows:

val selector = Intent(Intent.ACTION_MAIN)
selector.addCategory(Intent.CATEGORY_HOME)
selector.flags = Intent.FLAG_ACTIVITY_NEW_TASK
val receiver = Intent(this, MyBroadcastReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT)
val chooser = Intent.createChooser(selector, "Select a Home app", pendingIntent.intentSender);
startActivity(chooser)

The receiver looks as follows:

class MyBroadcastReceiver: BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val componentName = intent.extras.getParcelable<ComponentName>(Intent.EXTRA_CHOSEN_COMPONENT)
        //com.example.myapp if my app was choosen
        val pkg = componentName.packageName
    }
}

This results in default chooser, without options "JUST ONCE" or "ALWAYS". I don't have exact picture, but it looks similar to this one:

enter image description here

This works in a way, in the receiver's onReceive method I get ComponenName object, that holds selected app packageName. The problem is - again - Launcher Application is not set!

So question is: How can I let user set Launcher Application, and also receive information which one has he chosen?



from How can I listen to which app has been chosen as Launcher Application?

Chrome Back button issue after interaction with Iframe Angular

I have an Angular application. Below are the steps to follow:

  1. A customer goes through a flow and lands into one of the partial pages.

  2. From one of the partial page, I click a button to get an ID from a cross domain (done via service call, thus no CORS issue).

  3. Using this ID, I append on the cross domain url -- something like http://externalpahe.com?responseId=ID

  4. This url is executed a child component, inside an Iframe.

  5. In this Iframe cross domain's page, there are two button - 'Save' and 'Cancel'

  6. On Click of any of these buttons, the application is navigated back.

  7. ISSUE: After successful back navigation, on click of Chrome browser's back button, the application reloads.

Due to this, the flow of the application restarts again and the customer is required to go through the flow again. Though the data gets updated, on arriving back to the partial page, where the action has been performed previously, but it is not a good ease-of-use scenario.

I am making use of the below code to execute the cross domain's url in an iframe. I doubt that the DomSanitizer is causing the weird issue for Chrome. For others browsers', it works fine.

Angular Component:

constructor(private sanitizer: DomSanitizer) { }

ngOnInit() {
    this.targetUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.sourceUrl);
}

Angular Template:

<iframe #crossDomainIframe [src]="targetUrl" (load)="onPageLoad()">
</iframe>

In onPageLoad() I am doing simple business logic of emitting the response back to the parent component.

onPageLoad () {
    this.callbackResponse.emit(returnUrl);
}

Is there a way to handle the issue?

Or can the cross domain be executed on Iframe in a different way?



from Chrome Back button issue after interaction with Iframe Angular

Debugging C++ library with Android Studio

I'm working on an Android project which uses a Java class that is a wrapper on a C++ library. The C++ library is a company internal library and we have access to its source code, but in the Android project it is only dynamically linked, so it is used only in the form of headers(.h) and shared objects (.so). Having access to the library source code, is it possible to specify to Android Studio the path to the source code so I can step inside the library using the debugger?

The debugger works, I can step inside the Java_clory_engine_sdk_CloryNative_nativeInit function, but I would also like to further debug the library corresponding to the Clory::Engine class which, as I mentioned, is an internal library we have source code access to.

c_clory

For example, Clory::Engine::instance is part of the library and I would like to specify to Android Studio the location of the CloryEngine.cpp file so I can step inside Clory::Engine::instance with the debugger, thus debugging this static member function.

I am using Android Studio 3.1.4.

Is this possible?



from Debugging C++ library with Android Studio

How to use Openlayers3 library files in codeigniter View files

I am trying to use openlayers in my codeigniter for showing some map information when a user visit some place.

But I am stuck in initial stage. I know this is a stupid question, but I really need to use it.

I can use the Openlayer librarys like Vector, GeoJSON etc.. on main.js as it is mentioned in their website by running node.js.

But in codeignite I want to use it in a particular view page. So how can I import those js file in a particular view page.

Let's say I have my openlayer modules in root foler

Like
Porject
-- Application
-- openlayers_modules 

// which have ol folder inside it. -- system

-- stylesheets
-- index.php

In a normal way, we use it as index.html and main.js, both are in root folder.

I am kind of confusing how to use it.

If I use those js files in a view file ex: lightning.php then it shows like

<script type="text/javascript">
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import GeoJSON from 'ol/format/GeoJSON.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import {Fill, Stroke, Style, Text} from 'ol/style.js';

Uncaught SyntaxError: Unexpected identifier

So my question is how can we implement it on a particular view page in a codeigniter application with node js and without node js.

Any help is appreciate. Thanks



from How to use Openlayers3 library files in codeigniter View files

How to create a nested menu using CSV file content

I need to use a CSV file for creating a webpage menu structure.

Can anyone please help me to create a nested menu in Jacascript using the given CSV structure?

The columns are: Level, Menu name, URL

0;"Service";
1;"Service 1";"http://some-url-1.com"
1;"Service 2";"http://some-url-2.com"
0;"Sales";
1;"Sales 1";"http://some-url-3.com"
1;"Sales 2";"http://some-url-4.com"
1;"Sales 3";
2;"Sales 3 Sub 1";"http://some-ulr-5.com";
0;"Development";"http://some-url-6.com"
0;"Internet";
1;"Internet 1";
2;"Internet 1 Sub 1";"http://some-url-7.com";

The first column shows the menu levels. 0- root level 1- first level 2- second level

Also the order of the menu items should be exactly as given in the CSV file.



from How to create a nested menu using CSV file content

Nodemailer - dynamic transporter

I'm creating a nodemailer on my app, and I want to send email dynamically from input field that user will fill up. E.g. If the user writes on form input email value: 'test@test.com' I want to send this email from 'test@test.com' so later I can answer to this person and have all history of emails.

Edit

Step 1:

Fill up form on website with your personal data. E.g. I want to send email to company (name: josh, surname: murp, email: josh22@domain.com)

Step 2:

Send this json object to '/contactus/' with fetch and log this in console with req.body I'm getting this obj: { name: 'josh', surname: 'murp', email: 'josh22@domain.com' }

Step 3:

I want to setup Nodemailer in that way:

let mailOptions = {
        from: `${req.body.firstName} ${req.body.surname} <${req.body.email}>`, // sender address
        to: "mymail@gmail.com", // list of receivers
        subject: "hi", // Subject line
        text: "Hello world", // plain text body
        html: "<b>NodeJS Email Tutorial</b>" // html body
      };

That means. I want to get email FROM req.body.email, in real life I want to get EMAIL from josh22@domain.com but Nodemailer use TRANSPORTER to send email. It means I'm getting email from email configured in transporter but I want to get EMAIL from JOSH

This result brings me an issue.

When I got email from my account (transporter) I'm not able to answer this mail I need to find who is writing to me and in CONVERSATION HISTORY I don't have FIRST email of this conversation what was send via my website.

One big question here:

HOW TO SET DYNAMIC TRANSPORTER? or how to implement this in Node/express

let transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 465,
    secure: true, // true for 465, false for other ports
    auth: {
      user: keys.username, // generated ethereal user
      pass: keys.password // generated ethereal password
    }
  });

I'm looking all day to find this answer in web, but no result.



from Nodemailer - dynamic transporter

Nodejs - Passport-saml implementation with One-login

I'm trying run below passport-sample example with one login SSO. But I couldn't make it successful. I have given Onelogin HTTP-redirect url in the saml entry point(config.js). It was redirecting to one login authentication page and redirecting back to application page but the application is not loading.

https://github.com/gbraad/passport-saml-example

please advise what am missing here.



from Nodejs - Passport-saml implementation with One-login

JQuery Validation Form inside Bootstrap Modal won't submit after validation

UPDATE: To put the question into perspective I created another Fiddle that shows the same form outside of the modal.

When it meet the right conditions i.e you type an email address and hit the Get Started button it submits properly display the PHP page, in this case it shows a 404 error, but it does what is supposed to do, SUBMIT!

ORIGINAL PROBLEM: Now back to the problem: I would like to submit my form inside a bootstrap modal, but when I open the modal and type an email, and press the get started button: NOTHING HAPPENS

php won't submit

What am I doing wrong? Is there a JavaScript solution missing to submit the form correctly or are the validation errors interfering?

I'm a novice in JavaScript so I can't seem to figure out the coding solution if it's in fact js based.

Please help me figure this strange modal issue, thank you!

Fiddle: https://jsfiddle.net/o5vpt6ck/3/

HTML:

<form id="signup-form" class="cd-signin-modal__form" action="confirm.php" method="post">
                <h3 class="bigsentence black text-center font-weight-bold">Create</h3>
                <p class="cd-signin-modal__fieldset">
                    <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email">Enter your email address</label>
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border signupfield" id="email" type="email" name="email" placeholder="Enter your email address">
                </p>

                <p class="cd-signin-modal__fieldset">
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="submit" type="submit" value="GET STARTED">
                </p>
            </form>

JS:

$("#signup-form").validate ({

    // validation rules for registration formd
errorClass: "error-class",
validClass: "valid-class",
errorElement: 'div',
errorPlacement: function(error, element) {
    if(element.parent('.input-group').length) {
        error.insertAfter(element.parent());
    } else {
        error.insertAfter(element);
    }
},
onError : function(){
    $('.input-group.error-class').find('.help-block.form-error').each(function() {
      $(this).closest('.form-group').addClass('error-class').append($(this));
    });
},
        rules: {
    email: {email:true, required:true}
  },

    messages: {
        email: {
            required: "Please enter your email address",

        },


            highlight: function(element, errorClass) {
    $(element).removeClass(errorClass);
}    
    }

});



from JQuery Validation Form inside Bootstrap Modal won't submit after validation

Importing modules from parent folder

I am running Python 2.5.

This is my folder tree:

ptdraft/
  nib.py
  simulations/
    life/
      life.py

(I also have __init__.py in each folder, omitted here for readability)

How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.

Note: The main module being run is in the ptdraft folder.



from Importing modules from parent folder

JQuery Validation Form inside Bootstrap Modal won't submit after validation

UPDATE: To put the question into perspective I created another Fiddle that shows the same form outside of the modal.

When it meet the right conditions i.e you type an email address and hit the Get Started button it submits properly display the PHP page, in this case it shows a 404 error, but it does what is supposed to do, SUBMIT!

ORIGINAL PROBLEM: Now back to the problem: I would like to submit my form inside a bootstrap modal, but when I open the modal and type an email, and press the get started button: NOTHING HAPPENS

php won't submit

What am I doing wrong? Is there a JavaScript solution missing to submit the form correctly or are the validation errors interfering?

I'm a novice in JavaScript so I can't seem to figure out the coding solution if it's in fact js based.

Please help me figure this strange modal issue, thank you!

Fiddle: https://jsfiddle.net/o5vpt6ck/3/

HTML:

<form id="signup-form" class="cd-signin-modal__form" action="confirm.php" method="post">
                <h3 class="bigsentence black text-center font-weight-bold">Create</h3>
                <p class="cd-signin-modal__fieldset">
                    <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email">Enter your email address</label>
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border signupfield" id="email" type="email" name="email" placeholder="Enter your email address">
                </p>

                <p class="cd-signin-modal__fieldset">
                    <input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="submit" type="submit" value="GET STARTED">
                </p>
            </form>

JS:

$("#signup-form").validate ({

    // validation rules for registration formd
errorClass: "error-class",
validClass: "valid-class",
errorElement: 'div',
errorPlacement: function(error, element) {
    if(element.parent('.input-group').length) {
        error.insertAfter(element.parent());
    } else {
        error.insertAfter(element);
    }
},
onError : function(){
    $('.input-group.error-class').find('.help-block.form-error').each(function() {
      $(this).closest('.form-group').addClass('error-class').append($(this));
    });
},
        rules: {
    email: {email:true, required:true}
  },

    messages: {
        email: {
            required: "Please enter your email address",

        },


            highlight: function(element, errorClass) {
    $(element).removeClass(errorClass);
}    
    }

});



from JQuery Validation Form inside Bootstrap Modal won't submit after validation

How to lowercase a string in Python?

Is there a way to convert a string from uppercase, or even part uppercase to lowercase?

E.g. Kilometers --> kilometers.



from How to lowercase a string in Python?

How to efficiently extract all slices of given length using tensorflow

I am trying to extract all slices of length 4 along 0th axis of a 2-dim tensor. So far I can do it mixing numpy with tensorflow.

r = test.shape[0]
n = 4
a_list = list(range(r))
the_list = np.array([a_list[slice(i, i+n)] for i in range(r - n+1)])
test_stacked = tf.stack(tf.gather(test, the_list))

What would be an efficient way of doing that without using numpy and list comprehension?

A full vanilla example:

array = np.array([[0, 1],[1, 2],[2, 3],[3, 4],[4, 5],[5, 6]])
array.shape # (6,2)

r = array.shape[0]
n = 4
a_list = list(range(r))
the_list = np.array([a_list[slice(i, i+n)] for i in range(r - n+1)])

result = array[the_list] # all possible slices of length 4 of the array along 0th axis
result.shape # (3, 4, 2)

result: [[[0 1] [1 2] [2 3] [3 4]]

[[1 2] [2 3] [3 4] [4 5]]

[[2 3] [3 4] [4 5] [5 6]]]



from How to efficiently extract all slices of given length using tensorflow

Monday 29 October 2018

How to store and extract data from WIND (.wnd) file in Android

I want that no one can copy the sound file of my app as it's copyrighted. For this I am thinking to store the sound file (.ogg) in the wind file and extract the sound file at runtime.

How can we do this?

Thank you



from How to store and extract data from WIND (.wnd) file in Android

Nested UIScrollviews behaving strangely

I have the following autolayout-driven setup:

One main viewController, with a scrollview inside it. Scrollview pinned to superview edges. This one scrolls up and down.

A few normal, fixed size views at the top of the scrollview, and then another scrollview. This one scrolls left and right.

The second scrollview contains a couple of tableviews, side by side. The idea is that the user can switch between them. They both contain a handful of cells, all the same width as the screen and 72pts tall.

The problem I'm trying to solve is that the tableview contents are not the same size. The left one has say, 6 cells, and the right one has 3.

My first approach was to dynamically change the second scrollview height to match which ever tableview was currently visible. What ended up happening was that switching between the two tableviews (by doing setContentOffset:animated:) went extremely wrong if animated was set to true - it would adjust the content offset so everything was offscreen. In fact it would set the content offset to and then as I switched, about a dozen times, then it'd reset. It was weird, I gave up.

Now I'm trying to just adjust the content inset of the main scrollview to offset the gap in the content of the current tableview, and it's also being weird. When I set the bottom content inset in viewDidLoad, it works fine. When I set it at the time the tableview becomes current, it does nothing.

What gives? What scenarios would lead to these view interactions not behaving properly?



from Nested UIScrollviews behaving strangely