Wednesday, 31 March 2021

How can i change form-check(Radio button ) to 5 points slider in HTML/JS page?

I have created a survey page but i want to change survey question from radio button to 5 point slider.I try to use

<input id="ex1" data-slider-id='ex1Slider' type="text" data-slider-min="0" data-slider-max="5" data-slider-step="1"/>

But it is not working also i need to define each value with some text as i did below in my radio button code ..please help me with that and suggest the solution.I also want to get value from those slider as i did it in below code.

HTML :-

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Survey Question</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>

<body>
  <style>

  </style>
  <section class="container py-4">
    <div class="row">
      <div class="col-md-12">
        <h2>Survey</h2>
        <ul id="tabs" class="nav nav-tabs">
          <li class="nav-item"><a href="" data-target="#section1" data-toggle="tab" class="nav-link small text-uppercase active">Section 1</a></li>
          <li class="nav-item"><a href="" data-target="#section2" data-toggle="tab" class="nav-link small text-uppercase">Section 2</a></li>
          <li class="nav-item"><a href="" data-target="#results" data-toggle="tab" class="nav-link small text-uppercase">Results</a></li>
        </ul>
        <br>
        <div id="tabsContent" class="tab-content">
          <div id="section1" class="tab-pane fade active show">
            <div class="section-1-questions">
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 1:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question1" id="gridRadios1" value="1">
                      <label class="form-check-label" for="gridRadios1">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input " type="radio" name="question1" id="gridRadios2" value="2">
                      <label class="form-check-label" for="gridRadios2">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question1" id="gridRadios3" value="3">
                      <label class="form-check-label" for="gridRadios3">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 2:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question2" id="gridRadios4" value="1">
                      <label class="form-check-label" for="gridRadios4">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question2" id="gridRadios5" value="2">
                      <label class="form-check-label" for="gridRadios5">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question2" id="gridRadios6" value="3">
                      <label class="form-check-label" for="gridRadios6">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 3:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question3" id="gridRadios7" value="1">
                      <label class="form-check-label" for="gridRadios7">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question3" id="gridRadios8" value="2">
                      <label class="form-check-label" for="gridRadios8">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-1">
                      <input class="form-check-input" type="radio" name="question3" id="gridRadios9" value="3">
                      <label class="form-check-label" for="gridRadios9">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
            </div>
          </div>


          <div id="section2" class="tab-pane fade">
            <div class="section-2-question">
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question4" id="gridRadios10" value="1">
                      <label class="form-check-label" for="gridRadios10">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question4" id="gridRadios11" value="2">
                      <label class="form-check-label" for="gridRadios11">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question4" id="gridRadios12" value="3">
                      <label class="form-check-label" for="gridRadios12">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 5:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question5" id="gridRadios13" value="1">
                      <label class="form-check-label" for="gridRadios13">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question5" id="gridRadios14" value="2">
                      <label class="form-check-label" for="gridRadios14">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question5" id="gridRadios15" value="3">
                      <label class="form-check-label" for="gridRadios15">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question6" id="gridRadios16" value="1">
                      <label class="form-check-label" for="gridRadios16">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question6" id="gridRadios17" value="2">
                      <label class="form-check-label" for="gridRadios17">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question6" id="gridRadios18" value="3">
                      <label class="form-check-label" for="gridRadios18">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
              <fieldset class="form-group">
                <div class="row">
                  <legend class="col-form-label col-sm-2 pt-0">Question 4:</legend>
                  <div class="col-sm-10">
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question7" id="gridRadios19" value="1">
                      <label class="form-check-label" for="gridRadios19">
                                            1
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question7" id="gridRadios20" value="2">
                      <label class="form-check-label" for="gridRadios20">
                                            2
                                        </label>
                    </div>
                    <div class="form-check section-2">
                      <input class="form-check-input" type="radio" name="question7" id="gridRadios21" value="3">
                      <label class="form-check-label" for="gridRadios21">
                                            3
                                        </label>
                    </div>
                  </div>
                </div>
              </fieldset>
            </div>
          </div>
          <div id="results" class="tab-pane fade">
            <div class="final-results"></div>
            <br>
            <button type="button" class="btn btn-success" onclick="displayRadioValue()">
                            Show Results
                        </button>
            <br>
            <br>
            <div id="control" style="display: none">
              <a id="toemail" class="btn btn-link" href="mailto:youremail@domain.com?subject=Survey response&body=">Send to
                                email</a>&nbsp;<button onclick="window.print();" class="btn btn-warning">Send to PDF</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </section>
</body>

</html>

JS :-

function displayRadioValue() {
  let section1 = document.querySelectorAll('.section-1 > input[type="radio"]')
  let section2 = document.querySelectorAll('.section-2 > input[type="radio"]')
  let section1Total = 0
  let section2Total = 0
  let section1Question = 0
  let section2Question = 0
  let finalResults = document.querySelector('.final-results')
  let result1 = ''
  let result2 = ''
  finalResults.innerHTML = ''

  //Section 1
  section1.forEach(function(radio, index) {
    if (radio.checked) {
      section2Question++
      section1Total += +radio.value
    }
  })

  //Section 2
  section2.forEach(function(radio, index) {
    if (radio.checked) {
      section1Question++
      section2Total += +radio.value
    }
  })

  //Final Results and validation
  if (section1Total > 0 && section2Total > 0) {
    finalResults.innerHTML += genTable(section1Question, section1Total, 1)
    finalResults.innerHTML += genTable(section2Question, section2Total, 2)
    document.getElementById("control").style.display = "block";
    document.getElementById("toemail").href += document.querySelector(".final-results").innerText;
  } else {
    finalResults.innerHTML = 'Snap! Please select the atleast one survey question from each section '
  }
}

function genTable(ques, total, section) {
  var result = "<b>Section " + section + ":</b><br>"
  var tr = "<tr><th>" + total + "</th><th>" + ((total / (ques * 3)) * 100).toFixed(2) + "</th></tr>"
  result += "<table><thead><tr><th>Total Score</th><th>Percentage</th></tr></thead><tbody>" + tr + "</tbody></table>"
  return result
}

CSS:-

@media print {
  body * {
    visibility: hidden;
  }
  .final-results * {
    visibility: visible;
  }
  .final-results {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
  }
}

table,
table tr th,
table tr td {
  border: 1px solid black;
}


from How can i change form-check(Radio button ) to 5 points slider in HTML/JS page?

Outlook Plugin upload FileReference as attachment

I am developing an outlook plugin that needs to upload not a file attachment but a reference file when the user compose a message.

I've tried to use these 3 methods :

  1. addFileAttachmentAsync(uri, attachmentName, [options], [callback])
  2. addItemAttachmentAsync(itemId, attachmentName, [options], [callback])
  3. makeEwsRequestAsync(data, callback, [userContext])

Results of the 3 methods :

  1. Not able to add referenceFile
  2. MessageText":"You cannot attach yourself.","ResponseCode":"ErrorCannotAttachSelf","ResponseClass":"Error"}]}}}
  3. HTTP 500 error.

Code of the second method :

var messageId = await getMessageItemId();
var exchangeAttachment = await uploadAttachmentToExchange(accessToken, messageId, attachment.name,fileUploaded.webUrl);
await addReferenceAttachment(exchangeAttachment.id, attachment.name);

var uploadAttachmentToExchange = async function(accessToken, messageId, fileName, fileUrl){
    var OneDriveURL = "https://graph.microsoft.com/beta/me/messages/"+messageId+"/attachments";
    var payload = JSON.stringify({ 
        "@odata.type": "#microsoft.graph.referenceAttachment", 
        "name": fileName, 
        "sourceUrl": fileUrl, 
        "providerType": "oneDriveBusiness", 
        "permission": "organizationEdit",
        "isFolder" : false,
        "isInline" : false
    }) ;
    
    return new Promise((successCallback, failureCallback) => {
        $.ajax({
            method: "POST",
            contentType: 'application/json',
            dataType: 'json',
            headers: {
                'Authorization': 'Bearer '+ accessToken
            },
            url: OneDriveURL,
            data : payload
        })
        .done(function( response ) {
            successCallback(response);
        })
        .fail(function(resultat, status, error) {
            failureCallback(resultat);
        });
    }); 
};

var getMessageItemId = async function(){
    return new Promise((successCallback, failureCallback) => {
        mailboxItem.getItemIdAsync(function(asyncResult){
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                failureCallback(asyncResult.error.message);
            } else {
                successCallback(asyncResult.value);
            }
        });
    });  
};

var addReferenceAttachment = async function(itemId, attachmentName){
    return new Promise((successCallback, failureCallback) => {
        mailboxItem.addItemAttachmentAsync(itemId, attachmentName, {}, function(asyncResult){
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                failureCallback(asyncResult.error.message);
            } else {
                successCallback(asyncResult);
            }
        });
    });
};

Code of the third method :

var messageId = await getMessageItemId();
await uploadAttachmentUsingEWSAPI(messageId);

var uploadAttachmentUsingEWSAPI = async function (messageId){
    var request = 
    '<?xml version="1.0" encoding="utf-8"?>'+
    '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'+
    '               xmlns:m="https://schemas.microsoft.com/exchange/services/2006/messages"'+
    '               xmlns:t="https://schemas.microsoft.com/exchange/services/2006/types"'+
    '               xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">'
    '  <soap:Header>'
    '    <t:RequestServerVersion Version="Exchange2007_SP1" />'
    '    <t:TimeZoneContext>'
    '      <t:TimeZoneDefinition Id="Central Standard Time" />'
    '    </t:TimeZoneContext>'
    '  </soap:Header>'
    '  <soap:Body>'
    '    <m:CreateAttachment>'
    '      <m:ParentItemId Id="'+ messageId +'" />'
    '      <m:Attachments>'
    '        <t:FileAttachment>'
    '          <t:Name>FileAttachment.txt</t:Name>'
    '          <t:Content>VGhpcyBpcyBhIGZpbGUgYXR0YWNobWVudC4=</t:Content>'
    '        </t:FileAttachment>'
    '      </m:Attachments>'
    '    </m:CreateAttachment>'
    '  </soap:Body>'
    '</soap:Envelope>';

    console.log(request);
    return sendEWSRequest(request);
};

var sendEWSRequest = async function(request){
    return new Promise((successCallback, failureCallback) => {
        Office.context.mailbox.makeEwsRequestAsync(request, function(asyncResult){
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
                failureCallback(asyncResult.error.message);
            } else {
                successCallback(asyncResult);
            }
        });
    });
};

None of the three methods works. Is there a way to upload a cloud attachment like this one ? :

enter image description here

If yes, what is the method to use ?

Regards



from Outlook Plugin upload FileReference as attachment

Animated interactive vibrating string using python

I would like to plot an animated vibrating string using python but to be able to play it and to control the parameters used during the vibration (much like this Desmos calculation). So far, this is my code:

from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import matplotlib as mpl

%matplotlib inline

def f(n=1, v=0.2, L=2, t=0):
    x = np.linspace(0, L, 2001)
    func = np.sin((n*np.pi*x)/L)*np.cos((n*np.pi*v*t)/L)

    
    plt.figure(figsize=(6,6))
    ax1 = plt.plot(x, func)
    plt.show()

interactive_plot = interactive(f, n=(0, 10, 1), v=(0.2, 5, 0.1), L=(0.2, 2, 0.1), t=(0, 10, 1))
output = interactive_plot.children[-1]
interactive_plot

I can control the wavefunction and all parameters, but I am not sure about what is the easiest way to animate it.

So far, I know that matplotlib can do it, but I am wondering if we have a more straightforward way to do animated interactive plots (using another package, maybe?).

Thanks in advance for any help.



from Animated interactive vibrating string using python

How to generate python code during a build and include those in a python wheel?

We have a package that generates code by means of

$PYTHON -m grpc_tools.protoc -I="foo_proto" --python-out="$package/out" \
         --grpc_python_out="$package/out" ./path/to/file.proto

This was integrated (read hacked) into our setup.py building by means of:

from distutils.command.build_py import build_py

class BuildPyCommand(build_py):
    """
    Generate GRPC code before building the package.
    """
    def run(self):
        import subprocess
        subprocess.call(["./bin/generate_grpc.sh", sys.executable], shell=True)
        build_py.run(self)

setup(
      ....
      cmdclass={
        'build_py': BuildPyCommand
    },
)

Which ugly as is, seems to work when building with the legacy setup.py, but when the package is built with wheel it doesn't work at all.

How can I make this work when installing my package by means of wheel?



from How to generate python code during a build and include those in a python wheel?

Vue CLI Module Federation is component is not found in the Host App

im implementing Module Federation in two Vue CLI Projects

Container App at: http://localhost:8082/ Component App at: http://localhost:8083/ I set up the ModuleFederation plugin in both apps, dont think there is a Problem with That: Component:

plugins: [
    new ModuleFederationPlugin({
        name: "data",
        filename: "remoteEntry.js",
        remotes: {},
        exposes: {
            './Bata' : './src/Bata.vue',

        },
        shared: {}
    }),
],

Container:

plugins: [
    new ModuleFederationPlugin({
        name: "appcontainer",
        filename: "remoteEntry.js",
        remotes: {
            "data" : "data@http://localhost:8083/remoteEntry.js" // Test app url see above
        },
        exposes: {},
        shared: {}
    }),
],

The components is getting served under: http://localhost:8083/remoteEntry.js: enter image description here

The Problem i encounter is when i try to use the component in the Container App:

enter image description here

It seems like the component is not found, what i noticed tho the request for the container goes to the Container app not to the Component app. Not sure if thats a problem or a normal behavior and something else is not working correctly.

enter image description here

8082 is the Container app, if i open the same url with 8083 (Component app) the component is there.

enter image description here



from Vue CLI Module Federation is component is not found in the Host App

Calculate xarray dataarray from coordinate labels

I have an DataArray with two variables (meteorological data) over time,y,x coordinates. The x and y coordinates are in a projected coordinate system (EPSG:3035) and aligned so that each cell covers pretty much exactly a standard cell of the 1km LAEA reference grid

I want to prepare the data for further use in Pandas and/or database tables, so I want to add the LAEA Gridcell Number/Label which can be calculated from x and y directly via the following (pseudo) function

def func(cell):
    return r'1km{}{}'.format(int(cell['y']/1000), int(cell['x']/1000))      # e.g. 1kmN2782E4850

But as far as I can see there seems to be no possibility, to apply this function to a DataArray or DataSet in a way so that I have access to these coordinate variables (at least .apply_ufunc() wasn't really working for me.

I am able to calc this on Pandas later on, but some of my datasets consists of 60 up to 120 Mio. Cells/Rows/datasets and pandas (even with Numba) seems to have troubles with that amount. On the xarray I am able to process this on 32 Cores via Dask.

I would be grateful on any advice on how to get this working.

EDIT: Some more insights of the data I`m working with:

This one is quite the largest with 500 Mio cells, but I am able to downsample this to squarekilometer resolution which ends up with about 160 Mio. cells

Xarray "vci" with monthly Vegetation Condition Indices over some decades

If the dataset is small enough, I am able to export it as a pandas dataframe and calculate there, but thats slow and not very robust as the kernel is crashing quite often

same calc in pandas



from Calculate xarray dataarray from coordinate labels

Espresso Mock Web Server not waiting OkHttp Idling Resource with Dagger Hilt

I am trying to write UI test for my Fragments with Espresso and MockWebServer. I am using OkHttp Idling Resource to tell Espresso to wait for the API calls to complete.

But somehow, sometimes my tests are working but sometimes not, because Espresso does its job before service request. So my recyclerView item click test fail.

I can not figure out why espresso does not wait for the API calls? Can anyone help?

Here is my test class

@MediumTest
@HiltAndroidTest
@UninstallModules(PersistenceModule::class, NetworkModule::class)
class MainFragmentTest {

    @get:Rule
    var hiltRule = HiltAndroidRule(this)

    private val mockWebServer = MockWebServer()

    @Inject
    lateinit var okHttp3IdlingResource: OkHttp3IdlingResource

    @Before
    fun setUp() {
        hiltRule.inject()
        // Prepare Mock Web Server
        mockWebServer.start(8080)
        IdlingRegistry.getInstance().register(okHttp3IdlingResource)
    }

    @Test
    fun mainFragmentTest(){

        // Prepare Mock Web Server
        mockWebServer.dispatcher = object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                return MockResponse()
                    .setResponseCode(200)
                    .setBody(MockResponseFileReader("post_success.json").content)
            }
        }

        val navController = mockk<NavController>(relaxed = true)

        launchFragmentInHiltContainer<MainFragment> {
            Navigation.setViewNavController(requireView(), navController)
        }

        onView(withId(R.id.rv_posts)).perform(
            RecyclerViewActions.actionOnItemAtPosition<PostViewHolder>(
                0,
                click()
            )
        )


        verify { navController.navigate(MainFragmentDirections.actionMainFragmentToDetailFragment().setPost(any())) }
    }

    @After
    fun tearDown() {
        mockWebServer.close()
    }

}

Here is my TestNetworkModule that holds network dependencies

@Module
@InstallIn(SingletonComponent::class)
object TestNetworkModule {

    /**
     * Provides [OkHttpClient] instance
     */
    @Provides
    @Singleton
    fun provideOkHttpClient() : OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .build()
    }

    /**
     * Provides [OkHttp3IdlingResource] instance
     */
    @Provides
    @Singleton
    fun provideIdlingResource(okHttpClient: OkHttpClient) : OkHttp3IdlingResource {
        return OkHttp3IdlingResource.create(
            "okhttp",
            okHttpClient
        )
    }

    /**
     * Provides [Retrofit] instance
     */
    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient) : Retrofit {
        val contentType = "application/json".toMediaType()
        return Retrofit.Builder()
            .baseUrl("http://127.0.0.1:8080")
            .client(okHttpClient)
            .addConverterFactory(Json.asConverterFactory(contentType))
            .build()
    }

    /**
     * Provides [ApiService] instance
     */
    @Provides
    @Singleton
    fun provideApiService(retrofit: Retrofit): ApiService {
        return retrofit.create(ApiService::class.java)
    }

}

I do not know what I am missing so any help will be appreciated

Current Versions;

androidTestImplementation "com.squareup.okhttp3:mockwebserver:4.6.0"
androidTestImplementation 'com.jakewharton.espresso:okhttp3-idling-resource:1.0.0'


from Espresso Mock Web Server not waiting OkHttp Idling Resource with Dagger Hilt

How to exit infinite JS execution loop when reading/loading Javascript in Java using GraalVM?

I found sandbox options as a way to set sandbox.MaxCPUTime in the graalVM documentation, to limit how long the thread runs - https://www.graalvm.org/reference-manual/embed-languages/

I've tried the following code -

                try (Context context = Context.newBuilder("js")
                        .allowExperimentalOptions(true)
                        .option("sandbox.MaxCPUTime", "10s")
                        .option("sandbox.MaxCPUTimeCheckInterval", "5ms")
                        .build())
                {
                    try {
                        context.eval("js", "while(true);");
                        assert false;
                    } catch (PolyglotException e) {
                        // Triggered after 500ms;
                        // Context is closed and can no longer be used
                        // Error message: Maximum CPU time limit of 500ms exceeded.
                        assert e.isCancelled();
                        assert e.isResourceExhausted();
                    }
                    context.close(true);
                }

This has been failing for me with the error -

java.lang.IllegalArgumentException: Could not find option with name sandbox.MaxCPUTime.

Is there a better way to achieve this or a way I can make these sandbox options work?



from How to exit infinite JS execution loop when reading/loading Javascript in Java using GraalVM?

React Native - Android PlayStore not returning product ids

I'm implementing an In-App purchase in React Native. I'm calling getSubscriptions function which returning an empty array for my ids that are added in the play store in-app -purchase panel. How to get product ids in my react-native app so I can continue the purchase process. Working fine in iOS but issue in Android only.



from React Native - Android PlayStore not returning product ids

Double sided input slider in React

I have an almost working solution in the sandbox linked in the update below, you should start with this.


I have one that's created without using React (Click "Run Code Snippet")

var thumbsize = 14;

function draw(slider,splitvalue) {

    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var thumbsize = parseInt(slider.getAttribute('data-thumbsize'));
    var rangewidth = parseInt(slider.getAttribute('data-rangewidth'));
    var rangemin = parseInt(slider.getAttribute('data-rangemin'));
    var rangemax = parseInt(slider.getAttribute('data-rangemax'));

    /* set min and max attributes */
    min.setAttribute('max',splitvalue);
    max.setAttribute('min',splitvalue);

    /* set css */
    min.style.width = parseInt(thumbsize + ((splitvalue - rangemin)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    max.style.width = parseInt(thumbsize + ((rangemax - splitvalue)/(rangemax - rangemin))*(rangewidth - (2*thumbsize)))+'px';
    min.style.left = '0px';
    max.style.left = parseInt(min.style.width)+'px';
    
    /* correct for 1 off at the end */
    if(max.value>(rangemax - 1)) max.setAttribute('data-value',rangemax);

    /* write value and labels */
    max.value = max.getAttribute('data-value'); 
    min.value = min.getAttribute('data-value');

}

function init(slider) {
    /* set function vars */
    var min = slider.querySelector('.min');
    var max = slider.querySelector('.max');
    var rangemin = parseInt(min.getAttribute('min'));
    var rangemax = parseInt(max.getAttribute('max'));
    var avgvalue = (rangemin + rangemax)/2;

    /* set data-values */
    min.setAttribute('data-value',rangemin);
    max.setAttribute('data-value',rangemax);
    
    /* set data vars */
    slider.setAttribute('data-rangemin',rangemin); 
    slider.setAttribute('data-rangemax',rangemax); 
    slider.setAttribute('data-thumbsize',thumbsize); 
    slider.setAttribute('data-rangewidth',slider.offsetWidth);

    /* draw */
    draw(slider,avgvalue);

    /* events */
    min.addEventListener("input", function() {update(min);});
    max.addEventListener("input", function() {update(max);});
}

function update(el){
    /* set function vars */
    var slider = el.parentElement;
    var min = slider.querySelector('#min');
    var max = slider.querySelector('#max');
    var minvalue = Math.floor(min.value);
    var maxvalue = Math.floor(max.value);
    
    /* set inactive values before draw */
    min.setAttribute('data-value',minvalue);
    max.setAttribute('data-value',maxvalue);

    var avgvalue = (minvalue + maxvalue)/2;

    /* draw */
    draw(slider,avgvalue);
}

var sliders = document.querySelectorAll('.min-max-slider');
sliders.forEach( function(slider) {
    init(slider);
});
.min-max-slider {
  position: relative;
  width: 200px;
  text-align: center;
  margin-bottom: 50px;
 }

.min-max-slider > label {
  display: none;
 }
 
.min-max-slider > input {
  cursor: pointer;
  position: absolute;
}


/* webkit specific styling */
.min-max-slider > input {
  -webkit-appearance: none;
  outline: none!important;
  background: transparent;
  background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}

.min-max-slider > input::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  width: 14px; /* Set a specific slider handle width */
  height: 14px; /* Slider handle height */
  background: #eee; /* Green background */
  cursor: pointer; /* Cursor on hover */
  border: 1px solid gray;
  border-radius: 100%;
}

.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
<div class="min-max-slider" data-legendnum="2">
    <label for="min">Minimum price</label>
    <input id="min" class="min" name="min" type="range" step="1" min="0" max="3000" />
    <label for="max">Maximum price</label>
    <input id="max" class="max" name="max" type="range" step="1" min="0" max="3000" />
</div>

I've tried to create the same sort of component using React. But each thumbgrip can only slide to the mid-point, where as with the non-react example, the lesser slider simply can't be higher than the higher slider and vice versa.

I would also like some way to make the slider which outside the range of the thumbgrips a darker color.

var thumbsize = 14;

const Slider = ({min, max}) => {
    const avg = (min + max)/2;
  const width = 300
  const minWidth = thumbsize + ((avg - min)/(max - min))*(width - (2*thumbsize))
  const styles={
      min:{
        width: minWidth,
        left: 0
      },
      max:{
        width: thumbsize + ((max - avg)/(max - min))*(width - (2*thumbsize)),
        left: minWidth
      }
  }
  
    return (
    <div 
      class="min-max-slider"
      data-legendnum="2"
      data-rangemin={min}
      data-rangemax={max}
      data-thumbsize={thumbsize}
      data-rangewidth={width}
    >
      <label htmlFor="min">Minimum price</label>
      <input 
        id="min"
        className="min"
        style={styles.min}
        name="min"
        type="range"
        step="1"
        min={min}
        max={avg}
        data-value={min}
       />
      <label htmlFor="max">Maximum price</label>
      <input
        id="max"
        className="max"
        style={styles.max}
        name="max"
        type="range"
        step="1"
        min={avg}
        max={max}
        data-value={max}
       />
    </div>
  )
}

ReactDOM.render(<Slider min={300} max={3000} />, document.querySelector("#root"))
 



.min-max-slider {
  position: relative;
  width: 200px;
  text-align: center;
  margin-bottom: 50px;
 }

.min-max-slider > label {
  display: none;
 }
 
.min-max-slider > input {
  cursor: pointer;
  position: absolute;
}


/* webkit specific styling */
.min-max-slider > input {
  -webkit-appearance: none;
  outline: none!important;
  background: transparent;
  background-image: linear-gradient(to bottom, transparent 0%, transparent 30%, silver 30%, silver 60%, transparent 60%, transparent 100%);
}

.min-max-slider > input::-webkit-slider-thumb {
  -webkit-appearance: none; /* Override default look */
  appearance: none;
  width: 14px; /* Set a specific slider handle width */
  height: 14px; /* Slider handle height */
  background: #eee; /* Green background */
  cursor: pointer; /* Cursor on hover */
  border: 1px solid gray;
  border-radius: 100%;
}

.min-max-slider > input::-webkit-slider-runnable-track {cursor: pointer;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

UPDATE

Using lissetdm's solution below, I have been able to create a double sided slider, which you can view on this sandbox, but there are still a few problems with it.

  1. The orange doesn't always look like it overlaps the gray

enter image description here

Sometimes, unpredictably, this difference is very noticeable

enter image description here enter image description here

  1. When both thumb pieces are dragged to the edges, the one pushes the other down

enter image description here

  1. I can't seem to remove this outline, which doesn't always appear

enter image description here


I have tested this out in firefox



from Double sided input slider in React

Cannot pre-populate room database when changing schema

I am at my wits end with a problem I cannot resolve - when trying to change the schema/data of a table in my database. I am pre-populating the database with Rooms .createFromAsset method.

Current schema and data (working) - as shown in DB Browser - this is the database used to Pre-Populate the apps database. enter image description here

enter image description here

As I build the database with this code:

 val instance = Room.databaseBuilder(
                context.applicationContext,
                MetarDatabase::class.java,
                "metar_database"
            )
                    .createFromAsset("database/metar_database.db")
                    .fallbackToDestructiveMigration()
                    .build()

And this data class:

    @Entity(tableName = "airport_table")
data class Airport(
    @PrimaryKey(autoGenerate = false)
    val icao : String,
    val name : String?,
    val municipality : String?,
    val scheduled : Boolean,
    val iata : String?
)

It successfully pre-populates the database into the app: as seen on Database Explorer: enter image description here



The problem is this: If I try and change the schema at all: adding columns, removing columns (done by changing a csv file and importing into a new table in DB Browser, then re-naming to airport_table and adding one to the database version), it does not load the data.

Eg: (Does NOT pre-populate):

 @Entity(tableName = "airport_table")
data class Airport(
    @PrimaryKey(autoGenerate = false)
    val icao : String,
    val name : String?
)

enter image description here enter image description here enter image description here I get NO errors apart from "E/libc: Access denied finding property "ro.serialno"" which I don't think is relevant.

In addition - changing this one table means that my other table does not pre-populate. However the empty database has still been made successfully, and I can add to it within the app.

Please help me - I've looked around stack overflow for similar questions. Some are similar, but involve getting anything to happen at all - my problem is it only works with one exact schema that I happen to succeed with whilst testing - but I want another schema.

Thanks a lot, Liam



from Cannot pre-populate room database when changing schema

Date-fns is returning incorrect dates

I have a collection of date strings stored in a database in this format:

2018-06-28T14:06:26.524Z

2018-07-02T10:32:18.818Z

2018-07-06T15:08:50.233Z

I need to convert these dates into a format like this on the frontend:

28 June 2018 14:06:26

02 July 2018 10:32:18

06 July 2018 08:50:23

My attempt at doing this using date-fns is:

format(new Date(date), 'dd MMMM yyyy HH:MM:ss')

The problem is that the dates returned from the above are incorrect:

2018-06-28T14:06:26.524Z returns 28 June 2018 15:06:26

2018-07-02T10:32:18.818Z returns 02 July 2018 11:07:18

2018-07-06T15:08:50.233Z returns 06 July 2018 16:07:50

What am I doing wrong here and how to I fix this so the dates are returned correctly?



from Date-fns is returning incorrect dates

Using apscheduler with asyncpg db as Job Store: Error MissingGreenlet

I'm trying to use Apscheduler with a postgresql db via an asyncpg connection. I thought it would working, because asyncpg supports sqlalchemy ref. But yeah, it isn't working. And to make it even worst, I don't understand the error message, so I have not even a guess what to google for.

import asyncio
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore

def simple_job():
    print('This was an easy job!')

scheduler = AsyncIOScheduler()
jobstore = SQLAlchemyJobStore(url='postgresql+asyncpg://user:password@localhost:5432/public')
scheduler.add_jobstore(jobstore)
# schedule a simple job
scheduler.add_job(simple_job, 'cron', second='15', id='heartbeat',
    coalesce=True, misfire_grace_time=5, replace_existing=True)
scheduler.start()

Versions:

python 3.7
APScheduler==3.7.0
asyncpg==0.22.0
SQLAlchemy==1.4.3

Error Message and traceback:

Traceback (most recent call last):
  File "C:/Users/d/PycharmProjects/teamutils/utils/automation.py", line 320, in <module>
    scheduler.start()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\apscheduler\schedulers\asyncio.py", line 45, in start
    super(AsyncIOScheduler, self).start(paused)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\apscheduler\schedulers\base.py", line 163, in start
    store.start(self, alias)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\apscheduler\jobstores\sqlalchemy.py", line 68, in start
    self.jobs_t.create(self.engine, True)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 940, in create
    bind._run_ddl_visitor(ddl.SchemaGenerator, self, checkfirst=checkfirst)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2979, in _run_ddl_visitor
    with self.begin() as conn:
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2895, in begin
    conn = self.connect(close_with_result=close_with_result)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3067, in connect
    return self._connection_cls(self, close_with_result=close_with_result)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 91, in __init__
    else engine.raw_connection()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3146, in raw_connection
    return self._wrap_pool_connect(self.pool.connect, _connection)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\base.py", line 3113, in _wrap_pool_connect
    return fn()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 301, in connect
    return _ConnectionFairy._checkout(self)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 755, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 419, in checkout
    rec = pool._do_get()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 145, in _do_get
    self._dec_overflow()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 72, in __exit__
    with_traceback=exc_tb,
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\util\compat.py", line 198, in raise_
    raise exception
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\impl.py", line 142, in _do_get
    return self._create_connection()
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 247, in _create_connection
    return _ConnectionRecord(self)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 362, in __init__
    self.__connect(first_connect_check=True)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 605, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 72, in __exit__
    with_traceback=exc_tb,
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\util\compat.py", line 198, in raise_
    raise exception
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\pool\base.py", line 599, in __connect
    connection = pool._invoke_creator(self)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\create.py", line 578, in connect
    return dialect.connect(*cargs, **cparams)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\engine\default.py", line 548, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\dialects\postgresql\asyncpg.py", line 744, in connect
    await_only(self.asyncpg.connect(*arg, **kw)),
  File "C:\Users\d\PycharmProjects\teamutils\venv\lib\site-packages\sqlalchemy\util\_concurrency_py3k.py", line 48, in await_only
    "greenlet_spawn has not been called; can't call await_() here. "
sqlalchemy.exc.MissingGreenlet: greenlet_spawn has not been called; can't call await_() here. Was IO attempted in an unexpected place? (Background on this error at: http://sqlalche.me/e/14/xd2s)
sys:1: RuntimeWarning: coroutine 'connect' was never awaited

I looked up the provided link, but not getting smart of it. So it would be nice, if somebody can tell me what is going on, so I can search for a solution by my own. (a solution would okay too, of course xD)

Sorry for this "open" question, but my understanding is so bad, that I dont know what to ask for.



from Using apscheduler with asyncpg db as Job Store: Error MissingGreenlet

logcat error : E/ExtMediaPlayer-JNI: env->IsInstanceOf fails

I am trying to get Album art for every song in my music player app. But I get nothing except a black screen, no album covers.It seems there are no errors as such in the code except log cat errors which I have never heard of.

Here is the Java file which contains the listener for button click. As soon I click the Button In my app I get an error in logcat : Bacon1.java

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;


public class Bacon1 extends Activity {

    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 1;
    private static int RESULT_LOAD_IMAGE = 1;
    public ArrayList<HashMap<String, String>> songsList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bacon1);


        Button button4 = (Button) findViewById(R.id.button4);

        button4.setOnClickListener(
                new Button.OnClickListener()

                {
                    public void onClick(View v) {
                        buttonClicked(v);

                       Intent p = new Intent(Bacon1.this,PlayListActivity.class);
                        startActivity(p);

                    }
                });
    }

    private void buttonClicked(View view) {

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
                .checkSelfPermission(this,
                        Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }


    }


    public void onClick2(View view) {

        Intent i = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        startActivityForResult(i, RESULT_LOAD_IMAGE);
    }


    public void onClick4(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "video/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick5(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "zip/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick6(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "text/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }

    public void onClick7(View view) {

        Intent viewIntent1 = new Intent(Intent.ACTION_VIEW);
        File file = Environment.getExternalStorageDirectory();
        viewIntent1.setDataAndType(Uri.fromFile(file), "application/*");
        startActivity(Intent.createChooser(viewIntent1, null));
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();




                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }


    }

Here is the Logcat :

07-11 17:11:04.222 13978-13978/com.example.dell_1.myapp3 E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
07-11 17:11:04.222 13978-13978/com.example.dell_1.myapp3 E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0
07-11 17:11:04.222 13978-13978/com.example.dell_1.myapp3 E/ExtMediaPlayer-JNI: env->IsInstanceOf fails
07-11 17:11:04.222 13978-13978/com.example.dell_1.myapp3 E/MediaPlayer-JNI: JNIMediaPlayerFactory: bIsQCMediaPlayerPresent 0

Here is the file which is responsible for displaying songs as listview : PlayListActivity.java

package com.example.dell_1.myapp3;


import android.app.Activity;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import java.io.File;
import java.io.IOException;

import com.bumptech.glide.Glide;


public class PlayListActivity extends Activity {

    private String[] mAudioPath;
    private MediaPlayer mMediaPlayer;
    private String[] mMusicList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_list);

        mMediaPlayer = new MediaPlayer();
        ListView mListView = (ListView) findViewById(R.id.list);

        mMusicList = getAudioList();

        ArrayAdapter<String> mAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, mMusicList);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                                    long arg3) {

                try {
                    playSong(mAudioPath[arg2]);
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private String[] getAudioList() {
        final Cursor mCursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA}, null, null,
                "LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");

        int count = mCursor.getCount();

        String[] songs = new String[count];
        mAudioPath = new String[count];
        int i = 0;
        if (mCursor.moveToFirst()) {
            do {
                songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                i++;
            } while (mCursor.moveToNext());
        }

        mCursor.close();

        return songs;
    }

    private void playSong(String path) throws IllegalArgumentException,
            IllegalStateException, IOException {

        setContentView(R.layout.activity_android_building_music_player);
        Log.d("ringtone", "playSong :: " + path);

        mMediaPlayer.reset();
        mMediaPlayer.setDataSource(path);
//mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.start();

        asd();

    }

    public void asd() {
        ImageView imageView = (ImageView) findViewById(R.id.coverart);


        File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        // Tested with music from Windows 7's c:\Users\Public\Music\Sample Music
        String filePath = new File(music, "I love you.mp3").getAbsolutePath();
        Glide
                .with(this)
                .load(new AudioCover(filePath))
                .placeholder(R.drawable.adele1)
                .error(R.drawable.adele1)
                .into(imageView);
    }
}

This is the xml file : activity_play_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#242424"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />

</LinearLayout>

activity_android_building_music_player.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:id="@+id/player_header_bg"
        android:layout_width="fill_parent"
        android:layout_height="60dip"
        android:layout_alignParentTop="true"
        android:background="@layout/bg_player_header"
        android:paddingLeft="5dp"
        android:paddingRight="5dp">

        <TextView
            android:id="@+id/songTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_weight="1"
            android:paddingLeft="50dp"
            android:text="The Good, The Bad And The Ugly"
            android:textColor="#04b3d2"
            android:textSize="16dp"
            android:textStyle="bold" />

        <ImageButton
            android:id="@+id/btnPlaylist"
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:background="@null"
            android:src="@drawable/btn_playlist" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/songThumbnail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/player_header_bg"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:gravity="center"
        android:paddingBottom="10dp"
        android:paddingTop="10dp">

        <ImageView
            android:id="@+id/coverart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/player_footer_bg"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="@layout/bg_player_footer"
        android:gravity="center">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:weightSum="1">
            <RelativeLayout
                android:layout_width="300dp"
                android:layout_height="match_parent">
                <ImageButton
                    android:id="@+id/btnPrevious"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="2.40"
                    android:layout_alignParentLeft="true"
                    android:paddingLeft="10dp"
                    android:background="@null"
                    android:src="@drawable/btn_previous" />

                <ImageButton
                    android:id="@+id/btnPlay1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:background="@null"
                    android:src="@drawable/btn_play"
                    android:onClick="buttonAction1"/>


                <ImageButton
                    android:id="@+id/btnNext"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:paddingLeft="250dp"
                    android:background="@null"
                    android:src="@drawable/btn_next" />
            </RelativeLayout>
        </LinearLayout>
    </LinearLayout>

    <SeekBar
        android:id="@+id/songProgressBar"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/player_footer_bg"
        android:layout_alignLeft="@+id/timerDisplay"
        android:layout_alignStart="@+id/timerDisplay"
        android:layout_marginBottom="10dp"
        android:paddingLeft="6dp"
        android:paddingRight="6dp"
        android:progressDrawable="@drawable/seekbar_progress"
        android:thumb="@drawable/download8" />

    <LinearLayout
        android:id="@+id/timerDisplay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/songProgressBar"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp">

        <TextView
            android:id="@+id/songCurrentDurationLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="left"
            android:textColor="#eeeeee"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/songTotalDurationLabel"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="right"
            android:textColor="#04cbde"
            android:textStyle="bold" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/timerDisplay"
        android:gravity="center">

        <ImageButton
            android:id="@+id/btnRepeat"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="5dp"
            android:background="@null"
            android:src="@drawable/btn_repeat" />

        <ImageButton
            android:id="@+id/btnShuffle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:background="@null"
            android:src="@drawable/btn_shuffle" />
    </LinearLayout>
</RelativeLayout>


from logcat error : E/ExtMediaPlayer-JNI: env->IsInstanceOf fails

How to convert mp3 to the sound wave image using javascript

I have a requirement in my project to convert mp3 audio to an image containing the waves for that mp3. Something like

enter image description here

Can I do this using javascript(specially nodejs)? Kindly help



from How to convert mp3 to the sound wave image using javascript

How to detect Caps Lock is ON on web browser on Android Devices using JavaScript?

We can very well detect CapsLock is ON/not on iPhone web browser using KeyboardEvent.getModifierState(), with sample code,

function checkCapsLock(e) {
  if (e.getModifierState("CapsLock")) {
    alert("Caps ON");
  }
}

But it doesn't work on a browser on Android Devices. I've tried many other solutions using charCode, keyCode, shiftKey, which, etc. methods on the event with listeners like keyup, keydown, keypress, etc. But no luck.

I've gone through the answers mentioned on stackoverflow, and other links too. But still no luck.

Is there any workaround for this?

PS: This is not a duplicate question, I'm asking about the issue on the Android web browser!

EDIT: On W3C, we can observe that CapsLock can be detected on Web or mobile web browser on iPhone, but not on a web browser on Android devices.



from How to detect Caps Lock is ON on web browser on Android Devices using JavaScript?

Expanding a User model property in Jenkins REST API

I am trying to extract last login details of a user by using Jenkins REST APIs, upon querying for the URL https://jenkinsurl/user/someusername/api/json I receive a response similar to the one shown below.

{
      "_class" : "hudson.model.User",
      "absoluteUrl" : "https://jenkinsurl/user/someusername",
      "description" : null,
      "fullName" : "someusername",
      "id" : "someusernameid",
      "property" : [
        {
          "_class" : "someProperty1"
        },
        {
          "_class" : "someProperty2"
        },
        
        {
          "_class" : "org.jenkinsci.plugins.saml.user.LoginDetailsProperty"
        },
      ]
    }

Now the details I am looking for are under LoginDetailsProperty which can be found in the source here. I have seen the details been used in the Jenkins UI when I open user/someusername/configure to modify user details or create access token. How can I expand the LoginDetailsProperty and extract the lastLoginTimestamp value for a particular user using REST APIs?



from Expanding a User model property in Jenkins REST API

Android Studio: Server's certificate is not trusted - issued by apple

Android studio, show me this dialog:

enter image description here

and after accepting that, it's show again after few seconds, i try automatic accepting, but android studio don't care about this , i read other topics before creating new topic, like:

Android Studio: Server's certificate is not trusted

Why is "Server's certificate is not trusted" is showing on Android studio?

one of them talk about kaspersky antivirus and another one suggested auto accepting and these topics not resolved my problem

i use android studio 4.1.2 on macOS Big Sure 11.2.3


and maybe my another problem is not far away from this one:

Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

details:

> Task :prepareKotlinBuildScriptModel UP-TO-DATE
IOException: https://dl.google.com/android/repository/addons_list-3.xml
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
IOException: https://dl.google.com/android/repository/addons_list-2.xml
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
IOException: https://dl.google.com/android/repository/addons_list-1.xml
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Failed to download any source lists!
IO exception while downloading manifest:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
    at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:167)
    at com.android.sdklib.repository.legacy.remote.internal.DownloadCache.openUrl(DownloadCache.java:247)
    at com.android.sdklib.repository.legacy.remote.internal.DownloadCache.downloadAndCache(DownloadCache.java:624)
    at com.android.sdklib.repository.legacy.remote.internal.DownloadCache.openCachedUrl(DownloadCache.java:455)
    at com.android.sdklib.repository.legacy.LegacyDownloader.downloadAndStream(LegacyDownloader.java:61)
    at com.android.repository.impl.downloader.LocalFileAwareDownloader.downloadAndStream(LocalFileAwareDownloader.java:51)
    at com.android.repository.impl.manager.RemoteRepoLoaderImpl.lambda$fetchPackages$0(RemoteRepoLoaderImpl.java:139)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:450)
    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:317)
    at sun.security.validator.Validator.validate(Validator.java:262)
    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:330)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:237)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1621)
    ... 21 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:445)
    ... 27 more

Still waiting for package manifests to be fetched remotely.
<ij_msg_gr>Gradle import errors<ij_msg_gr><ij_nav>/Users/shahriyar/MyFiles/Projects/Android/Other/CakeMake/app/build.gradle<ij_nav><i><b>project ':app': Unable to build Kotlin project configuration</b><eol>Details: org.gradle.api.internal.tasks.DefaultTaskContainer$TaskCreationException: Could not create task ':app:minifyReleaseWithR8'.<eol>Caused by: org.gradle.api.internal.provider.MissingValueException: Cannot query the value of this provider because it has no value available.</i>

when i try to sync gradle i got this error and this one took me 2 days (i never use minify or shirink or any things like that in this project and this happen to all of projects i try to sync, not just my projects)



from Android Studio: Server's certificate is not trusted - issued by apple

Why does [NaN].includes(NaN) return true in JavaScript?

I'm familiar with NaN being "weird" in JavaScript, i.e., NaN === NaN always returns false, as described here. So one should not make === comparisons to check for NaN, but use isNaN(..) instead.

So I was surprised to discover that

> [NaN].includes(NaN)
true

This seems inconsistent. Why have this behavior?

How does it even work? Does the includes method specifically check isNaN?



from Why does [NaN].includes(NaN) return true in JavaScript?

How to get the item view type of a SectionedRecyclerViewAdapter, properly?

I use this code to give header items in a RecyclerView a span of two columns using a GridLayoutManager:

MyAdapter myAdapter = new MyAdapter(this, items);
this.myRecyclerView.setAdapter(myAdapter);

GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch (myAdapter.getItemViewType(position)) {
            case -1: // VIEW_TYPE_ITEM
                return 1;
            default: // VIEW_TYPE_HEADER
                return 2;
        }
    }
});
this.myRecyclerView.setLayoutManager(layoutManager);

This works, but it complains about my usage of getItemViewType, because it's deprecated. My adapter extends SectionedRecyclerViewAdapter<RecyclerView.ViewHolder>.

What should I use, instead?

(Also, I don't know about the enum that I should use in the switch statement, instead, but this is a different story.)



from How to get the item view type of a SectionedRecyclerViewAdapter, properly?

Problem keeping a 3D cube correctly roll on its edges using rotate and translate

Please see my js Fiddle here: https://jsfiddle.net/mauricederegt/5ozqg9uL/3/

var xAngle = 0;
var yAngle = 0;
var xPos  = 0;
var yPos  = 0;

$('body').keydown(function(evt) {
    if(evt.keyCode == 37) 
    {
        //left
        yAngle -= 90;
        xPos -= 100;
        //rotate and translate the position of the cube
        $('#cube')[0].style["WebkitTransform"] = "translateX("+xPos+"px) translateY("+yPos+"px) rotateX(" + xAngle + "deg) rotateY(" + yAngle + "deg)";
    }
    if(evt.keyCode == 39) 
    {
        //right
        yAngle -= -90;
        xPos -= -100;
        //rotate and translate the position of the cube
        $('#cube')[0].style["WebkitTransform"] = "translateX("+xPos+"px) translateY("+yPos+"px) rotateX(" + xAngle + "deg) rotateY(" + yAngle + "deg)";
    }
    if(evt.keyCode == 38) 
    {
        //up
        xAngle -= -90;
        yPos -= 100;
        //rotate and translate the position of the cube
        $('#cube')[0].style["WebkitTransform"] = "translateX("+xPos+"px) translateY("+yPos+"px) rotateX(" + xAngle + "deg) rotateY(" + yAngle + "deg)";
    }
    if(evt.keyCode == 40) 
    {
        //down
        xAngle -= 90;
        yPos -= -100;
        //rotate and translate the position of the cube
        $('#cube')[0].style["WebkitTransform"] = "translateX("+xPos+"px) translateY("+yPos+"px) rotateX(" + xAngle + "deg) rotateY(" + yAngle + "deg)";
    }
});
#scene {
    padding: 10px;
    -webkit-perspective: 800;
}

#cube {
    position: relative;
    padding-top: 0;
    margin: 0 auto;
    height: 100px;
    width: 100px;
    -webkit-transition: -webkit-transform 0.4s linear;
    -webkit-transform-style: preserve-3d;

   
}

.face {
    position: absolute;
    height: 85px;
    width: 85px;
    border-style: solid;
    border-width: 5px;
    border-color: grey;
    padding: 5px;
    background-color: rgba(190, 190, 190, 0.7);
}

#cube .one  {
    -webkit-transform: rotateX(90deg) translateZ(50px);
}

#cube .two {
    -webkit-transform: translateZ(50px);
}

#cube .three {
    -webkit-transform: rotateY(90deg) translateZ(50px);
}

#cube .four {
    -webkit-transform: rotateY(180deg) translateZ(50px);
}

#cube .five {
    -webkit-transform: rotateY(-90deg) translateZ(50px);
}

#cube .six {
    -webkit-transform: rotateX(-90deg) translateZ(50px) rotate(180deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<body>
<div id="scene">
    Press the arrow keys...
    <div id="cube">
        <div class="face one">
            Face 1
        </div>
        <div class="face two">
            Face 2
        </div>
        <div class="face three">
            Face 3
        </div>
        <div class="face four">
            Face 4
        </div>
        <div class="face five">
            Face 5
        </div>
        <div class="face six">
            Face 6
        </div>
    </div>
</div>
</body>
</html>

As you can see I have a css3 3d cube which you can move by using your arrow keys. You can move it to the left, to the right, up and down. To achieve this I store the position and angle in various vars:

var xAngle = 0;
var yAngle = 0;
var xPos  = 0;
var yPos  = 0;

The cube always "rolls" correctly on its edges going up or down, but for left and right this is not always the case.

Example:

  1. At start press the left arrow key and the right as many times as you like. The cube behaves correctly
  2. Now press down once and then left twice (or right) again. The cube now rolls incorrectly
  3. BUT, if you press up or down again, it rolls correctly again going up or down

So the issue only seems to be with going left or right. How can I fix this?



from Problem keeping a 3D cube correctly roll on its edges using rotate and translate

Common Crawl data search all pages by keyword

I am wondering if it is possible to lookup a key word using the common crawl api in python and retrieve pages that contain the key word. For example, if I lookup "stack overflow" it will find the pages which the key word - "stack overflow" is in the HTML file. I have looked at the apis but I can only do URL lookup - not key word. Thank you for any responses in advance!



from Common Crawl data search all pages by keyword

React scroll to bottom only works for the first time (demo inside)

I have a react project where I am trying to implement infinite scroll, But not sure why it detects bottom only once, from next time onwards there is always 1 pixels difference in values so it never matches with element.clientHeight

Below is code that I am using to detect scroll to bottom

Math.ceil(element.scrollHeight - element.scrollTop) === element.clientHeight

Going forward I actually want to fire axios call 200 pixels before it reached to bottom so In the mean time I can fetch the data and append to bottom so user never have to wait for data to load.

I have created demo repo which has the same issue as my project CodeSandbox demo



from React scroll to bottom only works for the first time (demo inside)

How to display mat-menu after entering 3 characters in input field?

I'm implement this input field so that when I enter 3 characters I want to display mat-menu as a value of mat-option but for some reason the mat-menu never gets display. Can anyone point me in the right direction? thanks a lot in advance!

Here's LIVE DEMO

<mat-autocomplete #auto="matAutocomplete">
    <mat-option *ngIf="isSpinnerLoading">

  <div *ngIf="!menuContent">Loading...</div>
  <div *ngIf="menuContent">
    show menu

    <mat-menu #menu="matMenu" class="menu-select">
            <div (click)="$event.stopPropagation()">
                <div *ngFor="let item of myList">
                    <mat-checkbox
                        class="mat-menu-item">
                        
                    </mat-checkbox>
                </div>
            </div>
        </mat-menu>
  </div>
    </mat-option>
</mat-autocomplete>

This is what I'm trying to accomplish:

enter image description here



from How to display mat-menu after entering 3 characters in input field?

Why MDCSelect:change is not working with javascript for material design

Why MDCSelect:change is not working when i call it before appending all options

MDCSelect:change is working when i put it after appending list BUT UI does not look good.

Question: How to make MDCSelect:change to working without harming ui look.

It works perfectly when i shuffle the code of those 2 lines

$('#select_dropdown').html(usersStr);

initializeSelect();

With the above code select UI does not look good when you click outside anywhere or simply

for a better view, I have created codepen here: https://codepen.io/eabangalore/pen/poNmBpm?editors=1010

var selectBoxMap = {};
function initializeSelect(){
       var mdcSelectList = document.querySelectorAll(' .mdc-select');
        if(mdcSelectList){
            [].forEach.call(mdcSelectList,function(el){
                var select = new mdc.select.MDCSelect(el);
                el.setAttribute('ripple-attached', true);
                var dropDownId = $(el).find('ul.mdc-list').attr('id');
                selectBoxMap[dropDownId] = select;
            });
        }

}


$(async function(){

  var results = await $.get('https://jsonplaceholder.typicode.com/users');
var usersStr = '';
for(var i = 0; i < results.length; i++){
    var item = results[i];
           usersStr += `<li class="mdc-list-item" data-id="${item.id}" role="option">
                              <span class="mdc-list-item__ripple"></span>
                              <span class="mdc-list-item__text" data-id="${item.id}">
                                  ${item.name}
                              </span>
                          </li>`
}

initializeSelect();

$('#select_dropdown').html(usersStr);

     for(var key in selectBoxMap){
            if(selectBoxMap[key]){
              selectBoxMap[key].listen('MDCSelect:change', (e) => {
                  alert('dropdown changed');
              });
            }
        }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
  <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
 <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
 <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>

</head>


<!-- select dropdown -->

 <div class="mdc-select mdc-select--filled demo-width-class">
         <div class="mdc-select__anchor" role="button" aria-haspopup="listbox" aria-expanded="false">
                      <span class="mdc-select__ripple"></span>
                      <span class="mdc-floating-label">Status</span>
                      <span class="mdc-select__selected-text-container">
                        <span id="" class="mdc-select__selected-text"></span>
                      </span>
                      <span class="mdc-select__dropdown-icon">
                          <span class="mdc-select__dropdown-icon-inactive material-icons">arrow_drop_down</span>
                          <span class="mdc-select__dropdown-icon-active material-icons">arrow_drop_up</span>
                      </span>
                      <span class="mdc-line-ripple"></span>
                    </div>
                  
                    <div class="mdc-select__menu mdc-menu mdc-menu-surface mdc-menu-surface--fullwidth">
                      <ul class="mdc-list" id="select_dropdown"  role="listbox" aria-label="listbox">

                      </ul>
          </div>
   </div>

Still i'm looking for solution please help me thanks in advance!!



from Why MDCSelect:change is not working with javascript for material design

Python - Not Expecting Data by Unpacking Ethernet Frame Getting 0xc0a8 on Type Expecting 0x800

I have this Python function which unpacks ethernet frame:

ethernet frame

def ethernet_frame(data):
        ipheader = struct.unpack('!6s6sH', data[0:14])
        dest_mac = binascii.hexlify(ipheader[0])
        src_mac = binascii.hexlify(ipheader[1])
        proto = ""

        protoType = ipheader[2]
        nextProto = hex(protoType)
        
        print(nextProto)
        if(nextProto == '0x800'):
            proto = 'IPV4'
        elif(nextProto == '0x86dd'):
            proto = 'IPV6'
        print(nextProto)
        
        return dest_mac, src_mac, proto, data[14:]

I was expecting to get 0x800 for IPV4 or 0x86dd for IPV6. But after unpacking the frame I got 0xc0a8. Can someone explain why I'm getting this unexpected data? and how to fix it to get correct data?



from Python - Not Expecting Data by Unpacking Ethernet Frame Getting 0xc0a8 on Type Expecting 0x800

Tuesday, 30 March 2021

Ionic Input file capture file or memory is saved on mobile

So with my Ionic app I have some functionality to upload pictures. For taking or selecting these images I use two inputs:

 <input hidden="true" #fileCamera type="file" accept="image/*" capture="environment" (change)="uploadFile($event)">
 <input hidden="true" #fileGallery type="file" accept="image/*" (change)="uploadFile($event)">

When I run this code it works. With the #fileCamera it opens the camera and with the #fileGallery it opens the gallery.

But when I check my data from my android settings the data size keeps on increasing, when I use the fileinput with the capture="environment", so the one where it opens the camera. The size is increasing by approximately 2.4 MB so the size of a taken picture.

And when I use the other input (the gallery) it doesn't increase the size.

So I guess the pictures that are taken through the input and the app are getting saved somewhere, but I can't find them anywhere on my phone.

I don't know if it's a Ionic specific thing, but I can't find a solution. Is there some way to delete the file/image that is taken through the input?

This is my code which handles the file input:

    this.uploading = true;

    const eventObj: MSInputMethodContext = event as MSInputMethodContext;
    const target: HTMLInputElement = eventObj.target as HTMLInputElement;
    const file: File = target.files[0];

    this.media.uploadImageFile(file).then((attachment: Attachment) => {
      this.attachments.push(attachment);
    }).catch(() => this.translate.get('MESSAGES.ERROR').subscribe(msg => this.showToast(msg, 'danger')))
      .finally(() => this.uploading = false);


from Ionic Input file capture file or memory is saved on mobile