text:
Q: No sound on USB headset. How to manage soundcards and audio devices? I had a fresh reinstall of Lubuntu 13.10 and my USB headset seems to be not working. I looked for solutions in some forums, but these didn't work for me.
My headset is a Genius Wire Gaming headset.
Thank you!

A: Managing soundcards and audio devices
USB and Bluetooth audio devices are individual sound cards, which means that connecting a Bluetooth headset doesn't work like connecting a headset via 3.5mm audio jack, where jack sensing assumes that you want to play audio through the recently connected headset instead of the laptop speakers.
Therefore when adding new audio devices like Bluetooth or USB headsets and speakers as well es new soundcards or audio interfaces, you should check your configuration to make sure that the sound is played by the device you intend to use. The easiest way is via the Sound Indicator in Unity or via System Settings > Sound:

If your new connected device is the Sennheiser BTD 500 USB in this example, then you should check that it is selected in the Play sound through list.
Alternatively you can use PulseAudio Volume Control to manage your sound cards. It provides many more options such as routing only certain streams (sound from applications) to certain devices. Some applications such as VLC (via package vlc-plugin-pulse) also offer to choose the audio device independently.

Related topics and questions

*

*For KDE and Kubuntu, take a look at Phonon.

*Question: Is there any Sound enhancers/equalizer?

*Question: How to play music, coming from the microphone jack?

*Question: How to play audio from different applications on different output devices?

*For further troubleshooting see the Debugging Sound Problems guide.

A: This seems to have fixed it for me,
http://ubuntuforums.org/showthread.php?t=1813750&p=11096695#post11096695

Determine your sound device order: Code: cat /proc/asound/cards Dell laptop with Logitech USB headset plugged in:

rj@lubuntu:~$ cat /proc/asound/cards
0 [Intel          ]: HDA-Intel - HDA Intel HDA Intel at 0xdfebc000 irq 21
1 [Headset        ]: USB-Audio - Logitech USB Headset
                     Logitech Logitech USB Headset at usb-0000:00:1d.2-1, full speed

sudo leafpad /etc/asound.conf

Set sound device 1 USB Headset as default:

defaults.ctl.card 1
defaults.pcm.card 1

File/Save/Quit Reboot
If you use both soundcard/speakers and USB headset: UDEV rule switch's
  default sound device when USB headsets are plugged in. Software
  producing sound must be restarted after USB is inserted/removed.

sudo leafpad /etc/udev/rules.d/00-local.rules

KERNEL=="pcmC[D0-9cp]*", ACTION=="add", PROGRAM="/bin/sh -c 'K=%k;K=$${K#pcmC}; K=$${K%%D*}; echo defaults.ctl.card $$K > /etc/asound.conf; echo defaults.pcm.card $$K >>/etc/asound.conf'"
KERNEL=="pcmC[D0-9cp]*", ACTION=="remove", PROGRAM="/bin/sh -c 'echo  defaults.ctl.card 0 > /etc/asound.conf; echo defaults.pcm.card 0 >>/etc/asound.conf'"

File/Save/Quit

A: Run
sudo apt install pavucontrol
pavucontrol

Go to configuration and set all the audio output to off except the USB headset.

A: Open a command line via Ctrl+Alt+T then type:    alsamixer and press Enter.
After that you will be promted with the sound devices settings on your PC  make sure the headphones are not on mute (or any other device) (OO means not mute MM means mute) you can toggle the values via the m key on your keyboard.

A: For Kubuntu users:
If you want your USB or Bluetooth audio device to be recognized automatically on connection, you need to right-click on KDE sound indicator and select Audio Setup in the menu.
Alternatively, you may open Application Launcher by pressing Alt+F1 and choose System Settings in Computer tab. In Hardware category select Multimedia item. Then select Audio and Video Settings on the left.
You will see the window Settings for the Phonon multimedia framework. On the first tab you can set Device Preference for all software by choosing Audio Playback item, or set preferences for each software type individually. After you connect your USB headset it will appear it the list as Audio Adapter Analog Stereo. Use Prefer button in the bottom right corner to move your device to the top and press Apply. Afterwards, you may close all your applications. When you open them next time they will be using your USB headset to playback audio.

A: *

*Install pluseAudio in Ubuntu.
Using Command:
sudo apt-get purge pulseaudio

and remove fwupd
sudo apt-get remove fwupd

*Open it and Setting for Simultaneous devise connected
With paprefs install paprefs you have access to a virtual output device that enables simultaneous output to all attached sound cards/devices:
paprefs

*Then run command combined input/output devise support in Ubuntu.
gconftool --set --type string /system/pulseaudio/modules/combine/args0 sink_properties=device.description=Combined

*Go to System Setting > Sound and select Combined  options for input/output


text:
Q: Assign and immediately delete property I am no javascript programmer and am totally puzzled by what this code does and what it is used for:
function map(x) {
    x = Object.create(null);
    x.x = 0;
    delete x.x;
    return x;
}

It's part of what you get when using the dart2js compiler.
I'm not trying to understand the whole context, but what does assigning a property and deleting it directly again help achieve?
This looks like outsmarting some internal JS engine behaviour.
EDIT: As requested, here's the complete out.js as generated by dart2js (input is the "Hello world!" example from Wikipedia): https://gist.github.com/Blutkoete/59be155b2642832e9acd383df0857d02
EDIT 2: gurvinder372's link indicates is has to do with "delegating to anonymous JS objects for performance", but I'll probably need a lot of experience with JS to understand that.

A: Well... This is an interesting topic and understanding this trick takes to read a little bit on the object representation of V8 compiler. I am not an expert on this but the topic was interesting enough to intrigue me to search for some answer. So here is what i have found.
First of all deleting a property seems to be a trick to change the internal structure of how object properties are kept and accessed. In other words deleting a property switches the object to dictionary mode where the properties are kept in a hash map. So when a dummy property is deleted immediately after it's created gives you an object in dictionary mode.

V8 can handle minor divergences like this just fine, but if your code
  assigns all sorts of random properties to objects from the same
  constructor in no particular order, or if you delete properties, V8
  will drop the object into dictionary mode, where properties are stored
  in a hash table. This prevents an absurd number of maps from being
  allocated.

Taken from this nice article A tour of V8: object representation

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't access window object property in Nuxt (Vue) mounted I have a TronLink chrome extension, this extension provides a window.tronWeb property and I want to access this property after document load. I am trying to do that in the mounted() section of my Nuxt page component:
// ...
mounted() {
  this.tronWeb = window.tronWeb;
},
// ...

but I receive undefined.
I have resolved this problem with a timeout:
// ...
mounted() {
  let _this = this;

  let attempts = 0;
  setTimeout(function startGame() {
    if (window.tronWeb) {
      _this.tronWeb = window.tronWeb;
    } else {
      attempts++;
      if (attempts >= 5) {
        console.log(error);
      } else {
        setTimeout(startGame, 500);
      }
    }
  }, 0);
},
// ...

But it looks like this a very strange solution. Why can't I access this property directly in the mounted() section?

A: try this:
if (process.browser) {
  console.log('The window object:', window)
}

A: you may refer to :
nuxt docs > ssr section > window is not defined
because this code is rendered in the server, you can't access the window object.
you may use the process.client to check and run the code only on the client-side
if (process.client){
   console.log('do sth')
}


text:
Q: Extracting text from dynamically created textfields inside various rows of gridpane I'm trying to create a grid with a textbox on each row where user can enter a number, and corresponding number of new rows are added. This works well, as shown below in the screenshot.
Now I'm trying to extract the text from those textfields created based on the question "how many?" and since they are nested within various node elements, I'm having a hard time identifying the right way.Can anyone tell me what I'm doing wrong? I tried testing it using the save button, but I always go into the else statement of "Vboxgrid2 is empty!"on my console. I don't know why it says that my VBoxgrid2 is empty!
Following is a Minimal, Complete, and Verifiable example I've recreated:
package testing;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ExtractThatText extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("GridPane Experiment");
        GridPane gridPane = new GridPane();

        for(int i=0;i<5;i++) {
            VBox mainVBox = new VBox();
            VBox vboxgrid1 = new VBox();
            VBox vboxgrid2 = new VBox();
            HBox hboxgrid = new HBox();
            hboxgrid.setPadding(new Insets(5,5,5,5));

            RadioButton rbYes = new RadioButton("Yes");
            RadioButton rbNo = new RadioButton("No");
            Label howmanyLabel = new Label("   How many?   ");
            TextField howManytxtB = new TextField();

            hboxgrid.getChildren().add(rbYes);
            hboxgrid.getChildren().add(rbNo);
            hboxgrid.getChildren().add(howmanyLabel);
            hboxgrid.getChildren().add(howManytxtB);

            vboxgrid1.getChildren().add(hboxgrid);

            howManytxtB.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    vboxgrid2.getChildren().clear();
                    Integer howManyNum = Integer.valueOf(howManytxtB.getText());
                    for(int row=0;row<howManyNum;row++) {
                        //creating rows for entering the new entities
                        HBox innerRowbox = new HBox();
                        TextField name = new TextField();
                        ComboBox cb = new ComboBox(); //empty cb for now
                        name.setPromptText("Enter name of the new Entity");
                        name.setMinWidth(200);
                        innerRowbox.getChildren().add(name);
                        innerRowbox.getChildren().add(cb);
                        vboxgrid2.getChildren().add(innerRowbox);
                    }
                }

            });

            mainVBox.getChildren().add(vboxgrid1);
            mainVBox.getChildren().add(vboxgrid2);
            gridPane.add(mainVBox,1, i);
        }

        for(int i=0;i<5;i++) {
            gridPane.add(new Label("row"+i), 0 , i);
        }

        Button saveButton = new Button("save content");

        saveButton.setOnAction(e-> {
            Node mainVBox = gridPane.getChildren().get(1); //get just the first row's 1th column which contains mainVBox
            if(mainVBox instanceof VBox) {
                Node vboxgrid2 = ((VBox) mainVBox).getChildren().get(1);

                if(vboxgrid2 instanceof VBox) {

                    if(!((VBox) vboxgrid2).getChildren().isEmpty()) {

                        Node innerRowBox = ((VBox) vboxgrid2).getChildren().get(0);
                        if(innerRowBox instanceof HBox) {

                            for(Node howmanyTB:((HBox)innerRowBox).getChildren()) {
                                if(howmanyTB instanceof TextField) {
                                    System.out.println(((TextField) howmanyTB).getText()); //content to save, extracted from the dnamic textfields created.
                                }
                                else System.out.println("howmanyTB not an instance of TextField error!");
                            }
                        }
                        else    System.out.println("innerRowBox not an instance of HBox error!");
                    }
                    else System.out.println("Vboxgrid2 is empty!");
                }
                else System.out.println("vboxgrid2 not an instance of VBox error!");
            }
            else    System.out.println("mainVbox not an instance of VBox error!");
        });

        gridPane.add(saveButton, 1, 5);
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        Scene scene = new Scene(gridPane, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

** If it's difficult to understand the nesting of all my nodes, here is a summary:
gridPane -> mainVBox (in each row of the second/1th column) -> vboxgrid2 (along with vboxgrid1 above it for the radiobutton row in mainVBox) -> innerRowbox -> name (textfield)

A:
If it's difficult to understand the nesting of all my nodes

Since you do seem to realize that your nesting is a bit confusing, it would be preferable to save the TextFields in a data structure that is easier to access than your scene hierarchy. In this case since the number of items is known before they are created, a TextField[][] array could be used, but you could also go for a List<List<TextField>> to allow you to dynamically add (inner) rows.
BTW: since you use index 1 you access the second row, not the first one.
Also using a VBox just to contain your HBox seems unnecessary. You could simply use the HBox directly, since the VBox has no other children.
Label howmanyLabel = new Label("   How many?   ");

Better use a margin for this spacing instead of spaces.
@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("GridPane Experiment");
    GridPane gridPane = new GridPane();

    final int rowCount = 5;
    TextField[][] textFields = new TextField[rowCount][0];
    final Insets hboxPadding = new Insets(5);
    final Insets labelMargin = new Insets(0, 15, 0, 15);

    for (int i = 0; i < rowCount; i++) {
        VBox vboxgrid2 = new VBox();

        RadioButton rbYes = new RadioButton("Yes");
        RadioButton rbNo = new RadioButton("No");
        Label howmanyLabel = new Label("How many?");
        HBox.setMargin(howmanyLabel, labelMargin);
        TextField howManytxtB = new TextField();

        HBox hboxgrid = new HBox(rbYes, rbNo, howmanyLabel, howManytxtB);
        hboxgrid.setPadding(hboxPadding);

        final int rowIndex = i;

        howManytxtB.setOnAction(event -> {
            vboxgrid2.getChildren().clear();
            int howManyNum = Math.max(0, Integer.parseInt(howManytxtB.getText()));
            TextField[] fields = new TextField[howManyNum];
            for (int row = 0; row < howManyNum; row++) {
                //creating rows for entering the new entities
                TextField name = new TextField();
                ComboBox cb = new ComboBox(); //empty cb for now
                name.setPromptText("Enter name of the new Entity");
                name.setMinWidth(200);
                HBox innerRowbox = new HBox(name, cb);
                vboxgrid2.getChildren().add(innerRowbox);

                fields[row] = name;
            }
            textFields[rowIndex] = fields;
        });

        VBox mainVBox = new VBox(hboxgrid, vboxgrid2);
        gridPane.addRow(i, new Label("row" + i), mainVBox);
    }

    Button saveButton = new Button("save content");

    saveButton.setOnAction(e -> {
        TextField[] secondRowFields = textFields[1];
        if (secondRowFields.length == 0) {
            System.out.println("no TextFields in row1");
        } else {
            for (TextField textField : secondRowFields) {
                System.out.println(textField.getText());
            }
        }
    });

    gridPane.add(saveButton, 1, rowCount);
    gridPane.setHgap(10);
    gridPane.setVgap(10);
    Scene scene = new Scene(gridPane, 500, 500);
    primaryStage.setScene(scene);
    primaryStage.show();
}

A: In the demo app, I added a List<TextField> textFieldContainer = new ArrayList(); that stores the dynamically create TextFields.
The code below delete the appropriate TextFields if the numbers change and Enter is pressed.
textFieldContainer.removeIf(p -> p.getUserData().toString().startsWith("TextField_" + tempRow));

Full Code:

import java.util.ArrayList;
import java.util.List;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class ExtractThatText extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        List<TextField> textFieldContainer = new ArrayList();

        primaryStage.setTitle("GridPane Experiment");
        GridPane gridPane = new GridPane();

        for(int i=0;i<5;i++) {
            VBox mainVBox = new VBox();
            VBox vboxgrid1 = new VBox();
            VBox vboxgrid2 = new VBox();
            HBox hboxgrid = new HBox();
            hboxgrid.setPadding(new Insets(5,5,5,5));

            RadioButton rbYes = new RadioButton("Yes");
            RadioButton rbNo = new RadioButton("No");
            Label howmanyLabel = new Label("   How many?   ");
            TextField howManytxtB = new TextField();

            hboxgrid.getChildren().add(rbYes);
            hboxgrid.getChildren().add(rbNo);
            hboxgrid.getChildren().add(howmanyLabel);
            hboxgrid.getChildren().add(howManytxtB);

            vboxgrid1.getChildren().add(hboxgrid);

            final Integer tempRow = i;
            howManytxtB.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    vboxgrid2.getChildren().clear();
                    Integer howManyNum = Integer.valueOf(howManytxtB.getText());

                    //The next two lines clears TextFields if you change the amount and/or press enter
                    textFieldContainer.removeIf(p -> p.getUserData().toString().startsWith("TextField_" + tempRow));
                    for(int row=0;row<howManyNum;row++) {
                        //creating rows for entering the new entities
                        HBox innerRowbox = new HBox();
                        TextField name = new TextField();
                        final Integer innerRow = row;
                        name.setUserData("TextField_" + tempRow + "_" + innerRow);
                        System.out.println(name.getUserData().toString());
                        textFieldContainer.add(name);
                        ComboBox cb = new ComboBox(); //empty cb for now
                        name.setPromptText("Enter name of the new Entity");
                        name.setMinWidth(200);
                        innerRowbox.getChildren().add(name);
                        innerRowbox.getChildren().add(cb);
                        vboxgrid2.getChildren().add(innerRowbox);
                    }
                }

            });

            mainVBox.getChildren().add(vboxgrid1);
            mainVBox.getChildren().add(vboxgrid2);
            gridPane.add(mainVBox,1, i);
        }

        for(int i=0;i<5;i++) {
            gridPane.add(new Label("row"+i), 0 , i);
        }

        Button saveButton = new Button("save content");

        saveButton.setOnAction(e-> {
            System.out.println("Saving these TextField's Text:");
            for(TextField textField : textFieldContainer)
            {
                System.out.println(textField.getUserData() + ": " + textField.getText());
            }
        });

        gridPane.add(saveButton, 1, 5);
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        Scene scene = new Scene(gridPane, 500, 500);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Output:

Click save content to see the info currently in the TextFields.

Saving these TextField's Text:
TextField_0_0: one
TextField_1_0: two
TextField_1_1: three
TextField_2_0: four
TextField_3_0: seven
TextField_3_1: six
TextField_4_0: five


text:
Q: react-native-navigation Tab Bar Icon from Android Drawables and iOS xcassets I am using react-native-navigation as a preferred navigation approach in our react-native application. We are planning on using the hybrid approach for icons where we still add icons in xcassets and drawables.
I am seeing a specific issue with icons for tab-bar on android when loading them from drawables. My code is below which works perfectly fine for iOS:
Tabs Definition:
const Tabs = [
{
    label: 'Home',
    screen: 'HomeScreen',
    //icon: require('../../assets/images/test.png'),
    icon: { uri: 'icon_home', scale: Dimensions.get('window').scale },
    selectedIcon: { uri: 'icon_home', scale: Dimensions.get('window').scale },
    title: 'Home'
},
{
    label: 'Message',
    screen: 'MessageScreen',
    icon: { uri: 'icon_home', scale: Dimensions.get('window').scale },
    selectedIcon: { uri: 'icon_home_selected', scale: Dimensions.get('window').scale },
    title: 'Message'
}]

Navigation Code:
_navigateToHomeScreen = () => {
Navigation.startTabBasedApp({
  tabs: Tabs,
  tabsStyle: tabsStyle,
  appStyle: tabsStyle
 });
}

Tab Styles:
tabStyle = {
  tabBarBackgroundColor: Colors.DefaultWhiteColor,
  tabBarButtonColor: Colors.NavigationBarItemColor,
  tabBarLabelColor: Colors.NavigationBarItemColor,
  tabBarSelectedButtonColor: Colors.PrimaryButtonBackground,
  tabBarSelectedLabelColor: Colors.PrimaryButtonBackground,
  forceTitlesDisplay: true
}

What we have tried:

*

*I tried using the same image in a list view and it shows up correctly so I don't think that react-native is not able to find the image from drawable.

*I tried specifying the height/width (without scale) for the image and it still does not work.

*If I use require('') to load an image which is in JS then it works correctly but we want to use drawables.

*I tried removing scale and it still doesn't work.

*For iOS, loading image from xcassets and using it in tab bar works without any issues.

Version Information:
react-native: 0.52.0
react-native-navigation: 1.1.314
Android-Version: Emulator: Android 5.1, Android 6.0
We are running out of options. The final solution would be to use local images and not images from native.
Any help is appreciated.
Note:This question is not for react-navigation. It is for react-native-navigation library by wix available at https://wix.github.io/react-native-navigation/#/.


text:
Q: TypeScript errors while trying to assign properties from one object to another My code:
const state = { activeRequests: 0, test: true };
type state = typeof state;
type pState = Partial<state>;
type stateKeys = keyof state; // "activeRequests" | "test"
...
set: (state: state, p: pState) => Object.keys(p).forEach(k => (state[k] = p[k]))

Error at state[k] = p[k]:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ activeRequests: number; test: boolean; }'.
No index signature with a parameter of type 'string' was found on type '{ activeRequests: number; test: boolean; }'

Looks like k has string type.
There are some of my attempts:
Object.keys(p).forEach((k: stateKeys) => state[k].push(p[k]))
Error: Type 'string' is not assignable to type '"activeRequests" | "test"'`.

Object.keys(p).forEach(k => (state[k as stateKeys] = p[k])
Error: Type 'any' is not assignable to type 'never'`

(Object.keys(p) as stateKeys[]).forEach(k => (state[k] = p[k]))
Error: Type 'number | boolean | undefined' is not assignable to type 'never'.
  Type 'undefined' is not assignable to type 'never'.

What is wrong?

A: because you are trying to assing object like this:
{
  activeRequests: number | boolean | undefined,
  test: number | boolean | undefined
}

to:
{
  activeRequests: number,
  test: boolean,
}

because of the partial and stateKeys part.
Solution is simple like that:
const set = (state: state, p: pState) => ({...state, ...p})

A: You can't do that cleanly without generics. Plus you are trying to assign a partially undefined value to a type that doesn't allow undefined. So you need to handle that scenario. Here's a potential solution:
var t = function<TState>(state: TState, p: Partial<TState>) {
    let keys = Object.keys(p) as (keyof TState)[];
    for (let key of keys) {
        state[key] = p[key] ?? state[key];
    }
}


text:
Q: Delete row with empty line csv 1 1479870 5022248660

1 1911574 3015889020 8

1 1569783 5029193930

Output should be
1 1911574 3015889020 8

I used
awk '$4!=""' number.csv

but it didn't work. Can anyone give me a clue?

A: Keep only lines with more than three columns:
awk 'NF>3' file

Output:

1 1911574 3015889020 8

8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR


text:
Q: Dynamic enum values on nested classes with Python Consider the following enum class:
from enum import Enum

class Namespace:

    class StockAPI(Enum):
        ITEMS = "{url}/items"
        INVENTORY = "{url}/inventory"

    class CustomerAPI(Enum):
        USERS = "{url}/users"
        PURCHASES = "{url}/purchases"

    def __init__(self, url):
        self.url = url

I am trying to make url a dynamic value for each enum class.
What can I do here so that I can call some enum class in one of the following ways:

*

*Namespace.StockAPI.ITEMS.value would return http://localhost/items?

*Namespace(url="http://localhost").StockAPI.ITEMS.value would also return http://localhost/items
Is this possible to do without doing variable interpolation each time I access each enum property? Could factory pattern be of any help here?

A: I did it the following way, while keeping the inner enum classes:
from enum import Enum

class Namespace:

    class StockAPI(Enum):
        ITEMS = "{url}/items"
        INVENTORY = "{url}/inventory"

    class CustomerAPI(Enum):
        USERS = "{url}/users"
        PURCHASES = "{url}/purchases"

    def __init__(self, url: str):
        attrs = (getattr(self, attr) for attr in dir(self))
        enums = (a for a in attrs if isinstance(a, type) and issubclass(a, Enum))
        for enum in enums:
            kv = {e.name: e.value.format(url=url) for e in enum}
            setattr(self, enum.__name__, Enum(enum.__name__, kv))

print(Namespace(url="http://test.com").StockAPI.ITEMS.value)
# http://test.com/items

A: use f-string:
ITEMS = "{}/items".format(url)

and so on,
but if you use classes, then add new attribute and call it in f-string:
class MyClass:
   url = "htpp://www.some.thing"

obj = MyClass()
ITEMS = "{0.url}/items".format(obj)

if you don't have same names, it is possible to implement it without any Enum:
class Namespace:
    def __init__(self, url):
        USERS = "{}/users".format(url)
        PURCHASES = "{}/purchases".format(url)
        ITEMS = "{}/items".format(url)
        INVENTORY = "{}/purchases".format(url)

obj = Namespace("https://www.some.news")
print(obj.USERS)        # https://www.some.news/users
print(obj.PURCHASES)    # https://www.some.news/purchases
print(obj.ITEMS)        # https://www.some.news/items
print(obj.INVENTORY)    # https://www.some.news/inventory


text:
Q: DiscordJS - Embedding a random image from an array I have a command for my DiscordJS bot that has an array of Imgur links. I want it to select a single link randomly and embed that in a message to the channel. I think I am close. How do I call it from the array?
if (command == "dude") return dude(args, message);

function dude(args, message) {
  if (args.length > 0)
    return message.channel.send(You are not using this command correctly.);
  const embed = new Discord.RichEmbed();
  var dudes = ["imgururl1", "imgururl2", "imgururl3", "imgururl4" ];
  var dude = Math.floor(Math.random() * dudes.length);
  embed.setImage([dude]);
  message.channel.send(embed);
};

A: You just needed to access the array with the given index.
embed.setImage(dudes[dude]);

A: It looks good, just make sure, as Kaynn said, to call the dude variable from the dudes array:
dudes[dude];

Or, you can define dude with it altogether:
var dude = dudes[Math.floor(Math.random() * dudes.length)];

Also, make sure to send the message within double quotes to make it a string, otherwise, the system is going to give a syntax error.


text:
Q: Create JWT token using PEM certificate in node I need to convert a Java code to node.js.
The Java code reads a p12 file, retrieves a public key from it and creates a JWT token using the following code —
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWEHeader;
import com.nimbusds.jose.crypto.RSADecrypter;
import com.nimbusds.jose.crypto.RSAEncrypter;
import com.nimbusds.jwt.EncryptedJWT;
import com.nimbusds.jwt.JWTClaimsSet;
//
// ...
//
            JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder().issuer(iss).subject(sub).
                    claim("usr", usr).claim("pwd", pwd).expirationTime(exp).notBeforeTime(nbf).issueTime(iat).jwtID(jti).build();

            // Request JWT encrypted with RSA-OAEP and 128-bit AES/GCM
            JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);

            // Create the encrypted JWT object
            EncryptedJWT jwt = new EncryptedJWT(header, jwtClaims);

            // Create an encrypter with the specified public RSA key
            RSAEncrypter encrypter = new RSAEncrypter((java.security.interfaces.RSAPublicKey) pubKey);

            // Do the actual encryption
            jwt.encrypt(encrypter);

The node.js code that I thought might help me achieve the same is —
const forge = require('node-forge');
const jose = require('jose');
//
// ...
//
        jwtString = await new jose.EncryptJWT({ usr, pwd })
            .setProtectedHeader({ alg: 'RSA-OAEP', enc: 'A128GCM' })
            .setIssuedAt(iat)
            .setIssuer(iss)
            .setSubject(sub)
            .setExpirationTime(exp)
            .setNotBefore(nbf)
            .setJti(jti)
            .encrypt(pubKey);

When I pass the PEM public certificate to the encrypt method, it throws an error —
TypeError: Key must be of type KeyObject.
    at asymmetricTypeCheck (\node_modules\jose\dist\node\cjs\lib\check_key_type.js:17:15)
    at checkKeyType (\node_modules\jose\dist\node\cjs\lib\check_key_type.js:44:9)
    at encryptKeyManagement (\node_modules\jose\dist\node\cjs\lib\encrypt_key_management.js:17:37)
    at FlattenedEncrypt.encrypt (\node_modules\jose\dist\node\cjs\jwe\flattened\encrypt.js:109:96)
    at CompactEncrypt.encrypt (\node_modules\jose\dist\node\cjs\jwe\compact\encrypt.js:26:43)
    at EncryptJWT.encrypt (\node_modules\jose\dist\node\cjs\jwt\encrypt.js:69:20)

If I try to convert the certificate to a key using crypto.createPublicKey(pubKey, 'pem', null, 'utf8'), I get this error —
TypeError: RSA-OAEP requires key modulusLength to be 2048 bits or larger

I understand that the key I am passing to the encrypt method isn't of sufficient length. Since the Java code reading the same certificate file runs but the node.js code doesn't, I am assuming the issue is with converting the key to a proper format. Any tips on how can I create a public key of sufficient length using the certificate?

A: The RSA key sizes allowed by the respective JOSE RFCs are at minimum 2048 bits.
That's it. Use a key of an appropriate bit length and you're set to go.


text:
Q: Speed up reaction to TouchableWithoutFeedback I need to deal with a rapid clicks of a button; as fast as the user can click.
This will update a number at the top of the screen.
Code:
Rendered:
<TouchableWithoutFeedback onPress={this.clickClickBtn}>
    <View style={styles.clickSummary}>
        <Text>Click</Text>
    </View>
</TouchableWithoutFeedback>

Which calls:
clickClickBtn = () => {
    this.props.clickClickBtn(this.props.serviceId);
}

Which calls:
clickClickBtn = (id) => {
    this.setState(prevState => ({
        saveData:{
            ...prevState.saveData,
            currentBalance: String(bigInt(this.state.saveData.currentBalance).add(this.getPerClick(id))),
        }
    }));
}

This is rather slow and laggy (still in expo though, is that the reason?). I was unsure as to whether this could be the setState taking a while as the total is rendered on the screen via a call of the current state.
I've tried to optimize my program to speed it up to no avail.
Any ideas of how to speed this up?
Thanks, Ed.

A: looking at your code, I feel like slowness resides in this.getPerClick(id).
everything else doesn't need to change.
FYI nothing is wrong with Expo.
also it's different in every case but sometimes it's better to keep local changes to state and then batch update them at once.


text:
Q: Vertical Gap at End of List? I have a vertical UL list on a html page, with a sublist inside of it. At the end of the sublist, it has an unwanted gap, like a linebreak, though I can't seem to find anything in my css or html that would cause it (and my attempts at trying to get it to go away aren't working very well).
Here's what it looks like;
1. Item
2. Item
   1. Sub Item
   2. Sub Item

3. Item
4. Item

My html code:

item

item

item

item

item

item

item

item

item

item

item

item

item

And my css code that I was trying to use;
.fic ul {
    padding: 0px;
    margin: 0px;
}

And since my template came with menu code for the ul used in the navigation bar, here's that;
#menu ul {
    display: block;
    width: 778px;
    margin: 0em auto;
    list-style: none;
    padding-left: 2.5em;
}

#menu li {
    display: inline;
}

#menu li a {
    color: #ffffff;
    font-weight: bold;
    font-size: 1.2em;
    text-decoration: none;
    padding: 0.25em 0.75em 0.25em 0.75em;
}

#menu li a:hover {
    background: #342117 url('images/hover.gif') top left repeat-x;
    color: #fffdc6;
}

html code for navigation menu;

Home

Fan Art

Fan Fiction

Fan Videos

Other

Forum

Help would be appreciated, thank you.

A: The menu styles are the culprit, need full code


text:
Q: Dokuwiki on Raspbian "wheezy" (Raspberry Pi) I've installed the dokuwiki via apt-get. The first call to http://localhost/dokuwiki give me "403 Forbidden" as response:
Achtung! HTTP/1.1 403 Forbidden
You don't have permission to access /dokuwiki on this server.

In the log filee (/var/log/apache2/error.log) i found following:
client denied by server configuration: /usr/share/dokuwiki/

I don't have an idea, what is really wrong. So i've tried this:
sudo chmod -R 755 /usr/share/dokuwiki
sudo chown -R www-data:root /usr/share/dokuwiki

but the problem was not solved. Any ideas?
edit:
https.conf is empty, here the output
-rw-r--r-- 1 root root 0 Mai  2 21:11 /etc/apache2/httpd.conf

and the  /usr/share/dokuwiki/.htaccess looks good (imho):
## Enable this to restrict editing to logged in users only

## You should disable Indexes and MultiViews either here or in the
## global config. Symlinks maybe needed for URL rewriting.
#Options -Indexes -MultiViews +FollowSymLinks

## make sure nobody gets the htaccess, README, COPYING or VERSION files
<Files ~ "^([\._]ht|README$|VERSION$|COPYING$)">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

## Uncomment these rules if you want to have nice URLs using
## $conf['userewrite'] = 1 - not needed for rewrite mode 2
#RewriteEngine on
#
## Not all installations will require the following line.  If you do,
## change "/dokuwiki" to the path to your dokuwiki directory relative
## to your document root.
#RewriteBase /dokuwiki
#
## If you enable DokuWikis XML-RPC interface, you should consider to
## restrict access to it over HTTPS only! Uncomment the following two
## rules if your server setup allows HTTPS.
#RewriteCond %{HTTPS} !=on
#RewriteRule ^lib/exe/xmlrpc.php$      https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]
#
#RewriteRule ^_media/(.*)              lib/exe/fetch.php?media=$1  [QSA,L]
#RewriteRule ^_detail/(.*)             lib/exe/detail.php?media=$1  [QSA,L]
#RewriteRule ^_export/([^/]+)/(.*)     doku.php?do=export_$1&id=$2  [QSA,L]
#RewriteRule ^$                        doku.php  [L]
#RewriteCond %{REQUEST_FILENAME}       !-f
#RewriteCond %{REQUEST_FILENAME}       !-d
#RewriteRule (.*)                      doku.php?id=$1  [QSA,L]
#RewriteRule ^index.php$               doku.php

A: I have found a solution:
In the /etc/apache2/sites-available/default i put following:
    <Directory /usr/share/dokuwiki/>
      Options FollowSymLinks
      AllowOverride None
      Order allow,deny
      Allow from all
    </Directory>

If you are migrating from other machine, then you need to copy the data folder to /var/lib/dokuwiki/
sudo cp -r ~/data /var/lib/dokuwiki/

after that i changed only the permissions for the data folder:
sudo chmod -R 775 /var/lib/dokuwiki/data
sudo chown -R www-data:www-data /var/lib/dokuwiki/data

Now is my dokuwiki working fine.


text:
Q: Prove that $\int_0^1 x(1+x^2)^n dx = \dfrac{1}{2n+2}$ $\int_0^1 x(1+x^2)^n dx = \dfrac{1}{2n+2}$
How is this calculated?
This is an interesting case because as a consequence of this, $\int_0^1 n^2x(1+x^2)^n dx$ converges to infinity with n to infinity, but the integrant converges point wise to 0.
(see Rudin "Real and complex Analysis" example 7.6.)

A: By the change of variable
$$
u=1+x^2, \quad du=2x\: dx,
$$ we rather get
$$
\int_0^1 x(1+x^2)^n dx=\frac12\int_1^2 u^n du=\frac{2^{n+1}-1}{2(n+1)}.
$$

Edit. If you meant $x(1-x^2)^n$ as being the integrand (as suggested by @Pjotr5), the similar change of variable
$$
v=1-x^2, \quad dv=-2x dx,\quad v(0)=1,\quad v(1)=0,
$$ gives

$$
\int_0^1 x(1-x^2)^n dx=\frac12\int_{\color{red}{0}}^{\color{red}{1}} v^n dv=\frac12\cdot\frac{1^{n+1}-0^{n+1}}{n+1}=\frac1{2n+2}.
$$

A: $$\int _{ 0 }^{ 1 } x(1+x^{ 2 })^{ n }dx=\frac { 1 }{ 2 } \int _{ 0 }^{ 1 } (1+x^{ 2 })^{ n }d\left( 1+{ x }^{ 2 } \right) =\frac { 1 }{ 2 } { \left[ \frac { { \left( 1+{ x }^{ 2 } \right)  }^{ n+1 } }{ n+1 }  \right]  }_{ 0 }^{ 1 }=\frac { { 2 }^{ n+1 }-1 }{ 2n+2 } $$

A: We use substitution rule with $1 - x^2 = t$. We have
\begin{align}
   &dt = -2x dx \nonumber \\
   &x dx = - \frac{1}{2} dt \nonumber
\end{align}
\begin{align}
  &x = 0, \quad t = 1 - 0 = 1 \nonumber \\
  &x = 1, \quad t = 0 \nonumber
\end{align}
Pulling it all into one single expression.
$$
\int_{0=x}^{1=x} x(1-x^2)^n dx = \int_{0=t}^{1=t} \cdot \left( - \frac{1}{2} \right) t^n dt = \frac{1}{2} \int_{0}^{1} t^n dt = \frac{1}{2} \cdot \frac{t^{n+1}}{n+1}  \Bigg\rvert^1_0 = \frac{1}{2} \frac{1}{n+1} $$


text:
Q: Is there a way to re-enable name mangling after using extern 'C'? Lets say I have a c++ header file that looks like this:
/* cpp_header.h */
#include <vector>

#ifdef __cplusplus
extern 'C' {
#endif
void foo1(int x);
void foo2(int y);
#ifdef __cplusplus
}
#endif

#ifdef __cplusplus
/* function I don't want visible to C compiler */
void foo3(vector<int> &v);
#endif

Now I include this header file into a C header file:
/* c_header.h - all implementation built with C compiler */
#include <stdio.h>
#include "cpp_header.h"

int cfoo();
int cfoo1(int x);

Now lets say I want to use cfoo() and cfoo1() in another cpp file and i do something like this:
/* crazy.cpp - this will cause a build breakage */
extern 'C' {
#include "c_header.h"
}
#include <iostream>

int main() {
   cfoo();
   cfoo1(88);
   std::cout << "Yes, this is crazy!" << std::endl;
   return 0;
}

The code above will never build because 'foo3()' in the first header file will complain that we are trying to build a template with C-linkage. This happen because we wrapped the entire c_header.h file within a 'extern C' guard. Is there a way I can add something that can reverse the 'extern C' guard so that foo3 will be built with C++ linkage. Maybe something like this:
#ifdef __cplusplus
extern 'CPP' {  /* re-enable C++ name-mangling/linkage */
   foo3(vector<int> &v);
}

Thanks.

A: As explained in https://en.cppreference.com/w/cpp/language/language_linkage, you can use both extern "C" and extern "C++" (the latter being the default for C++).
It also says

When language specifications nest, the innermost specification is the one that is in effect.

So
extern "C" {
    extern "C++" void foo3(vector<int> &v);
}

should work fine.
That said, a better solution would be to add the #ifdef __cplusplus / extern "C" { parts to the declarations in the C header itself. Then you don't need to wrap the #include in your main cpp file.
As in:
/* c_header.h - all implementation built with C compiler */
#include <stdio.h>
#include "cpp_header.h"

#ifdef __cplusplus
extern "C" {
#endif
int cfoo();
int cfoo1(int x);
#ifdef __cplusplus
}
#endif

Then all consumers can just #include "c_header.h", no matter whether they're in C++ or C.


text:
Q: Share a VPN connection over ethernet Quite new to linux, running Ubuntu 18.04 LTS.
I'm looking to replicate functionality I can do on the macos hardware & OS: Share the OS-level VPN connection with a hardware interface.
In this particular case, a laptop connects to unsercure wifi, establishes VPN tunnel, the VPN is then shared with an Ethernet interface, upon which I connect a DD-WRT router (double-nat, obviously) that supplies secure wifi/ethernet to clients. The reason for using a laptop with a real OS for the gateway is to handle captive portals via browser (as many hotels do).
This setup makes it impossible for the clients' traffic to leak over the gateway wifi since only the VPN connection is shared. If VPN drops, the clients have no connectivity at all. Easy enough to do under macos with l2tp.
Is there a reasonably simple way to do this from the gnome GUI? It took me hours trying to get just the L2TP+IPsec tunnel to work and finally gave up. I am using OpenVPN now. But I can't find a simple way of sharing the OpenVPN connection specifically, just the wifi, which would fall to insecure if the tunnel ever dropped, exposing the client traffic.
Thank you!

A: With some trial and error and help from a different forum, I managed to get this working. Note, I switched to OpenVPN protocol on account of better support in linux and just overall better throughput.
The only part that can be done with GUI is setup for the OpenVPN connection, and the client network on the second interface (this is done in network manager). In my case, ens9 is a secondary Ethernet interface that I configured with static IP on a unique local subnet. Client devices were pre-configured to use this IP as their gateway.
Full verbose details of my solution here: https://www.linuxquestions.org/questions/linux-networking-3/share-vpn-with-ethernet-interface-4175655027/
VPN kill-switch for the Gateway device itself goes like this:
Make these changes in /etc/sysctl.conf
#disable ipv6
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
#enable packet forwarding
net.ipv4.ip_forward=1

In UFW's default config file (/etc/default/ufw), make this change:
DEFAULT_FORWARD_POLICY="ACCEPT"

Through command line, edit the ufw rules as so:
sudo ufw default deny incoming
sudo ufw default deny outgoing
sudo ufw allow out on tun0
sudo ufw allow out on wlp2s0 to XXX.YYY.ZZZ.AAA port 1194 proto udp

In the last line, use the name of the interface you are using for the WAN connection (use ifconfig command to see all interfaces), and use the IP address and port number for your OpenVPN server – this can be lifted from the ovpn.config file supplied.
This much gets you a working VPN kill-switch on the gateway device. The last step is masquerading the VPN connection on the secondary interface (in my case, the Ethernet device called ens9).
Don't use the GUI method from nm-connection-editor to enable sharing, it will bypass your kill switch. Instead, edit the file /etc/ufw/before.rules by adding a nat section just above the *filter heading:
### Start OpenVPN Share rules
### NAT table rules
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 192.168.10.0/24 -o tun0 -j MASQUERADE
COMMIT

Where 192.168.10.0/24 stands in for the IP address range of your client network. In my case, I defined it statically within that range.
And that was pretty much it.
I expected to need a ufw rule like this:
sudo ufw allow out on ens9 to 192.168.10.0/24

But it works just fine without it.


text:
Q: WCF Windows Authentication silverlight login screen I have a WCF service with the given security in my config:
<security mode="Transport">
   <transport clientCredentialType="Windows" />
</security>

I am connecting to my WCF service with Silverlight over a basicHttpBinding. What I want, is when my silverlight application starts, they input their windows login/password (this is an intranet app).
In Silverlight, I am able to set my username and password before making any calls.  However, if I put an incorrect password or username, I get an error returned (http 500 I believe).
ServiceManager.exporterClient.ClientCredentials.UserName.UserName = "myUserName";
ServiceManager.exporterClient.ClientCredentials.UserName.Password = "myPassword";

Making a login screen in Silverlight is simple enough, but how can I call a function on my WCF service to ask if this given username and password is valid if it just returning and error because the windows credentials are invalid to begin with and therefore can not call the service?

A: I have been implementing integrated authentication in a Silverlight PRISM based application and I found Various posts by Mike Taulty invaluable.
Here is a search result on his blog, he has 6 blog entries all well worth a read/watch
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/search.aspx?q=RIA+Services

A: First Silverlight has nothing with Win Auth. It is managed by browser and since it uses Kerberos methodology your credentials are converted to a token. Setting your WCF service as WinAuth, Browser asks for Windows credentials and this user is checked at Active Directory both at client and server side automatically because your credentials are passed to server attached to your call as Kerberos tokens. There is an other issue here which is setting your site as trusted in your browser. This enables your WinAuth without prompt screen by using your computers current users credentials.
Regards,
Şerif


text:
Q: Is this a botnet? I manage networking equipment at a small ISP for 60 highrise buildings. Each building has anywhere from 1 to 60 24 port switches, or some DSLAMs, or some coax gateways, with p2p radios on the roof, with a main router at a central building.
I recently got an email from a guy working for SiteTruth that explains that there's phishing emails coming from a phony email address, but that the IP associated with the domain of the email is one of ours. He goes on to say that a traceroute to the IP bounces around a bunch of our IPs before hitting the trace IP, and hints that we may be hosting an entire botnet. I did the same traceroute and saw the same route he included in the email.
So the route hits on about 60 of our dynamic IPs before hitting the target IP. We use dhcp for clients on our entire network and all these hops were off dynamically assigned IPs, so hops off client boxes(sorry if I seem redundant).
I'm an aspiring network admin so I have no clue what this is. What is the reason for so many random hops to random customer routers/computers? Is it evidence of a botnet if a domain is registered to one of our IPs and a tracert to it hops across 60 other client devices on our network? I could find the MAC of the offending IP on the router and track it down to a particular port on a switch in a building and shut off that port, but if the client has no idea he's part of a botnet and has no idea this is occurring than I'll have to re-enable the port as they are paying customers.
Interestingly enough I've just performed the same tracert as I did a few days ago when I got the email and now there's only about 20 hops on our IPs before the target of the trace is hit. I'm guessing this is just due to dhcp being involved? I really have no clue.
Does anyone know what the heck this is? And if it's a botnet how am I supposed to cripple it? I'm guessing I would need to block only particular traffic?
Any more info on exactly what's happening and how to deal with it would be much appreciated. I don't understand why there's so many hops between dynamic IPs on our network during a simple tracert, does that confirm a botnet? I'd really like to do something so that our IPs don't end up being blacklisted.

A: Seeing a the route "hop around" on your network is really bizarre. You should see a traffic flow that hops form your edge router through your distribution routers. You definitely shouldn't be seeing traffic being routed through end user Customer addresses / devices. I tend to think you're seeing some kind of artifact of your configuration in these traceroute outputs, rather than evidence that routing is somehow being done by your end user Customers, but I can't say for sure without seeing it. (I also wonder what protections you've got enabled to prevent one Customer from spoofing the IP addresses assigned to another. Typical low-end layer 2 switches aren't going to provide a lot of protection on that front.)
Your network is different than a typical corporate network in that you're providing access to the Internet for paying Customers. Were I in your shoes I'd err on the side of not filtering any traffic if at all possible. (Your other question re: outbound TCP port 25 is an example of where it has become acceptable to filter traffic. Egress and ingress filtering to prevent spoofed IPs from entering / leaving your network are also good filtering rules.)
I think it's perfectly reasonable to shut down a client sourcing malicious traffic (and it should be noted in your service agreements that you have such a policy). Obviously, you should try to contact the Customer in question to let them know why they've been cut off. It would be nice if you provided them some packet captures to allow them to locate the source and eliminate it.
I don't have experience running an ISP to tell you what you should be monitoring for, in terms of oddball traffic patterns from Customers. Botnets try to mimic "normal" user traffic to circumvent monitoring and filtering anyway. I'd be more worried about monitoring your own equipment for unauthorized access attempts, locking down management interfaces to allow access with secure protocols from only authorized hosts, and employing routing and switching gear that prevents Customers from interfering with other Customers, spoofing their source addresses, exhausting your DHCP pool, putting up rogue DHCP servers, etc.


text:
Q: 'Object is possibly null' after destructuring with default value I'm rather new to TypeScript. I have an interface like so:
export interface Stop {
  sequenceNumber?: number | null;
}

I then try to do this:
  stops.sort((stopA: Stop, stopB: Stop) => {
    const { sequenceNumber: seqA = 0 } = stopA;
    const { sequenceNumber: seqB = 0 } = stopB;
    return seqA - seqB;
  });

It complains with Object is possibly 'null' for both seqA and seqB, even though I have destructured them with a default value of 0.
Why does it do this and how do people usually overcome this?
Even more confusing is the fact that if I write it like so:
const seqA = stopA.sequenceNumber || 0;
const seqB = stopB.sequenceNumber || 0;

Typescript does not complain. Aren't both ways effectively doing the same thing?


text:
Q: VBA - excluding wildcard values in autofilter? I have to make 2 excel sheets. One for all accounts of a certain customer, one without. Unfortunately, the way the customer name is laid out, I have to search for these customers using a wildcard.
The Macro for only the customer works fine, but the macro to exclude the customer does not.
Working Macro:
Sheets("AR Aging").Range("A:J").AutoFilter Field:=2, Criteria1:=Array( _
"*COMPANY*"), Operator:=xlFilterValues

Range("A:J").Copy
Sheets.Add After:=Sheets(7)
ActiveSheet.Paste
Sheets(8).Select
Sheets(8).Name = "XYZ"

Sheets("AR Aging").AutoFilterMode = False
Sheets("AR Aging").Activate
Application.CutCopyMode = False

The only difference is in the non-working macro,
Criteria1:=Array( "*COMPANY*")

was changed to
Criteria1:=Array( "<>*COMPANY*")

and the sheet numbers were changed.


text:
Q: не отображается bacground-image Помогите пожалуйста, не отображается фоновая картинка в блоке. Проверял колором, работает, а вот сама картинка не отображается, ни та что в папке с проектом, ни браузерная. Может что-то недосмотрел?

html,
#about {
  width: 99.6%;
  height: auto;
  background: #f7f7f7;
  padding-top: 40px;
}

.BacgroundWall {
  margin-left: 140px;
  width: 300px;
  height: 400px;
  position: relative;
  background-color: #2B446B;
}

.BacgroundWall2 {
  margin: 20px auto;
  left: 60%;
  width: 260px;
  height: 360px;
  position: absolute;
  background-color: #F7F7F7;
  margin-left: -160px;
}

.aboutImg {
  margin: 10px 25px;
  border: 2px solid red;
  width: 300px;
  height: 400px;
  background-size: 50%;
  background-image: url("https://images.unsplash.com/photo-1551715435-55b2b13a5257?ixlib=rb-1.2.1&auto=format&fit=crop&w=1525&q=80");
  background-color: black;
}
<!DOCTYPE html>

  <title>Personal</title>

    Hello

A: Замените ваш css для класса aboutImg на следующий:
.aboutImg {
    margin: 10px 25px;
    border: 2px solid red;
    width: 300px;
    height: 400px;
    background-image: url(https://images.unsplash.com/photo-1551715435-55b2b13a5257?ixlib=rb-1.2.1&auto=format&fit=crop&w=1525&q=80);
    background-repeat: no-repeat;
    background-size: cover;
}

background-size: cover; - адаптирует изображение под ваш контейнер (так то оно на много больше вашего контейнера, что бы оно нормально стало, лучше прописать это).
background-repeat: no-repeat; - отдельное свойство, не пихайте его в background-image. Такой синтаксис применим для общего свойства background, но не для background-image, указанного отдельно.


text:
Q: Gtk.StatusIcon freezing in multi-threaded app I have a problem with an application on CentOs / RH to show download statuses from the API. Everything works fine using the PyCharm IDE, but after compiling with PyInstaller (one folder) the application is very unstable and I can't find an error. I run the thread and download API statuses every 10 seconds and if there is a change, I update the icon and send a notification. After left-clicking on the icon, the statuses are displayed in Gtk.ApplicationWindow.

*

*Sometimes Gtk.StatusIcon can not change status or be inactive - left / right clicking doesn't work (but notifications of status changes come)

*the application may end unexpectedly
I suspect the problem is in threads, but I can't find a proper solution.
Code (main.py)
class ExampleSystemTrayInit(Gtk.StatusIcon):

def __init__(self):
    super().__init__()
    app.tray = Gtk.StatusIcon()
    app.tray.set_from_file(ico_start)
    app.tray.connect('popup-menu', self.on_right_click)
    app.tray.connect('activate', self.on_left_click, app)

def on_right_click(self, icon, event_button, event_time):
    self.menu = Gtk.Menu()
    quit = Gtk.MenuItem("Quit")
    quit.connect('activate', self.quitApp)
    self.menu.append(quit)
    self.menu.show_all()
    self.menu.popup(None, None, Gtk.StatusIcon.position_menu, app.tray, event_button, event_time)

def on_left_click(self, icon, app):
    try:
        self.app = app
        if app.all_status:
            data = self.app.all_status
            Controller.show_window(self, data, self.app, refresh=False)
            #call to class MainWindow(Gtk.ApplicationWindow) and show some data
        else:
            pass;
    except Exception as e:
        print(e)
        app.tray.set_from_file(ico_disconnect)

def quitApp(self, par):
    app.quit()

class ExampleSystemTray(Gtk.Application):

def __init__(self, *args, **kwargs):
    super().__init__(
        application_id="example-system-tray2.app"
    )
    self.tray = None
    self.mainWindow = None

def do_activate(self):
    if not hasattr(self, "my_app"):
        self.hold()
        self.my_app_settings = "Primary application instance."
        self.systray = ExampleSystemTrayInit()
        TrayController(app)

    else:
        print("Already running!")

def do_startup(self):
    Gdk.threads_init()
    Gdk.threads_enter()
    Gtk.Application.do_startup(self)
    Gdk.threads_leave()

if __name__ == "__main__":
   GObject.threads_init()
   app = ExampleSystemTray()
   app.run()

TrayController (traycontroller.py)
class TrayController(threading.Thread):

def __init__(self, app):
    self.app = app
    self.cache = None
    threading.Thread.__init__(self, name='TrayController', )
    self.interval = 10
    self.finished = threading.Event()
    self.daemon = True
    self.start()

def run(self):
    while True:
        try:
            self.finished.wait(self.interval)
            if not self.finished.is_set():
                self.connect(self.app)
        except Exception as e:
            print(e)

def cancel(self):
    """Stop the timer if it hasn't finished yet."""
    self.finished.set()

def connect(self, app):
    try:
        self.result = GetJson.get_json(self, api_view)
        if self.result == None:
            self.cache = None
            self.show_status(2)
            app.all_status = None
        elif (self.cache != self.result):
            self.cache = self.result
            app.all_status = AllStatusInstance(self.result)
            self.show_status(app.all_status.status)
            Controller.show_main_window(self, app.all_staus, app, refresh=True)
    #call to class  MainWindow(Gtk.ApplicationWindow) if window is visble, then refresh

    except Exception as e:
        print(e)
        self.show_status(2)
        app.all_status = None

def show_status(self, status):
    self.status = status
    if self.status == 0:
        return self.change_tray_icon(ico_red, notify_red, tag_red, widget=Gtk.StatusIcon)
    elif self.status == 1:
        return self.change_tray_icon(ico_gray, notify_gray, tag_gray, widget=Gtk.StatusIcon)
    elif self.status == 2:
        return self.change_tray_icon(ico_disconnect, notify_disconnect, tag_disconnect,
               widget=Gtk.StatusIcon)

def change_tray_icon(self, icon, notification, tag, widget):
    if self.app.tray.get_title() != tag:
        self.app.tray.set_from_file(icon)
        self.app.tray.set_title(tag)
        self.notify("Notification:", notification, icon)

def notify(self, title, body, link):
    notify2.init("Alert", mainloop=None)
    icon = GdkPixbuf.Pixbuf.new_from_file(link)
    n = notify2.Notification(title, body)
    n.set_icon_from_pixbuf(icon)
    n.set_urgency(notify2.URGENCY_CRITICAL)
    n.show()

class AllStatusInstance(object):
__instance = None

def __new__(cls, val):
    if AllStatusInstance.__instance is None:
        AllStatusInstance.__instance = object.__new__(cls)
    AllStatusInstance.__instance.val = val
    return AllStatusInstance.__instance

A: Indeed, the problem is threads, in the sense that you cannot use GTK API from multiple threads, ever, as the documentation clearly states.
You should use Gio.Task if you have a blocking, synchronous operation and you wish to update some UI state at the end of it; or, if you're using a thread object in Python, always use GLib.MainContext.invoke_full() to invoke a function within the same thread that is running the GTK main loop.
What you should not do, is this:
def do_startup(self):
    Gdk.threads_init()
    Gdk.threads_enter()
    Gtk.Application.do_startup(self)
    Gdk.threads_leave()

and then call GTK API from a separate thread than the one that is running GTK's event loop; that is entirely undefined, non-portable behaviour.


text:
Q: Integral of a Recursive Function in MATLAB I want to compute the following symbolic integral which is recursive :
function [y] = myfunc(i,T)
    s = sym('s');
    x= sym('x');
    h=[....]  %matrix n*n (function of x)
    d=[....]  %matrix n*1 (constants)
    for k=1:n
        if (T>0)
           y= int(exp(-s*x)*h(i,k)*myfunc(k,T-x/d(i)),'x',0,T);
    end
end

I expected MATLAB, while computing the integral, calls myfunc(k,T-x/d(i)) for different values of 'x' from 0 to T. However, it returns error since myfunc would be called with symbolic value 'x' and not the real value. Indeed, it cannot determine if (T>0) expression is true or false.
I would be thankful if you can suggest how this recursive integral can be computed ?. Thanks

A: If you want to ensure that a different real value is used in each step of a recursive function, you can define a variable to account for how deep you are.
Suppose we call it depth, and on the top level it is equal to 1. Each time you go one step deeper you increase depth by 1.
Now, if you want to get a number corresponding to the right depth, you can just call it as y(depth).


text:
Q: How to insert a newline before a range of specific formatted text in Microsft Word? I scanned a dictionary in color with two columns and OCR'd it with Abby, which gave pretty good results. Now sometimes a newline is not recognised well enough, so I need to insert a newline before every colored text (I know the RGB color).
I convert my scanned images to word (abby strips all headers, pagenumbers,..) and now I want on every line "phrase:description". Phrase is in a blue color.
Using the find and replace tool, I search for (<*>) with format -> font -> textcolor = RGB(xx,xx,xx).  I replace this with ^p \1, and this works great when phrase is a single word.
However, sometimes (most of the times), my phrase consists of multiple words, and I would only like one newline per phrase.
Is it possible to search for a range in a specific formatting (blue in my example), and add a newline in front of it using the find-and-replacetool or do I need a VBA-macro or is this not possible at all?
Thank you,
Wout

A: For future reference,
I solved my problem by first replacing all word with ###word, and then replacing word ### with word. This way I only have ### in front of words that have no blue textcolor before them.
After that I replaced ### with ^p (for some reason you can't use ^p together with wildcards..).
Not very clean and probably nicer in VBA, but it ain't stupid if it works.
Thank you for your input!


text:
Q: ffmpeg - fit multiple lines of text (having different fonts) with auto line wrap and auto font size? Trying to keep this question to a minimum as in terms of info. Sorry if it's too long and thank you for reading it!
I'm trying to make these texts fit (they have different fonts and font sizes) to the right of the avatar image but having difficulties doing it. The output is an m3u8 playlist file that gets played by a front-end JS video player. Please see the current output: https://postimg.cc/nXx34z96. This command is generated by a Node.js controller (that's why you can find multiple drawtext filters in it, those come from a for loop) and due to privacy I can't copy paste it here.
Question: is there any way we can render all text copies, no matter what their font families and font sizes are, for all the three texts:

*

*without text being cut/missing

*newlines being auto-added

*and the font size auto scaled

so that the text will fit on maximum 2 lines per each? Let's assume a number of maximum X chars per each line based on font-family (there are fonts whose glyphs are wider than others).
Any feedback/direction is greatly appreciated! Thank you much!
Graphic sketch needed can be found below.
           line1-with-font1
           line2-with-font1(-if-needed)

[avatar]   line1-with-font2
[ here ]   line2-with-font2(-if-needed)

           line1-with-font3
           line2-with-font3(-if-needed)

I've also tried writing texts to an image with a transparent background (so I could overlay that into the video afterwards) but I'm having troubles with the png image having the text too blurry (used imagemagick's convert and played with different settings).
Current command
time ffmpeg -y -i 5e47a1be4df117b7f79596dda7987c45.mp4 -i avatar.png -i ../../preview/helper-videos/bokeh.mp4 -i 1629885277.mp3 -preset ultrafast -crf 18 -filter_complex " [0:v]scale=878:494:force_original_aspect_ratio=decrease,pad=878:494:(ow-iw)/2:(oh-ih)/2,setsar=1,format=yuva420p[video]; [video]fade=in :0 :25[video]; [2:v]scale=1756:988:force_original_aspect_ratio=increase,format=rgba,colorchannelmixer=aa=0.2[motionOverlay];[video][motionOverlay]overlay[video]; [video]drawbox= x=0 :y=0 :w=iw :h=ih :color=0x000000@0.3 :t='fill' :enable='between(t,3,21)'[video]; [1:v]scale=-2:247:force_original_aspect_ratio=increase,format=yuva420p[scaledCoverPhoto]; [video][scaledCoverPhoto]overlay=:x=w/2:y=(H-h)/2:enable='between(t,4,21)' ,drawtext=fontfile=../../preview/fonts/opensans-regular.ttf\n` +
"              :text='Main text here, could be long enough to split in multiple lines'\n" +
'              :fontcolor=0xFFFFFF\n' +
'              :fontsize=40\n' +
"              :alpha='\n" +
'              \n' +
"              if(lt(t,5),0,if(lt(t,6),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'              :x=W/2\n' +
'              :y=h/2-120, drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='This is'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=200 - text_h/2,drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='the title'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=250 - text_h/2,drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='that can'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=300 - text_h/2,drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='be long'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=350 - text_h/2,drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='enough'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=400 - text_h/2,drawtext=fontfile=../../preview/fonts/greatvibes-regular.ttf\n' +
"            :text='too'\n" +
'            :fontcolor=0xFFFFFF\n' +
'            :fontsize=46\n' +
"            :alpha='if(lt(t,5),0,if(lt(t,7),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'                :x=(w-text_w)/2 + 100\n' +
'                :y=450 - text_h/2, drawtext=fontfile=../../preview/fonts/opensans-regular.ttf\n' +
"          :text='A subtitle here, can be long, also'\n" +
'          :fontcolor=0xFFFFFF\n' +
'          :fontsize=20\n' +
"          :alpha='if(lt(t,5),0,if(lt(t,8),(t-5)/1,if(lt(t,22),1,if(lt(t,28),(1-(t-27))/1,0))))'\n" +
'              :x=(w-text_w)/2 + 120\n' +
'              :y=(h-text_h)/2 + text_h*2 + 180, format=yuv420p, scale=-2:494 " -shortest -map 3:a -format hls -sn -hls_time 5 -hls_list_size 0 -hls_flags split_by_time -hls_playlist_type event -g 4 -r 25 output/index.m3u8'

Command output
LOG: [
'INFO',
'stderr:',
'ffmpeg version 4.4 Copyright (c) 2000-2021 the FFmpeg developers\n' +
'  built with Apple clang version 12.0.5 (clang-1205.0.22.9)\n' +
'  configuration: --prefix=/usr/local/Cellar/ffmpeg/4.4_2 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-avresample --enable-videotoolbox\n' +
'  libavutil      56. 70.100 / 56. 70.100\n' +
'  libavcodec     58.134.100 / 58.134.100\n' +
'  libavformat    58. 76.100 / 58. 76.100\n' +
'  libavdevice    58. 13.100 / 58. 13.100\n' +
'  libavfilter     7.110.100 /  7.110.100\n' +
'  libavresample   4.  0.  0 /  4.  0.  0\n' +
'  libswscale      5.  9.100 /  5.  9.100\n' +
'  libswresample   3.  9.100 /  3.  9.100\n' +
'  libpostproc    55.  9.100 / 55.  9.100\n' +
"Input #0, image2, from '07201487ede265cdea98d02930cd90dd.jpg':\n" +
'  Duration: 00:00:00.04, start: 0.000000, bitrate: 62761 kb/s\n' +
'  Stream #0:0: Video: mjpeg (Baseline), yuvj444p(pc, bt470bg/unknown/unknown), 411x494 [SAR 96:96 DAR 411:494], 25 fps, 25 tbr, 25 tbn, 25 tbc\n' +
'Stream mapping:\n' +
'  Stream #0:0 (mjpeg) -> scale\n' +
'  fade -> Stream #0:0 (libx264)\n' +
'Press [q] to stop, [?] for help\n' +
'[swscaler @ 0x7fceb8008000] deprecated pixel format used, make sure you did set range correctly\n' +
'[libx264 @ 0x7fceb3809400] using SAR=411/494\n' +
'[libx264 @ 0x7fceb3809400] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2\n' +
'[libx264 @ 0x7fceb3809400] profile High 4:4:4 Predictive, level 1.0, 4:4:4, 8-bit\n' +
'[libx264 @ 0x7fceb3809400] 264 - core 163 r3060 5db6aa6 - H.264/MPEG-4 AVC codec - Copyleft 2003-2021 - http://www.videolan.org/x264.html - options: cabac=1 ref=3 deblock=1:0:0 analyse=0x3:0x113 me=hex subme=7 psy=1 psy_rd=1.00:0.00 mixed_ref=1 me_range=16 chroma_me=1 trellis=1 8x8dct=1 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=4 threads=3 lookahead_threads=1 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=3 b_pyramid=2 b_adapt=1 b_bias=0 direct=1 weightb=1 open_gop=0 weightp=2 keyint=250 keyint_min=25 scenecut=40 intra_refresh=0 rc_lookahead=40 rc=crf mbtree=1 crf=23.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=1:1.00\n' +
"Output #0, mp4, to 'coverPhoto-35034893880715867923.mp4':\n" +
'  Metadata:\n' +
'    encoder         : Lavf58.76.100\n' +
'  Stream #0:0: Video: h264 (avc1 / 0x31637661), yuvj444p(pc, bt470bg/unknown/unknown, progressive), 100x100 [SAR 411:494 DAR 411:494], q=2-31, 25 fps, 12800 tbn\n' +
'    Metadata:\n' +
'      encoder         : Lavc58.134.100 libx264\n' +
'    Side data:\n' +
'      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A\n' +
'frame=    1 fps=0.0 q=0.0 size=       0kB time=00:00:00.00 bitrate=N/A speed=   0x    \rframe=  102 fps=0.0 q=28.0 size=       0kB time=00:00:02.08 bitrate=   0.2kbits/s speed=4.14x    \rframe=  200 fps=199 q=28.0 size=       0kB time=00:00:06.00 bitrate=   0.1kbits/s speed=5.96x    \rframe=  327 fps=217 q=28.0 size=       0kB time=00:00:11.08 bitrate=   0.0kbits/s speed=7.35x    \rframe=  456 fps=227 q=28.0 size=       0kB time=00:00:16.24 bitrate=   0.0kbits/s speed=8.08x    \rframe=  475 fps=225 q=-1.0 Lsize=      32kB time=00:00:18.88 bitrate=  13.7kbits/s speed=8.95x    \n' +
'video:25kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 25.380770%\n' +
'[libx264 @ 0x7fceb3809400] frame I:3     Avg QP:14.28  size:  3258\n' +
'[libx264 @ 0x7fceb3809400] frame P:120   Avg QP:23.93  size:    91\n' +
'[libx264 @ 0x7fceb3809400] frame B:352   Avg QP:33.22  size:    13\n' +
'[libx264 @ 0x7fceb3809400] consecutive B-frames:  1.1%  0.0%  1.3% 97.7%\n' +
'[libx264 @ 0x7fceb3809400] mb I  I16..4:  2.0% 58.5% 39.5%\n' +
'[libx264 @ 0x7fceb3809400] mb P  I16..4:  0.0%  0.0%  0.1%  P16..4:  5.5%  0.6%  0.8%  0.0%  0.0%    skip:93.0%\n' +
'[libx264 @ 0x7fceb3809400] mb B  I16..4:  0.0%  0.0%  0.0%  B16..8:  0.2%  0.0%  0.0%  direct: 0.0%  skip:99.8%  L0: 0.0% L1:93.1% BI: 6.9%\n' +
'[libx264 @ 0x7fceb3809400] 8x8 transform intra:56.2% inter:44.5%\n' +
'[libx264 @ 0x7fceb3809400] coded y,u,v intra: 58.3% 48.0% 46.2% inter: 1.0% 0.7% 0.7%\n' +
'[libx264 @ 0x7fceb3809400] i16 v,h,dc,p:  0%  0% 100%  0%\n' +
'[libx264 @ 0x7fceb3809400] i8 v,h,dc,ddl,ddr,vr,hd,vl,hu:  6%  5% 72%  3%  3%  3%  2%  3%  3%\n' +
'[libx264 @ 0x7fceb3809400] i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 21% 23% 10%  6%  9%  6%  7%  7% 11%\n' +
'[libx264 @ 0x7fceb3809400] Weighted P-Frames: Y:6.7% UV:6.7%\n' +
'[libx264 @ 0x7fceb3809400] ref P L0: 93.6%  2.7%  2.0%  1.7%\n' +
'[libx264 @ 0x7fceb3809400] ref B L1: 96.6%  3.4%\n' +
'[libx264 @ 0x7fceb3809400] kb/s:10.57\n' +
'ffmpeg version 4.4 Copyright (c) 2000-2021 the FFmpeg developers\n' +
'  built with Apple clang version 12.0.5 (clang-1205.0.22.9)\n' +
'  configuration: --prefix=/usr/local/Cellar/ffmpeg/4.4_2 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-avresample --enable-videotoolbox\n' +
'  libavutil      56. 70.100 / 56. 70.100\n' +
'  libavcodec     58.134.100 / 58.134.100\n' +
'  libavformat    58. 76.100 / 58. 76.100\n' +
'  libavdevice    58. 13.100 / 58. 13.100\n' +
'  libavfilter     7.110.100 /  7.110.100\n' +
'  libavresample   4.  0.  0 /  4.  0.  0\n' +
'  libswscale      5.  9.100 /  5.  9.100\n' +
'  libswresample   3.  9.100 /  3.  9.100\n' +
'  libpostproc    55.  9.100 / 55.  9.100\n' +
"Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '5e47a1be4df117b7f79596dda7987c45.mp4':\n" +
'  Metadata:\n' +
'    major_brand     : isom\n' +
'    minor_version   : 512\n' +
'    compatible_brands: isomiso2avc1mp41\n' +
'    encoder         : Lavf58.29.100\n' +
'    media_type      : 0\n' +
'    hd_video        : 0\n' +
'  Duration: 00:00:21.29, start: 0.000000, bitrate: 1139 kb/s\n' +
'  Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 878x494 [SAR 3952:3951 DAR 16:9], 1136 kb/s, 24 fps, 24 tbr, 12288 tbn, 48 tbc (default)\n' +
'    Metadata:\n' +
'      handler_name    : VideoHandler\n' +
'      vendor_id       : [0][0][0][0]\n' +
"Input #1, png_pipe, from '07201487ede265cdea98d02930cd90dd.jpg.png':\n" +
'  Duration: N/A, bitrate: N/A\n' +
'  Stream #1:0: Video: png, rgb24(pc), 431x514 [SAR 3779:3779 DAR 431:514], 25 fps, 25 tbr, 25 tbn, 25 tbc\n' +
"Input #2, mov,mp4,m4a,3gp,3g2,mj2, from '../../preview/helper-videos/bokeh.mp4':\n" +
'  Metadata:\n' +
'    major_brand     : mp42\n' +
'    minor_version   : 0\n' +
'    compatible_brands: isommp42\n' +
'    creation_time   : 2012-03-21T12:18:56.000000Z\n' +
'  Duration: 00:00:07.00, start: 0.000000, bitrate: 1060 kb/s\n' +
'  Stream #2:0(und): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 1152x720, 1054 kb/s, 25 fps, 25 tbr, 50 tbn, 50 tbc (default)\n' +
'    Metadata:\n' +
'      creation_time   : 1970-01-01T00:00:00.000000Z\n' +
'      handler_name    : VideoHandler\n' +
'      vendor_id       : [0][0][0][0]\n' +
'  Stream #2:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 3 kb/s (default)\n' +
'    Metadata:\n' +
'      creation_time   : 2012-03-21T12:18:56.000000Z\n' +
'      handler_name    : IsoMedia File Produced by Google, 5-11-2011\n' +
'      vendor_id       : [0][0][0][0]\n' +
"Input #3, mp3, from '1629885277.mp3':\n" +
'  Metadata:\n' +
'    title           : The Gift of Love\n' +
'    TLEN            : 228773\n' +
'    publisher       : Musical Reflections, Inc.\n' +
'    genre           : Instrumental\n' +
"    album           : Love's Journey\n" +
'    album_artist    : Tami Briggs\n' +
'    track           : 7\n' +
'    artist          : Tami Briggs\n' +
'    date            : 1999-00-00\n' +
'    encoder         : Lavf58.29.100\n' +
'    id3v2_priv.WM/MediaClassPrimaryID: \\xbc}`\\xd1#\\xe3\\xe2K\\x86\\xa1H\\xa4*(D\\x1e\n' +
'    id3v2_priv.WM/MediaClassSecondaryID: \\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n' +
'    id3v2_priv.WM/WMContentID: \\xee\\xb1,V\\xa5H*A\\x9c\\x07\\xbb/\\xbb3\\xc2\\xba\n' +
'    id3v2_priv.WM/UniqueFileIdentifier: A\\x00M\\x00G\\x00a\\x00_\\x00i\\x00d\\x00=\\x00R\\x00 \\x00 \\x00 \\x007\\x007\\x003\\x003\\x008\\x008\\x00;\\x00A\\x00M\\x00G\\x00p\\x00_\\x00i\\x00d\\x00=\\x00P\\x00 \\x00 \\x00 \\x007\\x000\\x007\\x000\\x009\\x004\\x00;\\x00A\\x00M\\x00G\\x00t\\x00_\\x00i\\x00d\\x00=\\x00T\\x00 \\x00 \\x007\\x008\\x00\n' +
'    id3v2_priv.WM/WMCollectionID: (\\xc2\\xd0\\x91\\x17\\xa1rK\\xa3\\xfd\\xea\\xe6QBA\\x81\n' +
'    id3v2_priv.WM/WMCollectionGroupID: (\\xc2\\xd0\\x91\\x17\\xa1rK\\xa3\\xfd\\xea\\xe6QBA\\x81\n' +
'    id3v2_priv.WM/Provider: A\\x00M\\x00G\\x00\\x00\\x00\n' +
'    id3v2_priv.XMP  : <?xpacket begin="\\xef\\xbb\\xbf" id="W5M0MpCehiHzreSzNTczkc9d"?>\\x0a<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.6-c014 79.156821, 2014/08/29-03:07:50        ">\\x0a <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">\\x0a  <rdf\n' +
'  Duration: 00:03:44.21, start: 0.025057, bitrate: 128 kb/s\n' +
'  Stream #3:0: Audio: mp3, 44100 Hz, stereo, fltp, 128 kb/s\n' +
'    Metadata:\n' +
'      encoder         : Lavc58.54\n' +
'Codec AVOption format (set pixel type) specified for output file #0 (output/index.m3u8) has not been used for any stream. The most likely reason is either wrong type (e.g. a video option with no video streams) or that it is a private option of some encoder which was not actually used for any stream.\n' +
'Stream mapping:\n' +
'  Stream #0:0 (h264) -> scale (graph 0)\n' +
'  Stream #1:0 (png) -> scale (graph 0)\n' +
'  Stream #2:0 (h264) -> scale (graph 0)\n' +
'  scale (graph 0) -> Stream #0:0 (libx264)\n' +
'  Stream #3:0 -> #0:1 (mp3 (mp3float) -> aac (native))\n' +
'Press [q] to stop, [?] for help\n' +
'[libx264 @ 0x7fd66c813400] using SAR=1/1\n' +
'[libx264 @ 0x7fd66c813400] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX FMA3 BMI2 AVX2\n' +
'[libx264 @ 0x7fd66c813400] profile Constrained Baseline, level 3.1, 4:2:0, 8-bit\n' +
'[libx264 @ 0x7fd66c813400] 264 - core 163 r3060 5db6aa6 - H.264/MPEG-4 AVC codec - Copyleft 2003-2021 - http://www.videolan.org/x264.html - options: cabac=0 ref=1 deblock=0:0:0 analyse=0:0 me=dia subme=0 psy=1 psy_rd=1.00:0.00 mixed_ref=0 me_range=16 chroma_me=1 trellis=0 8x8dct=0 cqm=0 deadzone=21,11 fast_pskip=1 chroma_qp_offset=0 threads=15 lookahead_threads=2 sliced_threads=0 nr=0 decimate=1 interlaced=0 bluray_compat=0 constrained_intra=0 bframes=0 weightp=0 keyint=4 keyint_min=1 scenecut=0 intra_refresh=0 rc=crf mbtree=0 crf=18.0 qcomp=0.60 qpmin=0 qpmax=69 qpstep=4 ip_ratio=1.40 aq=0\n' +
"Output #0, hls, to 'output/index.m3u8':\n" +
'  Metadata:\n' +
'    major_brand     : isom\n' +
'    minor_version   : 512\n' +
'    compatible_brands: isomiso2avc1mp41\n' +
'    hd_video        : 0\n' +
'    media_type      : 0\n' +
'    encoder         : Lavf58.76.100\n' +
'  Stream #0:0: Video: h264, yuv420p(tv, progressive), 878x494 [SAR 1:1 DAR 439:247], q=2-31, 25 fps, 90k tbn (default)\n' +
'    Metadata:\n' +
'      encoder         : Lavc58.134.100 libx264\n' +
'    Side data:\n' +
'      cpb: bitrate max/min/avg: 0/0/0 buffer size: 0 vbv_delay: N/A\n' +
'  Stream #0:1: Audio: aac (LC), 44100 Hz, stereo, fltp, 128 kb/s\n' +
'    Metadata:\n' +
'      encoder         : Lavc58.134.100 aac\n' +
"frame=    1 fps=0.0 q=0.0 size=N/A time=00:00:00.00 bitrate=N/A speed=   0x    \rframe=   26 fps=0.0 q=19.0 size=N/A time=00:00:00.40 bitrate=N/A dup=1 drop=0 speed=0.677x    \rframe=   55 fps= 50 q=14.0 size=N/A time=00:00:01.56 bitrate=N/A dup=2 drop=0 speed=1.41x    \rframe=   82 fps= 51 q=15.0 size=N/A time=00:00:02.64 bitrate=N/A dup=3 drop=0 speed=1.63x    \rframe=  104 fps= 49 q=19.0 size=N/A time=00:00:03.52 bitrate=N/A dup=4 drop=0 speed=1.64x    \rframe=  129 fps= 49 q=17.0 size=N/A time=00:00:04.52 bitrate=N/A dup=5 drop=0 speed= 1.7x    \r[hls @ 0x7fd66c80ba00] Opening 'output/index0.ts' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index.m3u8.tmp' for writing\n" +
"frame=  150 fps= 47 q=16.0 size=N/A time=00:00:05.36 bitrate=N/A dup=6 drop=0 speed=1.69x    \rframe=  169 fps= 46 q=18.0 size=N/A time=00:00:06.12 bitrate=N/A dup=7 drop=0 speed=1.66x    \rframe=  227 fps= 54 q=15.0 size=N/A time=00:00:08.44 bitrate=N/A dup=9 drop=0 speed=2.02x    \r[hls @ 0x7fd66c80ba00] Opening 'output/index1.ts' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index.m3u8.tmp' for writing\n" +
"frame=  280 fps= 60 q=20.0 size=N/A time=00:00:10.56 bitrate=N/A dup=11 drop=0 speed=2.25x    \rframe=  342 fps= 66 q=17.0 size=N/A time=00:00:13.04 bitrate=N/A dup=14 drop=0 speed=2.51x    \r[hls @ 0x7fd66c80ba00] Opening 'output/index2.ts' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index.m3u8.tmp' for writing\n" +
"frame=  410 fps= 72 q=18.0 size=N/A time=00:00:15.76 bitrate=N/A dup=16 drop=0 speed=2.76x    \rframe=  490 fps= 79 q=16.0 size=N/A time=00:00:18.96 bitrate=N/A dup=20 drop=0 speed=3.06x    \r[hls @ 0x7fd66c80ba00] Opening 'output/index3.ts' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index.m3u8.tmp' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index4.ts' for writing\n" +
"[hls @ 0x7fd66c80ba00] Opening 'output/index.m3u8.tmp' for writing\n" +
'frame=  532 fps= 82 q=-1.0 Lsize=N/A time=00:00:21.28 bitrate=N/A dup=21 drop=0 speed=3.29x    \n' +
'video:11798kB audio:333kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: unknown\n' +
'[libx264 @ 0x7fd66c813400] frame I:133   Avg QP:14.64  size: 68603\n' +
'[libx264 @ 0x7fd66c813400] frame P:399   Avg QP:17.71  size:  7410\n' +
'[libx264 @ 0x7fd66c813400] mb I  I16..4: 100.0%  0.0%  0.0%\n' +
'[libx264 @ 0x7fd66c813400] mb P  I16..4:  9.8%  0.0%  0.0%  P16..4: 28.5%  0.0%  0.0%  0.0%  0.0%    skip:61.7%\n' +
'[libx264 @ 0x7fd66c813400] coded y,uvDC,uvAC intra: 58.0% 41.2% 27.3% inter: 16.6% 7.9% 0.1%\n' +
'[libx264 @ 0x7fd66c813400] i16 v,h,dc,p: 36% 28% 18% 18%\n' +
'[libx264 @ 0x7fd66c813400] i8c dc,h,v,p: 61% 20% 14%  6%\n' +
'[libx264 @ 0x7fd66c813400] kb/s:4541.68\n' +
'[aac @ 0x7fd66c820400] Qavg: 931.453\n' +
'\n' +
'real\t0m6.605s\n' +
'user\t0m16.878s\n' +
'sys\t0m0.465s'
]


text:
Q: Best way to create json with 100+ keys I have to create a JSON object that contains 100+ keys and some of them start with a number (2nd_). Because of that, I can't have an object to use it as a template, I had it set it up that way until those pre-fixed numeric keys were added to the web service. I used to have a function to fill that object with reflection but now I need to find a new way.
Is there's a way to have a dictionary with all the keys I need to just start filling it with the data I need? Something like a template dictionary or anything else that can be more elegant?
I tried with DataAnnotations but it newtonsoft json doesn't support the "Display Name" attribute.
Btw, it's a UWP app, so it has .Net Core
Thanks!

A: I resolved it by using JsonProperty[("1st_key")] data annotation. That way I still can have my class with all the objects mapped and have the numeric key that the web service requires


text:
Q: Facebook login redirect issue I have a site with a working Facebook login.
The problem is happens when the user comes to the site for the first time (or after clearing cookies).
The user flow is the following:

*

*User clicks "Sign Up with Facebook"

*User is redirected to Facebook authentication

*If User accepts, he/she is redirected to the 'Sign Up' page.

The problem is that if the person is doing this for the first time, they are always redirected back to the home page.
There are only 2 possible views that can be given for this url

*

*The Sign Up page, with only some form data sent as parameters

*An alert box upon successful DB persistence

Thus, I have ruled out PHP as a possible cause of the redirect.
I have included the JavaScript managing the Facebook interaction.
All other relevant code can be found in the HTML of the page.
The Page can be found at http://trioisrael.com
function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            window.location = "http://trioisrael.com/signup"
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                user_email = response.email; //get user email
                // you can store this data into your database
            });

        } else {
            //user hit cancel button
            alert('We use facebook to make sure that everyone is really who they say they are');

        }
    }, {
        scope: 'user_photos,user_birthday'
    });
}

A: Trying to do additional stuff after assigning a new value to window.location (which should be window.location.href, of course) does not make sense.
If you want to do additional stuff after login, do it before redirecting the user somewhere else.


text:
Q: How to tell if an SQL Server is clustered, without interacting with it, preferably via the Registry? I need to find out if a given SQL Server instance which its instance name I have, is clustered, without actually connecting it and running queries.
Options:

*

*SqlDataSourceEnumerator.Instance.GetDataSources(): even when it works, it is extremely slow. And again, it doesn't always work (returns empty enumeration??)

*Registry - I'm sure that information is there, but don't know where...

*Haven't tried WMI as I'm sure there's an easier solution (e.g. registry...)

A: TSQL:
SELECT 'IsClustered', SERVERPROPERTY('IsClustered')

Powershell:
$s = Get-WmiObject -Class Win32_SystemServices -ComputerName $server
if ($s | select PartComponent | where {$_ -like "*ClusSvc*"}) { Write-Output "$server is Clustered" }
else { Write-Output "$server is Not clustered" }

Reference http://www.sqlservercentral.com/Forums/Topic1182082-1351-1.aspx
There are registry keys that can be checked see https://www.mssqltips.com/sqlservertip/3440/registry-check-pointing-in-a-windows-cluster-to-bring-sql-server-online/ for details.
However TSQL and powershell are much quicker than a remote registry call. If you can make a ADO.NET connection to the instance the TSQL method is the quickest by far.


text:
Q: why are my buttons not fitting properly? In landscape mode they properly stretch to fit the width..but in portrait the Exit button is extending too far to the right.
layout code: http://pastebin.com/KZVCdVJw

A: The reason why it wasnt properly fitting the screen was due to the orientation of the LinearLayout it was in. By changing the orientation from horizontal to vertical it solved the problem.


text:
Q: UICollectionViewLayout - 3 cells in 2 columns I am trying to create a UICollectionView with a 7-cell repeating layout that looks like this:

However, with CollectionViewLayout, I can't seem to get the 6th and 7th cell into the same column.
Here's the relevant code:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let collectionViewWidth = self.collectionView.bounds.width
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        let spaceBetweenCells = flowLayout.minimumInteritemSpacing
        var adjustedWidth = collectionViewWidth - spaceBetweenCells

        if indexPath.row % 7 == 0 {
            return CGSize(width: collectionViewWidth, height: collectionViewWidth)
        }

        if indexPath.row % 7 == 1 || indexPath.row % 7 == 2 || indexPath.row % 7 == 3 {
            adjustedWidth = collectionViewWidth - (spaceBetweenCells * 2)
            return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
        }

        if indexPath.row % 7 == 4 {
            adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
            return CGSize(width: floor(adjustedWidth / 3) * 2 + spaceBetweenCells, height: floor(adjustedWidth / 3) * 2 + spaceBetweenCells)
        }

        if indexPath.row % 7 == 5 || indexPath.row % 7 == 6 {
            adjustedWidth = collectionViewWidth - spaceBetweenCells * 2
            return CGSize(width: floor(adjustedWidth / 3), height: floor(adjustedWidth / 3))
        }

        let width: CGFloat = adjustedWidth / 2
        let height: CGFloat = width;
        return CGSize(width: width, height: height)
    }

And this is the result:

I've even tried using a smaller height for the last two cells, to make sure the height wasn't an issue. Thanks for any help.

Update
I got it to work via UIStackViews, albeit pretty annoying.

A: This won't be an easy task by just using the UICollectionViewFlowLayout's sizeForItem method. You would have to use
if indexPath.row % 7 == 0 || indexPath.row % 7 == 4 {
    return CGSize(width: collectionViewWidth, height: collectionViewWidth)
}

And then within the cellForItemAt method:
if indexPath.row % 7 == 4 {
    // Provide a UIStackView with your required layout
    // Or maybe even you could provide a smaller UICollectionView with just 3 cells, but that seems like overkill.
}


text:
Q: Loop through arrays in dataframe and plot by group I have a dataframe that contains X & Y position data and has 3 grouping variables:

*

*obsScenario (0, 1 or 2)

*startPos (1 or 2)

*targetPos (1, 2, or 3).

Thus there are 18 combinations of these grouping variables: 3 x 2 x 3
The X and Y data is approx 300-500 data points in length per participant (it varies).
The dataframe looks like this:
              X         Y  participantNum  obsScenario  startPos  targetPos
0    -16.000000  5.000000         6432024            0         1          1
1    -16.000000  5.000000         6432024            0         1          1
2    -15.833450  5.000000         6432024            0         1          1
3    -15.667200  5.000000         6432024            0         1          1
4    -15.500100  5.000000         6432024            0         1          1
        ...       ...             ...          ...       ...        ...
2185  -1.572058 -3.982638         7830381            2         2          2
2186  -1.406996 -3.958967         7830381            2         2          2
2187  -1.242231 -3.935339         7830381            2         2          2
2188  -1.077516 -3.911718         7830381            2         2          2
2189  -0.912604 -3.888069         7830381            2         2          2

I need to plot the X, Y data separately for each of these 18 combinations.
Im trying to use something like this, but this just plots all the XY trajectories on the same plot:
for aid, grp in df.groupby(['obsScenario', 'startPos', 'targetPos']):
    plt.plot(grp[0].values, grp[1].values)
plt.show()

And using something like this doesnt take the different combinations of grouping variables into account:
fig, axs = plt.subplots(nrows=3, ncols=6)

for ax in axs.flat:
    plotxy(ax,x,y)

A: This does what I was looking for:
fig, axs = plt.subplots(6,3)
grp = df.groupby(['obsScenario', 'startPos', 'targetPos'])
for (name, df), ax in zip(grp, axs.flat):
    df.plot(x='X',y='Y', ax=ax)


text:
Q: what should i use instead of Directory.SetCurrentDirecory? i have a multi environment program that runs on windows ce machines, regular pc and windows mobile.
I am using a database and files.
because of the windows CE i need to use the Directory.GetCurrentDirectory() func before the file use and then reset the current directory (using the Directory.SetCurrentDirectory() func) back to the old one because it changes once i do the I\O in order to continue using the DB.
because the windows mobile does not support this functions there is an exception thrown during runtime a "NotSupporetedException".
any functions that i could use instead of this that should fix my problem?
or any way i can check during runtime what environment the application is running on and not use this functions if the application runs on mobile?
please help,
thanks in advance.

A: I don't fully understand your directory problem, but you can certainly check which platform you're on at runtime:
if (Environment.OSVersion.Platform == PlatformID.WinCE)
{
    ...
}
else
{
    ...
}


text:
Q: Terminal Command Mac Alter table SQLite3 What is the terminal command, or where is a good resource to get them, to alter a table. And, do I need to re run the $rake db:migrate after I do this? I am running RoR on Snow Leopard. Last question, can I make an already created column non-null.
UPDATE: figured out how to alter, just need to know if I need to rake db:migrate after alter.

A:
good resource to get them, to alter a
  table

Check these to get a grasp at how migrations work
Rails Migrations Cheatsheet
Railsguides: Migrations

@run rake db:migrate: yes

@created to non-null: yes (Check 7.1 add_column and 7.2 change_column in the first link


text:
Q: How to add field with static value to mongodb find query? Can we add some custom field with static value to mongodb find query?
I am trying to add/append API request UId to all the queries that we are making to mongodb, so that  we can map requests with slow queries from mongodb logs.
I am doing it in aggregate queries by using '$literal' in projected fields.
My Aggregate queries looks something like :
db.test.aggregate({
    $project: {
        "custom_id": { $literal: "uid" }
        ..
    }
    ..
})

Also I can't include each field individually in projected fields and add the "custom_id" field with the static value.

A: Instead of using $comment, you can give a try to the aggregate function and the literal:
db.bids.aggregate( [
   { $project: { item: 1, startAt: { $literal: 1 } } }
] )

And as a result you get:
{ "_id" : 1, "item" : "abc123", "startAt" : 1 }
{ "_id" : 2, "item" : "xyz123", "startAt" : 1 }

Doc: $literal

A: Found answer to the question on mongoDb jira.
The best way to do this would be using the $comment operator.
Here's the link to Documentation.


text:
Q: Прокрутка блоками css Сделал для примера три блока. У всех высота 100vh. Не пойму как сделать так, чтобы если мы прокрутили вниз (тоже самое и вверху), второй блок вылетал на всю высоту, то есть на весь экран, и тд, а не смотрелся половина одного, половина другого блока.
<!doctype html>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Блоки</title>
        <link rel="stylesheet" href="style.css" />

html {
    height: 100vh;
}
.block1 {
    display: flex;
    height: 100vh;
    background-color: aqua;
}
.block2 {
    display: flex;
    height: 100vh;
    background-color: chocolate;
}
.block3 {
    display: flex;
    height: 100vh;
    background-color: firebrick;
}

A: Если изобретать свои велосипеды, то можно так :)
И да, на чистом CSS это сделать нельзя.

// подписываемся на события скрола колесиком
$(window).on('mousewheel', function(e) {
  // тут мы определяем в какую сторону скрольнули и в зависимости от этого будем показывать соответсвующий блок
  if (e.originalEvent.wheelDelta / 120 > 0) {
    scroller.showPrev();
  } else {
    scroller.showNext();
  }
});

var scroller = {};
// показывает следующий блок после текущего
// принцип: хватаем текущий блок,
// берем следующий через .next(), если он существует - скроллим к нему
// предварительно смотрим чтобы мы уже не скроллились
scroller.showNext = function() {
  if (this.isScrolling) {
    return;
  }
  let current = scroller.getDisplayingBlock();
  let next = $(current).next();
  if (next) {
    scroller.scrollToElement(next);
  }
}
// показывает предыдущий блок
// принцип: хватаем текущий блок,
// берем предыдущий через .prev(), если он существует - скроллим к нему
// предварительно смотрим чтобы мы уже не скроллились
scroller.showPrev = function() {
  if (this.isScrolling) {
    return;
  }
  let current = scroller.getDisplayingBlock();
  let prev = $(current).prev();
  if (prev) {
    scroller.scrollToElement(prev);
  }
}
// возвращает текущий блок
// принцип: смотрим текущую позицию скролла
// по коллекции элементов .block ищем первую,
// которая находится на позиции текущего скролла +-10
scroller.getDisplayingBlock = function() {
  let scrollPosition = $(window).scrollTop();
  let item = Array.from($('.block')).find(function(el) {
    return Math.abs(el.offsetTop - scrollPosition) < 10;
  });
  return item;
}
// скроллит к блоку
// сетает флаг isScrolling=true
// с помощью .animate анимирует скролл
// после завершения скролла сетаем обратно isScrolling=false
scroller.scrollToElement = function(el) {
  this.isScrolling = true;
  let thisScroller = this;
  let elTopOffset = el.offset().top;
  $("html, body").animate({ scrollTop: elTopOffset },
    600, function() { thisScroller.isScrolling = false; });
}
body {
  height: 100vh;
  overflow: hidden;
}

.block {
  height: 100vh;
}

.block1 {
  background-color: aqua;
}

.block2 {
  background-color: chocolate;
}

.block3 {
  background-color: firebrick;
}

Почитать:

*

*.next()

*.prev()

*.animate()

A: Самый простой способ - использовать плагин fullpage.