Saturday 30 June 2018

How to skip or remove some file at run time from uploading list

I'm using blueimp plugin https://github.com/blueimp/jQuery-File-Upload/wiki/API

I need to remove some files, during run time, from the queue.

When status code 17 (File Already Exits) from the server, then that particular file should be removed.

This is what I have tried so far to no success.

  $('#fileupload').fileupload({
         url: 'url.php',
         maxChunkSize: 65536, // 120 KB,
         maxRetries: 10,
         dataType: 'json',
         multipart: false,
        sequentialUploads: true,

             add:function(){........},

            done:function(){........}

    }).on('fileuploadchunkdone', function (e, data) {

       if(data.result.status == 17){
            var currentFileObject = data.files[0];
            var index = data.originalFiles.indexOf(currentFileObject); // find index in originalFiles
            data.originalFiles.splice(0,index);
            //data.files.length = 0; // if i uncomment this line some error will come, like undefined fileName
            data.submit();
        }
     });

I am removing the file by finding in data.originalFiles

NOTE:(please note) i'm not using any ui (cancel, update, cropimage, thumbnail) etc

Please help me to solve this problem.

Thanks in advance !!!!!!!!!!!



from How to skip or remove some file at run time from uploading list

How to skip or remove some file at run time from uploading list

I'm using blueimp plugin https://github.com/blueimp/jQuery-File-Upload/wiki/API

I need to remove some files, during run time, from the queue.

When status code 17 (File Already Exits) from the server, then that particular file should be removed.

This is what I have tried so far to no success.

  $('#fileupload').fileupload({
         url: 'url.php',
         maxChunkSize: 65536, // 120 KB,
         maxRetries: 10,
         dataType: 'json',
         multipart: false,
        sequentialUploads: true,

             add:function(){........},

            done:function(){........}

    }).on('fileuploadchunkdone', function (e, data) {

       if(data.result.status == 17){
            var currentFileObject = data.files[0];
            var index = data.originalFiles.indexOf(currentFileObject); // find index in originalFiles
            data.originalFiles.splice(0,index);
            //data.files.length = 0; // if i uncomment this line some error will come, like undefined fileName
            data.submit();
        }
     });

I am removing the file by finding in data.originalFiles

NOTE:(please note) i'm not using any ui (cancel, update, cropimage, thumbnail) etc

Please help me to solve this problem.

Thanks in advance !!!!!!!!!!!



from How to skip or remove some file at run time from uploading list

How to skip or remove some file at run time from uploading list

I'm using blueimp plugin https://github.com/blueimp/jQuery-File-Upload/wiki/API

I need to remove some files, during run time, from the queue.

When status code 17 (File Already Exits) from the server, then that particular file should be removed.

This is what I have tried so far to no success.

  $('#fileupload').fileupload({
         url: 'url.php',
         maxChunkSize: 65536, // 120 KB,
         maxRetries: 10,
         dataType: 'json',
         multipart: false,
        sequentialUploads: true,

             add:function(){........},

            done:function(){........}

    }).on('fileuploadchunkdone', function (e, data) {

       if(data.result.status == 17){
            var currentFileObject = data.files[0];
            var index = data.originalFiles.indexOf(currentFileObject); // find index in originalFiles
            data.originalFiles.splice(0,index);
            //data.files.length = 0; // if i uncomment this line some error will come, like undefined fileName
            data.submit();
        }
     });

I am removing the file by finding in data.originalFiles

NOTE:(please note) i'm not using any ui (cancel, update, cropimage, thumbnail) etc

Please help me to solve this problem.

Thanks in advance !!!!!!!!!!!



from How to skip or remove some file at run time from uploading list

Apache two apps one domain share language /en - Magento & Wordpress

We have Wordpress in the root / in a physical subfolder /wp and Magento in /products.

We are wanting to make the sites multi-language using sub folders e.g domain.com/en

The problem arises as magento appends the store code (language) after the url so we have

domain.com/en (wordpress)
domain.com/products/en (magento)

Naturally we would like

domain.com/en
domain.com/en/products

Now it's very easy to make it work with some rewrite rule

RewriteRule ^(.*)/products/?(.*)$ /products/$1 [L]

But still we have an issue as Magento generates the links as /products/en it's possible to start modifying where these links are generated like in

\Magento\Store\Model\Store 

In the _updatePathUseStoreView function, this doesn't seem to handle all links though

In general seems like a bad solution, another idea is to use Apache mod_substitute also seems bad practice, and overhead.

Another option is to have both apps in the root and have some lookup logic to see which url belongs to which app.

Any ideas for a setup that can purely use just Nginx/Apache. That does not compromise on having unique url's or regex'ing content.



from Apache two apps one domain share language /en - Magento & Wordpress

iOS CoreBluetooth print CBService and CBCharacteristic

I am using Swift to develop a iOS application to integrate bluetooth printer to print out information. I have used CoreBluetooth framework but can't know which service, characteristic I can writevalue to print out

//find CBService
func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {
    //println("CBPeripheralDelegate didDiscoverServices")

    for service in peripheral.services {

        println("Service: Discover service \(service)")
        println("Service: UUID \(service.UUID) ")

        peripheral.discoverCharacteristics(nil, forService: service as! CBService)

    }
}

//find CBCharacteristics
func peripheral(peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!, error: NSError!) {

    //if service.UUID == CBUUID(string: "18F0"){
        for characteristic in service.characteristics {

            let chara: CBCharacteristic? = characteristic as? CBCharacteristic
            println("Char: service \(service.UUID) Discover char \(chara)")
            println("Char: UUID \(chara!.UUID)")

            peripheral.readValueForCharacteristic(chara)

            /*
            println("0")

            switch chara!.UUID {

            case CBUUID(string: "2AF1"):
                println("1")

                var rawArray:[UInt8] = [0x01];
                let data = NSData(bytes: &rawArray, length: rawArray.count)

                peripheral.writeValue(data, forCharacteristic: chara, type: CBCharacteristicWriteType.WithoutResponse)

            default: println("")
            }
            */
        }
    //}

}

and the system display result like below:

Service: Discover service Service: UUID Battery Service: Discover service Service: UUID 1803 Service: Discover service Service: UUID 1802 Service: Discover service Service: UUID 1811 Service: Discover service Service: UUID 1804 Service: Discover service Service: UUID 18F0 Service: Discover service Service: UUID Device Information Service: Discover service Service: UUID E7810A71-73AE-499D-8C15-FAA9AEF0C3F2

Char: Discover char Char: UUID Battery Level Char: Discover char Char: UUID 2A06 Char: Discover char Char: UUID 2A06 Char: Discover char Char: UUID 2A47 Char: Discover char Char: UUID 2A46 Char: Discover char Char: UUID 2A48 Char: Discover char Char: UUID 2A45 Char: Discover char Char: UUID 2A44 Char: Discover char Char: UUID 2A07 Char: Discover char Char: UUID 2AF1 Char: Discover char Char: UUID 2AF0 Char: Discover char Char: UUID System ID Char: Discover char Char: UUID Manufacturer Name String Char: Discover char Char: UUID BEF8D6C9-9C21-4C9E-B632-BD58C1009F9F

can any bluetooth expert can guide me, thanks



from iOS CoreBluetooth print CBService and CBCharacteristic

Finding repeated character combinations in string

I have a string that holds a very long word, only one word without whitespaces/spaces.

mystring = "abcdthisisatextwithsampletextforasampleabcd"

I would like to find all of the repeated character combinations that contains minimum 4 chars.

So I would like to achieve something like this:

'text' 2 times
'sample' 2 times
'abcd' 2 times

As both abcd,text and sample can be found two times in the mystring they were recognized as propely matched chars combinations with more than 4 char length. It's important that I am seeking repeated char combinations, finding only existing english words is not a requirement.

The answers I found are helpful for finding duplicates in texts with whitespaces, but I couldn't find a proper resource that covers the situation when there are no spaces and whitespaces in the string. I would really appreciate if somebody could show me how this should be done the most efficient way.



from Finding repeated character combinations in string

How to combine a Vuetify data table and Vuetify list?

I need to use this Vuetify data table but with the layout of this Vuetify list. The list should be searchable and every entry a button.

How to do that?

Here is my result so far: https://codepen.io/anon/pen/ZRqwYG

HTML:

<div id="app">
  <v-app id="inspire">
    <v-card>

      <v-card-title>
        Vuetify Data-Table + Vuetify List
        <v-spacer></v-spacer>
        <v-text-field
          v-model="search"
          append-icon="search"
          label="Search"
          single-line
          hide-details
        ></v-text-field>
      </v-card-title>

      <v-data-table
        :headers="headers"
        :items="desserts"
        :search="search"
      >

        <template slot="items" slot-scope="props">
              <v-list-tile-content>
                <v-list-tile-title></v-list-tile-title>
                <v-list-tile-sub-title class="text--primary"></v-list-tile-sub-title>
                <v-list-tile-sub-title></v-list-tile-sub-title>
              </v-list-tile-content>

              <v-list-tile-action>
                <v-list-tile-action-text></v-list-tile-action-text>
                <v-icon color="grey lighten-1">star_border</v-icon>
              </v-list-tile-action>

         </>    
        </template>

        <v-alert slot="no-results" :value="true" color="error" icon="warning">
          Your search for "" found no results.
        </v-alert>

      </v-data-table>

    </v-card>
  </v-app>
</div>



from How to combine a Vuetify data table and Vuetify list?

Complex R Shiny input binding issue with datatable

I am trying to do something a little bit tricky and I am hoping that someone can help me.

I would like to add selectInput inside a datatable. If I launch the app, I see that the inputs col_1, col_2.. are well connected to the datatable (you can switch to a, b or c)

BUT If I update the dataset (from iris to mtcars) the connection is lost between the inputs and the datatable. Now if you change a selectinput the log doen't show the modification. How can I keep the links?

I made some test using shiny.bindAll() and shiny.unbindAll() without success.

Any Ideas?

Please have a look at the app:

library(shiny)
library(DT)
library(shinyjs)
library(purrr)

    ui <- fluidPage(
      selectInput("data","choose data",choices = c("iris","mtcars")),
      DT::DTOutput("tableau"),
      verbatimTextOutput("log")
    )

    server <- function(input, output, session) {
      dataset <- reactive({
        switch (input$data,
          "iris" = iris,
          "mtcars" = mtcars
        )
      })

      output$tableau <- DT::renderDT({
        col_names<-
          seq_along(dataset()) %>% 
        map(~selectInput(
          inputId = paste0("col_",.x),
          label = NULL, 
          choices = c("a","b","c"))) %>% 
          map(as.character)

        DT::datatable(dataset(),
                  options = list(ordering = FALSE, 
                          preDrawCallback = JS("function() {
                                               Shiny.unbindAll(this.api().table().node()); }"),
                         drawCallback = JS("function() { Shiny.bindAll(this.api().table().node());
                         }")
          ),
          colnames = col_names, 
          escape = FALSE         
        )

      })
      output$log <- renderPrint({
        lst <- reactiveValuesToList(input)
        lst[order(names(lst))]
      })

    }

    shinyApp(ui, server)



from Complex R Shiny input binding issue with datatable

How to disable dragging windows for all Tablets such as: iPads, iPods, etc?

I did some research on this and still can't find a good solution for it. I wrote my app in ExtJS 4.1 and when I run it on iPod the dragging functionality is disabled by default (which is want I want), but if I write the same app in ExtJS 6.2 all windows can be draggable which causes issues of visibility of the app. With that being said, Does anyone know how to disable window dragging when using Tablets (iPod, iPad, etc)? I'm using ExtJS 6.2. Thanks a lot in advance!

Here's my working code that works great for a single window, but I want a general solution that will stop ALL windows from being dragged.

       var win = Ext.create('Ext.Window', {
            title: "My Window",
            width: 500,
            modal: true,
            layout: 'fit',
            items: form,
            buttons: [{
                text: 'Close',
                handler: function() {
                    win.hide();
                }
            }]
        });

        win.show();

        if(Ext.os.deviceType === 'Tablet') {
            win.dd.disable();
        }



from How to disable dragging windows for all Tablets such as: iPads, iPods, etc?

Flask-Admin create view with SQLAlchemy context-sensitive functions

I have a data model which has a column that depends on other column values, following the instructions in this page I've created a context-sensitive function which is used to determine the value of this particular column on creation, something like this:

def get_column_value_from_context(context):
    # Instructions to produce value

    return value


class MyModel(db.Model):
    id = db.Column(db.Integer,
                   primary_key=True)
    my_column = db.Column(db.String(64),
                          nullable=False,
                          default=get_column_value_from_context)
    name = db.Column(db.String(32),
                     nullable=False,
                     unique=True,
                     index=True)
    title = db.Column(db.String(128),
                      nullable=False)
    description = db.Column(db.String(256),
                            nullable=False)

This approach works pretty decent, I can create rows without problems from the command line or using a script.

I've also added a ModelView to the app using Flask-Admin:

class MyModelView(ModelView):
    can_view_details = True
    can_set_page_size = True
    can_export = True


admin.add_view(MyModelView(MyModel, db.session))

This also works pretty decent until I click the Create button in the list view. I receive this error:

AttributeError: 'NoneType' object has no attribute 'get_current_parameters'

Because the implementation of the create_model handler in the ModelView is this:

def create_model(self, form):
    """
        Create model from form.
        :param form:
            Form instance
    """
    try:
        model = self.model()
        form.populate_obj(model)
        self.session.add(model)
        self._on_model_change(form, model, True)
        self.session.commit()
    except Exception as ex:
        if not self.handle_view_exception(ex):
            flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
            log.exception('Failed to create record.')

        self.session.rollback()

        return False
    else:
        self.after_model_change(form, model, True)


    return model

and here there isn't a context when the model is instantiated. So, I've created a custom view where the model instantiation in the creation handler could be redefined:

class CustomSQLAView(ModelView):
    def __init__(self, *args, **kwargs):
        super(CustomSQLAView, self).__init__(*args, **kwargs)

    def create_model(self, form):
        """
            Create model from form.
            :param form:
                Form instance
        """
        try:
            model = self.get_populated_model(form)
            self.session.add(model)
            self._on_model_change(form, model, True)
            self.session.commit()
        except Exception as ex:
            if not self.handle_view_exception(ex):
                flash(gettext('Failed to create record. %(error)s', error=str(ex)), 'error')
                log.exception('Failed to create record.')

            self.session.rollback()

            return False
        else:
            self.after_model_change(form, model, True)

        return model

    def get_populated_model(self, form):
        model = self.model()
        form.populate_obj(model)

        return model

Now I can redefine the get_populated_model method to instantiate the model in the usual way:

class MyModelView(CustomSQLAView):
    can_view_details = True
    can_set_page_size = True
    can_export = True

    def get_populated_model(self, form):
        model = self.model(
            name=form.name.data,
            title=form.title.data,
            description=form.description.data,
        )

        return model

Despite that this works, I suspect it breaks something. Flask-Admin has several implementation of the populate_obj method of forms and fields, so I would like to keep everything safe.

What is the proper way to do this?



from Flask-Admin create view with SQLAlchemy context-sensitive functions

Readonly form field in edit view - Flask-Admin

I tried to set a form field as readonly just for the edit view in a Flask-Admin application. Following the answers to this question I know that if I have this

class MyView(ModelView):
    form_widget_args = {
        'title': {
            'readonly': True
        }
    }

I can set a form field as readonly, but this is applied to both create and edit views. How can I apply an argument to the edit view only?



from Readonly form field in edit view - Flask-Admin

Dynamic select2 options using api

I'll try to explain my problem as much as I can. I am trying to create, with select2 plugin, a way for the user to write some letters and on each letter pressed a call to an API that gives the first 20 results given by that API.

So I have my HTML select :

<select name="filtre_products[]" class="form-control products-select2" multiple> 

</select>

And then my JS (it's commented) :

$(".products-select2").select2({ 
    width: '100%', 
    closeOnSelect: false,
    placeholder: '',
    minimumInputLength: 3,
    query: function (query) {
        var data = {results: []}, i, j, s;
        if(query.term != null) {
            var ajax_r = [];
            $.ajax({
                url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
                success: function(data_a){
                    //Getting the data
                    data_a = JSON.parse(data_a);

                    //Looping through the each data and putting them inside a table
                    data_a.forEach( (e) => {
                        ajax_r.push(e);
                    });

                    //Filtering the data to get from it the id and the text to be used
                    ajax_r.forEach( (e) => {
                        var tmp = e.split('-');
                        var id = tmp[0];
                        var name = tmp[2];

                        data.results.push({value: id, text: name});
                    });

                    query.callback(data);
                }
            });
        }
    },
    //Sending the results to the function to modify the options as I please
    templateResult: formatResult
});

And this is the formatResult function I use :

function formatResult(d) {
    if(d.loading) {
        return d.text;
    } 

    // Creating an option of each id and text
    $d = $('<option/>').attr({ 'value': d.value }).text(d.text);

    return $d;
}

My problem is that select2 is supposed to be creating the options dynamically upon initialization and thus actually creating <li> out of the options and adding to them dynamically id's and such. But in the way I'm creating it, it's putting the options INSIDE the <li> tags which is not what I want, I want it to treat it as dynamic options like he does without the query call.

Some doc sources for you guys, it shows a part of what I'm trying to do, but the example shows how to show results from what we write, I want it to show from the api upon each click, and of course having multiple select added : http://select2.github.io/select2/#data



from Dynamic select2 options using api

No index exists while trying to sort using an indexed field (Mango Queries)

I'm not sure how to figure out how to sort my documents using a Mango query. Any help would be greatly appreciated:


I do the following find query and get the following error:

return db.find({ sort: ['timestamp'], selector: {$and: [{type:"revision"},{doc_id: doc_id}] } })

Note, if I do the following I also get the same error:

return db.find({ sort: ['timestamp'], selector: {$and: [{type:"revision"}] } })

{ error: 'no_usable_index', reason: 'No index exists for this sort, try indexing by the sort fields.', name: 'no_usable_index', status: 400, message: 'No index exists for this sort, try indexing by the sort fields.' }

I created a filter like so:

db.createIndex({
  index: {fields: ['type', 'timestamp']}
})

This is what pops up in my design documents:

{
  "_id": "_design/b661014513bf0c13270a9033d6d1c1853a8b5dbf",
  "_rev": "1-1d871456b0a78952845705f4e8dd2c26",
  "language": "query",
  "views": {
    "b661014513bf0c13270a9033d6d1c1853a8b5dbf": {
      "map": {
        "fields": {
          "type": "asc",
          "timestamp": "asc"
        },
        "partial_filter_selector": {}
      },
      "reduce": "_count",
      "options": {
        "def": {
          "fields": [
            "type",
            "timestamp"
          ]
        }
      }
    }
  }
}



from No index exists while trying to sort using an indexed field (Mango Queries)

Why do I get "requesting permission to use WLAN. Allow?" prompt window in real mobile phone?

I use the Code A to set the enabled status of WiFi, it works well when I use Android Emulator with both API 26 and API 23 in Android Studio 3.1.3 , and none of prompt window display!

But I get a prompt window "An App is requesting permission to use WLAN. Allow?" in real mobile phone with Android 5.1 when I run the code A.

How can I make the prompt window not to display in real mobile phone? Thanks!

BTW,the real mobile phone is Samsung SM-J5008 with Android 5.1

Prompt Window

enter image description here

I have set the permissions

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

Code A

fun setWiFi(aWiFiDef: WiFiDef): Unit{
    val wifiManager =mContext.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
    wifiManager.isWifiEnabled=aWiFiDef.status        
}



from Why do I get "requesting permission to use WLAN. Allow?" prompt window in real mobile phone?

How to define MIME types with Create-React-App's node server?

I'm trying to deal with this WebAssembly note: "Note: To run with instantiateStreaming and compileStreaming, you need your webserver to serve .wasm file with application/wasm MIME type. The https crate can be used to serve files from localhost, and includes the application/wasm MIME type out of the box."

Indeed, I get a MIME error in the JS console. A Google search revealed no way to configure this. Mozilla recommends instantiateStreaming over the depricated WebAssembly.instantiate. The latter doesn't work for me either, if using stdweb or bindgen: It wants a second argument which I'm not sure how to provide.



from How to define MIME types with Create-React-App's node server?

Set app as default Assist Intent

So currently at my wits end for this issue.

I am trying to set my app as the default app launched when long pressing the Home button.

I am doing this by:

  1. Setting Intent Filters in the manifest (I also experimented with adding MAIN and LAUNCHER action/category tags)
 <action android:name="android.intent.action.ASSIST" />
 <action android:name="android.intent.action.SEARCH_LONG_PRESS" />
 <category android:name="android.intent.category.DEFAULT" />

  1. Requesting the default app on an intent to allow users to change (there's also one for the Search Long Press action)
Intent intent = new Intent(Intent.ACTION_ASSIST);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

This approach works perfectly fine for devices running pre 6.0 software. On post 6 devices the request is asked but the default assistant app is unchanged.

My app can be set as the default home app on post 6 devices perfectly fine when using these exact steps.

I'm unsure as to whether there's some kind of specific permission I'm missing or something. Nothing seems to work at all. The google app will always be used on long press. If I disable the google app then my app will run on long press.

Extra information: This is a kiosk app for business so I prefer to not have to disable the Google app for every single device this will go on. I don't mind if solutions are hacky as this is not going on the app store.



from Set app as default Assist Intent

How to fix ANR issue on /data/app/com.android.chrome-1/base.apk?

can you help me with this ANR issue? Users reports lots of times to Google Play Console, but I cannot reproduce it myself. Many thanks.

"main" prio=5 tid=1 Native
  | group="main" sCount=1 dsCount=0 obj=0x73898658 self=0xb0204400
  | sysTid=3708 nice=-4 cgrp=default sched=0/0 handle=0xb2f69534
  | state=S schedstat=( 5873509009 1942619080 10289 ) utm=484 stm=102 core=3 HZ=100
  | stack=0xbe00c000-0xbe00e000 stackSize=8MB
  | held mutexes=
  #00  pc 00000000000174d4  /system/lib/libc.so (syscall+28)
  #01  pc 0000000000046a5d  /system/lib/libc.so (_ZL24__pthread_cond_timedwaitP23pthread_cond_internal_tP15pthread_mutex_tbPK8timespec+102)
  #02  pc 0000000000039bb1  /data/app/com.android.chrome-1/base.apk (???)
  at org.chromium.ui.base.WindowAndroid.nativeOnVSync (Native method)
  at org.chromium.ui.base.WindowAndroid.access$700 (WindowAndroid.java:134)
  at org.chromium.ui.base.WindowAndroid$1.onVSync$5166USJ75THMGSJFDLKNAR9FELKIULIJF5N66JBFDPKN8RRI7D52ILG_0 (WindowAndroid.java:16)
  at org.chromium.ui.VSyncMonitor$1.doFrame (VSyncMonitor.java:22)
  at android.view.Choreographer$CallbackRecord.run (Choreographer.java:872)
  at android.view.Choreographer.doCallbacks (Choreographer.java:686)
  at android.view.Choreographer.doFrame (Choreographer.java:618)
  at android.view.Choreographer$FrameDisplayEventReceiver.run (Choreographer.java:860)
  at android.os.Handler.handleCallback (Handler.java:751)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:154)
  at android.app.ActivityThread.main (ActivityThread.java:6165)
  at java.lang.reflect.Method.invoke! (Native method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:888)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:778)


from How to fix ANR issue on /data/app/com.android.chrome-1/base.apk?

Adjust collectionView.scrollToItem to consider inset?

I'm sometimes scroll to the left of a cell like this:

collectionView.scrollToItem(
    at: IndexPath(row: 5, section: 0),
    at: .left, // TODO: Left ignores inset
    animated: true
)

This is how it starts out before scrollToItem implemented:

enter image description here

However, when I try to use scroll to item, it sticks the cell to the edge instead of considering the inset:

enter image description here

Is there an easy way to fix collectionView.scrollToItem to accommodate the insets?



from Adjust collectionView.scrollToItem to consider inset?

Google App Engine SDK: ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql

I am trying to run my Django app on Google App Engine SDK (locally) inside a virtualenv with MySQL as a database. Everything in my requirements.txt file is installing perfectly. When I start the Google App Engine SDK environment, it throws me a nasty error that seems common, but Stack Overflow doesn't have any examples of solving this within Google App Engine SDK yet.
Here is my work flow from the root dir of my project...
virtualenv venv && mkdir lib
source venv
pip install -r requirements.txt -t lib/ && pip install -r requirements.txt
When I run the following command to start up the SDK....
dev_appserver.py app.yaml
I get the following error in my traceback...
File "/Users/username/Repositories/projectname/lib/django/db/utils.py", line 211, in __getitem__
backend = load_backend(db['ENGINE'])
File "/Users/username/Repositories/projectname/lib/django/db/utils.py", line 115, in load_backend
INFO     2018-06-26 20:09:30,812 module.py:846] default: "GET /_ah/start HTTP/1.1" 500 -
return import_module('%s.base' % backend_name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/Users/username/Repositories/projectname/lib/django/db/backends/mysql/base.py", line 30, in <module>
'Did you install mysqlclient or MySQL-python?' % e
ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql.
Did you install mysqlclient or MySQL-python?

My requirements.txt
Django==1.11.8
djangorestframework==3.8.2
facebook-sdk
oauth2client==2.0.1
google-api-python-client==1.6.2
facebookads==2.11.1
httplib2==0.10.3
enum==0.4.6
requests-toolbelt==0.8.0
google-cloud-storage==1.6.0
google-resumable-media==0.3.1
google-auth
requests==2.18.0
lxml==3.8.0
pycrypto==2.6.1
MySQL-python==1.2.5

Contents of lib/ Contents of <code>lib/</code>
I am calling MySQLdb in my app.yaml as well...
libraries:
- name: MySQLdb
  version: "latest"

Some things I have checked off the list while debugging...
1) MySQL-python==1.2.5 is installed when I do a pip freeze in my virtual environment.
2) MySQL is installed and works perfectly on my local computer.
3) I've looked through the lionshare of Stack Overflow's questions thus far and none of them seem to help.


from Google App Engine SDK: ImproperlyConfigured: Error loading MySQLdb module: No module named _mysql

NoClassDefFoundError while running unit tests with Roboelectric 3.8

My Android project has several modules (one application and multiple libraries) and when I try to run all the unit tests (Robolectric 3.8) from the command line

./gradlew testDebugUnitTest

I get the following error (not when I run the same task from Android Studio)

java.lang.NoClassDefFoundError: android/content/Context at java.base/java.lang.Class.getDeclaredConstructors0(Native Method) at java.base/java.lang.Class.privateGetDeclaredConstructors(Class.java:3110) at java.base/java.lang.Class.getConstructor0(Class.java:3315) at java.base/java.lang.Class.getConstructor(Class.java:2108) at org.robolectric.RobolectricTestRunner.getHooksInterface(RobolectricTestRunner.java:473) at org.robolectric.RobolectricTestRunner.beforeTest(RobolectricTestRunner.java:308) at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:241) at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:123) at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:42) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:77) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57) at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66) at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32) at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93) at com.sun.proxy.$Proxy1.processTestClass(Unknown Source) at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:108) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:564) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35) at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:146) at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:128) at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404) at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63) at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55) at java.base/java.lang.Thread.run(Thread.java:844) Caused by: java.lang.ClassNotFoundException: couldn't load android.content.Context at org.robolectric.internal.bytecode.SandboxClassLoader.maybeInstrumentClass(SandboxClassLoader.java:174) at org.robolectric.internal.bytecode.SandboxClassLoader.lambda$findClass$0(SandboxClassLoader.java:133) at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:50) at org.robolectric.internal.bytecode.SandboxClassLoader.findClass(SandboxClassLoader.java:132) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ... 45 more Caused by: java.lang.IllegalArgumentException at org.objectweb.asm.ClassReader.(Unknown Source) at org.objectweb.asm.ClassReader.(Unknown Source) at org.robolectric.internal.bytecode.SandboxClassLoader$ClassInstrumentor.isOverridingFinalMethod(SandboxClassLoader.java:502) at org.robolectric.internal.bytecode.SandboxClassLoader$ClassInstrumentor.instrumentInheritedObjectMethod(SandboxClassLoader.java:523) at org.robolectric.internal.bytecode.SandboxClassLoader$ClassInstrumentor.instrument(SandboxClassLoader.java:395) at org.robolectric.internal.bytecode.SandboxClassLoader$InvokeDynamicClassInstrumentor.instrument(SandboxClassLoader.java:1274) at org.robolectric.internal.bytecode.SandboxClassLoader.getInstrumentedBytes(SandboxClassLoader.java:271) at org.robolectric.internal.bytecode.SandboxClassLoader.lambda$maybeInstrumentClass$1(SandboxClassLoader.java:166) at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:50) at org.robolectric.internal.bytecode.SandboxClassLoader.maybeInstrumentClass(SandboxClassLoader.java:165) ... 50 more

The build.gradle file on each module contains the following configuration

testOptions {
    unitTests {
        returnDefaultValues true
    }
}

The application module defines a couple of flavours all running in the same dimension

flavorDimensions 'default'

Any idea?



from NoClassDefFoundError while running unit tests with Roboelectric 3.8

serverless: function doesn't exist in this service

In serverless i have the following directory structure for my functions:

serverless.yml
functions -
    stories -
        create.js
        get.js

my serverless.yml then looks like this:

functions:
  stories:
    create:
      handler: functions/stories/create.main
      events:
        - http:
          path: stories/create
          method: post
          cors: true
          authorizer: aws_iam
    get:
      handler: functions/stories/get.main
      events:
        - http:
          path: stories/{id}
          method: get
          cors: true
          authorizer: aws_iam

however when i run a test to check the create: serverless invoke local --function create --path mocks/create-event.json i get the following error:

Serverless Error ---------------------------------------

  Function "create" doesn't exist in this Service

I managed to get one function working that looks like this:

functions:
  stories:
    handler: functions/stories/create.main
    events:
      - http:
        path: stories/create
        method: post
        cors: true
        authorizer: aws_iam

Since i added the get function, i decided i needed to add the create and get parts after stories, but no matter how i change the handler the functions never seem to exist.

I've tried changing the path to functions/stories/create/create.main with no difference, is there anything obvious i'm missing to allow multiple handlers within the same location?

I was looking at the following example, which uses one folder of "todos" which contains multiple functions, but i can't see any obvious difference between it and mine, except i've added an extra folder.



from serverless: function doesn't exist in this service

Angular Universal Starter Cannot find module

I am using Angular Universal Starter and I am very new to it. I inherited an existing project so I am trying to run it on my local machine. When I first try to run the project I get this error:
ERROR in src/app/auth/authentication.service.ts(5,26): error TS2307: Cannot find module '../../app/globals'.
src/pages/register/register.component.ts(2,26): error TS2307: Cannot find module '../../app/globals'.

Okay, so I created a file called globals.ts:
export class GlobalsModule {}

And so I run my project again and I get this error:
src/shared/user/profile-tabs/profile-tabs.component.ts(53,19): error TS2339: Property
 'baseUrl' does not exist on type 'typeof "/Users/jsuske/Downloads/paindown_front/src/app/globals"'.
src/shared/user/profile-tabs/profile-tabs.component.ts(61,21): error TS2339: Property
 'storageUrl' does not exist on type 'typeof "/Users/jsuske/Downloads/paindown_front/src/app/globals"'.
src/shared/user/profile-tabs/profile-tabs.component.ts(70,29): error TS2339: Property 
'imageUserDefault' does not exist on type 'typeof "/Users/jsuske/Downloads/paindown_front/src/app/globals"'.

So it appears this file is now missing 3 Properties.
My question is how do I define there 3 Properties (baseUrl, storageUrl and imageUserDefault) and possibly populate them?
Here is a little more information, the globals is imported into a component like so:
import * as globals from '../../app/globals';

and Property is called like so:
source = globals.baseUrl

PLEASE HELP!


from Angular Universal Starter Cannot find module

Bouncing burger menu

I need to realize burger menu with bouncing metaball effect or water drop (name it what as you want) something like that.

I don't need all effect's from there I need only this water drop effect with explanations.

Here's my code.

As you see there is nothing incomprehensible here.

Simple jQuery with toggle method CSS with some mediaqueries for small screen show or hide burger ..

$(".menu-trigger").click(function() {
    $(this).toggleClass('active');
    $("ul.menu li").slideToggle('fast');
})
body {
  background: lightblue !important;
  height: 1000px;
}

.header {
  height: 57px;
  background-color: #fff;
  -webkit-filter: url("#goo");
  filter: url("#goo");
}
.header h1 {
  margin: 0;
  margin-left: 60px;
}
.header h1 a {
  float: left;
  line-height: 1.5;
  width: auto;
  height: 57px;
}
.header h1 a img {
  width: 90px;
  height: 57px;
}
.header .menu-trigger {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #ddd;
  position: fixed;
  top: 10px;
  right: 30px;
  z-index: 50;
}
.header .menu-trigger span {
  top: 50%;
  left: 50%;
  -webkit-transition: background-color 0.2s ease-in-out;
  -o-transition: background-color 0.2s ease-in-out;
  transition: background-color 0.2s ease-in-out;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}
.header .menu-trigger span:after {
  top: 6px;
  -webkit-transition: 0.5s ease-in-out;
  -o-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}
.header .menu-trigger span:before {
  top: -6px;
  -webkit-transition: 0.5s ease-in-out;
  -o-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}
.header nav {
  width: 60%;
  margin: 0 auto;
}
.header nav .menu {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  text-decoration: none;
  -ms-flex-pack: distribute;
  justify-content: space-around;
  list-style-type: none;
  margin: 0;
  height: 57px;
  line-height: 3.5;
}
.header nav .menu li a {
  text-decoration: none;
}

.active span {
  background-color: transparent !important;
  -webkit-transition: background-color 0.2s ease-in-out;
  -o-transition: background-color 0.2s ease-in-out;
  transition: background-color 0.2s ease-in-out;
}
.active span:after {
  top: -1px !important;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
  -webkit-transition: 0.5s ease-in-out;
  -o-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}
.active span:before {
  top: -1px !important;
  -webkit-transform: rotate(-45deg);
  -ms-transform: rotate(-45deg);
  transform: rotate(-45deg);
  -webkit-transition: 0.5s ease-in-out;
  -o-transition: 0.5s ease-in-out;
  transition: 0.5s ease-in-out;
}

.header .menu-trigger span, .header .menu-trigger span:after, .header .menu-trigger span:before {
  width: 20px;
  height: 2px;
  background-color: #aaa;
  position: absolute;
  content: '';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="header">
  <div class="menu-trigger">
    <span></span>
  </div>
  <h1 class="logo clearfix"><a href="#">Brand</a></h1>
  <nav>
    <ul class="menu">
      <li>
        <a href="#">One</a>
      </li>
      <li>
        <a href="#">Two</a>
      </li>
      <li>
        <a href="#">Three</a>
      </li>
      <li>
        <a href="#">Four</a>
      </li>
      <li>
        <a href="#">Five</a>
      </li>
      <li>
        <a href="#">Six</a>
      </li>
    </ul>
  </nav>
</header>

 <svg>
    <defs>
        <filter id="goo"> 
            <feGaussianBlur in="SourceGraphic" stdDeviation="5" result="blur"/> 
                <feColorMatrix in="blur" 
                mode="matrix" 
                values="1 0 0 0 0 
                0 1 0 0 0 
                0 0 1 0 0 
                0 0 0 18 -8" result="goo"/> 
                <feBlend in="SourceGraphic" in2="goo"/> 
        </filter>
    </defs>
</svg>


from Bouncing burger menu

Multiple Restangular services with different run time configurations

I'm dealing with an AngularJS (v1.6) + Restangular (v1.6.1) single page application and I'm struggling to get 2 different Restangular services to work as I expect to.

The idea is to retrieve a list of ProductTypes from the back-end and then a list of Products for each type the final user is allowed to interact with; keep in mind that ProductTypes and Products APIs use different base URLs.

The problem:

the products element transformers are never called: what am I doing wrong?

I tried the following approach:

// index.js file
// here I require everything the web-app needs...
angular.
  module('ProductReader', ['ui.router', 'restangular'])
  .config(ProductTypesConfig)
  .config(Routing)
  .service('ProductsRestangular', ProductsRestangular)
  .constant('PRODUCT_TYPES_CONST', PRODUCT_TYPES_CONST)
  .constant('PRODUCTS_CONST', PRODUCTS_CONST);

// PRODUCT_TYPES_CONST file
PRODUCT_TYPES_CONST = {
  API_URL: 'product_types_api',
  ENDPOINT: 'product_types'
};

module.exports = PRODUCT_TYPES_CONST;

// PRODUCTS_CONST file
PRODUCTS_CONST = {
  API_URL: 'products_api',
  TYPES: {}
    /**
     * here the structure built via the config below should be looking like the following 
     * TYPES: {
        PRODUCT_TYPE_1: {
          ENDPOINT: 'product_type_1'
        },
        PRODUCT_TYPE_2: {
          ENDPOINT: 'product_type_2'
        }
     }
    */
}

module.exports = PRODUCTS_CONST;

// ProductTypesConfig file
/** @ngInject */
function ProductTypesConfig(RestangularProvider, PRODUCT_TYPES_CONST, PRODUCTS_CONST) {

  RestangularProvider.setBaseUrl(PRODUCT_TYPES_CONST.API_URL);

  //ProductTypes
  RestangularProvider
    .addElementTransformer(PRODUCT_TYPES_CONST.ENDPOINT, false, function(productType) {

      PRODUCTS_CONST.TYPES[productType.name.toUpperCase()] = {
        ENDPOINT: productType.endpoint
      }

      //Products
      RestangularProvider
        .addElementTransformer(productType.endpoint, false, function(singleProduct) {
          let frontEndSingleProductStuff = {};

          // ... here stuff is added to the object above...

          return angular.extend(rw9Item, {
            frontEnd: frontEndSingleProductStuff
          });

        });

      return productType;
    });
}

module.exports = ProductTypesConfig;

// Products Custom Factory
/** @ngInject */
function ProductsRestangular(Restangular, PRODUCTS_CONST) {

  return Restangular.withConfig(function(RestangularConfigurer) {
    RestangularConfigurer.setBaseUrl(PRODUCTS_CONST.API_URL);
  });
}

module.exports = ProductsRestangular;

// Routing file
/** @ngInject */
function Routing($stateProvider, PRODUCT_TYPES_CONST) {

  $stateProvider
    .state('landing', {
      abstract: true,
      url: '/product-reader',
      resolve: {
        productTypes: function(Restangular, PRODUCT_TYPES_CONST) {
          return Restangular.all(PRODUCT_TYPES_CONST.ENDPOINT).getList();
        },
      }
    })
    .state('product-list', {
      parent: 'landing',
      url: '/list/{:productType}',
      resolve: {
        productLists: function($transition$, ProductsRestangular, PRODUCTS_CONST) {
          return ProductsRestangular.all(PRODUCTS_CONST[$transition$.params().productType].ENDPOINT).getList();
        }
      }
    });
}



from Multiple Restangular services with different run time configurations

Set app level proxy

I'm trying to create some sort of SDK that we intercept each request from my app regardless of which HTTP client it's using (native HttpClient, OkHttp, Retrofit etc.) including traffic from third-party libraries like Firebase Analytics.

I need to intercept and check few parameters then decide whether to allow or block current request.



from Set app level proxy

Friday 29 June 2018

Convert css gradient in to android gradient (xml)

I would like to convert css gradient to android xml gradient (shape) file

for e.g

background-image: linear-gradient(to right, #ff8177 0%, #ff867a 0%, #ff8c7f 21%, #f99185 52%, #cf556c 78%, #b12a5b 100%);

to

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:angle="0"
        android:endColor="#b12a5b"
        android:startColor="#ff867a"
        android:type="linear" />
</shape>

I don't know much about css. I know only android and there are only three parameters for colors android:endColor, android:startColor, android:centerColor How can I define this % and various colors presented in css

is there any online tool from where I can generate the xml file by giving css input.



from Convert css gradient in to android gradient (xml)

Angular2 fire listen to node changes throws an error

THe code below was working and it should listen for changes in a node and execute a function but now am getting an error

ncaught TypeError: Object(...) is not a function
at SwitchMapSubscriber.eval [as project] (changes.js:7)

SO in my angular2 component i have

private subscriptions = new Subscription();

registered: AngularFireList<any>;
constructor(private _af: AngularFireDatabase){
     this.registered = _af.list('/registered');
 }

ngOnInit() {
    this.subscriptions.add(
        this.registered.valueChanges().subscribe(
            res => {
                console.log("the value has changed");
            }
        )
    );
}

So where am i going wrong as getting the error above which point to

angular2fire/database/list/changes

What i need my code to do is to listen to whenever there is a change in a firebase node and log to the console

The subscriptions have also been defined by

    private subscriptions = new Subscription();

AAdding it to the subscriptions then i can use onDestroy lifecycle and prevent memory leaks as shown below

    ngOnDestroy() {
      this.subscriptions.unsubscribe();
    }



from Angular2 fire listen to node changes throws an error

How Immutability is Implemented

I am trying to grasp how the trie and such in immutability is implemented, as relates to immutability in JS. I understand how there is supposed to be significant structural sharing.

My question is say you have a graph sort of structure like this:

a -- b
     |
     c
     |
     d -- h
          |
     e -- i -- l
          |
     f -- j -- m
          |
     g -- k -- n

So then you add an x to the system. I'll try it two different ways:

a -- b
     |
     c
     |
     d -- h -- x
          |
     e -- i -- l
          |
     f -- j -- m
          |
     g -- k -- n

That one is just added as a leaf node.

a -- b
     |
     c
     |
     d -- h
          |
          x
          |
     e -- i -- l
          |
     f -- j -- m
          |
     g -- k -- n

That one is added in the middle of a path.

I am wondering what the immutable data structure would be to handle these 2 situations. So essentially we have a function f : graph -> graph' that changes the graph into a "new graph", when under the hood it should only be making a small adjustment to the data structure. Not sure how this would look or how it works. My first attempt at an explanation would be something like this...

It starts of in a wrapper object which is like ImmutableJS's API layer on top of the JS objects.

 --------------------------
|                          |
|    a -- b                |
|         |                |
|         c                |
|         |                |
|         d -- h           |
|              |           |
|         e -- i -- l      |
|              |           |
|         f -- j -- m      |
|              |           |
|         g -- k -- n      |
|                          |
 --------------------------

Then you make the change and it creates a new wrapper object.

 --------------------------           --------------------------
|                          |         |                          |
|    a -- b                |         |                          |
|         |                |         |                          |
|         c                |         |                          |
|         |                |         |                          |
|         d -- h --------------------------------- x            |
|              |           |         |                          |
|         e -- i -- l      |         |                          |
|              |           |         |                          |
|         f -- j -- m      |         |                          |
|              |           |         |                          |
|         g -- k -- n      |         |                          |
|                          |         |                          |
 --------------------------           --------------------------

Then likewise for the second example:

 --------------------------           -------------------------- 
|                          |         |                          |
|    a -- b                |         |                          |
|         |                |         |                          |
|         c                |         |                          |
|         |                |         |                          |
|         d -- h           |         |                          |
|              |           |         |                          |
|              o --------------------------------- x            |
|              |           |         |                          |
|         e -- i -- l      |         |                          |
|              |           |         |                          |
|         f -- j -- m      |         |                          |
|              |           |         |                          |
|         g -- k -- n      |         |                          |
|                          |         |                          |
 --------------------------           --------------------------

The boxes are the API objects you use, and the graphs inside are the plain JS data objects.

But in these examples the original graph structure is modified (placing a link to h in the first example, and placing an o placeholder in the second one). So I'm wondering how specifically you would make these things immutable. Every change I make to the graph I would like to "return a new object", but under the hood there is optimal structural sharing.

Thank you for your help.



from How Immutability is Implemented

How to convert SOAP response to XML or JSON format?

<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:body>
        <ns1:mbillcommandresponse xmlns:ns1="http://www.mysoap.com/SoapService/">
            <returnvalues>
                <name>status</name>
                <value>TEHNICAL_ERROR</value>
            </returnvalues>
            <returnvalues>
                <name>description</name>
                <value>Please contact your administrator</value>
            </returnvalues>
        </ns1:mbillcommandresponse>
    </soapenv:body>
</soapenv:envelope>

Above I got response in my CURL response. Here is my PHP code:

    $response = curl_exec($ch);
    $xml = simplexml_load_string($response);
    //$result = $xml->xpath('//name'); //echo "<pre>"; print_r($result); exit;
    $xml->registerXPathNamespace('ns1', 'http://www.mysoap.com/SoapService/');
    foreach ($xml->xpath('//returnvalues') as $item) {
        $json = json_encode($item);
        $convrt_arr = json_decode($json, true);
        break;
    }
    print_r($json); exit;

On my above code I got empty json. Could you please help me.



from How to convert SOAP response to XML or JSON format?

Dynamic select2 options using api

I'll try to explain my problem as much as I can. I am trying to create, with select2 plugin, a way for the user to write some letters and on each letter pressed a call to an API that gives the first 20 results given by that API.

So I have my HTML select :

<select name="filtre_products[]" class="form-control products-select2" multiple> 

</select>

And then my JS (it's commented) :

$(".products-select2").select2({ 
    width: '100%', 
    closeOnSelect: false,
    placeholder: '',
    minimumInputLength: 3,
    query: function (query) {
        var data = {results: []}, i, j, s;
        if(query.term != null) {
            var ajax_r = [];
            $.ajax({
                url: 'ajax_products_recherche.php?limite=10&real_json=1&recherche='+query.term,
                success: function(data_a){
                    //Getting the data
                    data_a = JSON.parse(data_a);

                    //Looping through the each data and putting them inside a table
                    data_a.forEach( (e) => {
                        ajax_r.push(e);
                    });

                    //Filtering the data to get from it the id and the text to be used
                    ajax_r.forEach( (e) => {
                        var tmp = e.split('-');
                        var id = tmp[0];
                        var name = tmp[2];

                        data.results.push({value: id, text: name});
                    });

                    query.callback(data);
                }
            });
        }
    },
    //Sending the results to the function to modify the options as I please
    templateResult: formatResult
});

And this is the formatResult function I use :

function formatResult(d) {
    if(d.loading) {
        return d.text;
    } 

    // Creating an option of each id and text
    $d = $('<option/>').attr({ 'value': d.value }).text(d.text);

    return $d;
}

My problem is that select2 is supposed to be creating the options dynamically upon initialization and thus actually creating <li> out of the options and adding to them dynamically id's and such. But in the way I'm creating it, it's putting the options INSIDE the <li> tags which is not what I want, I want it to treat it as dynamic options like he does without the query call.

Some doc sources for you guys : http://select2.github.io/select2/#data



from Dynamic select2 options using api

GoogleFit distinguish data between from different devices

I am using GoogleFit HistoryAPI for get step data from user. It's working well.
However, in my case, I want to distinguish data between from different devices (using same account) because I don't want user using same account for 2 or more devices (it is a game base on step so I don't want user play on 1 device and have achievement on many devices).

I found that Device from DataSource#getDevice, Device#getLocalDevice can help me distinguish data between from different devices. Below is info from official docs:

To get information about the device for a data source, use the DataSource.getDevice method. The device information is useful to distinguish from similar sensors on different devices, show the device information from a sensor to the user, or process data differently depending on the device. For example, you may be interested in reading data specifically from the a sensor on a wearable device but not from the same type of sensor on the phone.

To get a Device instance for the device that is running your activity, use the Device.getLocalDevice static method. This is useful when you want to check if a data source is on the same device that your app is running on.

So,

// My idea is comparing the uid of local device and uid of device in datasource
// if it is same => step come from THIS device
// if not => step come from OTHER device
private void dumpDataSet(DataSet dataSet) {
    for (DataPoint dp : dataSet.getDataPoints()) {
        Log.i(Constant.TAG, "Origin type uid: " + dp.getOriginalDataSource().getDevice().getUid());
        Log.i(Constant.TAG, "Local device uid: " + Device.getLocalDevice(getApplicationContext()).getUid());

        ... 
     }
}

However, the logcat result for datasource from only 1 DEVICE is

Origin type uid: 9ff67c48
Local device uid: f2b01c49ecd9c389
// Only the model, manufacturer is same (but I can not use 2 fields because user can use 2 devices with same model, manufacturer)

You can see that the uid from datasource is different to local device uid, so I can not distinguish data.

Is there any way to distinguish data between from different devices? Any help or suggestion would be great appreciated.

DEMO project



from GoogleFit distinguish data between from different devices

Woocommerce: Only show some variations on a product page

I have a Woocommerce website with many variable products. These products have numerous colour and size options.

I'd like to limit which variations are displayed, based on which category the product is accessed through.

I thought about creating multiple variable products, but this would have implications for stock. I need a single variable product but multiple "views" of the product that limit which variations are shown.

Detecting the parent category is no problem. I can't work out how limit the number of variations that are displayed. I could prevent the purchase of certain variations using the Woocommerce filter woocommerce_available_variation, but I actually want to remove the options from the page all together.

I see references documentation to "invisible" and "disabled" variations, but I can't see how I might be able to harness these.

I found two filters woocommerce_variation_is_active and woocommerce_variation_is_visible which allow you to grey-out or hide certain information for a particular variation. This still doesn't allow me to prevent them from displaying all together.



from Woocommerce: Only show some variations on a product page

MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis teners added. Use emitter.setMaxListeners() to increase limit

I know this might flag as a duplicate solution but solution on stack overflow is not working for me.

Problem:

(node:5716) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis
teners added. Use emitter.setMaxListeners() to increase limit.

My code base is huge and i facing this error sometimes i don't know why it is happening

What I tried :

Tried to increase the listeners limit but unfortunately it is not working.

const EventEmitter = require('events');
const emitter = new EventEmitter()
emitter.setMaxListeners(50)



from MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 message lis teners added. Use emitter.setMaxListeners() to increase limit

iOS Swift playing audio (aac) from network stream

I'm developing an iOS application and I'm quite new to iOS development. So far I have implemented a h264 decoder from network stream using VideoToolbox, which was quite hard. Now I need to play an audio stream that comes from network, but with no file involved, just a raw AAC stream read directly from the socket. This streams comes from the output of a ffmpeg instance. The problem is that I don't know how to start with this, it seems there is little information about this topic. I have already tried with AVAudioPlayer but found just silence. I think I have first need to decompress the packets from the stream, just like with the h264 decoder.

I have been trying also with AVAudioEngine and AVAudioPlayerNode but no sucess, same as with AVAudioPlayer. Can someone provide me some guidance? Maybe AudioToolbox? AudioQueue?

Thank you very much for the help :)

Edit: I'm playing around with AVAudioCompressedBuffer and having no error using AVAudioEngine and AVAudioNode. But, I don't know what this output means:

inBuffer: <AVAudioCompressedBuffer@0x6040004039f0: 0/1024 bytes>

Does this mean that the buffer is empty? I have been trying to feed this buffer in several ways, but always returns something like 0/1024. I think I'm not doing this right:

compressedBuffer.mutableAudioBufferList.pointee = audioBufferList

Any idea?

Thank you!

Edit 2: I'm editing for reflecting my code for decompressing the buffer. Maybe some one can point me in the right direction. Note: The packet that is ingested by this function actually is passed without the ADTS header (9 bytes) but I have also tried passing it with the header.

func decodeCompressedPacket(packet: Data) -> AVAudioPCMBuffer {

    var packetCopy = packet
    var streamDescription: AudioStreamBasicDescription = AudioStreamBasicDescription.init(mSampleRate: 44100, mFormatID: kAudioFormatMPEG4AAC, mFormatFlags: UInt32(MPEG4ObjectID.AAC_LC.rawValue), mBytesPerPacket: 0, mFramesPerPacket: 1024, mBytesPerFrame: 0, mChannelsPerFrame: 1, mBitsPerChannel: 0, mReserved: 0)
    let audioFormat = AVAudioFormat.init(streamDescription: &streamDescription)
    let compressedBuffer = AVAudioCompressedBuffer.init(format: audioFormat!, packetCapacity: 1, maximumPacketSize: 1024)

    print("packetCopy count: \(packetCopy.count)")
    var audioBuffer: AudioBuffer = AudioBuffer.init(mNumberChannels: 1, mDataByteSize: UInt32(packetCopy.count), mData: &packetCopy)
    var audioBufferList: AudioBufferList = AudioBufferList.init(mNumberBuffers: 1, mBuffers: audioBuffer)
    var mNumberBuffers = 1
    var packetSize = packetCopy.count
    // memcpy(&compressedBuffer.mutableAudioBufferList[0].mBuffers, &audioBuffer, MemoryLayout<AudioBuffer>.size)
    // memcpy(&compressedBuffer.mutableAudioBufferList[0].mBuffers.mDataByteSize, &packetSize, MemoryLayout<Int>.size)
    // memcpy(&compressedBuffer.mutableAudioBufferList[0].mNumberBuffers, &mNumberBuffers, MemoryLayout<UInt32>.size)

    // compressedBuffer.mutableAudioBufferList.pointee = audioBufferList

    var bufferPointer = compressedBuffer.data

    for byte in packetCopy {
        memset(compressedBuffer.mutableAudioBufferList[0].mBuffers.mData, Int32(byte), MemoryLayout<UInt8>.size)
    }

    print("mBuffers: \(compressedBuffer.audioBufferList[0].mBuffers.mNumberChannels)")
    print("mBuffers: \(compressedBuffer.audioBufferList[0].mBuffers.mDataByteSize)")
    print("mBuffers: \(compressedBuffer.audioBufferList[0].mBuffers.mData)")


    var uncompressedBuffer = uncompress(inBuffer: compressedBuffer)
    print("uncompressedBuffer: \(uncompressedBuffer)")
    return uncompressedBuffer
}



from iOS Swift playing audio (aac) from network stream

Create Gradient in View With locations from zeplin

I am working on a project where i need to apply gradients to the view. I am having sketch file and have colors which i am going to use for gradient with the locations but i am unable to get the exact view.

Can anyone please help how to get that?

I have created a function to apply gradient:-

func applyGradient(colours: [UIColor]) -> Void {
        let gradient: CAGradientLayer = CAGradientLayer()
        gradient.frame = self.bounds
        gradient.colors = colours.map { $0.cgColor }
        self.layer.insertSublayer(gradient, at: 0)
    }

func applyGradientToView(){
        let firstColor = UIColor(red: 26/255, green: 169/255, blue: 186/255, alpha: 1.0)
        let secondColor = UIColor(red: 26/255, green: 97/255, blue: 157/255, alpha: 1.0)
        let thirdColor = UIColor(red: 27/255, green: 65/255, blue: 144/255, alpha: 1.0)
        self.applyGradient(colours: [firstColor, secondColor, thirdColor])
    }

Here array UIcolor is a combination of colors to be used, I used all three but still, I didn't get the same as in the sketch

What I created :-

enter image description here

Gradient colors in sketch file:-

enter image description here

The view in sketch file is like this:-

enter image description here



from Create Gradient in View With locations from zeplin

Cannot solve SonarQube error "Make this line start at column 3"

I am having a lot of lines with this errors in xml (layout, strings, drawables...). I tried to change the space of each colum to 3, to put 3 tabs in the lines that I have this error but I am still having this error in SonarQube. How can I solve this?

I put here an example where I am getting this error:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="64.42dp"
    android:height="68.76dp"
    android:viewportWidth="64.42"
    android:viewportHeight="68.76">
    <path
        android:fillColor="#141412"
        android:fillType="evenOdd"
        android:pathData="M38.62,43.24c0.69,0.1,1.2,0.75,2.01,0.86c1.33,0.18,2.57-0.02,3.7-0.77 c1.98-1.33,3.56-3.23,3.66-5.65c0.01-0.34-0.04-1.42-0.04-1.69c0-1.01-0.57-1.32-0.75-2.3c-0.3-1.61,1.23-0.8,1.42,0.33 c-0.13-0.77,0.69-4.28,2.59-2.64c1.63,1.4,0.07,2.82-0.24,4.24c-0.14,0.63-0.45,1.84-0.54,2.48c0,0,0,0-0.01,0 c-0.35,2.33-1.41,4.8-2.95,6.34c-1.35,1.35-3.05,2.76-5.02,2.92c-1.15,0.1-3.25-0.08-4.27-0.66l0.21,0.42 C36.59,47.68,36.57,42.95,38.62,43.24z" />
    <path
        android:fillColor="#C31924"
        android:fillType="evenOdd"
        android:pathData="M61.69,43.35c0.82-2.66,2.14-11.44,2.28-12.49c0.13-1.05,0.42-2.32,0.45-3.83 c0.03-1.51-1.36-3.05-3.35-3.04c-0.36,0-16.15,0.06-16.92,0.07c-0.52,0-0.66-0.27-0.63-0.56c0.27-2.7,0.8-6.13,0.88-6.58 c0.08-0.41,0.16-0.8,0.17-1c0.02-0.2,0.06-0.49-0.42-0.62c-0.49-0.12-4.1-0.59-21.86-0.5C5.2,14.89,0.91,15.4,0.43,15.53 c-0.49,0.13-0.44,0.42-0.42,0.62c0.01,0.2,0.13,0.7,0.18,0.99c0.07,0.33,0.71,3.87,0.96,6.58c0.68,7.77,1.49,39.99,1.6,41.09 c0.08,0.77,0.31,2.1,1.91,3.03c1.6,0.94,16.85,0.92,17.9,0.91c1.05,0.01,16.3-0.13,17.89-1.09c1.59-0.96,1.81-2.28,1.88-3.05 c0.04-0.41,0.14-5.19,0.15-5.43c0.02-0.25,0.17-0.69,0.63-0.75c0.82-0.1,1.64-0.2,2.9-0.46c3.83-0.79,6.07-2.06,8.61-3.89 C59.28,50.69,60.88,46.02,61.69,43.35 M56.84,43.88c-1.03,2.45-3.81,7.25-8.9,9.07c-1.94,0.7-4.31,1.21-4.71,1.21 c-0.56,0.01-0.63-0.04-0.63-0.39c0-0.36,0.17-9.65,0.21-10.87c0.22-6.95,2.25-12.22,4.9-13.52c0.57-0.28,1.45-0.75,3.89-0.76 c2.95-0.02,6.98-0.03,7.36-0.04c0.38,0,0.66,0,0.66,0.31c0.01,0.44-0.61,4.63-0.67,5.04C58.87,34.35,57.85,41.49,56.84,43.88" />
    <path
        android:fillColor="#141412"
        android:pathData="M24.38,32.2c0,0.97,0.53,1.76,1.16,1.75c0.64,0,1.15-0.79,1.14-1.77c0-0.97-0.53-1.75-1.16-1.75 C24.89,30.44,24.37,31.23,24.38,32.2z" />
    <path
        android:fillColor="#141412"
        android:pathData="M17.59,32.23c0,0.97,0.53,1.76,1.16,1.75c0.64,0,1.15-0.79,1.15-1.77c0-0.97-0.53-1.75-1.16-1.75 C18.1,30.47,17.59,31.26,17.59,32.23z" />
    <path
        android:fillColor="#141412"
        android:pathData="M17.88,35.89c0.01,2.3,1.88,4.15,4.17,4.13c2.29-0.01,4.15-1.88,4.13-4.18" />
    <path
        android:fillColor="#D38690"
        android:fillType="evenOdd"
        android:pathData="M22.61,1.28c0.61-0.69,1.27-1.36,2.61-1.26c1.32,0.09,2.12,0.97,2.44,1.94 c0.41,1.25-0.12,2.55-0.74,3.34c-1.26,1.59-3.27,2.66-4.27,4.49c-0.54-0.68-1.07-1.39-1.74-2.01c-0.63-0.58-1.34-1.13-1.98-1.77 c-0.61-0.6-1.19-1.35-1.39-2.35c-0.23-1.17,0.11-2.21,0.74-2.84c0.4-0.4,0.98-0.75,1.72-0.81C21.33-0.1,22.05,0.55,22.61,1.28z" />
</vector>



from Cannot solve SonarQube error "Make this line start at column 3"

Integrating the OHLC value from Python API to MT5 using MQL5

I have obtained the OHLC values from the iqoption and trying to find out a way to use it with MT5.
Here is how I got the values:

import time
from iqoptionapi.stable_api import IQ_Option
I_want_money=IQ_Option("email","password")
goal="EURUSD"
print("get candles")
print(I_want_money.get_candles(goal,60,111,time.time()))

The above code library is here: iqoptionapi

The line: I_want_money.get_candles(goal,60,111,time.time()) output json as : Output of the command

Now I am getting json in the output so it work like an API, I guess so.

Meanwhile, I try to create a Custom Symbol in MT5 as iqoption. Now I just wanted to add the data of the OHLC from the API to it, so that it will continue fetching data from the Iqoption and display the chart on the chart window for the custom symbol iqoption.

But I am not able to load it in the custom symbol. Kindly, help me.



from Integrating the OHLC value from Python API to MT5 using MQL5

Thumb image is slightly on left of thumb

enter image description hereI did some editing in the CrysalRangeBar to display text over the thumb, on which I found some success but I am facing a issue that the thumbImage is slighlty on left of original thumb which means if I have to slide the thumb I have to drag it from right white space of thumb. Over all I want to say that the image thumb is not properly set on thumb place. If I remove all my editing then the thumb image is on right place.

Below is the code for CrystalRangeBar.Java

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

        // prevent render is in edit mode
        if (isInEditMode()) return;

        // setup bar
        setupBar(canvas, _paint, _rect);

        // setup seek bar active range line
        setupHighlightBar(canvas, _paint, _rect);

        // draw left thumb
        //  setupLeftThumb(canvas, _paint, _rect);
        // getSelectedMinValue(), getSelectedMaxValue()
        String minText = String.valueOf(getSelectedMinValue());
        String maxText = String.valueOf(getSelectedMaxValue());
        boolean selectedValuesAreDefaultMax = (maxText.equals(String.valueOf((int) absoluteMaxValue)));
        boolean selectedValuesAreDefaultMin = (minText.equals(String.valueOf((int) absoluteMinValue)));

        leftThumbColor = (Thumb.MIN.equals(pressedThumb)) ? leftThumbColorPressed : leftThumbColorNormal;
        rightThumbColor = (Thumb.MAX.equals(pressedThumb)) ? rightThumbColorPressed : rightThumbColorNormal;
        _paint.setColor(leftThumbColor);
        _paint.setStyle(Paint.Style.FILL);
        _paint.setTextSize(mTextSize);
        _paint.setAntiAlias(true);
        float minMaxLabelSize = 0;

        padding = mInternalPad + minMaxLabelSize + mThumbHalfHeight;

        // draw seek bar background line
        mRect.left = padding;
        mRect.right = getWidth() - padding;
        canvas.drawRect(mRect, _paint);
/*
        mRect.left = normalizedToScreen(normalizedMinValue);
        mRect.right = normalizedToScreen(normalizedMaxValue);*/

        int offset = PixelUtil.dpToPx(getContext(), TEXT_LATERAL_PADDING_IN_DP);


        if (!selectedValuesAreDefaultMax) {

            float maxTextWidth = _paint.measureText(maxText) + offset;
            float maxPosition = Math.min(getWidth() - maxTextWidth, normalizedToScreen(normalizedMaxValue) - maxTextWidth * 0.5f);
            canvas.drawText(maxText,
                    maxPosition,
                    mDistanceToTop + mTextSize,
                    _paint);


        }


        if (!selectedValuesAreDefaultMin) {

            float minTextWidth = _paint.measureText(minText) + offset;
            float minPosition = Math.max(0f, normalizedToScreen(normalizedMinValue) - minTextWidth * 0.5f);

            canvas.drawText(minText,
                    minPosition,
                    mDistanceToTop + mTextSize,
                    _paint);

        }


        rectLeftThumb.left = normalizedToScreen(normalizedMinValue);
        rectLeftThumb.right = Math.min(rectLeftThumb.left + mThumbHalfWidth + barPadding, getWidth());
        rectLeftThumb.bottom = thumbHeight;

        rectRightThumb.left = normalizedToScreen(normalizedMaxValue);
        rectRightThumb.right = Math.min(rectRightThumb.left + mThumbHalfWidth + barPadding, getWidth());
        rectRightThumb.bottom = thumbHeight;

        if (leftThumb != null) {
            drawLeftThumb(normalizedToScreen(normalizedMinValue), Thumb.MIN.equals(pressedThumb), canvas, selectedValuesAreDefaultMin);
        } else {
            drawLeftThumbWithColor(canvas, _paint, rectLeftThumb);
        }

        if (rightThumb != null) {
            drawRightThumb(normalizedToScreen(normalizedMaxValue), Thumb.MAX.equals(pressedThumb), canvas, selectedValuesAreDefaultMax);
        } else {
            drawRightThumbWithColor(canvas, _paint, rectRightThumb);
        }
        // draw right thumb
        //setupRightThumb(canvas, _paint, _rect);

    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // setMeasuredDimension(getMeasureSpecWith(widthMeasureSpec), getMeasureSpecHeight(heightMeasureSpec));
        int width = 200;
        if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(widthMeasureSpec)) {
            width = MeasureSpec.getSize(widthMeasureSpec);
        }
        int height = rightThumb.getHeight()
                + PixelUtil.dpToPx(getContext(), HEIGHT_IN_DP);
        if (MeasureSpec.UNSPECIFIED != MeasureSpec.getMode(heightMeasureSpec)) {
            height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
        }
        setMeasuredDimension(width, height);
    }

    /**
     * Handles thumb selection and movement. Notifies listener callback on certain events.
     */
    @Override
    public synchronized boolean onTouchEvent(MotionEvent event) {

        if (!isEnabled())
            return false;


        final int action = event.getAction();

        switch (action & MotionEvent.ACTION_MASK) {

            case MotionEvent.ACTION_DOWN:
                mActivePointerId = event.getPointerId(event.getPointerCount() - 1);
                pointerIndex = event.findPointerIndex(mActivePointerId);
                float mDownMotionX = event.getX(pointerIndex);

                pressedThumb = evalPressedThumb(mDownMotionX);

                if (pressedThumb == null) return super.onTouchEvent(event);

                touchDown(event.getX(pointerIndex), event.getY(pointerIndex));
                setPressed(true);
                invalidate();
                onStartTrackingTouch();
                trackTouchEvent(event);
                attemptClaimDrag();

                break;

            case MotionEvent.ACTION_MOVE:
                if (pressedThumb != null) {

                    if (mIsDragging) {
                        touchMove(event.getX(pointerIndex), event.getY(pointerIndex));
                        trackTouchEvent(event);
                    }

                    if (onRangeSeekbarChangeListener != null) {
                        onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue());
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mIsDragging) {
                    trackTouchEvent(event);
                    onStopTrackingTouch();
                    setPressed(false);
                    touchUp(event.getX(pointerIndex), event.getY(pointerIndex));
                    if (onRangeSeekbarFinalValueListener != null) {
                        onRangeSeekbarFinalValueListener.finalValue(getSelectedMinValue(), getSelectedMaxValue());
                    }
                } else {
                    // Touch up when we never crossed the touch slop threshold
                    // should be interpreted as a tap-seek to that location.
                    onStartTrackingTouch();
                    trackTouchEvent(event);
                    onStopTrackingTouch();
                }

                pressedThumb = null;
                invalidate();
                if (onRangeSeekbarChangeListener != null) {
                    onRangeSeekbarChangeListener.valueChanged(getSelectedMinValue(), getSelectedMaxValue());
                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN: {
                //final int index = event.getPointerCount() - 1;
                // final int index = ev.getActionIndex();
                /*mDownMotionX = event.getX(index);
                mActivePointerId = event.getPointerId(index);
                invalidate();*/
                break;
            }
            case MotionEvent.ACTION_POINTER_UP:
                /*onSecondaryPointerUp(event);*/
                invalidate();
                break;
            case MotionEvent.ACTION_CANCEL:
                if (mIsDragging) {
                    onStopTrackingTouch();
                    setPressed(false);
                    touchUp(event.getX(pointerIndex), event.getY(pointerIndex));
                }
                invalidate(); // see above explanation
                break;
        }

        return true;

    }
}



from Thumb image is slightly on left of thumb

How to use YouTube Android Player API with AppCompatActivity

To play a video in my app I decided to extend from YouTube Android Player API. But the problem is my menu is disappeared because I'm not extending from AppCompatActivity. The question is: how to use YouTube Android Player API and have the menu in the app?

public class TutorialsActivity extends YouTubeBaseActivity {

private YouTubePlayerView youTubePlayerView;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.youtube);

    youTubePlayerView = (YouTubePlayerView) findViewById(R.id.video1);
    youTubePlayerView.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
        @Override
        public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
            youTubePlayer.loadVideo("c9q88492aas");
            youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
        }

        @Override
        public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {

        }
    });
}

XML

    <com.google.android.youtube.player.YouTubePlayerView
    android:id="@+id/video1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

When I extend from AppCompatActivity, it just gives me an error.

Error Log:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hyber.app/com.hyber.app.TutorialsActivity}: android.view.InflateException: Binary XML file line #12: Binary XML file line #12: Error inflating class com.google.android.youtube.player.YouTubePlayerView

enter image description here



from How to use YouTube Android Player API with AppCompatActivity

Visual Studio Code debugger for Python

I have this setting file at Visual Studio Code launch.json:

"name": "Django",
"type": "python",
"request": "launch",
"stopOnEntry": true,
"pythonPath": "${config:python.pythonPath}",
"program": "${workspaceFolder}/manage.py",
"cwd": "${workspaceFolder}",
"args": [
    "runserver",
    "--noreload",
    "--nothreading"
],
"env": {},
"envFile": "${workspaceFolder}/.env",
"debugOptions": [
    "RedirectOutput",
    "Django"
]

When I click on Debug --> Start Debugging, it auto generates the following syntax which is different from my setting file above:

C:\Users\HP\Work\ABC>cd C:\Users\HP\Work\ABC && cmd /C "set "PYTHONIOENCODING=UTF-8" && set "PYTHONUNBUFFERED=1" && C:\Users\HP\Work\Scripts\python.exe c:\Users\HP.vscode\extensions\ms-python.python-2018.5.0\pythonFiles\PythonTools\visualstudio_py_launcher.py C:\Users\HP\Work\ABC 65530 34806ad9-833a-4524-8cd6-18ca4aa74f14 RedirectOutput,RedirectOutput,DjangoDebugging C:\Users\HP\Work\ABC/manage.py runserver --noreload --nothreading "

When executing the above debugger, it always return inconsistent error messages such as:

  • RuntimeError: Set changed size during iteration

  • raise Exception('failed to attach') Exception: failed to attach



from Visual Studio Code debugger for Python

Postgres Javascript (pg.js) dynamic column names

I have searched and searched and am just not finding the answer to this one.

I am using pg.js to run queries from my Node.js server to a Postgres database. I would like to use 1 function to run queries on two different tables. So I would like to do this:

database.query("SELECT * FROM $1 WHERE $2 = $3;",
  [type, idName, parseInt(id, 10)],
  (error, result) => {});

This results in a syntax error.

error: syntax error at or near "$1"

I found some SO articles that use either :name or a ~ to cast the variable as a "name". Like this:

database.query("SELECT * FROM $1~ WHERE $2~ = $3;",
  [type, idName, parseInt(id, 10)],
  (error, result) => {});

This results in the same error.

If I hard-code the table name and try to use the ~ on just the column name. I get the error:

error: operator does not exist: unknown ~

The only thing that seems to work is this very bad solution:

database.query("SELECT * FROM "+type+" WHERE "+idName+" = $1;",
  [parseInt(id, 10)],
  (error, result) => {});

Any help appreciated.



from Postgres Javascript (pg.js) dynamic column names

How to fit video in Live wallpaper, by center-crop and by fitting to width/height?

Background

I'm making a live wallpaper that can show a video. In the beginning I thought this is going to be very hard, so some people suggested using OpenGL solutions or other, very complex solutions (such as this one).
Anyway, for this, I've found various places talking about it, and based on this github library (which has some bugs), I finally got it to work.

The problem

While I've succeeded showing a video, I can't find the way to control how it's shown compared to the screen resolution.
Currently it always gets to be stretched to the screen size, meaning that this (video taken from here) :
enter image description here
gets to show as this:
enter image description here
Reason is the different aspect ratio : 560x320 (video resolution) vs 1080x1920 (device resolution).

What I've tried

I tried to play with various fields and functions of the SurfaceHolder, but with no luck so far.
Here's the current code I've made (full project available here) :
class MovieLiveWallpaperService : WallpaperService() {
    override fun onCreateEngine(): WallpaperService.Engine {
        return VideoLiveWallpaperEngine()
    }

    private enum class PlayerState {
        NONE, PREPARING, READY, PLAYING
    }

    inner class VideoLiveWallpaperEngine : WallpaperService.Engine() {
        private var mp: MediaPlayer? = null
        private var playerState: PlayerState = PlayerState.NONE

        override fun onSurfaceCreated(holder: SurfaceHolder) {
            super.onSurfaceCreated(holder)
            Log.d("AppLog", "onSurfaceCreated")
            mp = MediaPlayer()
            val mySurfaceHolder = MySurfaceHolder(holder)
            mp!!.setDisplay(mySurfaceHolder)
            mp!!.isLooping = true
            mp!!.setVolume(0.0f, 0.0f)
            mp!!.setOnPreparedListener { mp ->
                playerState = PlayerState.READY
                setPlay(true)
            }
            try {
                //mp!!.setDataSource(this@MovieLiveWallpaperService, Uri.parse("http://techslides.com/demos/sample-videos/small.mp4"))
                mp!!.setDataSource(this@MovieLiveWallpaperService, Uri.parse("android.resource://" + packageName + "/" + R.raw.small))
            } catch (e: Exception) {
            }
        }

        override fun onDestroy() {
            super.onDestroy()
            Log.d("AppLog", "onDestroy")
            if (mp == null)
                return
            mp!!.stop()
            mp!!.release()
            playerState = PlayerState.NONE
        }

        private fun setPlay(play: Boolean) {
            if (mp == null)
                return
            if (play == mp!!.isPlaying)
                return
            when {
                !play -> {
                    mp!!.pause()
                    playerState = PlayerState.READY
                }
                mp!!.isPlaying -> return
                playerState == PlayerState.READY -> {
                    Log.d("AppLog", "ready, so starting to play")
                    mp!!.start()
                    playerState = PlayerState.PLAYING
                }
                playerState == PlayerState.NONE -> {
                    Log.d("AppLog", "not ready, so preparing")
                    mp!!.prepareAsync()
                    playerState = PlayerState.PREPARING
                }
            }
        }

        override fun onVisibilityChanged(visible: Boolean) {
            super.onVisibilityChanged(visible)
            Log.d("AppLog", "onVisibilityChanged:" + visible + " " + playerState)
            if (mp == null)
                return
            setPlay(visible)
        }

    }

    class MySurfaceHolder(private val surfaceHolder: SurfaceHolder) : SurfaceHolder {
        override fun addCallback(callback: SurfaceHolder.Callback) = surfaceHolder.addCallback(callback)

        override fun getSurface() = surfaceHolder.surface!!

        override fun getSurfaceFrame() = surfaceHolder.surfaceFrame

        override fun isCreating(): Boolean = surfaceHolder.isCreating

        override fun lockCanvas(): Canvas = surfaceHolder.lockCanvas()

        override fun lockCanvas(dirty: Rect): Canvas = surfaceHolder.lockCanvas(dirty)

        override fun removeCallback(callback: SurfaceHolder.Callback) = surfaceHolder.removeCallback(callback)

        override fun setFixedSize(width: Int, height: Int) = surfaceHolder.setFixedSize(width, height)

        override fun setFormat(format: Int) = surfaceHolder.setFormat(format)

        override fun setKeepScreenOn(screenOn: Boolean) {}

        override fun setSizeFromLayout() = surfaceHolder.setSizeFromLayout()

        override fun setType(type: Int) = surfaceHolder.setType(type)

        override fun unlockCanvasAndPost(canvas: Canvas) = surfaceHolder.unlockCanvasAndPost(canvas)
    }
}

The questions

  1. How can I make the content fit the screen, without losing aspect ratio and without cropping (meaning there will be margins) ?
  2. How can I make it fill entire screen, without losing aspect ratio, and allowing content to crop (meaning like center-crop) ?


from How to fit video in Live wallpaper, by center-crop and by fitting to width/height?