Wednesday, 30 September 2020

NodeJS testing datetimes with different times of the day and timezone

I have a situation that places today date in DB and I use vanilla code.

const todayCloseDate = new Date().toISOString().slice(0, 10);

This obviously introduces a problem with my timezone (CST) that after 5:00 PM date becomes the next day value. I changed handling to the package data-fns (moments.js is not an option).

const todayCloseDate = DF.format(new Date(), 'yyyy-MM-dd');

It works as expected. My question is how to unit test such change? It would require to make a change in system time of a local machine what locally run tests as well in any testing environment that would run tests in CI/CD pipeline (it would CircleCI, and Jenkins).

Would to start test scenario that would cover such bug and ensure fix? My test runner is Jest.



from NodeJS testing datetimes with different times of the day and timezone

Check if a large matrix is diagonal matrix in python

I have compute a very large matrix M with lots of degenerate eigenvectors(different eigenvectors with same eigenvalues). I use QR decomposition to make sure these eigenvectors are orthonormal, so the Q is the orthonormal eigenvectors of M, and Q^{-1}MQ = D, where D is diagonal matrix. Now I want to check if D is truly diagonal matrix, but when I print D, the matrix is too large to show all of them, so how can I know if it is truly diagonal matrix?



from Check if a large matrix is diagonal matrix in python

PHP Configuration Setting for 404 Errors

Our PHP installation is intercepting 404 Page Not Found errors and displaying this basic and generic 404 error message on pages with the .php extension:

File not found.

It is preventing the requestor from seeing our nicely formatted ERROR 404 Page.

How do I shut off the PHP setting to have the server use our Apache directives for 404's?



from PHP Configuration Setting for 404 Errors

ADB command toggles don't keep activities developer options setting but it has no real effect

As the title says, if I issue the following command

adb shell settings put global always_finish_activities 1

if I go to Developer Options, I can see that the toggle as changed from OFF to ON. Also, adb shell settings get global always_finish_activities outputs 1

The problem is that, although the setting has been turned ON, in fact, don't keep activities isn't doing what it is expected.

I only have the launcher and Chrome running and after I issue the ADB command, this is the stack that I have

enter image description here

On the other hand, if I do the same test and manually go to Developer Options settings and manually toggle the setting, this is the stack

enter image description here

Any idea how to bypass this?



from ADB command toggles don't keep activities developer options setting but it has no real effect

Catch any error in Python

Is it possible to catch any error in Python? I don't care what the specific exceptions will be, because all of them will have the same fallback.



from Catch any error in Python

Angular module fabric

I have a following module

@NgModule({
  declarations: [
    AgPaginationComponent,
    AgGridNoRowsComponent,
    // a huge list of components
  ],
  exports: [AgPaginationComponent, AgGridModule],
  imports: [
    CommonModule,
    InputsModule,
    FormsModule,
    NgbPaginationModule,
    NgbPopoverModule,
    AgGridModule.withComponents([
      AgGridNoRowsComponent,
      // the same huge list from declarations
    ]),
    PipesModule,
  ]
})
export class MyAgGridAddonsModule { }

You see here that it's possible to configure AgGridModule by specifying a list of components in withComponents array. The idea behind MyAgGridAddonsModule module was to create one module that I can use every time when I need to initialize AgGridModule. But turns out the module is growing too fast and has too many components under AgGridModule.withComponents declaration. Now I want to have a possibility to specify which dependencies I want to use each particular time but in the same time copy base configuration that is the same for every case.

I want to accomplish something like

@NgModule({
  imports: [
    MyAgGridAddonsModule.withComponents([
      MyAgInputFilter,
      MyAgLiveSearchFilter,
      MyAgSelectFilter,
      MyAgDateCellRenderer,
    ])
  ]
})
export class MyAnotherModule { }

And the array of components from MyAgGridAddonsModule.withComponents should be passed down to MyAgGridAddonsModule:

@NgModule({
  declarations: [
    AgPaginationComponent,
    AgGridNoRowsComponent,
    // components passed down from MyAnotherModule
  ],
  exports: [AgPaginationComponent, AgGridModule],
  imports: [
    CommonModule,
    InputsModule,
    FormsModule,
    NgbPaginationModule,
    NgbPopoverModule,
    AgGridModule.withComponents([
      // components passed down from MyAnotherModule
      AgGridNoRowsComponent
    ]),
    PipesModule,
  ]
})
export class MyAgGridAddonsModule { }

Is it even possible? Thanks.



from Angular module fabric

How to use AMAZON_COGNITO_USER_POOLS with apollo-client

I am trying to populate my jwtToken with the newer @aws-amplify packages and it is proving somewhat difficult.

When trying to run a Query I will get the following error: Uncaught (in promise) No current user

I can see from the source that if I have auth type set to AMAZON_COGNITO_USER_POOLS then I have to use a jwt token

        case AUTH_TYPE.AMAZON_COGNITO_USER_POOLS:
        case AUTH_TYPE.OPENID_CONNECT:
            const { jwtToken = '' } = auth;
            promise = headerBasedAuth({ header: 'Authorization', value: jwtToken }, operation, forward);

So this leads me to trying to generate my JWT token and this is where my knowledge fails me. I know that jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(), returns a promise as is required as seen in the above code... So I cannot see why this would fail?

_app.js (next.js)

import Amplify from '@aws-amplify/core'
import { Auth } from '@aws-amplify/auth'
import { ApolloProvider } from '@apollo/react-hooks'
import { ApolloLink } from 'apollo-link'
import { createAuthLink } from 'aws-appsync-auth-link'
import { InMemoryCache, ApolloClient } from '@apollo/client'
import { createHttpLink } from 'apollo-link-http'

import awsExports from '../aws-exports'

Amplify.configure(awsExports)
Auth.configure(awsExports)

const url = awsExports.aws_appsync_graphqlEndpoint
const region = awsExports.aws_appsync_region

const auth = {
  type: awsExports.aws_appsync_authenticationType,
  jwtToken: async () => (await Auth.currentSession()).getIdToken().getJwtToken(),
}
const link = ApolloLink.from([createAuthLink({ url, region, auth }), createHttpLink({ uri: url })])
const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
})

const MyApp = function ({ Component, pageProps, router }) {
  return (
        .....
          <ApolloProvider client={client}>
        .....
  )
}

export default MyApp


from How to use AMAZON_COGNITO_USER_POOLS with apollo-client

Getting path to file in published webcomponent

I have a webcomponent where i need to add a link tag to the head and set the href equal to a folder inside that node module.

Right now im in the building phase of this component where my structure look like this:

enter image description here

So i need to add the fontawsome.css script to the head of my page. ive created the following script:

  constructor() {
    super();
    if (!this.isFontAwesomeLoaded()) {
      this.iclass = '';
      const fontEl = document.createElement('link');
      fontEl.rel = 'stylesheet';    
      fontEl.href = "./fontawesome/css/all.css";
      document.head.appendChild(fontEl);    
    }
  }

Now there is a problem with this the path ./fontawesome/css/all.css wont work when it hits the head tag because the index.html file that attempts to load it doesnt have the folder in its project. instead when it hits product it needs to find the absoulte path to my module and then to the fontawesome folder.

My question is how can i get that path?



from Getting path to file in published webcomponent

Build on Xcode 12 showing 'Any iOS Device(armv7, arm64)'

I migrated my existing project to Xcode12. I had to remove VALID_ARCHS from Build Settings. And added arm64 for Excluded Architecture (Any iOS simulator SDK). Then I am able to run app on iOS14 simulator.

But now while creating archive it is showing.

Any iOS Device(armv7, arm64)

Please refer this screenshot.

enter image description here

In previous Xcode it was showing Generic iOS Device

Does this mean app will not support all iOS Phones?



from Build on Xcode 12 showing 'Any iOS Device(armv7, arm64)'

Sheetjs - Sheet add Json ignores date format

I have a JSON that contains some data and I want to export it to Excel. Problem is that I can not achieve the correct date format when saved to Excel. The date format that I want to achieve is something like that 2020-07-30 07:31:45

I followed the advise from this post but it didn't really help: sheetjs

The JSON:

{
  "source": "internal",
  "account": "Test",
  "posted_at": new Date("2020-09-25T07:11:19.0000000")
  "content": "some content"
}

My code:

ws = XLSX.utils.aoa_to_sheet([[formattedQuery]]);

XLSX.utils.sheet_add_json(ws, json, { origin: -1, display: true }, { cellDates: true, dateNF: 'YYYYMMDD HH:mm:ss' });

var workbook = XLSX.utils.book_new();

XLSX.utils.book_append_sheet(workbook, ws, filename.substring(0, 29));

XLSX.writeFile(workbook, filename);

Date as saved on Excel: enter image description here



from Sheetjs - Sheet add Json ignores date format

WP Admin: Include custom post type archive in link search results

I've been searching for examples of this online and through the WP documentation on filters but I can't find a suitable hook, so apologies for posting a question without a good example of what I'm trying to do!

When you add a link to text or to a button in the editor, you can search for the page/post you want to link to. What you can't search for is a post type archive link.

I want to be able to type the name of a post type into the search box (pictured below), and include the post type archive link in the search results. In this example, I have a post type called members that I'd like to link to.

enter image description here

I find the need to do this a lot, and I always end up just typing /post-type-link into the box and leaving it at that, but I don't think this is an elegant solution and is clunky for users.

I have tried to write some code, but I don't believe I have the right hook:

function include_cpt_search( $query ) {

    if ( is_admin() && is_single() ) {
        $query->set( 'post_type', array( 'services' ) );
    }

    return $query;

}
add_filter( 'pre_get_posts', 'include_cpt_search' ); 

Has anyone done this before? Know of a filter or hook I could work with? Anything really!



from WP Admin: Include custom post type archive in link search results

Header flickering and freezing issue with material table (implemented with react window + react window infinite loader)

I have implemented an Infinite scrolling table with react-window (based on #60) and material UI.

The table seems to be fulfilling the main objective but there are few issues with it -

  1. header is not sticking on the top in spite of having styles in place (stickyHeader prop).
  2. header is flashing/flickering while scrolling quickly towards up direction. [Steps to reproduce - scroll 50% down then do fast scroll up and observe the header movement ].

Here's the codesandbox example - https://codesandbox.io/s/react-window-with-table-elements-forked-huti6?file=/src/index.tsx:514-542



from Header flickering and freezing issue with material table (implemented with react window + react window infinite loader)

How to check if wkwebview finished loading in UItest

I want to take a screenshot of the app when it loads a html file. However sometimes the wkwebview takes a long time to load the html file.

Currently I have to use sleep(5) to wait for the wkwebview to finish loading.

//uitest.swift

sleep(5)
takeScreenshot()

Is there any way to check if wkwebview finished loading in UItest?



from How to check if wkwebview finished loading in UItest

Google Maps API searching for places based on city using dropdown (select option) not working

hello I want to ask about google maps API. Previously, I was a beginner in using Google Maps API. I want to make a search for places by city using select option.

I've tried reading documentation and a few videos on youtube, other posts on stackoverflow, but none of them fit what I want.

I want to make maps like below. when I search by select option, the selected city will appear. And when i click on the marker, i will see place descriptions such as photos, place names, and descriptions.

enter image description here

Is it possible for me to make a feature like that? I really stuck with what I make, I've made some code like the one below. please help me, i really need your help.

let map;
        let places;
        let infoWindow;
        let markers = [];
        let autocomplete;
        const countryRestrict = {
            country: "tangerang"
        };
        const MARKER_PATH = "https://developers.google.com/maps/documentation/javascript/images/marker_green";
        const hostnameRegexp = new RegExp("^https?://.+?/");
        const cities = {
            jakarta: {
                center: {
                    lat: -6.186286,
                    lng: 106.822746
                },
                zoom: 12
            },
            tangerang: {
                center: {
                    lat: -6.336135,
                    lng: 106.676924
                },
                zoom: 11
            }
        };

        function initMap() {
            map = new google.maps.Map(document.getElementById("map"), {
                zoom: cities["tangerang"].zoom,
                center: cities["tangerang"].center,
                mapTypeControl: false,
                panControl: false,
                zoomControl: false,
                streetViewControl: false,
                fullscreenControl: false,
            });

            infoWindow = new google.maps.InfoWindow({
                content: document.getElementById("info-content")
            });

            autocomplete = new google.maps.places.Autocomplete(
                document.getElementById("autocomplete"), {
                    types: ["(cities)"],
                    componentRestrictions: countryRestrict
                }
            );

            places = new google.maps.places.PlacesService(map);
            autocomplete.addListener("place_changed", onPlaceChanged);

            document.getElementById("country").addEventListener("change", setAutocompleteCountry);
}

function setAutocompleteCountry() {
            const country = document.getElementById("country").value;

            if (country == "all") {
                autocomplete.setComponentRestrictions({
                    country: []
                });
                map.setCenter({
                    lat: 15,
                    lng: 0
                });
                map.setZoom(2);
            } else {
                autocomplete.setComponentRestrictions({
                    country: country
                });
                map.setCenter(cities[country].center);
                map.setZoom(cities[country].zoom);
            }
        }
#mapsContent {
    position: relative;
}

#mapsContent #controls {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    position: absolute;
    left: 50%;
    top: 5%;
    -webkit-transform: translate(-50%, -5%);
    transform: translate(-50%, -5%);
    background-color: #fff;
    padding: 10px 30px;
    border-radius: 10px;
    z-index: 9;
}

#mapsContent #controls .city {
    padding-right: 30px;
    border-right: 1px solid #acacac;
    margin-right: 20px;
}

#contactContent #mapsContent #controls h4 {
    color: #16215C;
    font-size: 13px;
    margin: 0;
}

#contactContent #mapsContent #controls #country {
    border: none;
    cursor: pointer;
}

#map {
    position: relative;
    width: 100%;
    height: 900px;
    background-color: #CACACA;
    border-radius: 10px;
    z-index: 0;
}
<div class="container-fluid">
  <div class="row" id="mapsContent">
      <div id="controls">
          <div class="city">
               <h4>Kota</h4>
          </div>
          <select id="country">
               <option value="all">All</option>
               <option value="jakarta">DKI Jakarta</option>
               <option value="tangerang" selected>Tangerang</option>
          </select>
      </div>
  <div id="map"></div>
</div>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=places&v=weekly" async defer></script>


from Google Maps API searching for places based on city using dropdown (select option) not working

Array of objects as dataSource in mat-table

I have array of objects in this structure:

data = [ 
  {
    course: 'Angular',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  },
  {
    course: 'React',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  },
  {
    course: 'React Native',
    students: [
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''},
      {name: '', enrolled_date: '', email: ''}
    ]
  }
]

My objective is to display this student data in a mat table for each course. Expected table is to be:

__________________________________

|Name | Enrolled Date | Email      |
------------------------------------
|ANGULAR                           |
---------
|Stu1 | 20-09-2020    | stu1@gmail |
-----------------------------------
|Stu2 | 17-09-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 23-09-2020    | stu3@gmail |
-----------------------------------
|REACT                             |
--------
|Stu1 | 20-01-2020    | stu1@gmail |
-----------------------------------
|Stu2 | 17-01-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 25-01-2020    | stu3@gmail |
-----------------------------------
|REACT NATIVE                      |
--------
|Stu1 | 20-05-2020    | stu1@gmail |
----------------------------------
|Stu2 | 22-05-2020    | stu2@gmail |
-----------------------------------
|Stu3 | 16-05-2020    | stu3@gmail |
-----------------------------------

I need to loop the student data which is also an array. Hence, I sent data.students to mat-table dataSource by looping mat-table.

<ng-container *ngFor="let eachObj of data">
  <table mat-table [dataSource]="eachObj.students">
    <ng-container matColumnDef="name">...</ng-container>
    <ng-container matColumnDef="date">...</ng-container>
    <ng-container matColumnDef="email">...</ng-container>
  </table>
</ng-container>

Basically, the above code will pickup the first object from data array and render the table. And then pickup second object and print one more table and repeat...

I knew this is not the best approach. Can I get the better one?



from Array of objects as dataSource in mat-table

FIle doesn't get updated by appending text in PHP

I'm trying to append text with PHP to my text file, but 123.txt is still empty after the code execution.

Code:

<?php
$fp = fopen('123.txt', "a+");
fwrite($fp, 'Cats chase dogs');
fclose($fp);
?>

I don't see anything wrong and I don't understand why it's not writing.

Any kind of help would be highly appreciated.



from FIle doesn't get updated by appending text in PHP

sklearn.preprocessing.OneHotEncoder: using drop and handle_unknown='ignore'

I have some pandas.Seriess, below – that I want to one-hot-encode. I've found through research that the 'b' level is not important for my predictive modeling task. I can exclude it from my analysis like so:

import pandas as pd
from sklearn.preprocessing import OneHotEncoder

s = pd.Series(['a', 'b', 'c']).values.reshape(-1, 1)

enc = OneHotEncoder(drop=['b'], sparse=False, handle_unknown='error')
enc.fit_transform(s)
# array([[1., 0.],
#        [0., 0.],
#        [0., 1.]])
enc.get_feature_names()
# array(['x0_a', 'x0_c'], dtype=object)

But when I go to transform a new series, one containing both 'b' and a new level, 'd', I get an error:

new_s = pd.Series(['a', 'b', 'c', 'd']).values.reshape(-1, 1)
enc.transform(new_s)

Traceback (most recent call last): File "", line 1, in File "/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/site-packages/sklearn/preprocessing/_encoders.py", line 390, in transform X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) File "/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/site-packages/sklearn/preprocessing/_encoders.py", line 124, in _transform raise ValueError(msg) ValueError: Found unknown categories ['d'] in column 0 during transform

This is to be expected since I set handle_unknown='error' above. However, I'd like to completely ignore all classes except for ['a', 'c'] in both the fitting and subsequent transforming steps. I tried this:

enc = OneHotEncoder(drop=['b'], sparse=False, handle_unknown='ignore')
enc.fit_transform(s)
enc.transform(new_s)

Traceback (most recent call last): File "", line 1, in File "/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/site-packages/sklearn/preprocessing/_encoders.py", line 371, in fit_transform self._validate_keywords() File "/Users/user/Documents/assets/envs/data-science/venv/lib/python3.7/site-packages/sklearn/preprocessing/_encoders.py", line 289, in _validate_keywords "handle_unknown must be 'error' when the drop parameter is " ValueError: handle_unknown must be 'error' when the drop parameter is specified, as both would create categories that are all zero.

It seems this pattern is not supported in scikit-learn. Does anyone know a scikit-learn-compatible pattern to accomplish this task?



from sklearn.preprocessing.OneHotEncoder: using drop and handle_unknown='ignore'

iOS 14 Widget Not Refreshing

I am slowly getting my app ready for some iOS 14 features, but keep coming across bug after bug, or (MORE LIKELY) not doing things correctly on my end. I'm trying every thing in my power to get the widget to update but it will not. The widget itself is simple; it shows the title and some text of the most recent entry from an RSS feed. I built an XMLParser, and this code gets run for the timeline:

struct Provider: TimelineProvider {
    @State private var rssItems:[RSSItem]?
    let feedParser = FeedParser()
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date(), title:"News", description: "News article here", link: "Http://link", pubDate: "The day it posted")
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), title:"News", description: "News Article Here", link: "Http://link", pubDate: "The day it posted")
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> ()) {
        WidgetCenter.shared.reloadAllTimelines()

        var entries: [SimpleEntry] = []
        
        
        feedParser.parseFeed(url: "https://fritchcoc.wordpress.com/feed") {(rssItems) in
            self.rssItems = rssItems
            let currentDate = Date()
            let string1 = "Latest News: \n\n"
            let string2 = rssItems[0].title
             
                var appendString1 = string1+string2
                let entry = SimpleEntry(date: currentDate, title:appendString1, description: rssItems[0].description, link: rssItems[0].link, pubDate: rssItems[0].pubDate)
                entries.append(entry)
            let refreshDate = Calendar.current.date(byAdding: .minute, value: 2, to: Date())!
           let timeline = Timeline(entries: entries, policy: .after(refreshDate))
            completion(timeline)

        }
       
    }
}

When you first install the widget, it correctly shows the latest news item. However, I added some more entries to the RSS feed to test it, and it never updates to show these changes, only whatever is new at the time of install. I install on a 2nd device, and on the 2nd device, it DOES show the new ones that I added for testing, so I know that it is working properly on the parser end, and on the RSS itself.



from iOS 14 Widget Not Refreshing

Change legend items in plot-metrics chart of roc curve

I'm using plot-metrics library for creating ROC chart.

I'm trying to create the chart for three different models I have created in order to compare between them and show which model is the best one. The problem is that I cannot edit the legend and I get the random guess appear 3 times + cannot edit the item names in the legend (e.g model 1, model 2 and model 3).

this is how I generated this chart:

from plot_metric.functions import BinaryClassification
# Visualisation with plot_metric
bcl = BinaryClassification(y_test, predictions1, labels=["TREAT1", "TREAT2"])
bcrf = BinaryClassification(y_test, predictions2, labels=["TREAT1", "TREAT2"])
bcxgb = BinaryClassification(y_test, predictions3, labels=["TREAT1", "TREAT2"])

# Figures
plt.figure(figsize=(5,5))
bcl.plot_roc_curve(plot_threshold=False,c_roc_curve='b', title='Receiver Operating Characteristic')
bcrf.plot_roc_curve(plot_threshold=False,c_roc_curve='green')
bcxgb.plot_roc_curve(plot_threshold=False,c_roc_curve='purple')

plt.show()

enter image description here

I thought there is parameter for this (True ot false for the random guess) but there is only for the threshold and other parameters and also couldn't find any parameter for the legend:
https://plot-metric.readthedocs.io/en/latest/

My end goal: to change the legend items names and not to have the Random guess 3 times.



from Change legend items in plot-metrics chart of roc curve

iOS 14 WidgetKit Memory Issue - Photo Asset Dimensions

With iOS 14 WidgetKit, I am trying to display a widget with a 'particular' photo asset from the library. With a medium-size widget, I want the photo asset to fill the whole area (Aspect Fill), just like the native Photos widget.

    struct My_WidgetEntryView : View 
    {
       var entry : Provider.Entry
       var body: some View 
       {
         PhotoView(user: 1)
       }
    }
    
    struct PhotoView: View 
    {
                                 var user            : Int
        @ObservedObject  private var assetImageModel = AssetImageModel()
    
        init(user: Int)
        {
            self.user = user
            self.assetImageModel.loadAsset()
        }
    
        var body: some View {
                if self.assetImageModel.assetImage != nil {
                    Image(uiImage: self.assetImageModel.assetImage!)
                        .resizable()
                    
                } else {
                    Image(uiImage: UIImage(systemName: "photo")!)
                        .resizable()
                }
        }
    }
    
    
    class AssetImageModel: ObservableObject {
        @Published var assetImage: UIImage?
    
        init() {
            loadAsset()
        }
    
        func loadAsset() {
            if PHPhotoLibrary.authorizationStatus() == .authorized {
    
                let allPhotosOptions = PHFetchOptions()
                allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
                let assetsFetchResults = PHAsset.fetchAssets(with: allPhotosOptions)
                if assetsFetchResults.count > 0 {
                    let asset = assetsFetchResults.lastObject
                    if asset != nil {
                        let options = PHImageRequestOptions()
                        options.isSynchronous = true
                        options.deliveryMode = .highQualityFormat
                        options.resizeMode = .exact
                        options.version = .current
    
                        PHCachingImageManager().requestImage(for: asset!, targetSize: CGSize(width: 360 * UIScreen.main.scale, height: 170 * UIScreen.main.scale), contentMode: .aspectFill, options: options, resultHandler: { image, _ in
                              
                            //DispatchQueue.main.async {
                              self.assetImage = image
                            //}
     
                        })
                    } else {
                        //Asset was nil
                    }
                } else {
                    //No assets
                }
            } else {
                //No persmission    
            }
        }
    }

When the above is run, I get a crash with a memory warning stating allowed 30 MB memory limit has exceeded. This obvious due to this:

  • For the medium-size widget, I had to go by a 360 x 170 point size since there was no way to get the actual view dimensions before the the view gets displayed.
  • The actual target size then has to be multiplied by the screen scale, at the moment the test device is a 3x. Aspect Fill as to be the fill type. Due to this, PHCachingImageManager is returning a 360-point width with 480-point height for a portrait photo in order to fill the view. The final dimensions of the image end up being 1080 x 1440 pixel size. I imagine this is the reason for memory pressure.

Question

Is there a way to ask for a properly cropped 360 x 170 point size image? The stock Photos widget seems to manage this.

Things I Tried

  • I tried normalizedCropRect in PHImageRequestOptions and had no luck.
  • Lowering the image size by a huge margin works, but the image looks blurred visually.


from iOS 14 WidgetKit Memory Issue - Photo Asset Dimensions

Adding Fastly to a Heroku app does not forward to proper url

I currently have an Heroku app that is being served over a CDN. I have just added Fastly to my Heroku app as an addon and I am struggling to configure it properly. Here is my current configuration:

I have my domain registered on GoDaddy with the following CNAME configuration:

Host: www
Points to: my-site-herokuapp-com.global.ssl.fastly.net
TTL: Custom
Seconds: 600

Here is the GoDaddy forwarding configuration (not sure if this matters):

Forward to https://www.my-site.io/
(301 & forward only)

Here is my fastly configuration:

Domains:
my-site-herokuapp-com.global.ssl.fastly.net
*Provisioned for my-site via Heroku*

my-site.herokuapp.com
*Provisioned for my-site via Heroku*

www.my-site.io

And finally in Heroku in the domains configuration section of my app here are my settings:

Domain Name: my-site.io
DNS target: darwinian-kumquat-123456.herokudns.com

Domain Name: www.my-site.io
DNS target: serene-trout-123456.herokudns.com

Before I tried to make this change I had the CNAME pointing directly to: serene-trout-123456.herokudns.com an it was working fine. However after updating this value to the new Fastly value: my-site-herokuapp-com.global.ssl.fastly.net Fastly directs the site to my-site.herokuapp.com instead of just https://www.my-site.io. I followed the instructions listed here so not entirely sure where I have gone wrong. Any ideas?



from Adding Fastly to a Heroku app does not forward to proper url

Why is my function running twice in command line but not in vscode

I am using a function from one file, in another file, and calling it there. This is causing the function to run twice at the same time when ran in command line, but not when I run it in VSCode.

Here is an example:

// fileOne

async function task() {
    console.log('Hello')
}

module.exports = { task }

// fileTwo
const fileOne = require('./fileOne');

fileOne.task();

Output when ran in VSCode:

Hello

Output when ran in Command Line:

Hello
Hello

Im not sure why this is happening... No I am not calling it in fileOne on accident because then it would run twice in VSCode as well.

Thanks.



from Why is my function running twice in command line but not in vscode

Tuesday, 29 September 2020

How to get the exact smooth scrolling functionality of Chrome?

When the user clicks a button on my page it creates a new element below it and then scrolls downwards towards it. I'd like this to be done smoothly, and that can be accomplished like so:

window.scroll({ top: document.body.scrollHeight, behavior: "smooth" });

However, this does not work on Safari, so it appears that I need to use a custom function instead to get this functionality.

I searched around and found this (current answer, but suboptimal):

doScrolling = (elementY, duration) => { 
  let startingY = window.pageYOffset;
  let diff = elementY - startingY;
  var start;

  // Bootstrap our animation - it will get called right before next frame shall be rendered.
  window.requestAnimationFrame(function step(timestamp) {
    if (!start) { start = timestamp; }
    // Elapsed milliseconds since start of scrolling.
    let time = timestamp - start;
    // Get percent of completion in range [0, 1].
    let percent = Math.min(time / duration, 1);

    window.scrollTo(0, startingY + diff * percent);

    let isScrollAtBottom = (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight - 3;

    if (isScrollAtBottom) { return; }

    // Proceed with animation as long as we wanted it to.
    if (time < duration) {
      window.requestAnimationFrame(step);
    }
  })
}

Called like: this.doScrolling(document.body.scrollHeight, 750);

Which seems to work, but it doesn't seem to have the same semantics as window.scroll.

For one, you need to specify a duration, whereas with window.scroll it's implied.

Secondly, it seems as if window.scroll uses a different transition type? It's hard to tell, but it feels more like an ease as opposed to a linear transition, where it starts off slow, then goes fast, and then slows to a stop.

Is it possible to modify the above function to mimic the exact semantics of window.scroll such that you can't tell the difference between calling the two?

To clarify, I don't need to clone all the functionalities of window.scroll. The only thing I require is the ability to scroll to a given position (in my case it's always the end of the page) in a smooth manner. The function I provided above in my question is almost perfect, except that it's slightly janky and doesn't feel as smooth as window.scroll. I think it may be the animation style? It's kind of hard to tell why it looks "worse" since it's so fast.



from How to get the exact smooth scrolling functionality of Chrome?

Hide/Show Navigation Bar at ViewWillAppear and ViewWillDisappear UI Glitch

so I have 2 VC that I want to set its navigation bar hide when it appears and show again when it disappears. This is my code

class FirstNavigationVCViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "First Nav"
        button.addTarget(self, action: #selector(press), for: .touchUpInside)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    
    @objc func press() {
        navigationController?.pushViewController(SecondNavigationViewController(), animated: true)
    }

}

class SecondNavigationViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "Second Nav"
        button.addTarget(self, action: #selector(press), for: .touchUpInside)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: true)
    }
    
    @objc func press() {
        navigationController?.popViewController(animated: true)
    }
}

I assume with that code the navigation bar will not show up when the second vc pop, but instead I got this

enter image description here

do you guys have better solution so I can still hide navigation bar for both vc without that animation?



from Hide/Show Navigation Bar at ViewWillAppear and ViewWillDisappear UI Glitch

Changing vertical scroll to horizontal at a point for a specific element

What is the contexte ?

I have a website, which is a single page, where I will present my activity and projects After scrolling few sections we have a projects in a row.

What I want to do ?

I wanna swap the vertical scroll to horizonta when we arrive to my projects row. When you are at the end of the row it just has to get back to normal with a vertical scroll.

The code

...
<div className="projectsContainer">     // <--- height 100vh
    <div className="row projects">     //  <--- Positioned in the middle of the parent ↑
        <project1  />
        <project2  />
        <project3  />
        <project4  />
        <project5  />
    </div>
</div>
...

What is my code ? And what I thought

I have a method inTheMiddle() which is boolean. If <div className="row projects"> is in the middle of the viewport it returns true else false.

A method scrollDirection() which is boolean too, true when scroll goes down false when it is goes up.

Many different method disableScroll() The last disableScroll() method cancel the scroll by re-calculating it

componentDidMount() {
     window.addEventListener('wheel', (this.handleScroll));
}
...
disableScroll() {
    // Get the current page scroll position 
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
    // if any scroll is attempted, set this to the previous value 
    window.onscroll = () => {
        window.scrollTo(scrollLeft, scrollTop);
    };
}

And my handleScroll() method which manage all that

handleScroll(event) {
    const rowProjects = document.querySelector(".row.projects")
    const projectsContainer = document.querySelector(".projectsContainer")
    const isSticky = rowProjects.classList.contains("sticky") 
// isSticky is useless now was try by adding position fixed and no need to use disableScroll()

    if (this.inTheMiddle() && this.state.scrollDown && this.state.count < 1400 ) {
        this.disableScroll()
        this.setState({ count: this.state.count + 10 })
        rowProjects.scroll(this.state.count, 0)
    } else if ((!this.state.scrollDown) && this.state.count > 0) {
        this.setState({ count: this.state.count - 10 })
        rowProjects.scroll(this.state.count, 0)
    }

}

What I cannot manage is to get back to normal. When you arrive at the end of the row I cannot re-able the scroll nor when I scroll up to the top of the page. It stuck on the projects row.

I managed it with isSticky I removed disableScroll() and add a class with position fixed but the problem was that it bounced. Because when it is in the middle i fixed in the middle of the viewport so the element is no longer in position relative so it bounced like a glitch (like taking off a block of a stack block) sorry for the bad exemple :')

If you have any idea to help me it would be very kind. I am scratching my head for 3 days and I still did not find the perfect solution.



from Changing vertical scroll to horizontal at a point for a specific element

BillingClient.BillingClientStateListener.onBillingSetupFinished is called multiple times

I tried to write a wrapper for BillingClient v.2.2.0 with Kotlin Coroutines:

package com.cantalk.photopose.billing

import android.app.Activity
import android.content.Context
import com.android.billingclient.api.*
import com.android.billingclient.api.BillingClient.*
import com.cantalk.photopose.util.Logger
import kotlinx.coroutines.CompletableDeferred
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class BillingClientAsync(context: Context) {
    private val billingClient: BillingClient = setupBillingClient(context)
    private val pendingPurchaseFlows = HashMap<String, CompletableDeferred<Purchase>>()

    private fun setupBillingClient(context: Context): BillingClient {
        return newBuilder(context)
            .enablePendingPurchases()
            .setListener { billingResult, purchases ->
                if (billingResult.responseCode == BillingResponseCode.OK && purchases != null) {
                    for (purchase in purchases) {
                        val deferred = pendingPurchaseFlows.remove(purchase.sku)
                        deferred?.complete(purchase)
                    }
                } else {
                    val iterator = pendingPurchaseFlows.iterator()
                    while (iterator.hasNext()) {
                        val entry = iterator.next()
                        entry.value.completeExceptionally(BillingException(billingResult))
                        iterator.remove()
                    }
                }
            }
            .build()
    }

    suspend fun queryPurchases(): List<Purchase> {
        Logger.debug("query purchases")

        ensureConnected()
        val queryPurchases = billingClient.queryPurchases(SkuType.INAPP)
        if (queryPurchases.responseCode == BillingResponseCode.OK) {
            return queryPurchases.purchasesList
        } else {
            throw BillingException(queryPurchases.billingResult)
        }
    }

    suspend fun querySkuDetails(@SkuType type: String, skus: List<String>): List<SkuDetails> {
        Logger.debug("query sku details for", type)

        ensureConnected()
        return suspendCoroutine { continuation ->
            val params = SkuDetailsParams.newBuilder()
                .setType(type)
                .setSkusList(skus)
                .build()
            billingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    continuation.resume(skuDetailsList)
                } else {
                    continuation.resumeWithException(BillingException(billingResult))
                }
            }
        }
    }

    suspend fun purchase(activity: Activity, skuDetails: SkuDetails): Purchase {
        Logger.debug("purchase", skuDetails.sku)

        ensureConnected()
        val currentPurchaseFlow = CompletableDeferred<Purchase>()
            .also { pendingPurchaseFlows[skuDetails.sku] = it }
        val params = BillingFlowParams.newBuilder()
            .setSkuDetails(skuDetails)
            .build()
        billingClient.launchBillingFlow(activity, params)
        return currentPurchaseFlow.await()
    }

    suspend fun consume(purchase: Purchase): String {
        Logger.debug("consume", purchase.sku)

        ensureConnected()
        return suspendCoroutine { continuation ->
            val params = ConsumeParams.newBuilder()
                .setPurchaseToken(purchase.purchaseToken)
                .setDeveloperPayload("TBD")
                .build()
            billingClient.consumeAsync(params) { billingResult, purchaseToken ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    continuation.resume(purchaseToken)
                } else {
                    continuation.resumeWithException(BillingException(billingResult))
                }
            }
        }
    }

    suspend fun acknowledgePurchase(purchase: Purchase) {
        Logger.debug("acknowledge", purchase.sku)

        ensureConnected()
        return suspendCoroutine { continuation ->
            val params = AcknowledgePurchaseParams.newBuilder()
                .setPurchaseToken(purchase.purchaseToken)
                .setDeveloperPayload("TBD")
                .build()
            billingClient.acknowledgePurchase(params) { billingResult ->
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    continuation.resume(Unit)
                } else {
                    continuation.resumeWithException(BillingException(billingResult))
                }
            }
        }
    }

    private suspend fun ensureConnected() {
        if (!billingClient.isReady) {
            startConnection()
        }
    }

    private suspend fun startConnection() {
        Logger.debug("connect to billing service")

        return suspendCoroutine { continuation ->
            billingClient.startConnection(object : BillingClientStateListener {
                override fun onBillingSetupFinished(billingResult: BillingResult) {
                    if (billingResult.responseCode == BillingResponseCode.OK) {
                        continuation.resume(Unit)
                    } else {
                        // TODO: 3 Google Play In-app Billing API version is less than 3
                        continuation.resumeWithException(BillingException(billingResult))
                    }
                }

                override fun onBillingServiceDisconnected() = Unit
            })
        }
    }
}

As you can see, when I try to query purchases or purchase I ensure that client is ready. But in production there are many errors:

java.lang.IllegalStateException: 
  at kotlin.coroutines.SafeContinuation.resumeWith (SafeContinuation.java:2)
  at com.cantalk.photopose.billing.BillingClientAsync$startConnection$2$1.onBillingSetupFinished (BillingClientAsync.java:2)
  at com.android.billingclient.api.zzai.run (zzai.java:6)

I tried to understand what the cause of problem and got that if BillingClientStateListener.onBillingSetupFinished will be called multiple time there can be an exception IllegalStateException: Already resumed. I've wondered how is it possible, because I am creating new listener every startConnection call? I can't reproduce this issue on emulator or my test device. Can anybody explain me what does happen here and how to fix it?



from BillingClient.BillingClientStateListener.onBillingSetupFinished is called multiple times

Angular build deploy in PCF subdirectory

Currently we are using PCF to deploy an angular app. We got requirement to deploy another build but this time within Sub-directory.

For Example:

sites.example.com --> Build 1

sites.example.com/site2 --> Build 2

We might get more requirement in future to add more sites for different build.

I have used the below command to create a route in the PCF cloud.

cf create-route PROJECTS example.com --hostname sites --path site2

And then in the Angular side, i have created build using below command.

ng build --base-href=/site2/

cf push site2

Then after successful CF deployment, i mapped the app with this route sites.example.com/site2

But when i launch the URL in the browser, i am getting the below error with blank page.

enter image description here

Could someone help me on this please? I am not sure where i am going on right path or not.



from Angular build deploy in PCF subdirectory

Callback protocol for functions with different kwargs

I have a function that takes a callback function as a parameter:

def function(arg1: int, callback):
    ...

I am trying to add a type hint for the callback function. Now, the callback functions that are passed to this function have the same positional args but the kwargs can be completely different (both in type and name).

def function1(arg1: int, arg2: str, **kwargs1):
    ...

def function2(arg1: int, arg2: str, **kwargs2):
    ...

I am trying to write a Callback Protocol that fits these 2 functions, but so far I don't see a way to make this work when the kwargs are different. Is there a way to create a unified Callback protocol in this case?



from Callback protocol for functions with different kwargs

How to setup two PyPI indices

I have a local GitLab installation that comes with a local PyPI server to store company internal Python packages.

How can I configure my PyPI to search packages in both index servers?

I read about .pypirc / pip/pip.ini and found various settings but no solution so far.

  1. Most solutions permanently switch all searches to the other index server. But I want to be able to install and update packages from pypi.org as normal while some packages come from the local index.
  2. setting multiple index servers with credentials seams to be limited to distutils (used e.g. by twine) only, but is not used by pip
  3. There is confusion if to configure index servers in [global] or [install]. I assume the latter one is a rule subset for pip install. (The documentation is here unclear.)
  4. While twine can reference a repository entry in the config file like -r gitlab refers to a [gitlab] section, such a named reference can't be used by pip...

So what I want to achieve:

  • pip should be able to install and update regular packages from pypi.org like colorama
  • pip should be able to install and update packages from gitlab.company.com
    • authentication with username (__token__) and password (7a3b62342c784d87) must work

Experiment so far:

[global]


[install]
find-links =
    https://pypi.org
    https://gitlab.company.de/api/v4/projects/2142423/packages/pypi
trusted-host =
    https://pypi.org
    https://gitlab.company.de/api/v4/projects/2142423/packages/pypi

[distutils]
index-servers =
    gitlab

[gitlab]
repository = https://gitlab.company.de/api/v4/projects/2142423/packages/pypi
username = __token__
password = geheim


from How to setup two PyPI indices

Writing xarray multiindex data in chunks

I am trying to efficiently restructure a large multidimentional dataset. Let assume I have a number of remotely sensed images over time with a number of bands with coordinates x y for pixel location, time for time of image acquisition, and band for different data collected.

In my use case lets assume the xarray coord lengths are roughly x (3000), y (3000), time (10), with bands (40) of floating point data. So 100gb+ of data.

I have been trying to work from this example but I am having trouble translating it to this case.

Small dataset example

NOTE: the actual data is much larger than this example.

import numpy as np
import dask.array as da
import xarray as xr

nrows = 100
ncols = 200
row_chunks = 50
col_chunks = 50

data = da.random.random(size=(1, nrows, ncols), chunks=(1, row_chunks, col_chunks))

def create_band(data, x, y, band_name):

    return xr.DataArray(data,
                        dims=('band', 'y', 'x'),
                        coords={'band': [band_name],
                                'y': y,
                                'x': x})

def create_coords(data, left, top, celly, cellx):
    nrows = data.shape[-2]
    ncols = data.shape[-1]
    right = left + cellx*ncols
    bottom = top - celly*nrows
    x = np.linspace(left, right, ncols) + cellx/2.0
    y = np.linspace(top, bottom, nrows) - celly/2.0
    
    return x, y

x, y = create_coords(data, 1000, 2000, 30, 30)

src = []

for time in ['t1', 't2', 't3']:

    src_t = xr.concat([create_band(data, x, y, band) for band in ['blue', 'green', 'red', 'nir']], dim='band')\
                    .expand_dims(dim='time')\
                    .assign_coords({'time': [time]})
    
    src.append(src_t)

src = xr.concat(src, dim='time')

print(src)


<xarray.DataArray 'random_sample-5840d8564d778d573dd403f27c3f47a5' (time: 3, band: 4, y: 100, x: 200)>
dask.array<concatenate, shape=(3, 4, 100, 200), dtype=float64, chunksize=(1, 1, 50, 50), chunktype=numpy.ndarray>
Coordinates:
  * x        (x) float64 1.015e+03 1.045e+03 1.075e+03 ... 6.985e+03 7.015e+03
  * band     (band) object 'blue' 'green' 'red' 'nir'
  * y        (y) float64 1.985e+03 1.955e+03 1.924e+03 ... -984.7 -1.015e+03
  * time     (time) object 't1' 't2' 't3'

Restructured - stacked and transposed

I need to store the output of the following:

print(src.stack(sample=('y','x','time')).T)

<xarray.DataArray 'random_sample-5840d8564d778d573dd403f27c3f47a5' (sample: 60000, band: 4)>
dask.array<transpose, shape=(60000, 4), dtype=float64, chunksize=(3600, 1), chunktype=numpy.ndarray>
Coordinates:
  * band     (band) object 'blue' 'green' 'red' 'nir'
  * sample   (sample) MultiIndex
  - y        (sample) float64 1.985e+03 1.985e+03 ... -1.015e+03 -1.015e+03
  - x        (sample) float64 1.015e+03 1.015e+03 ... 7.015e+03 7.015e+03
  - time     (sample) object 't1' 't2' 't3' 't1' 't2' ... 't3' 't1' 't2' 't3'

I am hoping to use dask and xarray to write the result to disk (ideally hdf, but hdf can't store multiindex created by stacking multiple coords, in this case x,y,time), or in a format accessible for open_mfdataset since I will need to use lazy loading.

At this point I am just hoping for some good ideas. Thanks!



from Writing xarray multiindex data in chunks

UnauthorizedAccessException when calling FileInfo.Length

I do get reports via Crashlytics, that some of the Users of my Unity app (roughly 0.5%) get an UnauthorizedAccessException when I call FileInfo.Length;

the interesting part of the stacktrace is:

Non-fatal Exception: java.lang.Exception
UnauthorizedAccessException : Access to the path '/storage/emulated/0/Android/data/com.myCompany.myGreatGame/files/assets/myAsset.asset' is denied.
System.IO.__Error.WinIOError (System.IO.__Error)
System.IO.FileInfo.get_Length (System.IO.FileInfo)

The corresponding File (it's a different file for every report) was written (or is currently written) by the same application (possibly many sessions earlier). The call happens in a backgroundthread and there might be some writing going on at the same time. But according to the .net doc this property should be pre-cached (see https://docs.microsoft.com/en-us/dotnet/api/system.io.fileinfo.length?view=netframework-2.0)

The whole code causing it is:

private static long DirSize(DirectoryInfo d) 
{
    long size = 0;
    FileInfo[] fileInfos = d.GetFiles();
    foreach (FileInfo fileInfo in fileInfos) 
    {      
        size += fileInfo.Length;
    }
    ...

Did anyone experience something similar and knows what might be causing it?



from UnauthorizedAccessException when calling FileInfo.Length

Capture video without audio in camerax

I want to capture video without audio in in-app camera using camerax api

I am using camerax api of beta10

I have tried by setting audio buffer size and audio sources etc.



from Capture video without audio in camerax

Showing ToastAndroid when app is closed with react-native and Headless JS

I've been trying to integrate BroadcastReceiver with my react-native app. I want to show the ToastAndroid whenever someone calls me. It works great when the app is running (either in foreground and background) but when I kill the app it doesn't trigger ToastAndroid anymore.

I've seen a video (YT link) of someone doing it in native code and it works even when the app is killed.

How can I accomplish it with react-native?

My Service code:

public class CallService extends HeadlessJsTaskService {
@Override
protected @Nullable HeadlessJsTaskConfig getTaskConfig(Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
        return new HeadlessJsTaskConfig(
            "Call",
            Arguments.fromBundle(extras),
            5000,
            true
            );
    }
return null;
}
}

My Receiver code:

public final class CallReceiver extends BroadcastReceiver {

@Override
public final void onReceive(Context context, Intent intent) {
    Intent callIntent = new Intent(context, CallService.class);

    if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
        String phoneState = intent.getStringExtra("state");
        if (phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
            String phoneNumber = intent.getStringExtra("incoming_number");
            callIntent.putExtra("number", phoneNumber);
        } 
    }

    context.startService(callIntent);
    HeadlessJsTaskService.acquireWakeLockNow(context);
}
}

And JS code:

const Call = async (data) => {
  console.log('It works!', data);
  ToastAndroid.show('TEST ' + data.number, ToastAndroid.SHORT);
};
AppRegistry.registerHeadlessTask('Call', () => Call);


from Showing ToastAndroid when app is closed with react-native and Headless JS

Webkit Speech Recognition API: Single Syllables

I'm trying to use Webkit Speech Recognition API to recognize single syllables, rather than full words or sentences. As this API requires "grammar" definition, I wonder if there is a way to implement single syllable recognition. Something like "ah" or "bi".

Thanks



from Webkit Speech Recognition API: Single Syllables

Unable to retrieve countries, providers or devices tag stats from the Mailgun API

I am using the mailgun-php library (3.0).

In the example below I am able to retrieve regular stats but the providers list is empty.

var_dump: https://pastebin.com/HAt1JRPy

$mgClient = Mailgun::create('key-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx');

$stats = $mgClient->tags()->stats($this->mgDomain, 'nbxxx_1125', array(
    "event" => ["accepted","delivered"],
    "resolution" => "month",
    "duration" => "1m"
));

$providers = $mgClient->tags()->providers($this->mgDomain, 'nbxxx_1125');

var_dump($providers);
var_dump($stats);
die();

Any clue?



from Unable to retrieve countries, providers or devices tag stats from the Mailgun API

Core Audio: How to play MIDI MusicSequence by MusicPlayer while AUGraph is deprecated?

I have a MIDI Synth Unit

 AudioComponentDescription midiSynthDesc;
  midiSynthDesc.componentType = kAudioUnitType_MusicDevice;
  midiSynthDesc.componentSubType = kAudioUnitSubType_MIDISynth;
  midiSynthDesc.componentManufacturer = kAudioUnitManufacturer_Apple;
  midiSynthDesc.componentFlags = 0;
  midiSynthDesc.componentFlagsMask = 0;

which used to be in an AUGraph. But since AUGraph is deprecated, I used AudioComponentInstanceNew to create it without using AUNode and AUGraph

AudioComponent foundMIDISynthReference = AudioComponentFindNext ( NULL, &midiSynthDesc);
  AudioComponentInstanceNew(foundMIDISynthReference, &midiSynthUnit);

I was using it to play Sequence by attaching the Sequence to AUGraph

NSString *presetURLPath = [[NSBundle mainBundle] pathForResource:@"GortsMiniPianoJ1" ofType:@"SF2"];
NSURL * presetURL = [NSURL fileURLWithPath:presetURLPath]; 
[self loadFromDLSOrSoundFont: (NSURL *)presetURL withPatch: (int)3];

NSString *midiFilePath = [[NSBundle mainBundle] pathForResource:name ofType:@"mid"];
NSURL * midiFileURL = [NSURL fileURLWithPath:midiFilePath];

NewMusicPlayer(&musicPlayer);
MusicPlayerSetSequence(musicPlayer, musicSequence);
MusicSequenceSetAUGraph(musicSequence, _processingGraph);
MusicPlayerPreroll(musicPlayer);
MusicPlayerStart(musicPlayer);

But now that AUGraph is deprecated, using AudioUnit only, how can I use Play MIDI Files in Core Audio?



from Core Audio: How to play MIDI MusicSequence by MusicPlayer while AUGraph is deprecated?

Why doesn't my request.user have groups in Django?

I've got an endpoint built with Django Rest Framework, to which I now want to add permissions so that only users belonging to a certain group can access an endpoint. So I'm using token based access and inspired by this example I'm trying to use the following code:

class ReadPermission(BasePermission):
    def has_permission(self, request, view):
        return request.user.groups.filter(name=settings.GROUP_POST_DATA).exists()

class MyEndpoint(mixins.ListModelMixin, viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated, ReadPermission]
    http_method_names = ['get']
    # etc

But unfortunately I get anAttributeError: 'User' object has no attribute 'groups'

Why doesn't the user object have groups?



from Why doesn't my request.user have groups in Django?

Angular 9 hybrid with ui router causes Trying to get the AngularJS injector before it being set. How to debug/fix?

[EDIT] I've created a demo repository with this error: https://github.com/SamanthaAdrichem/hybrid-lazy-load-angularjs-injector-error

We've followed the instructions, and all runs fine on normal hybrid, but adding lazy loading fails with the strange error above, and always implemented ui router the way the docs say (as you can see in the code below).

When loading the app all is fine, but when then clicking onto a lazy-loaded route we get the error

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: Trying to get the AngularJS injector before it being set.)

I've tried the solutions listed here

https://github.com/ui-router/angular-hybrid/issues/93

https://github.com/ui-router/angular-hybrid/issues/150

https://github.com/ui-router/angular-hybrid/issues/395

https://github.com/ui-router/sample-app-angular-hybrid/issues/10

But none of these solve it. We don't use ng serve because that crashes with random memory issues (probably also due to hybrid), and we need to proxy to a login page, but the login page and our project would be running on the same port, which isn't possible. So that needs some refactoring in the backend.

It does sometimes load a new chunk file depending on what page i'm going to. But mostly i get this error.

Funny part is, in the page i'm testing we're not using any hybrid code. Basically we're are no longer upgrading any code, we're only downgrading some observers to open modals of the older pages.

These are the versions we're running

"@angular/cli": "9.1.7",
"@angular/animations": "9.0.7",
"@angular/common": "9.0.7",
"@angular/compiler": "9.0.7",
"@angular/core": "9.0.7",
"@angular/forms": "9.0.7",
"@angular/localize": "9.0.7",
"@angular/platform-browser": "9.0.7",
"@angular/platform-browser-dynamic": "9.0.7",
"@angular/router": "9.0.7",
"@angular/upgrade": "9.0.7",
"@uirouter/angular": "6.0.1",
"@uirouter/angular-hybrid": "10.0.1",
"@uirouter/angularjs": "1.0.26",
"@uirouter/core": "6.0.5",
"@uirouter/rx": "0.6.5",

Below the detailed error and some code, don't know what else to share or what i can safely share.

Any suggestions on how to debug this would be lovely!

detailed error

stateService.ts?8765:537 Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: Trying to get the AngularJS injector before it being set.)
$defaultErrorHandler @ stateService.ts?8765:537
eval @ stateService.ts?8765:379
processQueue @ angular.js?21b1:17963
eval @ angular.js?21b1:18037
$digest @ angular.js?21b1:19176
eval @ upgrade_module.ts?423f:268
schedulerFn @ event_emitter.ts?938d:96
SafeSubscriber.__tryOrUnsub @ Subscriber.ts?face:266
SafeSubscriber.next @ Subscriber.ts?face:208
Subscriber._next @ Subscriber.ts?face:140
Subscriber.next @ Subscriber.ts?face:100
Subject.next @ Subject.ts?4a10:71
EventEmitter.emit @ event_emitter.ts?938d:86
checkStable @ ng_zone.ts?9664:224
onHasTask @ ng_zone.ts?9664:314
ZoneDelegate.hasTask @ zone.js?d135:440
ZoneDelegate._updateTaskCount @ zone.js?d135:462
Zone._updateTaskCount @ zone.js?d135:284
Zone.runTask @ zone.js?d135:205
drainMicroTaskQueue @ zone.js?d135:601
Promise.then (async)
scheduleMicroTask @ zone.js?d135:584
ZoneDelegate.scheduleTask @ zone.js?d135:410
onScheduleTask @ zone.js?d135:294
ZoneDelegate.scheduleTask @ zone.js?d135:400
Zone.scheduleTask @ zone.js?d135:231
Zone.scheduleMicroTask @ zone.js?d135:251
scheduleResolveOrReject @ zone.js?d135:881
resolvePromise @ zone.js?d135:819
eval @ zone.js?d135:739
webpackJsonpCallback @ app.js?v=1591962370205:26
(anonymous) @ 0.js?v=1591962370205:1
stateService.ts?8765:538 Error: Trying to get the AngularJS injector before it being set.
    at injectorFactory (angular1_providers.ts?397c:22)
    at _callFactory (ng_module.ts?c185:163)
    at _createProviderInstance (ng_module.ts?c185:74)
    at resolveNgModuleDep (ng_module.ts?c185:74)
    at _callFactory (ng_module.ts?c185:163)
    at _createProviderInstance (ng_module.ts?c185:74)
    at resolveNgModuleDep (ng_module.ts?c185:74)
    at _callFactory (ng_module.ts?c185:163)
    at _createProviderInstance (ng_module.ts?c185:74)
    at resolveNgModuleDep (ng_module.ts?c185:74)
    at NgModuleRef_.get (refs.ts?151c:134)
    at applyNgModule (lazyLoadNgModule.ts?7cfb:143)
    at applyModule (lazyLoadNgModule.ts?7cfb:79)
    at ZoneDelegate.invoke (zone.js?d135:384)
    at Object.onInvoke (ng_zone.ts?9664:224)
    at ZoneDelegate.invoke (zone.js?d135:384)
    at Zone.run (zone.js?d135:143)
    at eval (zone.js?d135:891)
    at ZoneDelegate.invokeTask (zone.js?d135:419)
    at Object.onInvokeTask (ng_zone.ts?9664:224)
    at ZoneDelegate.invokeTask (zone.js?d135:419)
    at Zone.runTask (zone.js?d135:188)
    at drainMicroTaskQueue (zone.js?d135:601)

Our main.ts

// Bootstrapping
import {enableProdMode, NgModuleRef, NgZone, ViewEncapsulation} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import {dom, library} from '@fortawesome/fontawesome-svg-core';
import {UIRouter, UrlService} from '@uirouter/core';
import {icons} from 'app/scripts/modules/app-layout/icons/icons';
import 'bootstrap/dist/js/bootstrap.js';
import 'expose-loader?jQuery!expose-loader?$!jquery';
import 'expose-loader?moment!moment';
import 'scripts/app.module';
import 'scripts/homer';
import 'scripts/static.assets';
import {AppModule} from 'src/app/app.module';
import {environment} from 'src/environments/environment';

library.add(...icons);
dom.watch();

// If ready
if (/comp|inter|loaded/.test(document.readyState)) {
    bootstrap();
} else {
    document.addEventListener('DOMContentLoaded', bootstrap);
}

function bootstrap(): void {

    if (true === environment.production) {
        enableProdMode();
    }

    platformBrowserDynamic().bootstrapModule(
        AppModule,
        [{
            defaultEncapsulation: ViewEncapsulation.None
        }]
    ).then((platformRef: NgModuleRef<AppModule>) => {
        // Initialize the Angular Module
        // get() the UIRouter instance from DI to initialize the router
        const urlService: UrlService = platformRef.injector.get(UIRouter).urlService;

        // Instruct UIRouter to listen to URL changes
        platformRef.injector.get<NgZone>(NgZone).run(() => {
            urlService.listen();
            urlService.sync();
        });
    });
}

Our app.module.ts

import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {DoBootstrap, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {setAngularJSGlobal, UpgradeModule} from '@angular/upgrade/static';
import {MissingTranslationHandler, TranslateModule, TranslateService} from '@ngx-translate/core';
import {UIRouterUpgradeModule} from '@uirouter/angular-hybrid';
import * as angular from 'angular';
import {AngularModalObserver} from 'hybrid/modal/modal.observer';
import {AdvertiserLastTransactionsModalObserver} from 'hybrid/modals/advertiser-last-transactions-modal.observer';
import {CampaignsModalObserver} from 'hybrid/modals/campaigns-modal.observer';
import {GoogleModalObserver} from 'hybrid/modals/google-modal.observer';
import {InvoiceModalObserver} from 'hybrid/modals/invoice-modal.observer';
import {PublisherLastTransactionsModalObserver} from 'hybrid/modals/publisher-last-transactions-modal.observer';
import {TicketsModalObserver} from 'hybrid/modals/tickets-modal.observer';
import {AngularTranslationsObserver} from 'hybrid/translations/translations.observer';
import {DatepickerModule} from 'ngx-bootstrap/datepicker';
import {ModalModule} from 'ngx-bootstrap/modal';
import {PagesAdminModule} from 'pages/admin/admin.a2.module';
import {GdprCleanupModule} from 'pages/publisher/account/gdpr-cleanup/gdpr-cleanup.module';
import {LayoutEventsObserver} from 'scripts/modules/app-layout/layout-events.observer';
import {ElementsExternalLinkModule} from 'scripts/modules/elements/external-link.a2/external-link.module';
import {ElementsPageHeaderModule} from 'scripts/modules/elements/page-header/page-header.module';
import {LocalizationMissingTranslationsService} from 'scripts/modules/localization/missing-translations.service';
import {AdminRoutingModule} from 'src/app/admin/admin-routing.module';
import {AdvertiserModule} from 'src/app/advertiser/advertiser.module';
import {AccountModel} from 'src/app/core/auth/account.model';
import {AuthObserver} from 'src/app/core/auth/auth.observer';
import {AuthService} from 'src/app/core/auth/auth.service';
import {IdentityService} from 'src/app/core/auth/identity.service';
import {TokenModel} from 'src/app/core/auth/token.model';
import {CoreModule} from 'src/app/core/core.module';
import {UserProfileModel} from 'src/app/core/data/backend/user/profile/user-profile.model';
import {AuthInterceptor} from 'src/app/core/interceptors/auth.interceptor';
import {CacheInterceptor} from 'src/app/core/interceptors/cache.interceptor';
import {GetAsPostInterceptor} from 'src/app/core/interceptors/get-as-post.interceptor';
import {GetMultiInterceptor} from 'src/app/core/interceptors/get-multi.interceptor';
import {LocalizationService} from 'src/app/core/localization/localization.service';
import {LeadgenerationModule} from 'src/app/leadgeneration/leadgeneration.module';
import {EnergyNlModule} from 'src/app/publisher/pages/widgets/widgets/energy/energy-nl/energy-nl.module';
import {PublisherModule} from 'src/app/publisher/publisher.module';

setAngularJSGlobal(angular);

@NgModule({
    exports: [
        TranslateModule
    ],
    imports: [
        AdminRoutingModule,
        AdvertiserModule,
        BrowserModule,
        BrowserAnimationsModule,
        CoreModule,
        DatepickerModule.forRoot(),
        ElementsExternalLinkModule,
        ElementsPageHeaderModule,
        GdprCleanupModule,
        HttpClientModule,
        LeadgenerationModule,
        ModalModule.forRoot(),
        PagesAdminModule,
        PublisherModule,
        TranslateModule.forRoot({
            missingTranslationHandler: {
                provide: MissingTranslationHandler,
                useClass: LocalizationMissingTranslationsService
            }
        }),
        UIRouterUpgradeModule.forRoot(),
        UpgradeModule,

        // These modules are needed here during hybrid
        EnergyNlModule, // This one can be removed once the entire widget pages has been migrated
    ],
    // All providers you need in AngularJS
    providers: [
        // These observers need to be here, it's required outside of it's own scope.
        // Angular creates a new instance based on the require module level
        AdvertiserLastTransactionsModalObserver,
        AngularModalObserver,
        AngularTranslationsObserver,
        AuthObserver,
        CampaignsModalObserver,
        GoogleModalObserver,
        InvoiceModalObserver,
        LayoutEventsObserver,
        PublisherLastTransactionsModalObserver,
        TicketsModalObserver,

        // Request interceptors, might be able to move them to the actual modules, but those are generated
        { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: CacheInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: GetAsPostInterceptor, multi: true },
        { provide: HTTP_INTERCEPTORS, useClass: GetMultiInterceptor, multi: true },
    ]
})
export class AppModule implements DoBootstrap {

    constructor(
        private angularTranslationsObserver: AngularTranslationsObserver,
        private identityService: IdentityService,
        private authObserver: AuthObserver,
        private authService: AuthService,
        private localizationService: LocalizationService,
        private translateService: TranslateService,
        private upgrade: UpgradeModule
    ) {}

    ngDoBootstrap(): void {
        this.upgrade.bootstrap(document.body, ['dcApp'], { strictDi: true });

        this.angularTranslationsObserver.languageChange$.subscribe(
            (language: string) => this.localizationService.setLanguage(language)
        );
        this.angularTranslationsObserver.translationsChange$.subscribe(
            (translations: object) => this.setTranslations(translations)
        );
        this.authObserver.accountChange$.subscribe(
            (account: AccountModel) => this.identityService.setAccount(account)
        );
        this.authObserver.tokenChange$.subscribe(
            (token: string) => {
                this.authService.setToken(token);
                let decryptedToken: TokenModel = this.authService.getDecryptedToken();
                this.identityService.setAdmin(Boolean(decryptedToken && decryptedToken.admin));
                this.identityService.setPermissions(decryptedToken.usg);
            }
        );
        this.authObserver.userChange$.subscribe(
            (user: UserProfileModel) => {
                this.identityService.setUser(user);
                this.localizationService.checkLanguageLocale();
            }
        );
    }

    setTranslations(translations: object): void {
        for (const language in translations) {
            if (translations.hasOwnProperty(language)) {
                this.translateService.setTranslation(language, translations[language], true);
            }
        }
    }

}

The admin-routing.module.ts

import {NgModule} from '@angular/core';
import {NgHybridStateDeclaration, UIRouterUpgradeModule} from '@uirouter/angular-hybrid';

const states: NgHybridStateDeclaration[] = [{
    name: 'admin.**',
    url: '/admin',
    loadChildren: () => import('src/app/admin/admin.module')
        .then((result: {AdminModule: any}) => result.AdminModule)
}];

@NgModule({
    imports: [
        UIRouterUpgradeModule.forChild({states: states})
    ],
    exports: [
        UIRouterUpgradeModule
    ],
})
export class AdminRoutingModule {}

And then the admin module

import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {MessageCenterModule} from 'src/app/admin/pages/message-center/message-center.module';
import {NewsModule} from 'src/app/admin/pages/news/news.module';
import {SearchModule} from 'src/app/admin/pages/search/search.module';

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        MessageCenterModule,
        NewsModule,
        SearchModule
    ]
})
export class AdminModule {}

and for example search.module

import {CommonModule} from '@angular/common';
import {NgModule} from '@angular/core';
import {TranslateModule} from '@ngx-translate/core';
import {ElementsMessagesModule} from 'scripts/modules/elements/messages.a2/messages.module';
import {ElementsNoResultsModule} from 'scripts/modules/elements/no-results.a2/no-results.module';
import {ElementsPageHeaderModule} from 'scripts/modules/elements/page-header/page-header.module';
import {BackendModule} from 'src/app/admin/data/backend/backend.module';
import {ItemModule} from 'src/app/admin/pages/search/item/item.module';
import {SearchRoutingModule} from 'src/app/admin/pages/search/search-routing.module';
import {SearchComponent} from 'src/app/admin/pages/search/search.component';
import {FilterModule} from 'src/app/core/components/filter/filter.module';
import {InputModule} from 'src/app/core/components/filter/input/input.module';
import {PanelModule} from 'src/app/core/components/panel/panel.module';

@NgModule({
    declarations: [SearchComponent],
    imports: [
        BackendModule,
        CommonModule,
        ElementsMessagesModule,
        ElementsNoResultsModule,
        ElementsPageHeaderModule,
        InputModule,
        ItemModule,
        PanelModule,
        SearchRoutingModule,
        TranslateModule,
        FilterModule,
    ],
    exports: [SearchComponent]
})
export class SearchModule { }

with search routing module as you can see not yet lazy loaded, when that will be introduced we would include search-routing module inside the admin module and refer to the search module in the routing module

import {NgModule} from '@angular/core';
import {UIRouterUpgradeModule} from '@uirouter/angular-hybrid';
import {StateDeclaration} from 'hybrid/state.declaration';
import {SearchComponent} from 'src/app/admin/pages/search/search.component';
import {BASIC} from 'src/app/core/auth/permissions/admin.constant';

const states: StateDeclaration[] = [{
    name: 'admin.search',
    url: '/admin/search',
    component: SearchComponent,
    permissions: [BASIC],
    requiresAuth: true
}];

@NgModule({
    imports: [
        UIRouterUpgradeModule.forChild({states: states})
    ],
    exports: [
        UIRouterUpgradeModule
    ],
})
export class SearchRoutingModule {}

Our angularjs module

'use strict';

import angular from 'angular';
// Enable this line and the .run line to enable uiRouter visualizer
// import { visualizer } from '@uirouter/visualizer';

angular.module('dcApp', [
    'dcApp.config', // this needs to be the very first dependency
    'dcApp.publisher.campaigns.modal',

    'dcLayout',
    'dcLibRedirect',
    'dcLibUniqueId',

    /* Pages */
    'dcApp.admin',
    'dcApp.advertiser',
    'dcApp.common',
    'dcApp.leadgeneration',
    'dcApp.publisher'
]);
// Enable this line and the import line to enable uiRouter visualizer
// angular.module('dcApp').run(['$uiRouter', ($uiRouter) => visualizer($uiRouter) ]);

/* Config files */
require('scripts/app-config/app-config.module');
require('scripts/helper/downloadfix');
require('scripts/helper/helper');

/* main module files */
require('scripts/app.controller');
require('hybrid/modal/modal.downgrade');
require('hybrid/cache-service.downgrade');
require('hybrid/modals/campaigns-modal.downgrade');
require('hybrid/modals/invoice-modal.downgrade');
require('hybrid/modals/tickets-modal.downgrade');
require('hybrid/modals/google-modal.downgrade');
require('hybrid/modals/advertiser-last-transactions-modal.downgrade');
require('hybrid/modals/publisher-last-transactions-modal.downgrade');

/* Other main modules */
require('pages/admin/admin.module');
require('pages/advertiser/advertiser.module');
require('pages/common.module');
require('pages/leadgeneration/leadgeneration.module');
require('pages/publisher/publisher.module');
```

and main app.controller
```
'use strict';
import angular               from 'angular';
import $                     from 'jquery';

require('scripts/modules/app-layout/layout.module');

angular.module('dcApp')
    .controller( 'MainController', MainController );

MainController.$inject = [
    '$location',
    '$transitions',
    '$window',
    'AdvertiserFinancialInvoicesInvoiceDetailModal',
    'AdvertiserLastTransactionsModalObserver',
    'AdvertiserTransactionsOverviewDetailModal',
    'AngularModalObserver',
    'AppConfig',
    'AppLayout',
    'AuthAuthenticator',
    'AuthAuthenticatorHelper',
    'AuthIdentity',
    'AuthObserver',
    'CampaignInformationModal',
    'ConnectionsGoogleLoginModal',
    'ElementsMessagesHelper',
    'GoogleModalObserver',
    'InvoiceModalObserver',
    'MediaVerificationModal',
    'PublisherLastTransactionsModalObserver',
    'TicketDetailModal',
    'TicketsModalObserver',
    'TransactionModal'
];

function MainController(
    $location,
    $transitions,
    $window,
    AdvertiserFinancialInvoicesInvoiceDetailModal,
    AdvertiserLastTransactionsModalObserver,
    AdvertiserTransactionsOverviewDetailModal,
    AngularModalObserver,
    AppConfig,
    AppLayout,
    AuthAuthenticator,
    AuthAuthenticatorHelper,
    AuthIdentity,
    AuthObserver,
    CampaignInformationModal,
    ConnectionsGoogleLoginModal,
    ElementsMessagesHelper,
    GoogleModalObserver,
    InvoiceModalObserver,
    MediaVerificationModal,
    PublisherLastTransactionsModalObserver,
    TicketDetailModal,
    TicketsModalObserver,
    TransactionModal
) {

    let $ctrl = this;

    $ctrl.layout = AppLayout;

    $ctrl.$onInit = onInit;

    function onInit() {

        initPage(true);

        $transitions.onError( {}, function( transition ) {
            let transitionError = transition.error();
            if ([4,6].indexOf(transitionError.type) !== -1)
            {
                ElementsMessagesHelper.getInstance('generalError').addMessage( transition.error(), 'error', 'primaryError' );
                AppLayout.hideSplashPage();
                $location.path( '/error' );
            }
        } );

        $transitions.onSuccess({}, function(transition) {
            initPage(transition.from().name !== transition.to().name);
            if ($window.ga) {
                $window.ga('send', 'pageview', { page: $location.url() });
            }
        });

        // No on destroy since the entire app is then gone
        AuthObserver.loginAsChange$.subscribe(function __loginAs(loginAsModel) {
            AuthAuthenticatorHelper.loginAs(
                {
                    id: loginAsModel.account_id,
                    type: loginAsModel.account_type
                },
                loginAsModel.user_id || null,
                loginAsModel.destination || null,
                loginAsModel.sameWindow || null
            );
        });

        AuthObserver.activityChange$.subscribe(AuthAuthenticator.updateLastActivity);
        AuthObserver.logoutExpire$.subscribe(AuthAuthenticator.logoutExpire);
        AuthObserver.updateAccount$.subscribe((account) => AuthIdentity.initAccount(AuthIdentity.getAccountType(), account));

        AngularModalObserver.showMediaVerification$.subscribe((event) => MediaVerificationModal.show(event.mediaId));
        InvoiceModalObserver.openModal$.subscribe(AdvertiserFinancialInvoicesInvoiceDetailModal.show);
        PublisherLastTransactionsModalObserver.openModal$.subscribe((affiliatemarketingId) => TransactionModal.show(affiliatemarketingId));
        AdvertiserLastTransactionsModalObserver.openModal$.subscribe((affiliatemarketingId) => AdvertiserTransactionsOverviewDetailModal.show(affiliatemarketingId));
        TicketsModalObserver.openModal$.subscribe((ticketId) => TicketDetailModal.show(ticketId, false));
        GoogleModalObserver.openModal$.subscribe(() => ConnectionsGoogleLoginModal.show())
    }

    function initPage(pageChange) {
        if (pageChange) {
            $(window).scrollTop(0);
        }

        $ctrl.currentPage = $location.path();
        AppLayout.hideSplashPage();
    }

}


from Angular 9 hybrid with ui router causes Trying to get the AngularJS injector before it being set. How to debug/fix?

Video capture in mobile browser at 60 FPS

I am trying to capture video at 60 FPS from a web app in Chrome Android. I have the appropriate video.frameRate constraint set for the call to getUserMedia. Chrome recognizes the frameRate setting and reports through the video track setting that it is capturing at 60 FPS but visually the video is only 30 FPS and not 60. On the same device through the stock Android Camera app it captures smooth 60 FPS video at the same resolution as I am trying through the web app.

I am testing this with Chrome Android 84 on a Pixel 3a. I have also tested on other phones at resolutions that those phones support at 60 FPS and regardless it only captures at 30 FPS.

Below is example code that demonstrates this behavior.

How can I achieve this? Or is capturing at 60 FPS not currently possible with Chrome Android?

<html>
<head>
    <title>frameRate</title>
    <script>
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            var constraints = {
                video: {
                    width: { exact: 1920 },
                    height: { exact: 1080 },
                    facingMode: { ideal: "environment" },
                    frameRate: { exact: 60 }
                }
            };
            navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
                var video = document.getElementById('video');
                video.srcObject = stream;
                video.play();
                document.getElementById('frameRate').innerHTML = 'frameRate: ' + stream.getTracks()[0].getSettings().frameRate;
            });
        }
    </script>
</head>

<body>
    <p id="frameRate"></p>
    <video id="video" width="1920" height="1080"></video>
</body>
</html>


from Video capture in mobile browser at 60 FPS

Mock Javascript AWS.RDS.Signer

I have Connection class that is used to connect to AWS Rds Proxy via IAM Authentication. Part of that process is to create a token. I have a function to create the token but now I having a hard time to mock and test it.

Here is the Connection class with setToken method:

class Connection {
    constructor(username, endpoint, database) {
        this.username = username;
        this.endpoint = endpoint;
        this.database = database;
    }

    setToken () {
        let signer = new AWS.RDS.Signer({
            region: 'us-east-1', // example: us-east-2
            hostname: this.endpoint,
            port: 3306,
            username: this.username
        });

        this.token = signer.getAuthToken({
            username: this.username
        });
    }
}

And here I am trying to mock the return value of AWS.RDS.Signer.getAuthToken()

test('Test Connection setToken', async () => {
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('RDS.Signer', 'getAuthToken', 'mock-token');


    let conn = new connections.Connection(
        'testUser',
        'testEndpoint',
        'testDb');

    conn.setToken();

    console.log(conn.token);
});

I expected to see "mock-token" as the value for conn.token, but what I get is this:

{
  promise: [Function],
  createReadStream: [Function: createReadStream],
  on: [Function: on],
  send: [Function: send]
}

How can I get AWS.RDS.Signer.getAuthToken() to return a mock token?



from Mock Javascript AWS.RDS.Signer

How to Load two different Python Modules whose shared library requirements conflict if set globally

I am working on a project where I need to use two python modules together:

After following the instructions to install PyMesh from source, I was able to succesfully import pymesh with my Python 3.8 interpreter (on Ubuntu 18).

I then downloaded and installed PyRep. This initially didn't work, and gave the error:

    ~/.local/lib/python3.8/site-packages/pyrep/backend/sim.py in <module>
      1 from .simConst import *
----> 2 from ._sim_cffi import ffi, lib
      3 import numpy as np
      4 import collections
      5 

ImportError: libcoppeliaSim.so.1: cannot open shared object file: No such file or directory

The installation instructions for PyRep said this is because I need to ensure that PyRep has access to the shared libraries in my local CoppeliaSim installation, and that I should add the following lines to my .bashrc:

export COPPELIASIM_ROOT=EDIT/ME/PATH/TO/COPPELIASIM/INSTALL/DIR
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$COPPELIASIM_ROOT
export QT_QPA_PLATFORM_PLUGIN_PATH=$COPPELIASIM_ROOT

Success! I can import pyrep without issue. However, if I now import pymesh again, I get an error:

~/.local/lib/python3.8/site-packages/pymesh2-0.3-py3.8-linux-x86_64.egg/pymesh/Mesh.py in <module>
      3 import numpy as np
      4 
----> 5 import PyMesh
      6 
      7 class Mesh(object):

ImportError: /home/craig/Programs/CoppeliaSim/libtbb.so: file too short

By globally setting $LD_LIBRARY_PATH at bash login as suggested, I've caused pymesh to search for conflicting shared libraries in the Coppelia-Sim Root folder! (Looking for solutions, I found an article which condems changing $LD_LIBRARY_PATH in .bashrc for exactly this reason)

How do I resolve this dilemna? PyRep asks me to add a directory to the LD_LIBRARY_PATH, but PyMesh breaks if I do so (though I can get each to work in isolation).

Attempted Alternatives

I have learned through researching this problem that you can change where a particular shared library looks for dependencies using the patchelf command. So I tried just manually tweaking where the offending PyRep _sim_cffi library with:

patchelf --set-rpath "/home/craig/Programs/CoppeliaSim" ~/.local/lib/python3.8/site-packages/pyrep/backend/_sim_cffi.cpython-38-x86_64-linux-gnu.so

However, this just leads to transitive dependency errors one level down:

~/.local/lib/python3.8/site-packages/pyrep/backend/sim.py in <module>
      1 from .simConst import *
----> 2 from ._sim_cffi import ffi, lib
      3 import numpy as np
      4 import collections
      5 

ImportError: libQt5SerialPort.so.5: cannot open shared object file: No such file or directory


from How to Load two different Python Modules whose shared library requirements conflict if set globally