Monday 30 September 2019

Package doesn't relate on its internal node_modules packages dependencies, uses external scope instead

I can't figure out why project dependency babel-polifyll doesn't relate to its internal packages from the own node_modules root (they're present there actually). Instead, it trying to get some dependency packages from the same level as the common project node_modules scope...

I understand that this is not a bug in babel-polifyll, probably something happens in node/yarn environment for sure. Anyway, I can't spot what exactly wrong...

Error:enter image description here

Babel-polifyll reqiure imports that links from external scope: enter image description here



from Package doesn't relate on its internal node_modules packages dependencies, uses external scope instead

Fabricjs function to join 2 objects with line

I have a canvas where I can click to place icons and link those icons with a line, but I can't manage to get the lines to follow when moving the icon objects. I tried the following, but I can't manage to lock the ends of the lines to the icon objects.

My effort so far: JSFIDDLE

canvas.on('mouse:move', function (obj) {
var line = canvas.getItemByName('line');
var objEl = canvas.getActiveObject();
var type = objEl.get('type');
var leftEl = objEl.left;
var topEl = objEl.top;

canvas.getObjects().forEach((obj) => {
    var lineX1 = line.get('x1');
    var lineY1 = line.get('y1');
    var lineX2 = line.get('x2');
    var lineY2 = line.get('y2');

    if (lineX1 == leftEl && lineY1 == topEl) {
        line.set({
            x1: leftEl,
            y1: topEl
        });
        canvas.renderAll();
    };
});

line.set('opacity', 1);
});


from Fabricjs function to join 2 objects with line

Pass asynchronously loaded data to pug-html-loader in webpack

General setup

I am building a small website with webpack and pug based on this awesome boilerplate: https://github.com/alexnoz/webpack-pug-scss-boilerplate.git

The project is up and running and I am able to render pug files correctly.

Requirement

Now I need to load some data before all the webpack compiling happens. I want to pass that data to the pug-html-loader as described in this answered question.

Problem/Question

My problem is, that I have to load that data asynchronically. So what I have is a Promise. How can I make sure that the promise is finished before webpack compile happens?

This is my current aproach that doesn't work

// in webpack.config.js

var myData = []
loadSomeDataAsync().then(loadedData => myData = loadedData)

{
  loader: 'pug-html-loader',
  options: {
    data: myData    // <==== 
  }
}

pug-html-loader accepts the options.data If I put static data there, then this data is available inside the pug template.

I know that my problem seems to be, that my Promise is not yet resolved, before the webpack compile happens. But how can get webpack to somehow "wait" for the Promise to resolve?

I already tried to register webpack event hooks. But did not succeed. Any further suggestions?



from Pass asynchronously loaded data to pug-html-loader in webpack

Is there better way to open vcf file from react native except Linking

When I try:

Linking.openURL("....vcf");

My app open browser and contacts with specified vcf is displayed.
Is there way to avoid this in react native and open vcf without moving to browser first?



from Is there better way to open vcf file from react native except Linking

Is there better way to open vcf file from react native except Linking

When I try:

Linking.openURL("....vcf");

My app open browser and contacts with specified vcf is displayed.
Is there way to avoid this in react native and open vcf without moving to browser first?



from Is there better way to open vcf file from react native except Linking

Download Spotify Song Through Spotify api Swift

I am developing an iPhone application with integrating Spotify SDK. Is there any way I can download the Spotify song through any Spotify Api or any other way because I developing a music application which change the song bpm (Beats Per Minutes). But I can’t change Spotify song bpm because Spotify song play online through Spotify methods with the Spotify premium account. So any way to download Spotify song.



from Download Spotify Song Through Spotify api Swift

How to have a scroll down and up infinite animation in an overflow div in React?

Basically, I have an overflow list of items with fixed height, so it's always be able to scroll.

So the overflow div will scroll down its content, for example in 4 seconds with 0.5 second delay then scroll up its content in 4 seconds with 0.5 second delay. It will be an infinite loop animation.

The only thing that I know is to use scrollTop to make that works on react.

I'm using useAnimation from https://usehooks.com/useAnimation/.

Below is my attempt. Probably my logic is wrong and need some improvements, currently it only scrolls down, scrolls up will break the code

Current attempt on codesandbox :https://codesandbox.io/s/useanimation-ks9nd

import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

function App() {
  const [scrollValue, setScrollValue] = useState(0);
  const scrollListRef = useRef(null);
  const [scrollState, setScrollState] = useState("down");
  const [scrollHeight, setScrollHeight] = useState(0);
  const [offsetHeight, setOffsetHeight] = useState(0);

  useEffect(() => {
    if (scrollListRef.current !== null) {
      setScrollHeight(scrollListRef.current.scrollHeight);
      setOffsetHeight(scrollListRef.current.offsetHeight);
    }
  }, []);
  useEffect(() => {
    if (scrollValue === 0) {
      setScrollState("down");
    } else if (scrollValue === scrollHeight - offsetHeight) {
      console.log("state up ne");
      setScrollState("up");
    }
  }, [offsetHeight, scrollHeight, scrollValue]);

  let durationTime = 4000; // seconds
  const animationDown = useAnimation("linear", durationTime / 2, 500);
  let animationUp = useAnimation("linear", durationTime / 2, 500);

  useEffect(() => {
    let scrollMax = scrollHeight - offsetHeight;
    if (scrollState === "down") {
      let value = animationDown * scrollMax;
      setScrollValue(value);
    } else if (scrollState === "up") {
      let value = scrollMax - animationUp * scrollMax;
      // setScrollValue(value)
    }
  }, [animationDown, animationUp, offsetHeight, scrollHeight, scrollState]);

  useEffect(() => {
    let ele = document.getElementById("locationsListScroll");
    ele.scrollTop = scrollValue;
  }, [scrollValue]);

  const lists = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let ulStyle = {
    padding: 0,
    position: "relative",
    marginLeft: "50%",
    marginTop: "3rem",
    transform: "translate(-25%)",
    maxHeight: 200,
    overflow: "auto"
  };
  let liStyle = {
    listStyleType: "none",
    height: 80,
    width: 80,
    display: "flex",
    border: "1px solid black",
    justifyContent: "center",
    alignItems: "center"
  };
  return (
    <div style=>
      <ul
        ref={scrollListRef}
        id="locationsListScroll"
        className="row locations-list"
        style={ulStyle}
      >
        {lists.map((item, i) => (
          <li style={liStyle} key={i}>
            {item}
          </li>
        ))}
      </ul>
    </div>
  );
}
function useAnimationTimer(duration = 1000, delay = 0) {
  const [elapsed, setTime] = useState(0);

  useEffect(
    () => {
      let animationFrame, timerStop, start;

      // Function to be executed on each animation frame
      function onFrame() {
        setTime(Date.now() - start);
        loop();
      }

      // Call onFrame() on next animation frame
      function loop() {
        animationFrame = requestAnimationFrame(onFrame);
      }

      function onStart() {
        // Set a timeout to stop things when duration time elapses
        timerStop = setTimeout(() => {
          cancelAnimationFrame(animationFrame);
          setTime(Date.now() - start);
        }, duration);

        // Start the loop
        start = Date.now();
        loop();
      }

      // Start after specified delay (defaults to 0)
      const timerDelay = setTimeout(onStart, delay);

      // Clean things up
      return () => {
        clearTimeout(timerStop);
        clearTimeout(timerDelay);
        cancelAnimationFrame(animationFrame);
      };
    },
    [duration, delay] // Only re-run effect if duration or delay changes
  );

  return elapsed;
}

function useAnimation(easingName = "linear", duration = 500, delay = 0) {
  // The useAnimationTimer hook calls useState every animation frame ...
  // ... giving us elapsed time and causing a rerender as frequently ...
  // ... as possible for a smooth animation.
  const elapsed = useAnimationTimer(duration, delay);
  // Amount of specified duration elapsed on a scale from 0 - 1
  const n = Math.min(1, elapsed / duration);
  // Return altered value based on our specified easing function
  return easing[easingName](n);
}

// Some easing functions copied from:
// https://github.com/streamich/ts-easing/blob/master/src/index.ts
// Hardcode here or pull in a dependency
const easing = {
  linear: n => n,
  elastic: n =>
    n * (33 * n * n * n * n - 106 * n * n * n + 126 * n * n - 67 * n + 15),
  inExpo: n => Math.pow(2, 10 * (n - 1))
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


from How to have a scroll down and up infinite animation in an overflow div in React?

Does firebase set apns-push-type header automatically?

According to changes in iOS 13 for APNS, silent push notifications require additional header (apns-push-type).

I use Firebase as a mediator between backend and mobile, and I'm wondering if Firebase sets mentioned header automatically when content-available property is set to true.

It is already happening in AWS, as mentioned here.

Can I check somehow in iOS if this header was passed to silent push notification?

I've tested on my devices and everything is working after I updated Firebase dependency to the newest version, even in background. But still I don't have any proof how the header looks like.



from Does firebase set apns-push-type header automatically?

Enabling Bitcode in dynamic framework

I am currently building a dynamic framework for iOS and tvOS. Therefor I lipo simulator and device binaries to one fat library via script. Bitcode is enabled in Build Settings, as you can see here:

Build Settings

I verified the library after creation with otool. Bitcode is definitely enabled. When I now try to add this library to my Main App via Cocoapod and validate this App with Archive -> Validate, I am getting the following error message:

XCode error

Build Settings Demo App

Somebody has a clue why the AppStore is complaining?



from Enabling Bitcode in dynamic framework

wheel event PreventDefault does not cancel wheel event

I would like to get one event only per scroll event

I try this code but it produces "wheel" as many times the wheel event is triggered. Any help? Thank you

window.addEventListener("wheel",
    (e)=> {
        console.log("wheel");
        e.preventDefault();
    },
    {passive:false}
    );

Use case (edit) I want to allow scrolling from page to page only - with an animation while scrolling. As soon I detect the onwheel event, I would like to stop it before the animation finishes, otherwise the previous onwheel continues to fire and it is seen as new event, so going to the next of the targeted page



from wheel event PreventDefault does not cancel wheel event

Enter event doesn't trigger the function on Android device using angular

There are multiple questions with answers related to my problem but unfortunately, none worked for me.

I have to detect the enter pressed on android keyboard and change focus from current matInput to next matInput.

I have tried keyup.enter, keydown and keypress but none worked for me. I implemented directive approach but doesn't trigger method when I am debugging app on Android device. Although, it does trigger the method on browser.

Here is what I am using.

HTML:

    <mat-form-field class="ib-input-container-width">
  <input matInput data-dependency="lastName" (keypress)="onChange($event.keyCode)" (keyup.enter)="handleNext('lastName')"  [formControl]="form.get('FirstName')" type="text" >

</mat-form-field>

<mat-form-field class="ib-input-container-width" >
  <input #lastName id="lastName" matInput  [formControl]="form.get('LastName')" type="text">

TS:

  handleNext(elementId){
    let nextElement = document.getElementById(elementId);
    console.log(nextElement);
    nextElement.focus();
  }

  onChange(event){
    console.log(event.keycode);
  }

PS: I am on a working progressive web app using Cordova.

Update

I have tried solution from https://stackoverflow.com/a/28103608/3081929 But ng-change doesn't work either.



from Enter event doesn't trigger the function on Android device using angular

Enter event doesn't trigger the function on Android device using angular

There are multiple questions with answers related to my problem but unfortunately, none worked for me.

I have to detect the enter pressed on android keyboard and change focus from current matInput to next matInput.

I have tried keyup.enter, keydown and keypress but none worked for me. I implemented directive approach but doesn't trigger method when I am debugging app on Android device. Although, it does trigger the method on browser.

Here is what I am using.

HTML:

    <mat-form-field class="ib-input-container-width">
  <input matInput data-dependency="lastName" (keypress)="onChange($event.keyCode)" (keyup.enter)="handleNext('lastName')"  [formControl]="form.get('FirstName')" type="text" >

</mat-form-field>

<mat-form-field class="ib-input-container-width" >
  <input #lastName id="lastName" matInput  [formControl]="form.get('LastName')" type="text">

TS:

  handleNext(elementId){
    let nextElement = document.getElementById(elementId);
    console.log(nextElement);
    nextElement.focus();
  }

  onChange(event){
    console.log(event.keycode);
  }

PS: I am on a working progressive web app using Cordova.

Update

I have tried solution from https://stackoverflow.com/a/28103608/3081929 But ng-change doesn't work either.



from Enter event doesn't trigger the function on Android device using angular

Angular: FileReader - get Name from File out of list

I used this FileReader to read csvs:

readDocument(fileChangeEvent: Event) {
  return new Observable<any>(obs => {
      const file = (fileChangeEvent.target as HTMLInputElement).files[0];
      if (file) {
        const fileReader = new FileReader();
        fileReader.onload = e => {
          obs.next({
            name: file.name,
            result: fileReader.result
          });
        };
        fileReader.readAsText(file);
      } 
    });

With this, I could then use the file in my subscription and use it's name or value anytime:

this.readDocument(csv).subscribe(value => {
            console.log(value.name);
            console.log(value.result
}

Meanwhile I have this Filereader for reading a folder that has csvs stored inside:

  public readFolder(files: string[]) {
    this.fileCache = [];
    this.readFile(0, files);
    return this.folderReader$.asObservable();
  }

  private readFile(index, files) {
    const reader = new FileReader();
    if (index >= files.length) {
      this.folderReader$.next(this.fileCache);
      return;
    }
    const file = files[index];
    const filename = file.name;
    console.log(filename);
    reader.onload = (e: any) => {
      this.fileCache.push(e.target.result);

      this.readFile(index + 1, files);
    };
    reader.readAsBinaryString(file);
  }

Now, with this i do get an array which is filled with the data of each csv in the folder. I can then later use for example a loop to show the all the file-data.

files = []
this.folderReader.readFolder(csv.target.files).subscribe(files => {
      files.forEach((value, key) => {
            console.log(key + ': ' + value);
     }
}

My problem is, id like to be able to read the value and the name of the file again, like in the first example. It should look something like this in the end:

this.folderReader.readFolder(csv.target.files).subscribe(files => {
      files.forEach((file) => {
            console.log(file.name)
            console.log(file.result)

     }
}

I am struggling to modify the second FileReader to give a similar output as the first just in an array. What can i do to improve my FileReader so it will give the output i want to? Is there an even easier way maybe?



from Angular: FileReader - get Name from File out of list

Running ng build in gulp uses older version of node.js

I have a gulp script for building angular files with ng build. It works if I run it from command prompt, but fails when I run it from gulp with error:

You are running version v10.6.0 of Node.js, which is not supported by Angular CLI 8.0+.The official Node.js version that is supported is 10.9 or greater.Please visit https://nodejs.org/en/ to find instructions on how to update Node.js.Process terminated with code 0.C:***> cmd.exe /c gulp -b "C:***" --color --gulpfile "C:***\Gulpfile.js" default

I have globally installed version of node v10.16.3, but it for some reason it says that I have v10.6.0. I am also using Gulp 4.

My gulp file looks like this:

var exec = require('child_process').exec;

gulp.task('buildNg', async function (cb) {
  exec('ng build', function (err, stdout, stderr) {
    console.log(stdout);
    console.log(stderr);
    cb(err);
  });
})

Does gulp use its own version of node.js? I don't see any other reason.



from Running ng build in gulp uses older version of node.js

kafka client is sending request to partition where broker which went down

I am using kafka-node module to send message to kafka. In a clustered environment where I have a topic with 3 partitions and replication factor as 3.

Topic describe is -

Topic:clusterTopic      PartitionCount:3        ReplicationFactor:3    Configs:min.insync.replicas=2,segment.bytes=1073741824
        Topic: clusterTopic     Partition: 0    Leader: 1       Replicas: 1,2,3 Isr: 1,2,3
        Topic: clusterTopic     Partition: 1    Leader: 2       Replicas: 2,3,1 Isr: 1,2,3
        Topic: clusterTopic     Partition: 2    Leader: 3       Replicas: 3,1,2 Isr: 1,2,3

Producer config -

        "requireAcks": 1,
        "attributes": 2,
        "partitionerType": 2,
        "retries": 2

When I send data it follows partition-type as cyclic(2) like round-robin fashion

when I follow below steps

  • Get a HighLevelProducer instance connected to kafka:9092,kafka:9093
  • send a message
  • stop the kafka-server:9092 manually
  • try and send another message with the HighLevelProducer and send() will trigger the callback with error: TimeoutError: Request timed out after 30000ms

What I am expecting is if a partition is not accessible (as a broker is down) producer should automatically send data to next available partition but I am losing message because of exception



from kafka client is sending request to partition where broker which went down

Is it posible to see the async storage current limit React Native?

I would like to know how much is the remaining memory of a react native application using async storage.

I know in general is about 6 MB the total consumption, but I did not see in any of the methods of async storage "expo" from react native how much is the current consumption and how much is it allowed to be used from the current device.

I would love to have something like:

const currentMemory = AsyncStorage.currentMemoryConsumption();
const deviceMemoryLimit = AsyncStorage.deviceMemoryLimit();

And then I would be able to know the current memory consumption make an analysis and provide meaningful information to my client.

I don't see any information either in the current implementation of react native async storage from community.

Is it possible to know about the current memory state before using async storage to save an item?

Thanks in advance for the reading and help



from Is it posible to see the async storage current limit React Native?

RecyclerView: Inconsistency detected. Invalid item position - why is that?

Our QA has detected a bug: the following RecyclerView-related crash happened: `

java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position 2(offset:2).state:3

A brutal workaround could be perhaps to catch the exception when it happens and re-create the RecyclverView instance from scratch, to avoid getting left with a corrupted state.

But, if possible, I would like to understand the problem better (and perhaps fix it at its source), instead of masking it.

The bug is easy to reproduce scrolling continues fast creating this crash, but it is fatal when it happens.

My wokring code is:

public class MoviesGridRecyclerViewDataAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public static final int VIEW_ITEM = 1;
public static final int VIEW_PROG = -1;
private static final int FADE_DURATION = 500;
int pastVisiblesItems, visibleItemCount, totalItemCount;
private List<VideoEntity> dataList;
private FragmentActivity activity;
private int visibleThreshold = 1;
//private int lastVisibleItem, totalItemCount;
//private boolean loading = false;
private OnLoadMoreListener onLoadMoreListener;
private RecyclerView.OnScrollListener recyclerciewScrollListener;
private RecyclerView recyclerView;
private boolean followLargeItemOnDataRender;
private boolean loading = false;
private boolean isLiveChannel = false;

public MoviesGridRecyclerViewDataAdapter(FragmentActivity fragmentActivity, final List<VideoEntity> dataList, RecyclerView recycler, boolean followLargeItemOnOddData, boolean isLiveChannels) {
    this.dataList = dataList;
    this.activity = fragmentActivity;
    this.followLargeItemOnDataRender = followLargeItemOnOddData;
    this.recyclerView = recycler;
    isLiveChannel = isLiveChannels;

    Log.e("VideoGridRVDataAdapter", "True");

    if (this.recyclerView.getLayoutManager() instanceof GridLayoutManager) {

        final GridLayoutManager gridLayoutManager = (GridLayoutManager) this.recyclerView.getLayoutManager();
        recyclerciewScrollListener = new RecyclerView.OnScrollListener() {

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (dy > 0) //check for scroll down
                {
                    visibleItemCount = gridLayoutManager.getChildCount();
                    totalItemCount = gridLayoutManager.getItemCount();
                    pastVisiblesItems = gridLayoutManager.findFirstVisibleItemPosition();

                    if (!loading) {
                        if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                            loading = true;


                            if (onLoadMoreListener != null) {
                                onLoadMoreListener.onLoadMore(visibleItemCount + pastVisiblesItems);
                            }
                        }
                    }
                }
            }
        };

        this.recyclerView.addOnScrollListener(recyclerciewScrollListener);
    }
}


public void notifyDataLoadingStartProgress() {
    dataList.add(null);
    notifyItemInserted(dataList.size() - 1);
}

public void notifyDataLoaded() {
    dataList.remove(dataList.size() - 1);
    notifyItemRemoved(dataList.size());
    setLoaded();
}


public void resetItems(@NonNull List<VideoEntity> newDataSet) {
    loading = false;
    pastVisiblesItems = visibleItemCount = totalItemCount = 0;

    dataList.clear();
    addItems(newDataSet);
}

public void addItems(@NonNull List<VideoEntity> newDataSetItems) {
    dataList.addAll(newDataSetItems);
    postAndNotifyAdapter(new Handler());
}



public void addItem(VideoEntity item) {
    if (!dataList.contains(item)) {
        dataList.add(item);
        notifyItemInserted(dataList.size() - 1);
    }
}

public void removeItem(VideoEntity item) {
    int indexOfItem = dataList.indexOf(item);
    if (indexOfItem != -1) {
        this.dataList.remove(indexOfItem);
        notifyItemRemoved(indexOfItem);
    }
}

private void postAndNotifyAdapter(final Handler handler) {
    handler.post(new Runnable() {
        @Override
        public void run() {
            if (!recyclerView.isComputingLayout()) {
                try {
                    recyclerView.getRecycledViewPool().clear();
                    notifyDataSetChanged();
                } catch (IndexOutOfBoundsException ex) {
                }

            } else {
                postAndNotifyAdapter(handler);
            }
        }
    });
}

public void destroy() {
    this.recyclerView.removeOnScrollListener(recyclerciewScrollListener);
}


@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    RecyclerView.ViewHolder vh;
    View v;
    if (viewType == VIEW_PROG) {
        v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_progressbar, viewGroup, false);
        vh = new ProgressViewHolder(v);

    } else {
        Integer layoutResourceId;

        if (isLiveChannel) {
            layoutResourceId = R.layout.item_video_grid_norma_hs_overfow_overdraw;

        } else {
            layoutResourceId = R.layout.item_video_linear_overdraw;

        }
        v = LayoutInflater.from(viewGroup.getContext()).inflate(layoutResourceId, viewGroup, false);
        vh = new MoviesItemRowHolder(this, dataList, v, activity);
    }
    return vh;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int i) {

    if (holder instanceof MoviesItemRowHolder) {
        VideoEntity singleItem = dataList.get(i);
        ((MoviesItemRowHolder) holder).bind(singleItem,dataList);
        //setScaleAnimation(holder.itemView);
    } else {
        ((ProgressViewHolder) holder).progressBar.setIndeterminate(true);
    }
}

public boolean isLoading() {
    return loading;
}

public void setLoaded() {
    loading = false;
}

private void setFadeAnimation(View view) {
    AlphaAnimation anim = new AlphaAnimation(0.0f, 1.0f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

private void setScaleAnimation(View view) {
    ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    anim.setDuration(FADE_DURATION);
    view.startAnimation(anim);
}

/**
 * Return the view type of the item at <code>position</code> for the purposes
 * of view recycling.
 * <p/>
 * <p>The default implementation of this method returns 0, making the assumption of
 * a single view type for the adapter. Unlike ListView adapters, types need not
 * be contiguous. Consider using id resources to uniquely identify item view types.
 *
 * @param position position to query
 * @return integer value identifying the type of the view needed to represent the item at
 * <code>position</code>. Type codes need not be contiguous.
 */
@Override
public int getItemViewType(int position) {
    //return position;

    return dataList.get(position) != null ? position : VIEW_PROG;
}

@Override
public int getItemCount() {
    return (null != dataList ? dataList.size() : 0);
}

public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
    this.onLoadMoreListener = onLoadMoreListener;
}

public List<VideoEntity> getItems() {
    return dataList;
}
}

Please have a look my class and let me know whats going wrong, when i scrolling fast this crash happend in fewer devices.

Any lead highly appreciated Thanks.



from RecyclerView: Inconsistency detected. Invalid item position - why is that?

Separating business logic and Nodejs api for Angular Node JS project

I am crating a project with has the below components.

  1. Angular 7
  2. Node Js
  3. MongoDB

The Angular and the Node JS API is hosted on the same server because the Angular need to access API for action (it can be on different as well but both are internet facing).
The Node JS connects to MongoDB for database realated stuff.

The challenge is that we don't want to expose the Business Logic on internet due to security reasons and best practice.
Is that any way I can write any wrapper over NodeJs and host it over the internet and the original API (created in NodeJS) containing the business logic on non internet zone.
Any reference or link will be appreciated.



from Separating business logic and Nodejs api for Angular Node JS project

Separating business logic and Nodejs api for Angular Node JS project

I am crating a project with has the below components.

  1. Angular 7
  2. Node Js
  3. MongoDB

The Angular and the Node JS API is hosted on the same server because the Angular need to access API for action (it can be on different as well but both are internet facing).
The Node JS connects to MongoDB for database realated stuff.

The challenge is that we don't want to expose the Business Logic on internet due to security reasons and best practice.
Is that any way I can write any wrapper over NodeJs and host it over the internet and the original API (created in NodeJS) containing the business logic on non internet zone.
Any reference or link will be appreciated.



from Separating business logic and Nodejs api for Angular Node JS project

Keras U-Net weighted loss implementation

I'm trying to separate close objects as was shown in the U-Net paper (here). For this, one generates weight maps which can be used for pixel-wise losses. The following code describes the network I use from this blog post.

x_train_val = # list of images (imgs, 256, 256, 3)
y_train_val = # list of masks (imgs, 256, 256, 1)
y_weights = # list of weight maps (imgs, 256, 256, 1) according to the blog post 
# visual inspection confirms the correct calculation of these maps

# Blog posts' loss function
def my_loss(target, output):
    return - tf.reduce_sum(target * output,
                           len(output.get_shape()) - 1)

# Standard Unet model from blog post
_epsilon = tf.convert_to_tensor(K.epsilon(), np.float32)

def make_weighted_loss_unet(input_shape, n_classes):
    ip = L.Input(shape=input_shape)
    weight_ip = L.Input(shape=input_shape[:2] + (n_classes,))

    conv1 = L.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(ip)
    conv1 = L.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv1)
    conv1 = L.Dropout(0.1)(conv1)
    mpool1 = L.MaxPool2D()(conv1)

    conv2 = L.Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(mpool1)
    conv2 = L.Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv2)
    conv2 = L.Dropout(0.2)(conv2)
    mpool2 = L.MaxPool2D()(conv2)

    conv3 = L.Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(mpool2)
    conv3 = L.Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv3)
    conv3 = L.Dropout(0.3)(conv3)
    mpool3 = L.MaxPool2D()(conv3)

    conv4 = L.Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(mpool3)
    conv4 = L.Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv4)
    conv4 = L.Dropout(0.4)(conv4)
    mpool4 = L.MaxPool2D()(conv4)

    conv5 = L.Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(mpool4)
    conv5 = L.Conv2D(1024, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv5)
    conv5 = L.Dropout(0.5)(conv5)

    up6 = L.Conv2DTranspose(512, 2, strides=2, kernel_initializer='he_normal', padding='same')(conv5)
    conv6 = L.Concatenate()([up6, conv4])
    conv6 = L.Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
    conv6 = L.Conv2D(512, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv6)
    conv6 = L.Dropout(0.4)(conv6)

    up7 = L.Conv2DTranspose(256, 2, strides=2, kernel_initializer='he_normal', padding='same')(conv6)
    conv7 = L.Concatenate()([up7, conv3])
    conv7 = L.Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv7)
    conv7 = L.Conv2D(256, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv7)
    conv7 = L.Dropout(0.3)(conv7)

    up8 = L.Conv2DTranspose(128, 2, strides=2, kernel_initializer='he_normal', padding='same')(conv7)
    conv8 = L.Concatenate()([up8, conv2])
    conv8 = L.Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)
    conv8 = L.Conv2D(128, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv8)
    conv8 = L.Dropout(0.2)(conv8)

    up9 = L.Conv2DTranspose(64, 2, strides=2, kernel_initializer='he_normal', padding='same')(conv8)
    conv9 = L.Concatenate()([up9, conv1])
    conv9 = L.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
    conv9 = L.Conv2D(64, 3, activation='relu', padding='same', kernel_initializer='he_normal')(conv9)
    conv9 = L.Dropout(0.1)(conv9)

    c10 = L.Conv2D(n_classes, 1, activation='softmax', kernel_initializer='he_normal')(conv9)

    # Mimic crossentropy loss
    c11 = L.Lambda(lambda x: x / tf.reduce_sum(x, len(x.get_shape()) - 1, True))(c10)
    c11 = L.Lambda(lambda x: tf.clip_by_value(x, _epsilon, 1. - _epsilon))(c11)
    c11 = L.Lambda(lambda x: K.log(x))(c11)
    weighted_sm = L.multiply([c11, weight_ip])

    model = Model(inputs=[ip, weight_ip], outputs=[weighted_sm])
    return model

I then compile and fit the model as is shown below:

model = make_weighted_loss_unet((256, 256, 3), 1) # shape of input, number of classes
model.compile(optimizer='adam', loss=my_loss, metrics=['acc'])
model.fit([x_train_val, y_weights], y_train_val, validation_split=0.1, epochs=1)

The model can then train as usual. However, the loss doesn't seem to improve much. Furthermore, when I try to predict on new images, I obviously don't have the weight maps (because they are calculated on the labeled masks). I tried to use empty / zero arrays shaped like the weight map but that only yields in blank / zero predictions. I also tried different metrics and more standards losses without any success.

Did anyone face the same issue or have an alternative in implementing this weighted loss? Thanks in advance. BBQuercus



from Keras U-Net weighted loss implementation

How to grab indexPath item from a collection view cell for a delegate?

So I have a collection view that has a section header. In that header I have another collection view that scrolls horizontally. I want to fetch a fixed amount of users in this collection view and be able to push the view controller to the profile page of the selected user.

I have created a delegate since I cannot push view controllers from a reusable view. Here is that delegate.

protocol PeopleToFollowDelegate {
    func handleProfileTapped(for cell: FeedReusableView)
}
  // Create function to push users to the correct profile when selected
    func handleProfileTapped(for header: FeedReusableView) {

        print("profile tapped, push user to the correct profile page")
       let header = FeedReusableView()

        //try to grab the indexpath item so the corrext data is pushed
        let user = header.peopleToFollow // ??? What goes here? I cannot grab index path

            let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

           let profileViewController = storyBoard.instantiateViewController(withIdentifier: "profileViewController") as? ProfileViewController
            profileViewController?.user? = user


            self.navigationController?.pushViewController(profileViewController!, animated: true)

       }

This is where I have issues in the code above. Normally I would just grab the index path item of the profiles called peopleToFollow and push the user to the correct profile like this

        var peopleToFollow = [User]()

        let user = peopleToFollow[indexPath.item]
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let profileViewController = storyBoard.instantiateViewController(withIdentifier: "profileViewController") as? ProfileViewController


        profileViewController?.user = user

        // Then push to next controller

However I cannot write that code in didSelect of the collection view because the collection view is in a section header of collection view ( Reusable view)

How can I get the indexpath for the selected cell and put that code in the delegate?



from How to grab indexPath item from a collection view cell for a delegate?

Using Eigen with EIGEN_USE_BLAS in iOS project

Out of educational purposes I'm trying to use Eigen in my pet project. In order to speed the math I included macro EIGEN_USE_BLAS which activates use of blas library.

But I encountered an issue when I tried to upload my project to Testflight. The Apple response to that was:

ITMS-90338: Non-public API usage - The app references non-public symbols in My-Project: _saxpy_, _sgemm_, _sgemv_, _strmm_, _strmv_. If method names in your source code match the private Apple APIs listed above, altering your method names will help prevent this app from being flagged in future submissions. In addition, note that one or more of the above APIs may be located in a static library that was included with your app. If so, they must be removed. For further information, visit the Technical Support Information at http://developer.apple.com/support/technical/

I know that Apple has blas library as a part of Accelerate.framework and it should be use strictly through Accelerate API. But the thing is that Eigen also has their own blas included in their source and the library actually has no intention of using Accelerate.framework private guts. So that is why Apple asks me to rename those functions or remove them completely in order to get rid of that inconvenience.

But I'm not even sure that it is possible to do - to tune Eigen and its blas to use alternative names.

Is there maybe a way to solve that issue in some efficient manner? Or maybe I don't know something about Eigen usage in iOS environment?



from Using Eigen with EIGEN_USE_BLAS in iOS project

How to treat global user/user data in react?

I'm building a ReactJS project and I'm using something like this, to provide user data trough the app:

function Comp1() {
  const [user, setUser] = useState({});

  firebase.auth().onAuthStateChanged(function (_user) {
    if (_user) {
      // User is signed in.
      // do some firestroe queryes to get all the user's data
      setUser(_user);
    } else {
      setUser({ exists: false });
    }
  });

  return (
    <div>
      <UserProvider.Provider value=>
        <Comp2 />
        <Comp3 />
      </UserProvider.Provider>

    </div>
  );
}

function Comp2(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

function Comp3(props) {
  const { user, setUser } = useContext(UserProvider);
  return (
    <div>
      {user.exists}
    </div>
  )
}

//User Provider

import React from 'react';

const UserProvider = React.createContext();
export default UserProvider;

So, in this case, Comp1 provides user data to Comp2 & Comp3. The only problem is that when the user state changes or the page loads, it creates an infinite loop. If I'm not using an useState for storing the user data, then when it changes, the components do not get re-rendered. I also tried to do something like this in the index.js file:

firebase.auth().onAuthStateChanged(function (user) {
  if (user) {
     ReactDOM.render(<Comp1 user={user} />, document.getElementById('root'));
  } else { 
     ReactDOM.render(<Comp1 user= />, document.getElementById('root'));
  }
});

But this worked a bit weirdly sometimes, and it's kinda messy. What solutions are there? Thanks.

Edit: I'm triening to do it in the wrong way? How should I provide all user data with only one firebase query?



from How to treat global user/user data in react?

Disabling implicit animations in -[CALayer setNeedsDisplayInRect:]

I've got a layer with some complex drawing code in its -drawInContext: method. I'm trying to minimize the amount of drawing I need to do, so I'm using -setNeedsDisplayInRect: to update just the changed parts. This is working splendidly. However, when the graphics system updates my layer, it's transitioning from the old to the new image using a cross-fade. I'd like it to switch over instantly.

I've tried using CATransaction to turn off actions and set the duration to zero, and neither work. Here's the code I'm using:

[CATransaction begin];
[CATransaction setDisableActions: YES];
[self setNeedsDisplayInRect: rect];
[CATransaction commit];

Is there a different method on CATransaction I should use instead (I also tried -setValue:forKey: with kCATransactionDisableActions, same result).



from Disabling implicit animations in -[CALayer setNeedsDisplayInRect:]

Python CFFI: Build single module from multiple source files

My aim is to build a single module/extension from multiple C source files. What is the best practice to achieve this?

What I tried:

I know that theffi.set_source function has the optional sources and include_dir kwargs and that there should be a possibility to use these kwargs to build a single shared object from multiple source files. Unfortunately I cannot find anything regarding these kwargs in the API reference of the CFFI Documentation. So I can't figure out the details. Is there any document which explains how to properly use these kwargs?

I currently use:

SOURCES = ('file_1.c', 'file_2.c')
SRC_ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../src')

ffi_builder = FFI()
ffi_builder.set_source(
    'module_name._module_name',
    ''.join(f'#include "{source}"\n' for source in SOURCES),
    include_dirs=[SRC_ROOT],
)

...

Although this actually works, it seems a bit hacky to me. Is it possible to use sources kwarg instead of the 2nd positional arg source? This would allow me to get rid of the hacky ''.join(f'#include "{source}"\n' for source in SOURCES) part.

If there is even a simpler approach, I would also be interested!

Any help is appreciated. Thank you!



from Python CFFI: Build single module from multiple source files

How to balance two squares on a see saw in matter.js?

I have two boxes sitting on a rectangle that I want to balance on a 2D rectangle that acts like a see-saw.

   World.add(engine.world, [
        Bodies.rectangle(400, 0, 800, 50, { isStatic: true }),
        Bodies.rectangle(400, 600, 800, 50, { isStatic: true }),
        Bodies.rectangle(800, 300, 50, 600, { isStatic: true }),
        Bodies.rectangle(0, 300, 50, 600, { isStatic: true })
    ]);

    var boxA = Bodies.rectangle(283.6, 480, 80, 80, { density: 0.005 });
    var boxB = Bodies.rectangle(520, 480, 80, 80, { density: 0.005});

    var arrow = Vertices.fromPath('40 0 40 20 100 20 100 80 40 80 40 100 0 50'),
        chevron = Vertices.fromPath('100 0 75 50 100 100 25 100 0 50 25 0'),
        star = Vertices.fromPath('50 0 63 38 100 38 69 59 82 100 50 75 18 100 31 59 0 38 37 38'),
        horseShoe = Vertices.fromPath('35 7 19 17 14 38 14 58 25 79 45 85 65 84 65 66 46 67 34 59 30 44 33 29 45 23 66 23 66 7 53 7');
        var catapult = Bodies.rectangle(400, 520, 320, 20, { friction: 0.5, collisionFilter: { group: group } });


    var group = Body.nextGroup(true);
World.add(engine.world, [
    catapult,
    boxA,
    boxB,
    Bodies.rectangle(400, 600, 800, 50.5, { isStatic: true }),
    Constraint.create({ 
        bodyA: catapult, 
        pointB: Vector.clone(catapult.position),
        stiffness: 1,
        length: 0
    })
]);

I adapted it from http://brm.io/matter-js/demo/#catapult and removed a lot of the objects I felt weren't necessary.

I would like to get the objects to balance perfectly, but the issue is the boxes seem to always be sliding. How can I make it so that when the boxes are equal weights that they can balance perfectly, and if I adjust the weight of one side, the see-saw can lean towards the other weight, but not slide off the see-saw? I would prefer if the see-saw weren't overly sensitive to the weight.



from How to balance two squares on a see saw in matter.js?

Apply a 'table'-class to a WooCommerce table after AJAX-call

WooCommerce-tables comes with classes like these, out of the box: shop_table shop_table_responsive cart woocommerce-cart-form__contents. So no table-class, which means no nifty Bootstrap-tables.

Huh!

And since overriding the WooCommerce-templates should only be done when absolutely necessary, then let's solve it with JavaScript!

My entire site it encapsulated by a Vue-div, like so:

<div id="app">
  ...
  <table class="shop_table shop_table_responsive cart woocommerce-cart-form__contents">
    ...
    ...
  </table>
  ... 
</div>

So initially I wrote this code, to add the table-class to all tables:

let tableSelectors = [
  '.some-class table',
  '.woocommerce-product-attributes',
  '.woocommerce-cart-form > table'
];
for( let t = 0; t < tableSelectors.length; t++ ){
  let tables = document.querySelectorAll( tableSelectors[t] );
  if( tables ){
    for( let i = 0; i < tables.length; i++ ){
      tables[i].classList.add( 'table' );
    }
  }
}

... Putting that in the mounted(){ ... }-section.

That worked! So far so good.

But WooCommerce is using jQuery quite a lot. And on the cart page, if I change the quantity (and press 'Update'), then the table-contents are updated using AJAX. If you're curious how it works, then you can check it out here.

And when that runs, I assume that WooCommerce grabs the initial cart-template and reloads that whole table; without the newly added table-class. Bah humbug!

So how can I solve this?

  1. I can override the WooCommerce ./cart/cart.php-template and add the class to the template. Seems like quite the overkill for adding a class.

  2. I can scan the DOM for tables every second (or so) and apply the table class, if it's not there. Not cool... Regardless if it's done using jQuery or Vue.

Since the whole table is being replaced in the DOM, then it doesn't work to monitor the current table (using watch(){...} in Vue) and apply the class if it changes, - since it never changes (it's replaced).

I'm unable to find a Hook that I can use.

I also tried using ajaxComplete, but I can see in the network-tab that the XHR-request is firing, but this code here is never doing anything (in the console):

jQuery( document ).ajaxComplete(function( event, xhr, settings ) {
    console.log( 'Test' );
});

Any other suggestions?



from Apply a 'table'-class to a WooCommerce table after AJAX-call

visjs library - Rendering a network of nodes with svg and custom html

I'm working with the visjs library, and rendering nodes with custom html via the svg tag.

My online project is at: https://stackblitz.com/edit/visjs-with-angular

The problem I'm having is when I attempt to add an image to the div, which is inside an svg.

You can see the vis.component.ts in the 'app\app\vis' folder of my proj, and its associated html view file.

In the drawSvgNetwork() function you will see where I build out the svg. I figured I'd be able to add a <i> tag with a background-image url, but it doesn't seem to be rendering when visjs renders the nodes

var svg = '<svg xmlns="http://www.w3.org/2000/svg" width="390" height="65">' +
          '<rect x="0" y="0" width="100%" height="100%" fill="#7890A7" stroke-width="20" stroke="#ffffff" ></rect>' +
          '<foreignObject x="15" y="10" width="100%" height="100%">' +
          '<div xmlns="http://www.w3.org/1999/xhtml" style="font-family:Arial; font-size:30px">' +
          ' <em>I</em> am' +
          '<span style="color:white; text-shadow:0 0 20px #000000;">' +            
            ' HTML in SVG!</span>' +

          // * THIS IMAGE IS NOT RENDERING * 
          '<i style="background-image: url(https://openclipart.org/download/280615/July-4th-v2B.svg);"></i>' +

          '</div>' +
          '</foreignObject>' +
          '</svg>';

i.e. Here is what you will see when running my online project.

visjs network of nodes.

*For reference:

The full online examples are at: http://visjs.org/network_examples.html And the specific demo page is here (view source to see js code): http://visjs.org/examples/network/nodeStyles/HTMLInNodes.html



from visjs library - Rendering a network of nodes with svg and custom html

Sunday 29 September 2019

How to include nodejs modules in sub directory

I have a directory structure like this for an AWS Lambda layer.

main > nodejs > node_modules

I have a test.js file to test functionality before uploading to AWS. Is it possible to have my test.js file in the Main folder instead of the nodejs folder and still have it pick up the modules in the nodejs folder?

I'm asking because you compress the nodejs folder to upload for the AWS Lambda Layer but I don't want to include my test.js file in the archive.

UPDATE: An answer below helped my find the solution. You just enter the full path to the module in require.

require('./nodejs/node_modules/my_module');


from How to include nodejs modules in sub directory

BiqQuery Storage. Python. Reading multiple streams in parallel issue (multiprocessing)

I am trying to use BALANCED ShardingStrategy to get more then 1 stream and python multiprocessing lib to read stream in parallel.

However, when reading streams in parallel the same rows number and data is returned. As, if I understand correctly, no data is assigned to any stream before it starts reading and is finalized, so two parallel streams try to read same data and a part of data is never read as a result.

Using LIQUID strategy we can read all the data from one stream, which cannot be split.

According to documentation it is possible to read multiple streams in parallel with BALANCED one. However, I cannot figure out how to read in parallel and to assign different data to each stream

I have the following toy code:

import pandas as pd
from google.cloud import bigquery_storage_v1beta1
import os
import google.auth
from multiprocessing import Pool
import multiprocessing

os.environ["GOOGLE_APPLICATION_CREDENTIALS"]='key.json'
credentials, your_project_id = google.auth.default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
bq_storage_client = bigquery_storage_v1beta1.BigQueryStorageClient(credentials=credentials)

table_ref = bigquery_storage_v1beta1.types.TableReference()
table_ref.project_id = "bigquery-public-data"
table_ref.dataset_id = "ethereum_blockchain"
table_ref.table_id = "contracts"

parent = "projects/{}".format(your_project_id)
session = bq_storage_client.create_read_session(
    table_ref,
    parent,
    format_=bigquery_storage_v1beta1.enums.DataFormat.ARROW,
    sharding_strategy=(bigquery_storage_v1beta1.enums.ShardingStrategy.BALANCED),
)

def read_rows(stream_position, session=session):
    reader = bq_storage_client.read_rows(bigquery_storage_v1beta1.types.StreamPosition(stream=session.streams[stream_position]), timeout=100000).to_arrow(session).to_pandas()
    return reader

if __name__ ==  '__main__': 
    p = Pool(2)
    output = p.map(read_rows,([i for i in range(0,2)]))
    print(output)

Need assistance to have multiple streams being read in parallel. Probably there is a way to assign data to a stream before the reading starts. Any examples of code or explanations and tips would be appreciated



from BiqQuery Storage. Python. Reading multiple streams in parallel issue (multiprocessing)

Gae/cloudsql error: Access denied for user 'root'@'cloudsqlproxy

I am running GAE/python application (App Engine Standard Edition) in same project as (2nd Gen) CloudSQL, in same Region as well.

However I continue to get following error

OperationalError: (1045, "Access denied for user 'root'@'cloudsqlproxy~xx.xxx.xx.xx' (using password: NO)")

The apps automatically get authorized, so can't figure out the issue. Also shouldn't the connection be from root@localhost instead of cloudsqlproxy? Do I need to create a 'root'@'cloudsqlproxy user?



from Gae/cloudsql error: Access denied for user 'root'@'cloudsqlproxy

Angular Application Doesn't load up App Module/Components after Upgrade to Angular 8.3.5

We have an Angular 4 project that I've recently tried to upgrade to Angular 8. I followed the migration guide in Angular website, changed some of the syntaxes, and everything preventing project to be built. I faced the problem of my styles were not loading properly locally and not at all on Azure. I found Webpack and tried to configure it, added style-loader, sass-loader, and css-loader. Now when I'm running locally, I can see in the network tab in the browser that all styles are loading properly, but it only loads the default index.html file and not bootstrapping the application.

When I deploy the app on Azure, it loads other components, but none of the styles are loading. I spent 3 weeks on migration, nothing promising yet.

Tools/Plugins version:

Angular CLI: 8.3.5
Node: 10.15.1
OS: win32 x64
Angular: 8.2.7
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... platform-server, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.803.5
@angular-devkit/build-angular     0.803.5
@angular-devkit/build-optimizer   0.803.5
@angular-devkit/build-webpack     0.803.5
@angular-devkit/core              8.3.5
@angular-devkit/schematics        8.3.5
@angular/cdk                      8.2.0
@angular/cli                      8.3.5
@angular/http                     5.2.11
@angular/material                 8.2.0
@ngtools/webpack                  8.3.5
@schematics/angular               8.3.5
@schematics/update                0.803.5
rxjs                              6.5.3
typescript                        3.5.3
webpack                           4.40.2

Here is my Webpack config:

const { resolve } = require('path');
const rxPaths = require('rxjs/_esm5/path-mapping');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ProgressPlugin = require('webpack/lib/ProgressPlugin');
const CircularDependencyPlugin = require('circular-dependency-plugin');
const { AngularCompilerPlugin } = require('@ngtools/webpack');
const { IndexHtmlWebpackPlugin } = require('@angular-devkit/build-angular/src/angular-cli-files/plugins/index-html-webpack-plugin');

module.exports = {

  mode: 'development',

  devtool: 'eval',

  entry: {
    main: './src/main.ts',
    polyfills: './src/polyfills.ts',
    styles: './src/styles.scss'
  },

  output: {
    path: resolve('./dist/'),
    filename: '[name].js',
  },

  resolve: {
    extensions: ['.ts', '.js'],
    alias: rxPaths()
  },

  node: false,

  performance: {
    hints: false,
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: '@ngtools/webpack'
      },
      {
        test: /\.js$/,
        exclude: /(ngfactory|ngstyle).js$/,
        enforce: 'pre',
        use: 'source-map-loader'
      },
      {
        test: /\.html$/,
        use: 'raw-loader'
      },
      {
        test: /\.s[ac]ss$/i,
        use: ['sass-loader'],
        // use: ['to-string-loader, css-loader, sass-loader'],
        exclude: [resolve('./src/styles.scss')]
      },
      {
        test: /\.s[ac]ss$/i,
        // use: ['sass-loader'],
        include: [resolve('./src/styles.scss')]
      },
      {
        test: /\.(eot|svg|cur)$/,
        loader: 'file-loader',
        options: {
          name: `[name].[ext]`,
          limit: 10000
        }
      },
      {
        test: /\.(jpg|png|webp|gif|otf|ttf|woff|woff2|ani)$/,
        loader: 'url-loader',
        options: {
          name: `[name].[ext]`,
          limit: 10000
        }
      },

      // This hides some deprecation warnings that Webpack throws

      {
        test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
        parser: { system: true },
      }
    ]
  },

  plugins: [
    new IndexHtmlWebpackPlugin({
      input: 'index.html',
      output: 'index.html',
      inject: 'body',
      entrypoints: [
        'styles',
        'polyfills',
        'main'
      ]
    }),

    new AngularCompilerPlugin({
      mainPath: resolve('./src/main.ts'),
      sourceMap: true,
      nameLazyFiles: true,
      tsConfigPath: resolve('./src/tsconfig.app.json')
      // ,
      // skipCodeGeneration: true
    }),

    new ProgressPlugin(),

    new CircularDependencyPlugin({
      exclude: /[\\\/]node_modules[\\\/]/
    }),

    new CopyWebpackPlugin([
      {
        from: 'src/assets',
        to: 'assets'
      },
      {
        from: 'src/favicon.ico'
      }
    ])
  ]
};

Please note that the reason I've commented use[] in Webpack config was that it was throwing some postcss-loader exception and on an issue on Github found that some conflict will occur with default sass-loader and Webpack and you should remove them.

Here is the build config in angular.json

        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js",
              "replaceDuplicatePlugins": true
            },
            "outputPath": "./dist/",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets",
              "src/config",
              "src/favicon.ico"
            ],
            "styles": [
              "./src/styles.scss"
            ],
            "scripts": [
              "node_modules/jquery/dist/jquery.min.js",
              "node_modules/bootstrap/dist/js/bootstrap.min.js",
              "node_modules/metismenu/dist/metisMenu.js",
              "node_modules/vis/dist/vis.min.js",
              "vendor/js/jvectormap/jquery-jvectormap-2.0.2.min.js",
              "vendor/js/jvectormap/jquery-jvectormap-us-mill.js",
              "vendor/js/iCheck/icheck.js",
              "node_modules/toastr/toastr.js"
            ]
          },
          "configurations": {
            "dev": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.dev.ts"
                }
              ]
            },
            "local": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            },
            "production": {
              "optimization": true,
              "sourceMap": false,
              "extractCss": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "styles": [
                "./src/styles.scss"
              ]
            }
          }
        },

And here is the serve config in Angular.json.

"serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "browserTarget": "projectName:build",
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            }
          },
          "configurations": {
            "local":{
              "browserTarget": "projectName:build:local"
            }
            ,
            "dev": {
              "browserTarget": "projectName:build:dev"
            },
            "production": {
              "browserTarget": "projectName:build:production"
            }
          }
        },

I have imported all styles in styles.scss using @import statements. Just one thing I am not sure about is that I'm using Highcharts and getting some warnings during the build.

WARNING in ./node_modules/angular2-highcharts/dist/index.js
Module Warning (from ./node_modules/source-map-loader/index.js):
(Emitted value instead of an instance of Error) Cannot find source file '../src/index.ts': Error: Can't resolve '../src/index.ts'

Other than these, there is not compile/runtime error in the project.

Thank you for taking the time to read my problem. I appreciate any hint/tip.

Update: This is how the project structure looks like:

|   .editorconfig
|   .gitignore
|   angular.json
|   browserslist
|   karma.conf.js
|   package-lock.json
|   package.json
|   protractor.conf.js
|   README.md
|   tsconfig.json
|   tslint.json
|   webpack.config.js
|          
+---src
|   |   favicon.ico
|   |   index.html
|   |   index.js
|   |   main.ts
|   |   polyfills.ts
|   |   styles.scss
|   |   test.ts
|   |   tsconfig.app.json
|   |   tsconfig.spec.json
|   |   typings.d.ts
|   |   webpack.config.common.js
|   |   
|   +---app       
|   +---assets
|   |   |
|   |   +---images
|   |   \---styles
|   |       |   style.scss
|   |       |   
|   |               
|   +---config
|   |       dev-config.js
|   |       local-config.js
|   |       prod-config.js
|   |       qa-config.js
|   |       
|   +---environments
|   |       environment.dev.ts
|   |       environment.prod.ts
|   |       environment.qa.ts
|   |       environment.ts
 


from Angular Application Doesn't load up App Module/Components after Upgrade to Angular 8.3.5

How to unit test a click event of a button which is inside a private function?

I have a private function in a service that looks like this. How do I write a unit test for the click event of that button? The button is inside a dialog.

1) Is that even unit testable? 2) Since I've mentioned that this is inside a service and click event is involved, should it be tested like a component? meaning I have to setup TestBed so I can actually click the button, if yes, how? OR is there a more correct way to write a unit test for it, if so, how?

Thank you!

public callOpenDialog(){
   openDialog(formA, dataView, {}, true);
}
private openDialog(formA: FormA, dataView: DataView, placeholder: ViewContainerRef, okToAll: boolean): Observable<ResponseRequiredResult> {
    return new Observable<ResponseRequiredResult>(observer => {
      let dlgComponent: ResponseRequiredModalFormComponent;
      let dialog: DialogRef<ResponseRequiredModalFormComponent>;
      const dialogId = 'ResponseRequired';

      let buttons = [
        {
          id: this.lmUniqueIdService.uniqueId([formA.busFormA.name, dialogId, DialogButtonKey.OK]),
          text: Locale.translate(DialogButtonKey.OK),
          validate : false,
          isDefault: true,
          click: (e, modal) => {
            if (this.validateResponseRequiredForm(formA.busFormA, dlgComponent.formComponent.formModel)) {
              dialog.close(<ResponseRequiredResult> {
                result:     ResponseRequiredDialogResult.RESPONSE_OK,
                specFields: formA.busFormA.fields, model: dlgComponent.formComponent.formModel
              });
            }
          }
        }
      ];

     dialog = modalDialogService
      .modal(ResponseRequiredModalFormComponent, placeholder)
      .buttons(buttons)
      .title(Locale.translate('ResponseRequired'))
      .isAlert(true)
      .open();
}


from How to unit test a click event of a button which is inside a private function?

Securely set unknown property (mitigate square bracket object injection attacks) utility function

After setting up eslint-plugin-security, I went on to attempt to address nearly 400 uses of square brackets in our javascript codebase (flagged by the rule security/detect-object-injection). Although this plugin could be a lot more intelligent, any use of square brackets could possibly be an opportunity for a malicious agent to inject their own code.

To understand how, and to understand the whole context of my question, you need to read this documentation: https://github.com/nodesecurity/eslint-plugin-security/blob/master/docs/the-dangers-of-square-bracket-notation.md

I generally tried to use Object.prototype.hasOwnProperty.call(someObject, someProperty) where I could to mitigate the chance that someProperty is maliciously set to constructor. Lot of situations were simply dereferencing an array index in for loops (for (let i=0;i<arr.length;i++) { arr[i] }) If i is always an int, this is obviously always safe.

One situation I don't think I have handled perfectly, are square bracket assignments like this:

someObject[somePropertyPotentiallyDefinedFromBackend] = someStringPotentiallyMaliciouslyDefinedString

The status quo for StackOverflow is to "show me all the code" - when you are going through a codebase and fixing these in hundreds upon hundreds of instances, it takes a lot longer to go and read the code that comes before one of these assignments. Furthermore, we want to make sure this code stays secure as it's modified in the future.

How can we make sure the property being set is essentially not already defined on vanilla objects? (i.e. constructor)

Attempted to solve this myself, but missing some pieces - see if you can get rest of unit tests to pass:

So I think the easiest way to solve this issue is with a simple util, safeKey defined as such:

// use window.safeKey = for easy tinkering in the console.
const safeKey = (() => {
  // Safely allocate plainObject's inside iife
  // Since this function may get called very frequently -
  // I think it's important to have plainObject's
  // statically defined
  const obj = {};
  const arr = [];
  // ...if for some reason you ever use square brackets on these types...
  // const fun = function() {}
  // const bol = true;
  // const num = 0;
  // const str = '';
  return key => {
    // eslint-disable-next-line security/detect-object-injection
    if (obj[key] !== undefined || arr[key] !== undefined
      // ||
      // fun[key] !== undefined ||
      // bol[key] !== undefined ||
      // num[key] !== undefined ||
      // str[key] !== undefined
    ) {
      return 'SAFE_'+key;
    } else {
      return key;
    }
  };
})();

We could also write a util safeSet - instead of this:

obj[key] = value;

You would do this:

safeSet(obj, key, value)

Tests for safeKey (failing):

console.log(safeKey('toString'));
//     Good: => SAFE_toString

console.log(safeKey('__proto__'));
//     Good: => SAFE___proto__

console.log(safeKey('constructor'));
//     Good: => SAFE_constructor

console.log(safeKey('prototype'));
//     Fail: =>      prototype

console.log(safeKey('toJSON'));
//     Fail: =>      toJSON

You'd then use it like so:

someObject[safeKey(somePropertyPotentiallyDefinedFromBackend)] = someStringPotentiallyMaliciouslyDefinedString

This means if the backend incidentally sends json with a key somewhere of constructor we don't choke on it, and instead just use the key SAFE_constructor (lol). Also applies for any other pre-defined method/property, so now the backend doesn't have to worry about json keys colliding with natively defined js properties/methods.

This util function is nothing without a series of passing unit tests. As I've commented not all the tests are passing. I'm not sure which object(s) natively define toJSON - and this means it may need to be part of a hardcoded list of method/property names that have to be blacklisted. But I'm not sure how to find out every one of these property methods that needs to be blacklisted. So we need to know the best way anyone can generate this list, and keep it updated.

I did find that using Object.freeze(Object.prototype) helps, but methods like toJSON I don't think exist on the prototype.

Here's another little test case:

const prop = 'toString';
someData[safeKey(prop)] = () => {
    alert('hacked');
    return 'foo';
};
console.log('someProp.toString()', someData + '');


from Securely set unknown property (mitigate square bracket object injection attacks) utility function

Integrating two Unity projects in an Android application

I'm developing an Android app and I need to integrate Unity games/screens in it. I've already exported and added one Unity scene/project to my android app but I cannot figure out how to add two.

I found two main approaches to this:

  1. Create two separate projects: If I do this they clash either in the manifest or in the libraries/assets folder and unity ends up calling just one scene. For reference:

How to correctly import multiple unity module in single android app avoiding name conflict between different unity module in android studio?

  1. I also tried creating one Unity project with multiple scenes and use messages to call the required scene from Android. For me, Android still calls the same scene regardless of which button is pressed. Reference: https://stackoverflow.com/a/43224821/2617578

Does anyone have a solution for this? Either one of the solutions mentioned above would be okay for me.

I'm experienced in Android but a beginner in Unity so I think I might be doing something wrong in the unity code.

I have the unity projects and Android apps I created for the second approach in the following git repository.

https://github.com/hadi-mehmood/AndroidUnityIntegrationSample



from Integrating two Unity projects in an Android application

Send data to bootstrap-notify from a backend code

I am using a template that uses bootstrap-notify and I would like to send data to it from a view:

try:
    # things
except Exception as e:
    options = {
                    "icon": "glyphicon glyphicon-warning-sign",
                    "title": "Bootstrap notify",
                    "message": "Turning standard Bootstrap alerts into 'notify' like notifications",
                    "url": "https://github.com/mouse0270/bootstrap-notify",
                    "target": "_blank"
                }
    return JsonResponse(options)

In this example the message is showing but all the other options like "icon" and "title" are being ignored.

In JS, doing the same thing looks like:

$.notify({
// options
message: 'Hello World' ,
title: 'your title'
},{
// settings
type: 'danger'
});​

Any idea on how to fix this?



from Send data to bootstrap-notify from a backend code

why firebase firestore crash at [NSBundle bundleWithIdentifier:@"org.cocoapods.grpcpp"]?

enter image description here

this is the crash log from test flight. it only happens in test flight, I can not reproduce it locally, I have no idea what happed here.



from why firebase firestore crash at [NSBundle bundleWithIdentifier:@"org.cocoapods.grpcpp"]?

How to use my existing funciton global.parseData(id, name, url) in `await page.evaluate(indexTotal => {` in Puppeteer?

SITUATION:

I was able to use the variable indexTotal inside the page.evaluate context like this:

var indexTotal = ...
(do something with indexTotal)

const thedata = await page.evaluate(indexTotal => {

 }, indexTotal).catch( error => {
                        console.log("ERROR: "+error);
                    });

PROBLEM:

But when it comes to global.parseData, I get the following error:

Unexpected token .

for this code:

const thedata = await page.evaluate((global.parseData(id,name,url)) => {

 }, (global.parseData(id,name,url))).catch( error => {
                        console.log("ERROR: "+error);
                    });

QUESTION:

What is the proper syntax to use my global function inside page.evaluate ?


EDIT:

getData.js

    getData: function() {

            let getData = async () => {
                url = 'url';

                await page.exposeFunction('parseData', (items2, items3, item2, ...) => global.parseData(items2, items3, item2, ...));

                const thedata = await page.evaluate( async() => {

                    var items = [];
                    var items2 = [];
                    var items3 = [];

                    $('.htmlElement').find('.childElements').each(function(ind) {
                        ...

                        var returnedObject = await window.parseData(items2, items3, item2, ...);

                        items.push(returnedObject.item);
                        items2 = returnedObject.items2;
                        items3 = returnedObject.items3;

                    });

                    var largeObject = {
                        items: items,
                        items2: items2,
                        items3: items3
                    }

                    console.log("RETURNED OBJECT: "+JSON.stringify(returnedObject));

                    return largeObject;

                }).catch( error => {
                    console.log("ERROR: "+error);
                });

                browser.close();
                return thedata;
            }

            getData().then(largeObject => {

                global.saveData(largeObject);

            });
    }

app.js

global.parseData = function(items2, items3, item2, ...) {

    ...


    if(!item2 || item2 == "") {
        ...
    }
    else {
        items2.push(item2);
        var item3 = ...;
        items3.push(item3);
    }

    var item = {
        ...
    }

    var largeObject = {
        item: item,
        items2: items2,
        items3: items3
    }

    console.log("LARGE OBJECT: "+JSON.stringify(largeObject));

    return largeObject;
}

CONSOLE.LOG OUTPUT:

RETURNED OBJECT: {}
LARGE OBJECT: {data}
RETURNED OBJECT: {}
RETURNED OBJECT: {}
RETURNED OBJECT: {}


from How to use my existing funciton global.parseData(id, name, url) in `await page.evaluate(indexTotal => {` in Puppeteer?

How do i add multiple audio tracks from my array list

want to have multiple audio tracks for a single video file similar to this one https://codepen.io/eabangalore/pen/NZjrNd (they are using their own js with videojs)

i have list of sound tracks that i want to switch:

var usersAudioTrackList =  ["https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/glass.mp3","https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/door_bump.mp3","https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/camera_flashing_2.mp3"]

enter image description here

i have read doccumentation but did not understand: https://docs.videojs.com/tutorial-audio-tracks.html

PLEASE SEE codepen https://codepen.io/eabangalore/pen/pXPbwp?editors=1010 (as below code is not working).

tried something like below:

$(function(){
  var $refreshButton = $('#refresh');
  var $results = $('#css_result');
  
  function refresh(){
    var css = $('style.cp-pen-styles').text();
    $results.html(css);
  }

  refresh();
  $refreshButton.click(refresh);
  
  // Select all the contents when clicked
  $results.click(function(){
    $(this).select();
  });
  
var usersAudioTrackList = [{
  id: 'my-1',
  kind: 'translation',
  label: 'kannada',
  language: 'kannada',
  audio:'https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/glass.mp3',
},

{
  id: 'my-2',
  kind: 'translation',
  label: 'tamil',
  language: 'tamil',
  audio:'https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/door_bump.mp3',
},

{
  id: 'my-3',
  kind: 'translation',
  label: 'marathi',
  language: 'marathi',
  audio:'https://cdnjs.cloudflare.com/ajax/libs/ion-sound/3.0.7/sounds/camera_flashing_2.mp3',
}];
  
  // Create a player.
var player = videojs('my_video_1');
  
 for(var i = 0; i < usersAudioTrackList.length; i++){
    // Create a track object.
    var track = new videojs.AudioTrack();

    // Add the track to the player's audio track list.
    player.audioTracks().addTrack(track);
 }
});
/*
  Player Skin Designer for Video.js
  http://videojs.com

  To customize the player skin edit 
  the CSS below. Click "details" 
  below to add comments or questions.
  This file uses some SCSS. Learn more  
  at http://sass-lang.com/guide)

  This designer can be linked to at:
  https://codepen.io/heff/pen/EarCt/left/?editors=010
*/

// The following are SCSS variables to automate some of the values.
// But don't feel limited by them. Change/replace whatever you want. 

// The color of icons, text, and the big play button border.
// Try changing to #0f0
$primary-foreground-color: #fff; // #fff default

// The default color of control backgrounds is mostly black but with a little
// bit of blue so it can still be seen on all-black video frames, which are common.
// Try changing to #900
$primary-background-color: #2B333F;  // #2B333F default

// Try changing to true
$center-big-play-button: false; // true default

.video-js {
  /* The base font size controls the size of everything, not just text.
     All dimensions use em-based sizes so that the scale along with the font size.
     Try increasing it to 15px and see what happens. */
  font-size: 10px;

  /* The main font color changes the ICON COLORS as well as the text */
  color: $primary-foreground-color;
}

/* The "Big Play Button" is the play button that shows before the video plays.
   To center it set the align values to center and middle. The typical location
   of the button is the center, but there is trend towards moving it to a corner
   where it gets out of the way of valuable content in the poster image.*/
.vjs-default-skin .vjs-big-play-button {
  /* The font size is what makes the big play button...big. 
     All width/height values use ems, which are a multiple of the font size.
     If the .video-js font-size is 10px, then 3em equals 30px.*/
  font-size: 3em;

  /* We're using SCSS vars here because the values are used in multiple places.
     Now that font size is set, the following em values will be a multiple of the
     new font size. If the font-size is 3em (30px), then setting any of
     the following values to 3em would equal 30px. 3 * font-size. */
  $big-play-width: 3em; 
  /* 1.5em = 45px default */
  $big-play-height: 1.5em;

  line-height: $big-play-height;
  height: $big-play-height;
  width: $big-play-width;

  /* 0.06666em = 2px default */
  border: 0.06666em solid $primary-foreground-color;
  /* 0.3em = 9px default */
  border-radius: 0.3em;

  @if $center-big-play-button {
    /* Align center */
    left: 50%;
    top: 50%;
    margin-left: -($big-play-width / 2);
    margin-top: -($big-play-height / 2);   
  } @else {
    /* Align top left. 0.5em = 15px default */
    left: 0.5em;
    top: 0.5em;
  }
}

/* The default color of control backgrounds is mostly black but with a little
   bit of blue so it can still be seen on all-black video frames, which are common. */
.video-js .vjs-control-bar,
.video-js .vjs-big-play-button,
.video-js .vjs-menu-button .vjs-menu-content {
  /* IE8 - has no alpha support */
  background-color: $primary-background-color;
  /* Opacity: 1.0 = 100%, 0.0 = 0% */
  background-color: rgba($primary-background-color, 0.7);
}

// Make a slightly lighter version of the main background
// for the slider background.
$slider-bg-color: lighten($primary-background-color, 33%);

/* Slider - used for Volume bar and Progress bar */
.video-js .vjs-slider {
  background-color: $slider-bg-color;
  background-color: rgba($slider-bg-color, 0.5);
}

/* The slider bar color is used for the progress bar and the volume bar
   (the first two can be removed after a fix that's coming) */
.video-js .vjs-volume-level,
.video-js .vjs-play-progress,
.video-js .vjs-slider-bar {
  background: $primary-foreground-color;
}

/* The main progress bar also has a bar that shows how much has been loaded. */
.video-js .vjs-load-progress {
  /* For IE8 we'll lighten the color */
  background: lighten($slider-bg-color, 25%);
  /* Otherwise we'll rely on stacked opacities */
  background: rgba($slider-bg-color, 0.5);
}

/* The load progress bar also has internal divs that represent
   smaller disconnected loaded time ranges */
.video-js .vjs-load-progress div {
  /* For IE8 we'll lighten the color */
  background: lighten($slider-bg-color, 50%);
  /* Otherwise we'll rely on stacked opacities */
  background: rgba($slider-bg-color, 0.75);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://vjs.zencdn.net/5-unsafe/video.js"></script>


<!--
  Don't use the "5-unsafe" CDN version in your own code. It will break on you. 
  Instead go to videojs.com and copy the CDN urls for the latest version.
-->

<div id="instructions">

  <video id="my_video_1" class="video-js vjs-default-skin" width="640px" height="267px"
      controls preload="none" poster='http://video-js.zencoder.com/oceans-clip.jpg'
      data-setup='{ "aspectRatio":"640:267", "playbackRates": [1, 1.5, 2] }'>
    <source src="https://vjs.zencdn.net/v/oceans.mp4" type='video/mp4' />
    <source src="https://vjs.zencdn.net/v/oceans.webm" type='video/webm' />
  </video>

  <p>Custom skin for <a href="http://www.videojs.com" target="_blank">video.js</a>. Requires v5.0.0 or higher.</p>
  
  <h2>HOW TO CUSTOMIZE:</h2>
  <ol>
    <li>Click the CodePen <strong>Fork</strong> link above to create a new copy</li>
    <li>Change the CSS (SCSS) as desired</li>
    <li>Click <strong>Save</strong> to save your changes</li>
    <li>Click <strong>Settings</strong> to name and describe your skin</li>
    <li>Click the <strong>Share</strong> link to tweet your skin, and include @videojs so we know about it</li>
  </ol>
  <h2>HOW TO USE:</h2>
  <ol>
    <li>Click "Refresh" if you made any changes</li>
    <li>Copy the CSS contents of the following box</li>
    <li>Include it in the page with your player in a &lt;style&gt; tag or with a <a href="https://www.w3schools.com/css/css_howto.asp">stylesheet include</a></li>
  </ol>
  <textarea id="css_result"></textarea>
  <button id="refresh">Refresh</button>
</div>
  
<style>
  #instructions { max-width: 640px; text-align: left; margin: 30px auto; }
  #instructions textarea { width: 100%; height: 100px; }
  
  /* Show the controls (hidden at the start by default) */
  .video-js .vjs-control-bar { 
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
  }

  /* Make the demo a little prettier */
  body {
    margin-top: 20px;
    background: #222;
    text-align: center; 
    color: #aaa;
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    background: radial-gradient(#333, hsl(200,30%,6%) );
  }

  a, a:hover, a:visited { color: #76DAFF; }
</style>

Question: i want to achieve similar result as this one https://codepen.io/eabangalore/pen/NZjrNd

Codepen(working code): https://codepen.io/eabangalore/pen/pXPbwp?editors=1010

Please help me thanks in advance!!



from How do i add multiple audio tracks from my array list

Click event to apply only to container + make querySelectorAll work in IE11

The code opens a div/table in fullscreen.

I need the click event to apply to only the containing div so that the fullscreen effect is applied only to the div that has the button (where the click occurred).

Basically the click on the button "View fullscreen table" in the second table should work the same as the button above first table by only modifying the JS script and not the HTML. The second button should open the second table.

https://codepen.io/MistaPrime/pen/jONeKZZ

How to modify click event in that way?

var customFullscreen = document.getElementById("fullscreen-table")
        libraryFullscreen = document.getElementById("expand-fullscreen");

    if (customFullscreen && libraryFullscreen) {
        libraryFullscreen.addEventListener("click", function (evt) {
            if (customFullscreen.requestFullscreen) {
                customFullscreen.requestFullscreen();
            }
            else if (customFullscreen.msRequestFullscreen) {
                customFullscreen.msRequestFullscreen();
            }
            else if (customFullscreen.mozRequestFullScreen) {
                customFullscreen.mozRequestFullScreen();
            }
            else if (customFullscreen.webkitRequestFullScreen) {
                customFullscreen.webkitRequestFullScreen();
            }
        }, false);
    }

EDIT FOR BOUNTY: I got a working solution from @dacre-denny but it does not work in IE11. I would need to somehow make it work in IE11 as well.



from Click event to apply only to container + make querySelectorAll work in IE11

How to get updates of network type with PhoneStateListener in Android 7 and higher?

I have the following code that tells when the phone is connected to EDGE or UMTS network. It works on Android 6 (API 23) but when I test on Android 7 shows the network type only when I launch the app for first time, but there is no update when the phone changes from 2G to 3G and vice versa.

What is needed in order to make this code works updating the newtwork type in the moment that happens for Android 6 and 7+?

public class MainActivity extends AppCompatActivity {

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

    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    PhoneStateListener ConnectionStateListener = new PhoneStateListener() {

        @Override
        public void onDataConnectionStateChanged(int state, int networkType) {
            super.onDataConnectionStateChanged(state, networkType);
            String sState = "";

            switch (networkType) {
                case TelephonyManager.NETWORK_TYPE_EDGE:   sState = "EDGE (2G)";   break;
                case TelephonyManager.NETWORK_TYPE_UMTS:   sState = "UMTS (3G)";   break;                    
            }
            Toast.makeText(getApplicationContext(), sState, Toast.LENGTH_SHORT).show();
        }
    };
    telephonyManager.listen(ConnectionStateListener,PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
}

}

I've added to Manifest file the READ_PHONE_STATE permission as shown below.

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

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


from How to get updates of network type with PhoneStateListener in Android 7 and higher?