adding gnuradio in recipe Yocto Raspberrypi 4

Question: I'm trying to create a yocto recipe to add gnu radio on my raspberrypi 4 but I get the following error when I generate my image:
| ERROR: ExecutionError('/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/temp/run.do_compile.503884', 1, None, None)
ERROR: Task (/home/norian/Yocto/poky/meta/recipes-support/boost/boost_1.75.0.bb:do_compile) failed with exit code '1'

This is what the bitbake-layers show-layers command returns to me:
layer                 path                                      priority
==========================================================================
meta                  /home/norian/Yocto/poky/meta              5
meta-poky             /home/norian/Yocto/poky/meta-poky         5
meta-yocto-bsp        /home/norian/Yocto/poky/meta-yocto-bsp    5
meta-raspberrypi      /home/norian/Yocto/poky/meta-raspberrypi  9
meta-oe               /home/norian/Yocto/meta-openembedded/meta-oe  6
meta-python           /home/norian/Yocto/meta-openembedded/meta-python  7
meta-filesystems      /home/norian/Yocto/meta-openembedded/meta-filesystems  6
meta-networking       /home/norian/Yocto/meta-openembedded/meta-networking  5
meta-qt5              /home/norian/Yocto/meta-openembedded/meta-qt5  7
meta-sdr              /home/norian/Yocto/meta-openembedded/meta-sdr  5
meta-my-layer         /home/norian/Yocto/meta-my-layer          6

my recipe is in meta-my-layer and is called radio-image.bb
Here is its content:
SUMMARY = "A small image just capable of allowing a device to boot."

IMAGE_LINGUAS = " "

LICENSE = "MIT"

inherit core-image

CORE_IMAGE_EXTRA_INSTALL = "\
    packagegroup-sdr-base-extended \
    packagegroup-sdr-base-debug \
    packagegroup-sdr-base-devel \
    packagegroup-sdr-base-python \
    packagegroup-sdr-python-extended \
    packagegroup-sdr-gnuradio-base \
    packagegroup-core-eclipse-debug \
    "
IMAGE_INSTALL += "nano"
CONF_VERSION = "1"
ENABLE_UART="1"

I copied the contents of the gnuradio-image.bb recipe which is from meta-sdr.
I also copy the folder packagegroups into my recipe.
I am using Ubuntu 20.04.
My version of poky is :
DISTRO_VERSION = "3.3.4"
DISTRO_CODENAME = "hardknott"

Can you explain to me what boost is for and how to correct its compilation please ?
EDIT: I found the following error in the boost compilation logfile:
{standard input}: Assembler messages:
{standard input}:4183: Warning: end of file not at end of a line; newline inserted
{standard input}:4801: Error: unknown pseudo-op: `.l'
{standard input}: Error: open CFI at the end of file; missing .cfi_endproc directive
aarch64-poky-linux-g++: fatal error: Killed signal terminated program cc1plus
compilation terminated.

{standard input}: Assembler messages:
{standard input}: Error: open CFI at the end of file; missing .cfi_endproc directive
aarch64-poky-linux-g++: fatal error: Killed signal terminated program cc1plus
compilation terminated.

gcc.compile.c++ /home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/build/boost/bin.v2/libs/log/build/f79941b6f0ebe85fc9fba0b2ec31feac/syslog_backend.o

    "aarch64-poky-linux-g++" "-mcpu=cortex-a72" "-march=armv8-a+crc+crypto" "-Wl,-O1" "-Wl,--hash-style=gnu" "-Wl,--as-needed" "-Wl,-z,relro,-z,now" "-fstack-protector-strong" "-O2" "-D_FORTIFY_SOURCE=2" "-Wformat" "-Wformat-security" "-Werror=format-security" "--sysroot=/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/recipe-sysroot"  -ftemplate-depth-1024 -fvisibility-inlines-hidden  -O2 -pipe -g -feliminate-unused-debug-types -fmacro-prefix-map=/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0=/usr/src/debug/boost/1.75.0-r0                      -fdebug-prefix-map=/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0=/usr/src/debug/boost/1.75.0-r0                      -fdebug-prefix-map=/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/recipe-sysroot=                      -fdebug-prefix-map=/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/recipe-sysroot-native=  -fvisibility-inlines-hidden -fPIC -pthread -O3 -finline-functions -Wno-inline -Wall -fvisibility=hidden -fno-strict-aliasing -DBOOST_ALL_NO_LIB=1 -DBOOST_ATOMIC_DYN_LINK=1 -DBOOST_CHRONO_DYN_LINK=1 -DBOOST_FILESYSTEM_DYN_LINK=1 -DBOOST_LOG_BUILDING_THE_LIB=1 -DBOOST_LOG_DLL -DBOOST_LOG_HAS_PTHREAD_MUTEX_ROBUST -DBOOST_LOG_USE_NATIVE_SYSLOG -DBOOST_LOG_WITHOUT_DEBUG_OUTPUT -DBOOST_LOG_WITHOUT_EVENT_LOG -DBOOST_SPIRIT_USE_PHOENIX_V3=1 -DBOOST_THREAD_BUILD_DLL=1 -DBOOST_THREAD_DONT_USE_CHRONO=1 -DBOOST_THREAD_POSIX -DBOOST_THREAD_USE_DLL=1 -DNDEBUG -D_XOPEN_SOURCE=600 -D__STDC_CONSTANT_MACROS  -I"." -I"libs/log/src"  -c -o "/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/build/boost/bin.v2/libs/log/build/f79941b6f0ebe85fc9fba0b2ec31feac/syslog_backend.o" "libs/log/src/syslog_backend.cpp"

...skipped
libboost_log.so.1.75.0 for lack of
text_file_backend.o...
...skipped
libboost_log.so.1.75.0 for lack of
libboost_log.so.1.75.0...
...failed updating 2 targets...
WARNING: exit code 1 from a shell command.
ERROR: ExecutionError('/home/norian/Yocto/build-rpi/tmp/work/cortexa72-poky-linux/boost/1.75.0-r0/temp/run.do_compile.503884', 1, None, None)

Comment: You need to provide more information about the failed compilation, check the log and provide the reason of the failure
Answer: I think it is RAM issue ,check here and here.
I suggest you compile boost alone first:
bitbake boost -c compile

or reduce build threads and number of parallel compile processes:

local.conf

BB_NUMBER_THREADS = "2"
PARALLEL_MAKE = "-j 1"

You can change numbers to what you like (for threads its max is your cpu's cores)
Try adding PARALLEL_MAKE = "-j 1" in local.conf and :
bitbake boost -c compile

Comment: Hi, i used the command `bitbake boost -c compile` and the compilation passed, I also change the number of build threads and number of parrallel compile processes in my local.conf file , thanks for your help !


At which point should a partial translation of the UI of a desktop software become available as an option?

Question: I'm creating an open source software for which the user interface is translated to various languages by contributors (about 30 languages at the moment). The translation platform is online and the nature of benevolent contributions is such that not all languages have a complete translation. Several languages are fully translated but others are at 50% and some at less than 20%.
Personally I find it a bit disappointing/unprofessional to select a language just to find out that only a few parts of the UI are translated and the rest is in English. However I understand that some users might prefer this to nothing.
I've considered only including languages that have a certain threshold of translation, like more than 66% of strings or some other arbitrary number for the main/stable version of the application, and include them all in the more bleeding-edge version of the application.
Is there a best practice or an accepted sweet spot to include a language as an option even though its translation is not complete? Is there a better way to go about this?
Answer: I do prefer partial translation rather than nothing. However, please ensure that your language switcher works. One thing non-English users can tell you is that unless your entire computer is set to English from the OS to the browser to your browser cloud account, sites will magically find and choose your language setting from one of those levels and will not forget them, even when they have a language setting. English users don't notice this because they don't have to fight it, but even giants like Amazon can't get this right. So if you issue a partial translation, please test your language settings on devices set to other languages.
And I do not prefer machine translation for the rest. If something is untranslated, I can usually look it up, whereas machine translation tends to obscure the original meaning and sometimes make it unrecoverable. The most serious issue is that machine translation relies on context, whereas apps (unlike longer documents) tend to use very small snippets. For instance, on one platform I use for work, the word "subject" appears with the meaning "topic". But in the machine translation, it has assujettir ~ "subjugate" (i.e., the verbal meaning subject). This frustrates me and makes me have to reverse-engineer what was meant from the context.
As for what proportion, presumably you are translating by priority first. Rather than specify a %, you can probaly define the core functions that a user would need access to before you can say it's "in their language". For example, if I were releasing an email client in partial translation, I would ensure that the user has enough UI to log in, read and send email, change their password, without perhaps worrying about filter creation and so forth.  Whereas if you decide that most of your functions are core functions, wait for a full translation.
Comment: Thanks. The point about core functions vs global percentage is very good. Another person made the same point when I asked them about this. I don't completely control this as the translations are contributed by volunteers, but I can use it as an inclusion criteria. Furthermore, advanced users using the more technical aspects of the program are more likely to understand the English text.
Answer: Perhaps integrate the build process to use automated translation for parts that were not yet manually translated yet. Automated translation is worse than manual translation, but better than nothing.


Crashing when changing label text

Question: I'm trying to set a label depending on the UserDefault value but It's crashing with the error:

Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value: file

So, first time I run it the app does NOT crash using this code:
MainActivity
    override func viewDidLoad() {
    super.viewDidLoad()

    getAllVehicles()

}

func getAllVehicles(){

    let defaults = UserDefaults.standard

    if defaults.object(forKey: "currentCar") != nil{
        currentCar = defaults.string(forKey: "currentCar")

        registrationPlate.text = currentCar
    }
}

So the application is setting the label to it's UserDefault and that does work, but when I'm trying to change it (Just to mention, it's from another class/viewcontroller)
ChooseCarViewController
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let car = carsArray[indexPath.row]

    let defaults = UserDefaults.standard
    defaults.set(car, forKey: "currentCar")

    if let storyboard = storyboard{
        let vc = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController

        vc.getAllVehicles()

        self.dismiss(animated: true)
    }

}

So by any reason I can NOT change the name when calling the method.
I've also tried to set it directly by using

vc.registrationPlate.text = car

Just to mention:
I've tried to print out "car" and it does return the correct value.
I've also tried to print the "currentCar" in MainActivity after calling the method and It's returning the correct car. But the textfield cannot be changed because of unwrapping an Optional value.
Comment: the text field is nil because it is not loaded yet and is not visible to user.
Comment: @TejaNandamuri So how can that be fixed? Using ViewDidAppear? But how comes it's not loaded since the ViewController is still in the back stack right?
Comment: Instead of calling vc.getAllVehicle() from your ChooseCarViewController, you should call it in viewWillAppear of your MainActivity class. That will do your work.
Comment: @KeshuRai Do you mean viewDidAppear? I tried it by adding "viewDidAppear" in MainViewController and inside that one I'm calling "getAllVehicles". Still no process after I "dismiss" view controller B
Comment: No, I mean viewWillAppear only. try it once
Comment: how are you showing MainViewController?
Answer: All UI stuff that you build with storyboard are optional and they are implicitly unwrapped using !. For example
@IBOutlet weak var registrationPlate: UILabel! // <- Do you see the `!` here?

So as UIViewController default template suggests, you should

Do any additional setup after loading the view.

The first function you can do it in is viewDidLoad:
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

If you initialize a view controller from another one it doesn't grantees that all outlets are automatically have been assigned (yet).
First of all you must use the initializer from the storyboard or from the xib file to have the correct initializer set the outlets.
Then you should wait for viewDidLoad. (You can use vc.loadView() to force it, but it's not recommended at all)

In your code, you are using storyboard.instantiateViewController... that creates another instance and since you are just dismissing the view, it's not needed at all! Because the previous controller is already loaded and it exist in the memory.
And note that you are using reading the registrationPlate inside getAllVehicles and it should be done after view is loaded. So you can extract this part from it and move it somewhere after view gets loaded.
Comment: But on the second view controller I'm using "self.dismiss", will the "viewDidLoad" load again on ViewController 1? once the second view controller is dismissed?
Answer: Do not misuse UserDefaults to share data between controllers, pass the data directly.
The crash occurs because the outlet is not connected yet when the label is accessed.
The solution is to create a temporary variable in MainActivity and assign the value to the label in viewDidLoad
var currentCar = ""

override func viewDidLoad() {
    super.viewDidLoad()
    registrationPlate.text = currentCar
}

Assign the car to the temporary variable in ChooseCarViewController and you have to present the vc
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
    let car = carsArray[indexPath.row]
    UserDefaults.standard.set(car, forKey: "currentCar")

    if let vc = storyboard?.instantiateViewController(withIdentifier: "MainViewController") as? MainViewController {
        vc.currentCar = car
        present(vc, animated: true, completion: nil)
        self.dismiss(animated: true)
    }
}

Answer: You want to use the protocol / delegate pattern.
Define a protocol:
protocol ChangeCarDelegate: AnyObject {
    func changeCar(_ newCar: String)
}

Have your Main view controller "conform" to that protocol:
class MainViewController: UIViewController, ChangeCarDelegate {

    func changeCar(_ newCar: String) {
        currentCar = newCar
        registrationPlate.text = currentCar
    }

}

When you present the Choose Car VC, assign its ChangeCarDelegate property:
@IBAction func showChooseCar(_ sender: Any) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "ChooseCarVC") as? ChooseCarViewController {
        vc.changeCarDelegate = self
        present(vc, animated: true, completion: nil)
    }
}

Or, if you are using a Storyboard created Segue to present the Choose Car VC:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let vc = segue.destination as? ChooseCarViewController {
        vc.changeCarDelegate = self
    }
}

When you select a car from the table, tell the delegate of the new selection:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let car = carsArray[indexPath.row]
    let defaults = UserDefaults.standard
    defaults.set(car, forKey: "currentCar")

    // communicate with the delegate
    changeCarDelegate?.changeCar(car)

    dismiss(animated: true, completion: nil)
}

Here is a full set of classes for a simple "Main" VC with a label and a button. Tapping the button presents "ChooseCar" VC, which has a table of cars.
protocol ChangeCarDelegate {
    func changeCar(_ newCar: String)
}

class MainViewController: UIViewController, ChangeCarDelegate {

    @IBOutlet var registrationPlate: UILabel!

    var currentCar: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        getAllVehicles()
    }

    func getAllVehicles(){
        let defaults = UserDefaults.standard
        if defaults.object(forKey: "currentCar") != nil{
            currentCar = defaults.string(forKey: "currentCar") ?? ""
            registrationPlate.text = currentCar
        }
    }

    @IBAction func showChooseCar(_ sender: Any) {
        if let vc = storyboard?.instantiateViewController(withIdentifier: "ChooseCarVC") as? ChooseCarViewController {
            vc.changeCarDelegate = self
            present(vc, animated: true, completion: nil)
        }
    }

    // or, if you are using a Storyboard created Segue to present the Choose Car VC
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let vc = segue.destination as? ChooseCarViewController {
            vc.changeCarDelegate = self
        }
    }

    func changeCar(_ newCar: String) {
        currentCar = newCar
        registrationPlate.text = currentCar
    }

}

class ChooseCarViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    weak var changeCarDelegate: ChangeCarDelegate?

    @IBOutlet var tableView: UITableView!

    var carsArray: [String] = [
        "Ford",
        "Honda",
        "Toyota",
        "Chrysler",
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return carsArray.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CarCell", for: indexPath)
        cell.textLabel?.text = carsArray[indexPath.row]
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let car = carsArray[indexPath.row]
        let defaults = UserDefaults.standard
        defaults.set(car, forKey: "currentCar")
        changeCarDelegate?.changeCar(car)
        dismiss(animated: true, completion: nil)
    }

}

Answer: As you have mentioned this in your comments!!
@TejaNandamuri So how can that be fixed? Using ViewDidAppear?
But how comes it's not loaded since the ViewController is still in the back stack right?

In this code, vc is not pointing to the same view controller which is behind in the stack. It is creating a new view controller. In new vc, textfield is not yet loaded.
if let storyboard = storyboard{
    let vc = storyboard.instantiateViewController(withIdentifier: "MainViewController") as! MainViewController

    vc.getAllVehicles()

    self.dismiss(animated: true)
}

Use delegates to achieve what you want.
Answer: You are trying to assigning a nullable value to label, handle null using guard let or if let
like below
    guard let currentCar = defaults.string(forKey: "currentCar") else{
     registrationPlate.text = ""
     return
    }

    registrationPlate.text = currentCar ?? ""

Comment: Well, in this case the this might always return "", otherwise it would not crash right?
Comment: yes, if you want to not return use if let with else to give a default value to label\

Crashing when changing label text


booting to frozen virtual console after `prime-select intel`

Question: I've got a Dell inspiron 15 7559 laptop with a nVidia GM107M [GeForce GTX 960M] graphical card. After getting it to boot correctly and installing the nvidia drivers using the additional drivers tab (nvidia-352) I was able to boot perfectly normal.
When I switched to the intel card using prime-select intel and logged out I couldn't log back in. I was able to use a virtual console to revert back to nvidia and log back in. So I thought perhaps it needs a reboot for the changes. After the reboot I booted into a frozen virtual console. I had to go to recovery mode and execute prime-select nvidia in a console to be able to boot normally again.
My guess is that something with the intel drivers is broken and crashes xorg.
I've also tried bumblebee with the same results. It booted into a frozen VC and only worked after everything was run using Nvidia again.
Anyone got any suggestions??
edit: I think gpu-manager is writing using the nvidia driver. I am currently trying to find a way to get gpu-manager to work correctly.
Answer: Generally you should use the drivers from the official Ubuntu repositories. But when there are problems with the drivers ... you can install the more current drivers from the GPU Drivers PPA.
Uninstall the currently installed NVIDIA drivers and bumblebee - remove the xorg-edgers PPA.
Highlight the Ubuntu menu entry and  press the E key.
Add nouveau.modeset=0 to the end of the linux line.
Press the F10 key to boot into the Ubuntu system.
When the login screen appears press Ctrl+Alt+F1.
Enter your user name and the password, then execute :
Open a terminal and execute :
sudo apt-get purge nvidia* bumblebee
sudo apt-get install ppa-purge
sudo ppa-purge ppa:xorg-edgers/ppa
sudo reboot

Now install the latest official NVIDIA drivers 361 that support the NVIDIA GEFORCE GTX 960M.
Highlight the Ubuntu menu entry and  press the E key.
Add nouveau.modeset=0 to the end of the linux line.
Press the F10 key to boot into the Ubuntu system.
When the login screen appears press Ctrl+Alt+F1.
Enter your user name and the password, then execute :
Open a terminal and execute :
Open a terminal and execute :
sudo add-apt-repository ppa:graphics-drivers/ppa
sudo apt-get update
sudo apt-get install nvidia-361 nvidia-prime
sudo reboot


smart cast option for a specific champion?

Question: I usually tend to put smartcast on my w key for escapes on my champions which are corki,tristana and zed.But lately ive been trying out new champions,one of which is kayle and it feels uncromfortable and wierd in my opinion when i try to heal myself or an ally with my w on smartcast.
Is there an option i can use on the lol client to allow me to put smartcast key on any individual champion or does smartcast have to affect all the champions i use?
Answer: You can use a third-party program to achieve this. Enigma's Smartcast Manager is notable for allowing you to have a separate smartcast configuration for each champion. (Riot has no issue with you using programs like this.)
Comment: k,thnxxxxxxxx :)


Why Catalina 10.15.7 block JarLauncher when start from .app?

Question: I have My.app correctly working on(starts from two click):
High Sierra 10.13.6
Catalina 10.15.2
but refuse to start on Catalina 10.15.7, it starts than immediately quit.
My.app - it is java application(spring-boot, javaFX) which starts from bash script.
My.app structure
myJavaFX.jar running properly if I starts from terminal(java -jar myJavaFX.jar), on Catalina 10.15.7.
Do you have any ideas what can block JarLauncher when start from .app? Or else?
Answer: Actually the problem wasn't in versions of MacOS. The problem was in multiple simultaneous starting from one folder, probably due to security issues.


Is there any way to getElementBy the text content?

Question: I've got a problem I've been stuck with for a while, sorry for spamming the forum a little.
Is there any way I can get an element by it's text content? Here's an example:
Item | Anodized Navy

I'm trying to get the element by the text content which is 'Item | Anodized Navy'.
Is it possible to do something like:
function getelem {
    var item = document.getElementsByTextContent('Item | Anodized Navy');

    item[0].click();
}

I know this doesn't exist, but it's just so you get the idea. Also, I cannot use by Id or classname, and I can't change the HTML code of the element, so it has to be done with the text content, I don't see another way.
I'd greatly appreciate any feedback,
Thanks!
Comment: You need to get the content of the text nodes and compare them against you required string. Then you can choose the parent node that you want.
Comment: I've found this. https://gist.github.com/leodutra/692890a66d8d80829e743a181136d58c
Answer: Even though jQuery exposes the :contains pseudo selector, it would be wise to restrict the results first by using the class where possible:
$('.market_listing_item_name:contains("Item | Anodized Navy")')

Narrowing down the initial set of tags to search through improves the performance, otherwise all tags would be considered; also, overlapping tags would match as well.
On more modern browsers you could consider this, based on this answer:
function contains(selector, text) {
    var elements = document.querySelectorAll(selector);
    return [].filter.call(elements, function(element) {
        var contents = element.textContent || element.innerText || '';
        return contents.indexOf(text) != -1;
    });
}

var items = contains('.market_listing_item_name', 'Item | Anodized Navy')

items[0] && items[0].click();

Answer: Well, since you tagged the question with jquery, you could use the :contains selector:
var item = $(':contains(Item | Anodized Navy)');

Note, however, that this will return every element which contains that text, including the span and all the parent elements of the span. If you'd like to get just the inner-most element (assuming there is only one) just get the last item, like this:
var item = $(':contains(Item | Anodized Navy)').last();

To do the equivalent without using jQuery, you'd have to implement a function like this:
function getElementsByText(text) {
    var spans = document.getElementsByTagName('span'),
        results = [];
    for(var i = 0; i < spans.length; i++) {
        var content = spans[i].textContent || spans[i].innerText || '';
        if (content.indexOf(text) != -1)
            results.push(spans[i]);
    }
    return results;
}

Or possibly like this, depending on exactly what you need:
function getElementsByText(text) {
    function rec(ele, arr)
    {
        if (ele.childNodes.length > 0)
            for (var i = 0; i < ele.childNodes.length; i++)
                rec(ele.childNodes[i], arr);
        else if (ele.nodeType == Node.TEXT_NODE &&
                 ele.nodeValue.indexOf(text) != -1)
            arr.push(ele.parentNode);
        return arr;
    }
    return rec(document.body, []);
}

And then call this function like this:
var item = getElementsByText('Item | Anodized Navy');

Note also in your code, getelem needs to have () after the function name, like this:
function getelem() {
    var item = getElementsByText('Item | Anodized Navy');
    ...
}

Comment: @user3302404: *doesn't work === most complete*? ...Anyway, if you're testing in Firefox, it won't work because FF doesn't support `.innerText`. Depending on the browsers you're supporting, either use `spans[i].textContent.indexOf(...` or `(spans[i].textContent || spans[i].innerText).indexOf(...`
Comment: @cookiemonster Ahh thanks. I had forgotten about that. Updated to be more cross-browser compliant.
Comment: Now, if the span's `.textContent` is an empty string, it will use `.innerText` which may be `undefined` :) you need `.textContent || .innerText || ''` in case that happens.
Comment: Thanks alot for this, best comment thus far! Do you know any way to do this without jQuery though? because I thought tampermonkey supported jQuery but it looks like it doesn't so I'm stuck with only javascript now it looks like it, unless I could import a jQuery library or something?
Comment: Thanks so much for your effort, i appreciate it so much! I have a final question before putting you best answer ^^: do I replace the (text) with Item | Anodized Navy? I mean I'm a total noob, so it's not clear to me where to refer to the item in the code :)
Also, what do i refer to to click on it? Do I use spans[0].click? Thanks so much again <3
Comment: Well it doesn't seem to work out for me but you are by far the most complete answer so thank you for this, I'll try fixing it and probably ask more questions around here :)
Comment: @user3302404 Yeah `.click` is a function in jQuery. Your next step would probably be to see if you can find a way to emulate that function in plain JS. But that's a topic for another question. Glad I could help.
Answer: You want something like this
HTML
Item | Anodized Blue
Item | Anodized Navy
Item | Anodized Red
Item | Anodized Green
Item | Anodized Navy

Javascript
function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function getElementsByText(node, text) {
    var results = [];

    walkTheDOM(node, function (currentNode) {
        if (currentNode.nodeType === 3 && currentNode.nodeValue === text) {
            results.push(currentNode.parentNode);
        }
    });

    return results;
}

console.log(getElementsByText(document, 'Item | Anodized Navy'));

Output
[span#result_6_name.market_listing_item_name, span#result_9_name.market_listing_item_name]

On jsFiddle
Additional 1, as we talked about treeWalker
function getElementsByText(node, text) {
    var results = [],
        treeWalker = document.createTreeWalker(
        node,
        NodeFilter.SHOW_TEXT, {
            acceptNode: function (node) {
                return NodeFilter.FILTER_ACCEPT;
            }
        }, false);

    while (treeWalker.nextNode()) {
        if (treeWalker.currentNode.nodeValue === text) {
            results.push(treeWalker.currentNode.parentNode);
        }
    }

    return results;
}

console.log(getElementsByText(document, 'Item | Anodized Navy'));

On jsFiddle
Additional 2, as we talked about getElementsByTagName('*')
function getElementsByText(node, text) {
    var results = [],
        tags = node.getElementsByTagName('*'),
        tagsLength = tags.length,
        tagsIndex,
        currentTag,
        childNodes,
        childNodesLength,
        ChildNodesIndex,
        currentChildNode;

    for (tagsIndex = 0; tagsIndex < tagsLength; tagsIndex += 1) {
        currentTag = tags[tagsIndex];
        childNodes = currentTag.childNodes;
        childNodesLength = childNodes.length;
        for (ChildNodesIndex = 0; ChildNodesIndex < childNodesLength; ChildNodesIndex += 1) {
            currentChildNode = childNodes[ChildNodesIndex];
            if (currentChildNode.nodeType === 3 && currentChildNode.nodeValue === text) {
                results.push(currentTag);
            }
        }
    }

    return results;
}

console.log(getElementsByText(document, 'Item | Anodized Navy'));

On jsFiddle
Note that these solutions are the same but they are different to all the contains solutions given here. Because these solutions actually give you the nodes that have a matching text node as a child. The simple markup that I have used does not demonstrate this, but you will soon notice the difference when your markup is highly nested.
And finally here is a jsPerf of these 3 solutions.
Comment: For this purpose, `document.getElementsByTagName('*')` would make the code a whole lot simpler.
Comment: Yes, I used very simple (not nested) markup for this demonstration. I would be quite happy for you to demonstrate though? I could have used `treeWalker` but this code is cross browser.
Comment: Using `getElementsByTagName('*')` is cross browser too :)
Comment: I was not suggesting that it wasn't. :)
Comment: I didn't say that you did :) my point was that rolling your own traversal code is rarely necessary.
Comment: Noone else has demonstrated a `getElementsByTagName('*')` solution, go on, take the challenge! :P
Comment: I've already written my own answer, but using the more modern `document.querySelector()` :)
Comment: Indeed, though our solutions do not perform exactly the same tasks. I see p.s.w.g has now also added a variation of the DOM walker to his answer. Perhaps he will go a step further and add a `treeWalker` and a `getElementsByTagName('*')` solution too? :)
Comment: @Jack Has that simplified things? :)
Comment: Not sure why you're iterating over the child nodes if you can just use textContent (and friends) to find the text value.
Comment: Consider this [jsFiddle](http://jsfiddle.net/Xotic750/NrDED/), see the difference? I have given an alternative, it depends on how you interpret `Is there any way to getElementBy the text content?` Is that not also the reason why p.s.w.g added his DOM walker, because it depends on interpretation?
Answer: Maybe I'm late in answering this, but I didn't see the question tagged with JQuery, so here's a pure JavaScript solution:
var myID = getElementsByTextContent('Item | Anodized Navy');

function getElementsByTextContent (elText){
    var spanID;
    var allSpans = document.getElementsByTagName("span");
    for (var i = 0; i < allSpans.length; i++) {
        var spanText = allSpans[i].innerHTML;
        if(spanText == elText ){
            spanID = allSpans[i].id;
        }
    }
    return spanID;
}

Comment: The OP edited the question at a later point to remove the jquery tag :)
Answer: You can simply use Jquery's :contains()
If you want to select all spans containing the text "mytext", use
var elements=$('span:contains("mytext"));

Please mark as answer if I helped you.
Thank you :)
Answer: For my use-case, I wrote some simple version. :not(has(*)) is useful for preventing getting parents.
function getElementsByText(root, text, selector = 'div:not(:has(*))') {
  const els = [...root.querySelectorAll(selector)];
  return els.filter(el => el.innerText == text);
}


Guaranteed ordering of messages across a Kafka cluster

Question: I have read dozens of articles about Kafka message ordering and still don't see an out-of-the-box solution to my very common need - publishing messages with a sequentially-incrementing ID and consuming them in that same order.
Kafka preserves message order within a partition.  But what enterprise-grade solution would ever use a single partition for critical data (single point of data loss failure, reduced throughput without parallelism, etc.)?  So the challenge is how to consume messages in order across a multi-partitioned topic.
Doing blockchain analytics, we harvest sequentially-incrementing blocks of data from blockchain nodes and then publish them to our Kafka topic.  Key = block number, Value = block data.  Block numbers start at 0 and increment by 1 for eternity.
Our analytics code needs to consume those messages IN ORDER (block 1, block 2, block 3, etc.).  If a Smart contract get created on a blockchain in block 2 and then a transaction on it occurs in block 3, our analytics code would fail if we processed block 3 before block 2 ("no contract found error", for example).
Some more info about our use case.

The topic with block data will never be purged.  This will grow to several TB and will have millions of messages on it.  Though most consumers won't use this directly, it still servers as our off-chain copy of a blockchain and may fulfill future needs within our software.

We have a SQL database table which stores the stateful information about how much of a blockchain we've analyzed (example, highest block # is 25,555,555).

For guaranteed ordering, most articles recommend Kafka Streams and KTables.  If we use in-memory KTables, then we face major challenges (can't store TB of data in-memory, rebuilding the KTable at startup would take days, etc.)
If we use persisted KTables, then we're bloating our disk usage (several TB of data duplicated across the source topic and the KTable).
We can create a secondary "operational" single-partition topic [with a relatively short data retention time] and stream the data to that in order, and then have our consumers pull data from that topic.  But this is exactly the opposite of out-of-the-box and we'd like to avoid doing this for the hundreds of blockchains and messaging needs we have.  It'll become and administrative debacle.
This seems like a technical need that thousands of companies have had since the creation of Kafka (like what messaging queues have done for decades).  Is there no out-of-the-box solution for a KafkaListener to receive messages in order based on a numeric Key [in a multi-partition topic]?
Comment: That is not how the key is intended to be used; generally people use the key to ensure strict ordering for that key only; records with different keys can go to different partitions, but all records with the same key go, in order, to a single partition.
Comment: No; a Kafka topic is not a "queue"; it is a set of parallel immutable logs; there is no way (that I am aware of) to achieve your use case with Kafka, aside from using a single partition. Even if you have a only single consumer consuming from multiple partitions, there is no way to get strict ordering across partitions.
Comment: Your concern about single point of failure is trivially handled by just having replicas. As for throughput issues, even setting aside kafka, aren't you facing the same bottleneck at the consumer end? You can't use multiple consumers because messages need to be processed one by one. So really you're going to have the same throughput issues there.

I would personally rethink the requirement of a global order.
Comment: @GaryRussell  Good point.  Is there a different mechanism in Kafka that may suit our needs better?  Can we add this "key" somewhere else?  I previously built a JMS-based solution and put incrementally-incrementing message IDs into a message header.  But I don't think this would work in Kafka
Comment: I suppose I may need to stick to a single partition, but with robust replication design then.  Is that a best practice with Kafka?  My 2 main goals are 1) process messages in order and 2) never lose a message.
Answer:
publishing messages with a sequentially-incrementing ID and consuming them in that same order

A single partition is the only way to accomplish this when using Kafka.
One alternative design, from a blockchain perspective, would be to key by wallet address, for example, then you have ordered events per wallet. But then if you have transactions between wallets, there is no guarantee the "other wallet" from that withdraw/deposit event-value will exist, so you will need some other state-store (e.g. KTable) for all known wallet addresses before fully processing such events.

The topic with block data will never be purged. This will grow to several TB

Partition segments are not distributed. If you had one partition, that means you're limited to the size of one HDD.
Similarly, RocksDB or in-memory state-stores will have the same problem. But, the interface for those are pluggable and can be replaced, with some tradeoffs for processing ordering guarantees.


Narro API:: message: 'Unauthorized'

Question: I was trying to work with Narro API and MEAN stack. I have some text articles. I want to convert my text data to audio. From the requirements, it should use Narro.co for audio conversion. From their documentation, I started with authentication.
Here is the code,
<code>var request = require("request");

var options = {
    method: 'GET',
    url: 'https://www.narro.co/api/v1',
    headers: {
        authorization: 'Bearer <access_token>'
    }
};

request(options, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(body);
});
</code>
We can generate the clientId and clientSecret from the Narro developer account.

The ClientId(sample) :
  921edefq-540y-4g75-be2c-2ade450dc503
The clientSecret(sample):
  a904efd2-a362-4cc5-80qe-262b24728b47743e244e-e39c-44e7-a479-3f0bt3445245

But it is not working.
I always end up with -
<code>{ errors: [ { message: 'Unauthorized' } ] }
</code>
If it is not the right method, Please suggest me the best way to use Narro API with authentication.
Comment: A client secret is not an access token. You'll need to request one from the Narro API using your client secret. [Narro API Documentation - Authentication](https://docs.narro.co/#authentication)
Answer: You need to follow proper OAuth 2.0 flows.It would seem you want to use the Client Credential flow for your purposes, if you're not doing actions on behalf of a user.
I hope the ClientID and Secret there aren't actually yours.
Their own documentation page links to https://oauth.net/2/ which is where you can learn about the different flows, how to request a Bearer token, and how to then use that token to access the API endpoints. (Basically, read the docs...)

Narro API:: message: 'Unauthorized'


PHP wrapping a section in square brackets

Question: $arr = json_encode(
    array(
      'result'=>true,
      'user'=> array('id'=>null, 'email'=>null, 'auth'=>false)

      )
   );

I have the above PHP and i am trying to wrap the user portion in square brackets.
Comment: `array( 'user' => ... )` maybe ?
Answer: warp with one more array() of user portion
$arr = json_encode(
        array(
          'result'=>true,
          'user'=>array(
                      array('id'=>null, 'email'=>null, 'auth'=>false)
                     )
          )
       );


Text/Log Viewer that that will allow filtering by words/phrases?

Question: I'm looking for a GUI-based text/log viewer that will allow to only display lines that contain particular phrases/words/characters. The logs may not necessarily by OS related but from 3rd party applications.
Comment: Lots of good suggestions for you to try in this thread: http://askubuntu.com/questions/20173/gui-for-watching-logs-tail-and-grep
Answer: One suggestion is "glogg", it's available as an Ubuntu package and doesn't have nasty dependencies (Qt4-based).
Another one is ksystemlog, not sure if it does filtering as you require.
Finally I have to ask, why does it have to be GUI? Personally I'd use the old:
<code>tail -f $LOGFILE |grep particular-phrase
</code>
there's also swatch which is possibly nicer, though I have never used it.


How to pass a nullable variable as a composable?

Question: I want to make a TopAppBar switching its content while navigating. The goal is to use a flag and change the navigationIcon. But I can't pass the Composable/null as a parameter here. The code:
val navIcon = if (viewModel.isBackAvailable) NavIcon { navController.navigateUp() } else null

TopAppBar(navigationIcon = navIcon)// Required:(() → Unit)? Found:Unit?

@Composable
private fun NavIcon(navigate: () -> Unit) {
    IconButton(onClick = navigate) {
        Icon(
            imageVector = Icons.Rounded.ArrowBack,
            contentDescription = stringResource(R.string.navigate_back),
            tint = MaterialTheme.colorScheme.primary
        )
    }
}

I can't pass something like an empty value navigationIcon = {} because it takes its space in this case, I need to use null.
Answer: In your code, navIcon is a result of NavIcon function call, which is unit. You need to have function reference there, you can do that like this:
val navIcon: (@Composable () -> Unit)? = if (viewModel.isBackAvailable) {
    { NavIcon { navController.navigateUp() } }
} else null

Comment: Nice. Thought, Kotlin is smart enough to understand the type properly
Comment: Is it working for you without specifying the type explicitly? It can understand it's a function, but it doesn't allow calling `@Composable` functions from inside if I don't specify the type...
Comment: No, need to specify the type here `navIcon: (@Composable () -> Unit)?`


Pass a data.frame column name to a function that uses purrr::map

Question: I'm working with nested dataframes and want to pass the name of the top level dataframe, and the name of a column containing lower level dataframes, to a function that uses purrr::map to iterate over the lower level data frames.
Here's a toy example.
library(dplyr)
library(purrr)
library(tibble)
library(tidyr)

df1 <- tibble(x = c("a","b","c", "a","b","c"), y = 1:6)
df1 <- df1 %>%
  group_by(x) %>%
  nest()

testfunc1 <- function(df) {
  df <- df %>%
    mutate(out = map(data, min))
  tibble(min1 = df$out)
}

testfunc2 <- function(df, col_name) {
  df <- df %>%
    mutate(out = map(col_name, min))
  tibble(min2 = df$out)
}

df1 <- bind_cols(df1, testfunc1(df1))
df1 <- bind_cols(df1, testfunc2(df1, "data"))

df1$min1
df1$min2

testfunc1 behaves as expected, in this case giving the minimum of each data column in a new column. In testfunc2, where I've tried to pass the column name, a string reading "data" is passed to the new column. I think I understand from the thread here (Pass a data.frame column name to a function) why this doesn't behave as I want, but I haven't been able to figure out how to make it work in this case. Any suggestions would be great.
Answer: This should work for you, it uses the tidy eval framework.  This assumes col_name is a string.
testfunc2 <- function(df, col_name) {
     df <- df %>%
          mutate(out = map(!! rlang::sym(col_name), min))
    tibble(min2 = df$out)

}

EDIT:
If you'd rather pass a bare column name to the function, instead of a string, use enquo instead of sym.
testfunc2 <- function(df, col_name) {
     col_quo = enquo(col_name)
     df <- df %>%
          mutate(out = map(!! col_quo, min))
     tibble(min2 = df$out)

}

Comment: This would be nice if `col_name` didn't have to be a string so it could be lazily evaluated. Any idea how that would work?
Comment: @slhck I've updated my answer to include an example of the function if you wanted to pass it a bare column name as opposed to a string.


Replacing special characters that are within quotes inside files

Question: I didn't find an applicable answer for this question when seraching Google, Stackoverflow or any other source, so I decided to ask my own here.
In GNU Bash (Ubuntu), I'm trying to ONLY replace special characters that are between quotes in a file called test.txt, which has the following contents
foo_bar "foo_bar"

so that the resulting contents would be
foo_bar "foo bar"

Currently I haven't had any luck, I've tried several solutions such as
touch test2.txt
grep -o '".*"' test.txt | sed s/"_"/" "/g > test2.txt
rm test.txt
rename s/"test2"/"test"/ test2.txt

which would otherwise be fine, but that command causes the file content to only be "foo bar", not the whole file. I'm looking for a way to directly replace quoted special characters inside files, both sed and awk will do.
Answer: Using awk:
awk 'BEGIN{FS=OFS="\""} {for (i=2; i<=NF; i+=2) gsub(/_/, " ", $i)} 1' file
foo_bar "foo bar"

Comment: Not sure if escaped quotes are OP's requirements. If yes then answer needs to be modified accordingly.
Comment: What will happen if the following occurs: `foo bar "bar\"baz"`?
Comment: Thanks for all the answers. I was able to put them to good use.
Answer: With sed:
sed -ri 's/("[^_]*)_([^_]*")/\1 \2/g' test

-r enables extended regular expressions so you don't have to escape ()
-i replaces input file with result in-place
("[^_]*) matches " followed by anything but _ (repeated zero or more times) and captures the match
([^_]*") matches anything but _ (repeated zero or more times) followed by " and captures the match
\1 and \2 are backreferences to the captured groups
g is the "global" modifier: the substitution is repeated as often as possible on the same line

This only works with well-formed expressions (even number of quotes) and doesn't deal with escaped quotes.


multi module gradle project - grouping sub-projects under a parent

Question: I have been trying to create a multimodule gradle project, I have referred to these link apart from a few others

https://docs.gradle.org/current/userguide/multi_project_builds.html
https://docs.gradle.org/current/userguide/intro_multi_project_builds.html

I was able to create multiple modules and execute multiple commands for all modules and for specific modules using root level gradle wrapper, something like
./gradlew :java-libs:payment-lib:build works.
I am also publishing these libraries to a nexus repository that acts as an internal maven repository.
This is what my root build.gradle looks like:
apply plugin: 'base'

subprojects {
    apply plugin: 'java'
    apply plugin: 'maven-publish'

    publishing {
        publications {
            maven(MavenPublication) {
                artifact("build/libs/$project.name-$version" + ".jar") {
                    extension 'jar'
                }
            }
            mavenJava(MavenPublication) {
                from components.java
            }
        }

        repositories {
            maven {
                name 'nexus'
                url "<nexus_url>/repository/maven-snapshots/"
                credentials {
                    username nexusUsername
                    password nexusPassword
                }
            }
        }
    }
}

This enables me to publish any or all modules to nexus from the root gradlew, and I don't have to write the publications section in each module again and again.
What I want to achieve
As of now each module is treated as a separate project in nexus, with its own versioning, its own folder, and when 2 of these modules need to be imported in a different project, I need to include 2 statements that are unrelated to each other.
compile("com.something.payment-lib:0.3-SNAPSHOT")
compile("com.something.refund-lib:0.2-SNAPSHOT")

I have been using some external libraries where I was able to do something like this:
compile("org.apache.httpcomponents:httpclient:4.5.12"){
    exclude(module: 'commons-logging')
}

Which suggests that all modules within the multi-module gradle project are under a single group org.apache.httpcomponents:httpclient, which also has a version of its own. And I can include/exclude specific modules within that group.
I tried looking at its code, but it is using maven and the config looks quite different.
I also don't know even if I am able to achieve such a grouping, what will the folder structure look like inside the nexus repository. Would there be a folder for the project and then there would be sub-folders with the jars of the respective modules?
Answer: I think what you're missing is declared dependencies to subprojects in the root build.gradle. Take a look here https://docs.gradle.org/current/userguide/declaring_dependencies_between_subprojects.html#declaring_dependencies_between_subprojects
Adding
dependencies {
    api(project(":payment-lib"))
    api(project(":refund-lib"))
}

to the root build.gradle.
Should give you access to both modules, by just declaring the dependency to the root project.
Comment: same error when i use java-library plugin
Comment: this doesn't work. though i couldn't find any resources for this method of implementation, I tried using

```
dependencies {
    api(project(":payment-lib"))
    api(project(":refund-lib"))
}
```

replaced api with compile and implementation as well, but i got the same error
`could not find method api() for arguments [project ':payment-lib'] on object of type org.gradle.api.artifacts.dsl.DefaultDependencyHandler `
Comment: i also added the 'group' and 'version' clauses to the root build.gradle because i eventually want to version the whole project as well
Comment: You will need to declare the java-library plugin to be able to use `api`. https://docs.gradle.org/current/userguide/java_library_plugin.html. However, if I'm correct `compile` should work without the error. What version of Gradle are you using?
Comment: gradle version 6.8.3


How does one install a minimal gnome-shell?

Question: I've just installed xubuntu and removed everything I don't need. Now I'd like to install gnome -shell but not any of the other gnome packages. Ideally, I'll have only xfce related programs with the addition gnome-shell (and everything needed to have a fully functional gnome-shell panel / system tray).
What is the proper way to accomplish this? I'd like to keep the number of installed packages to a minimum.
Comment: You can use `sudo apt-get install gnome-shell` to install only  gnome-shell and some additional packages needed for it.
Answer: I often use this parameter of apt for such things:
   --no-install-recommends
       Do not consider recommended packages as a dependency for installing.
       Configuration Item: APT::Install-Recommends.

Use it as follows:
sudo apt-get --no-install-recommends install gnome-shell

Comment: Worked like a charm.


How to install iOS 9.x Simulator on Xcode 11?

Question: I'm developing and iOS app with iOS 9 support, but with Xcode 11 update I'm missing the possibility to add / install iOS 9 simulator.
Is there any chance to have iOS 9.x simulator in Xcode 11?
Comment: It is not working now....@JamesP After following every step it does load the simulator but with the minimum iOS version supported by Xcode 11.3 (iOS version - 10.3.1)
Comment: I have Mojave (10.14.6), but the 9.x simulators are not present :(
Comment: Same here, with 10.14.6 I lost 9.x simulators and none of the solutions provided here work.
Comment: Which macOS version you have? I seem to have lost iOS 9 simulator after upgrade to 10.15 Catalina.
Answer: It seems iOS 9 simulator is supported by Xcode 11, but only on macOS 10.14 Mojave. After upgrade to macOS 10.15 Catalina, this simulator is not supported any more.
Though I didn't find confirmation of this in any release notes. The only acknowledgment I found is this tweet by Apple engineer: https://twitter.com/xenadu02/status/1140093901438689280?lang=en
Comment: @Levi If you have Mojave, try to download iOS 9 simulator file with any download manager software and then install the simulator

9.3: https://devimages-cdn.apple.com/downloads/xcode/simulators/com.apple.pkg.iPhoneSimulatorSDK9_3-22.214.171.1240411551.dmg

9.0: https://devimages-cdn.apple.com/downloads/xcode/simulators/com.apple.pkg.iPhoneSimulatorSDK9_0-188.8.131.523554484.dmg
Comment: I have Mojave (10.14.6) but the 9.x simulators are not present
Comment: Thanks. I was looking for these exact links to the simulator dmg files. Guys, you can use iGetter fast downloader: https://www.igetter.net/downloads.html. And to install the downloaded files visit this article: https://hackernoon.com/manually-install-ios-simulators-in-xcode-f7e4bbe50753
Comment: Hasaan, that article is helpful, but after following the steps, my XCode 11.3.1 on Mojave 10.14.5 still doesn't show any iOS simulator version before 10.3.1.
Comment: Apple makes trouble for developer.
Answer: I tried installing Xcode 10.1 on my Mac, but it also did not work for iOS9, i suspect it has to do with Apple dropping support for 32 bit applications (like iOS9)
Answer: iOS 9.3 (9.3 - 13E233) - com.apple.CoreSimulator.SimRuntime.iOS-9-3 (unavailable, The iOS 9.3 simulator runtime is not supported on hosts after macOS 10.14.99.) (unavailable, The iOS 9.3 simulator runtime is not supported on hosts after macOS 10.14.99.)
Comment: looks like a warn or error can you also explain your answer to make it more acceptable
Answer: I've got macOS Catalina 10.15.5 currently installed and the only solution I found to test my app on iOS 9 simulator it's described in the following steps:

create a virtual machine with macOS Mojave 10.14.4 (following steps are done into the virtual machine)
install Xcode 10.2.1
Download and install the simulators you need from Preferences/Components
install Xcode 11

Now you should be able to test your app on iOS 9... kind of
Answer: iOS 9.0 is not supported by Xcode 11.
Answer: Jayaraj M, it's not a true:

Xcode 11 is available in the Mac App Store and includes SDKs for iOS
  13, macOS Catalina 10.15, watchOS 6, and tvOS 13. Xcode 11 supports
  development for devices running iOS 13.1. Xcode 11 supports on-device
  debugging for iOS 8 and later, tvOS 9 and later, and watchOS 2 and
  later. Xcode 11 requires a Mac running macOS Mojave 10.14.4 or later.

https://developer.apple.com/documentation/xcode_release_notes/xcode_11_release_notes
Comment: The important thing to note in Apple's note above is "on-device debugging". If you have a device with the older iOS, you can still debug it. But the simulators for iOS9  are gone. Tried to see if I could build an iOS 9 simulator (was successful building iOS 11 simulator that I needed). But following fails: xcrun simctl create "iPhone 5" "com.apple.CoreSimulator.SimDeviceType.iPhone-5" "com.apple.CoreSimulator.SimRuntime.iOS-9-0"


ionic 2:Supplied parameters do not match any signature of call target

Question: I'm getting an error when I try to build my app with

ionic run android

this is the error
[14:38:19]  lint finished in 1.88 s
[14:38:33]  Error: Error at
            C:/Users/adirz/myapps/studentAssistantApp/.tmp/pages/courses-page/courses-page.ngfactory.ts:943:29
[14:38:33]  Supplied parameters do not match any signature of call target.

I added the course-page.ts component
 import { Component } from '@angular/core';
import {NavController, LoadingController,AlertController,NavParams} from 'ionic-angular';

//import providers
import {CoursesData} from "../../providers/Courses-data";
import firebase from 'firebase';

/*
  Generated class for the CoursesPage page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-courses-page',
  templateUrl: 'courses-page.html'
})
export class CoursesPage {
  public pet: string = 'SemA';
  public coursesA: Array<any> = [];
  public coursesB: Array<any> = [];
  public department:any;
  public gaming: string = 'all';
  public courseNames: Array<any> = [];
  constructor(public navCtrl: NavController,private navParams:NavParams,private loadingCtrl: LoadingController,public coursesData:CoursesData,public alertCtrl: AlertController)
  {
    console.log("adir");
      this.department=this.navParams.get('department');
      console.log(this.department.id);

  }

  ionViewDidLoad() {
   let loader = this.loadingCtrl.create({});

    this.coursesA=this.coursesData.getCoursesList(this.department.id);
    if(this.coursesA){
      console.log("hello world");
      console.log(this.coursesA);
       loader.dismiss();

    }
     //this.coursesData.getCourse(this.department.id)ף

    /*this.getCoursesList().then((x: Array<any>) => {

      if (x) {
        this.coursesA = x;
        this.courseNames = x;
        loader.dismiss();
      }

    });
    */

  }

I added also the course-data provider
    import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import firebase from 'firebase'

/*
  Generated class for the CoursesData provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class CoursesData {
  //firebase datab
 public fireRef:any;
 public coursesList:any;
  public coursesA: Array<any> = [];

  constructor() {
   this.fireRef=firebase.database().ref();
   this.coursesList=firebase.database().ref('Courses/');
  }

  public getCourse(departmentId:any):any{
      var semesterRef = firebase.database().ref('Courses/'+departmentId+'/SemA');
      return semesterRef;
  /*semesterRef.on('child_added', function(courseSnapshot) {
    console.log(courseSnapshot.key);
    courseSnapshot.forEach(function(childSnapshot):boolean{

      return courseSnapshot.val(); // to appease TypeScript
    });
  });
  */

  }

  public getCoursesList(departmentId:any):any
  {
 var rootRef = firebase.database().ref('Courses/'+departmentId+'/SemA');
  var listChild =[];
        rootRef.on('child_added', function (childData) {

          childData.forEach(function(childData2){
           listChild.push(childData2.val());
            return false;
          })
        });
        return(listChild);

    }
  }

I guess it's something with my return from  function in course-data.ts getCoursesList(departmentId:any):any
I think I did something wrong.
when I run ionic serve it works fine.
Answer: I solved this issue by change into the parameters of the functions here. i marked the arguments with mark quote ? means that not necessary to pass them.
C:/Users/adirz/myapps/studentAssistantApp/.tmp/pages/courses-page/courses-page.ngfactory.ts:943:29


How to listen all changes in form with selects and inputs?

Question: I have form with selects and inputs, I need to make some actions onchange and onkeyup.
For now the following code
var $mainSearchForm = $('.form');
$mainSearchForm.on('change keyup', 'select input', function () {
  var infoForm = $mainSearchForm.serialize();
  var route = $('.form--url select').val();
  $('.btn').attr('href', route + '?' + infoForm);
});

How can I do it?
The example doesn't work!
Answer: select input looks for input elements inside select. You just need to add a comma to separate them:
$mainSearchForm.on('change keyup', 'select, input', fn);

Alternatively you could use the :input selector to match all available form elements:
$mainSearchForm.on('change keyup', ':input', fn)


Is there a more systematic way to populate my layout?

Question: I'm working on the layout as shown below.

So far I've had success with manually defining each View in xml (RelativeLayout within a ScrollView) and manually populating each spinner in java. But this is tedious. I wish I could somehow use "I have this array of items. For each item I want a row on the screen with a spinner and an EditText." I must then be able to grab the user input to put into a database. Eventually, I'll want to be able to come back and edit this screen, which means I'll have to repopulate these fields from a database query.
I tried working some with a ListView, but had trouble populating multiple rows and then read that RelativeLayout is supposed to perform better. What would you suggest? If I have to declare every field in xml and java manually, then so be it.
This is what my XML looks like...
<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="180dp" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="match_parent" >

        <Spinner
            android:id="@+id/category_spinner1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
             />

         <EditText
             android:id="@+id/editWeight1"
             android:layout_width="70dp"
             android:layout_height="wrap_content"
             android:layout_toLeftOf="@+id/percentSign1"
             android:layout_alignBaseline="@id/category_spinner1"
             android:inputType="numberDecimal"   >

        </EditText>

        <TextView
                android:id="@id/percentSign1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignBaseline="@id/category_spinner1"
                android:text="@string/percentSign"
                android:textSize="20sp" >
        </TextView>

        <Spinner
            android:id="@+id/category_spinner2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@id/category_spinner1"
             />

         <EditText
             android:id="@+id/editWeight2"
             android:layout_width="70dp"
             android:layout_height="wrap_content"
             android:layout_toLeftOf="@+id/percentSign2"
             android:layout_alignBaseline="@id/category_spinner2"
             android:inputType="numberDecimal"   >

        </EditText>

        <TextView
                android:id="@id/percentSign2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignBaseline="@id/category_spinner2"
                android:text="@string/percentSign"
                android:textSize="20sp" >
        </TextView>
...

And my Java...
Spinner catSpin1 = (Spinner) rootView.findViewById(R.id.category_spinner1);
         ArrayAdapter<String> catSpinAdapter1 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, DBAdapter.gradeTypes);
         catSpinAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         catSpin1.setAdapter(catSpinAdapter1);
         catSpin1.setSelection(0);

         Spinner catSpin2 = (Spinner) rootView.findViewById(R.id.category_spinner2);
         ArrayAdapter<String> catSpinAdapter2 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, DBAdapter.gradeTypes);
         catSpinAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         catSpin2.setAdapter(catSpinAdapter2);
         catSpin2.setSelection(1);

         Spinner catSpin3 = (Spinner) rootView.findViewById(R.id.category_spinner3);
         ArrayAdapter<String> catSpinAdapter3 = new ArrayAdapter<String>(this.getActivity(),android.R.layout.simple_spinner_item, DBAdapter.gradeTypes);
         catSpinAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
         catSpin3.setAdapter(catSpinAdapter3);
         catSpin3.setSelection(2);
...

Answer: Sure, create a String array, for example:
<string-array name="my_array">
<item>One</item>
<item>Two</item>
</string-array>

Then add it to te spinner on the xml this way:
<Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/my_array"/>

Comment: that's a way to fill the Spinner (and I'll probably implement it), but I'm more looking for a way to avoid having to create and declare the spinners (and other screen elements) one by one. What I'm looking for may or may not exist.
Comment: The only way to do that is programatically. Create a loop in which you create the spinners, set them (content, params, etc.) and then add them to the corresponding viewgroup.
Comment: that sounds good. But if I add them programmatically, then how will I reference them to retrieve user input? How would I know their id?
Comment: http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts ;D
Answer: My first intention would also have been a ListView, you could create a simple datastructure like a class with two string values that will get updated/displayed by this spinner/edittext combination and you could use this class also to persist it in your database.
Some side note: You should have a look at re-using layouts: http://developer.android.com/training/improving-layouts/reusing-layouts.html
That would have made your approach much easier. (define one spinner/edittext layout and re-use it inside your main xml)
Comment: Thanks for the reply. I read the "reusing layouts" article. How would I reference a field in order to retrieve and store a value if they are nested like that?
Comment: You would give every one of that views an id just like you did with your spinner and edittext like:

and then you could access your layout like:
ViewGroup my_first_layout = (ViewGroup) findViewById(R.id.my_first_layout)
and access your spinner/edittext there with:
my_first_layout.findViewById(R.id.category_spinner)


Why won't getline function work multiple times in a for loop with an array of structures?

Question: I have a little problem. I've created a program that asks user to enter part's name and part's price for four diffrent parts. Each name and price fills a structure, and I have an array of four structures. When i do a for loop to fill all the names and prices, my getline functon doesn't work properly, it simply just skipps the entering part after I enter the first part's name. Can you please tell me why?
Here's my code:
#include <iostream>
#include <string>

struct part {
    std::string name;
    double cost;
};

int main() {

    const int size = 4;

    part apart[size];

    for (int i = 0; i < size; i++) {
        std::cout << "Enter the name of part № " << i + 1 << ": ";
        getline(std::cin,apart[i].name);
        std::cout << "Enter the price of '" << apart[i].name << "': ";
        std::cin >> apart[i].cost;
    }
}

Comment: @Mykola yeah, I figured out that i need to ignore one newline after `cin`. Thanks.
Comment: Is there a particular reason the `getline` isn't prefixed by `std::`?
Comment: @Archimaredes it still doesn't work correctly even with `std::`
Comment: I wasn't implying it was the reason. I was just wondering.
Answer: std::getline consumes the newline character \n, whereas std::cin will consume the number you enter and stop.
To illustrate why this is a problem, consider the following input for the first two 'parts':
item 1\n
53.25\n
item 2\n
64.23\n

First, you call std::getline, which consumes the text: item 1\n. Then you call std::cin >> ..., which recognises the 53.25, parses it, consumes it, and stops. You then have:
\n
item 2\n
64.23\n

You then call std::getline for a second time. All it sees is a \n, which is recognised as the end of a line. Therefore, it sees a blank string, stores nothing in your std::string, consumes the \n, and stops.
To solve this, you need to make sure the newline is consumed when you store the floating-point value using std::cin >>.
Try this:
#include <iostream>
#include <string>
// required for std::numeric_limits
#include <limits>

struct part {
    std::string name;
    double cost;
};

int main() {

    const int size = 4;

    part apart[size];

    for (int i = 0; i < size; i++) {
        std::cout << "Enter the name of part № " << i + 1 << ": ";
        getline(std::cin,apart[i].name);
        std::cout << "Enter the price of '" << apart[i].name << "': ";
        std::cin >> apart[i].cost;

        // flushes all newline characters
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

Comment: The newline character in C++ is `'\n'` on **all** systems. The difference between Windows and Unix is in how that character gets written to a file and in what is treated as a the end of a line on input. But that's all irrelevant here: when you press `enter` on the terminal, the input functions see `'\n'`. There's no `'\r'` involved.
Comment: I've already solved this problem by myself with a similar `cin.ignore`. But anyway, thanks!
Comment: @PeteBecker Thanks - updated
Comment: (It's an honour, by the way!)
Comment: Your answer lays out the problem quite clearly. You might consider going on to what happens on the next extraction: in your example, after `getline` reads an empty line, `std::cin >> apart[i].cost;` will see the `'i'` in `"item 2"`, and the extraction will fail because that is not a valid representation of a floating-point value. That will set `std::cin` to a failed state, and any subsequent input attempts through `std::cin` will also fail. I've upvoted your answer; I don't think this addition is critical, and it might be too much of a distraction.


How to add columns with "a" in the field name

Question:
This above is a simple example
I want to add the data which columns with "a"
df['a+abc+bca'] = df[['a', 'abc','bca']].sum(axis=1)

Although this method can be counted successfully, it is not very flexible, because if I have many columns whose field names contain "A", the drawbacks of this method will appear.
I would like to know if there is a more convenient or flexible way to achieve this? I am a novice in Python, if this seems to be a very simple question, please be able to answer it for me, thank you very much for your help.
Comment: does it need to identify "a" and capital "A" aswell?
Answer: Use DataFrame.filter(like=)
cols = df.filter(like='a').columns
df['+'.join(cols)] = df[cols].sum(axis=1)

print(df)

   a  b  abc  bca  a+abc+bca
0  1  2    3    4          8

Comment: this filter method seems highly concise and intuitive then loc and [] indexing. Thanks
Answer: The filter solution is easier but this works too.
a_columns = [column for column in columns if 'a' in column]
df['all_a_sum'] = df[a_columns].sum(axis=1)


how to create multiple columns using values in one column pandas

Question: The data is currently structured like:

data

name1

addr1

url1

vol1

name2

addr2

url2

vol2

name3

addr3

url3

vol3

expected structure:

Name
Addr
url
Vol

name1
addr1
url1
vol1

name2
addr2
url2
vol2

name3
addr3
url3
vol3

I need to extract the data from a column and based on a criteria i.e. if the record is name, id, url or volume, create a column for each
Comment: Are the rows always in order: name, addr, urlm col?
Comment: No, there are some instances where the order changes
Answer: This answer assumes that the values you provided are not the real values: ie the values are meaningful and not literally numbered like that. Data usually just isn't that nicely stated.
It also assumes that you always have a recurrent series of name, addresses, etc that recurs every four rows without exception with a well-behaving df.index that is merely a numeric count for every row.
Make indicies specifying which row and which column each element will end up in.
>>> df['columns'] = df.index % 4
>>> df['rows'] = df.index // 4
>>> df[['rows', 'columns', 'data']]
    rows  columns   data
0      0        0  name1
1      0        1  addr1
2      0        2   url1
3      0        3   vol1
4      1        0  name2
5      1        1  addr2
6      1        2   url2
7      1        3   vol2
8      2        0  name3
9      2        1  addr3
10     2        2   url3
11     2        3   vol3

That will create a data frame that looks like the above (I sorted the columns to more easily visualise what's going on). Then unstack your data.
>>> df.set_index(['rows', 'columns']).unstack()
          data
columns      0      1     2     3
rows
0        name1  addr1  url1  vol1
1        name2  addr2  url2  vol2
2        name3  addr3  url3  vol3

After this, collapse columns multi-index df.columns = df.columns.get_level_values(1) and then rename df.rename(columns={INT: NAME, INT: NAME, ...}, inplace=True). If you have different variable names, adjust as required.
Comment: df['columns'] = df.index % 4 is not giving me an even series meaning
I am getting something like
0
1
2
3
4
0
1
3
4
5
which in turn is messing up the output any suggestions/recommendations?
Thanks
Comment: `df.reset_index(drop=True)`
Comment: Resetting the index would force the existing index, which it seems is not a simple serial count of the rows (from 0), to become a simple serial count.
Comment: Thanks @ifly6
Got the required output


How to deal with specific client configuration and apk

Question: im mostly a web developer but for one project i have to to create a mobile app certainly with xamarin.
As we deliver our webapp to each client we will also distribute the mobile app to each client.
The problem is that each client have specific configuration, for example, the url of the webservice the mobile app will connect.
My idea was to build the apk on my side, deploy it on each client and let a configuration file specific on each client (actually this configuration file exist because it is used by the webapp).
But it seem impossible in the mobile world, it seem the apk need embed everything.
Im surprised i don't find so much documentation about this, it seem nobody else seem concerned by this problem.
How do you guy deal with that ?
thanks !
Answer: I can think of multiple ways of getting the Client App configured.

Make a unique App for each customer, which is preconfigured. This can be done using CI and some configuration files.
Have the Client App configure itself, this could be either by

Scanning a QR code that directs the App to its configuration
Entering a Pin code that directs the App to its configuration
Having the customer host a Web API locally, with a specific DNS name, which your App gets configured by

Have the customer selecting a configuration from a list
Have the customer entering a URL for the configuration
If the customer has to sign in to the App, use that to identify their organization and select the configuration based on that

Just some different ideas how to solve your problem. Some are more involved than others.


shell variable substitution issue

Question: I have a command output a file path name starting with a variable, such as $DIR1/file1. I assign this path name to a variable pname, now when I use the path to read the file, the variable substitution doesn't work. To simulate the case,
-> cat paths.log
$DIR1/file1

-> DIR1=/var/tmp
-> touch $DIR1/file1
-> pname=`cat paths.log`
-> echo $pname
$DIR1/file1

-> ls -l $pname
$DIR1/file1: No such file or directory

Anyone knows how to workaround this problem?
Comment: Please don't mix script with output (you can use `>` or `$` before commands to let us know you're showing us an interactive session).
Comment: Or actually, you're more interested in the order of expansions here: see https://www.gnu.org/software/bash/manual/bash.html#Shell-Expansions. Parameter expansion occurs *before* command substitution, so the `$DIR1` in `$pname` is a literal string, rather than expanded.
Answer: You can do this with the envsubst command and avoid the dangers of eval like so:
$ cat path.log
$DIR1/file1

$ export DIR1=/var/tmp
$ pname=$(envsubst < path.log)
$ printf "%s\n" "$pname"
/var/tmp/file1

Note that you have to export DIR1 for this to work, not just assign it.
Answer: You need to use eval to effect expansion of variables inside a string.  Here I set expanded to the results of the expansion:
$ pname='$DIR1/file1'
$ echo $pname
$DIR1/file1
$ DIR1=/var/tmp
$ expanded=`eval echo $pname`
$ echo $expanded
/var/tmp/file1

shell variable substitution issue


C# pack.xz garbage after end of pack archive

Question: I have a C# program that should download a file from the internet and extract it.
The file is a .pack.xz file, i have no problem extracting the .xz, i tried even manually checking the checksum of the file and it was downloaded correctly.
For instance, one of the files i have to download is this:
http://files.minecraftforge.net/maven/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar.pack.xz
I downloaded it from the browser, then extracted the .xz part with 7zip and it was ok. Now i have a .pack file, i tried to unpack it with Java's unpack200 but it says me "garbage after end of pack archive".
It extracts the file anyway but it's corrupted infact if i open it with winrar it says unexpected end of archive. The jar file i extracted was 2,350,874 bytes while it should have been 2,553,197 bytes.
I really don't know how to solve it. I even checked some online programs but they seems to do the same thing i do the same way i do it so i can't figure out what's the problem
Comment: Thanks! That worked! I used that pattern for all of my files! Now i can even put away the libraries for xz and reduce the size of my exe!! Thanks again
Comment: As a workaround, why don't you grab this file from a different Maven repository? The Central Repository has this JAR as well as a bunch of newer versions. See [page 1](http://search.maven.org/#search|gav|a|g%3A"com.typesafe.akka"ANDa%3A"akka-actor_2.11") and [page 2](http://search.maven.org/#search|gav|2|g%3A"com.typesafe.akka"%20AND%20a%3A"akka-actor_2.11") which has version 2.3.3 as in your original URL.
Comment: No problem; I'll add this as an answer since comments are ephemeral.
Answer: As a workaround, you can grab this JAR from a different Maven repository, such as the Central Repository (which has this specific JAR and a bunch of newer versions). See this search to find all the versions. The older version in your original link is on the second page of this search (although it may be less functional or less secure than the latest version).


Is it safe to install Ubuntu on a mid 2014 retina Macbook Pro?

Question: I am currently interested in installing ubuntu on my Macbook Pro. I wish to know if it is safe to install Ubuntu as a full replacement of Mac OS X or if I should install with dual-boot first. This concern is mostly because of an apparent incompatibility between Ubuntu and Apple's custom EFI implementation, which by my understanding can "brick" my laptop.
I also looked for guides on how to replace Mac OS X with Ubuntu but the ones I found are old, and the software that they use (namely reEFIt) does not seem to work well on OS X Yosemite. Can someone point me to more recent tutorials/guides?
Lastly, is Ubuntu 15.04 capable of scaling everything (excluding applications) well?
[Edit]: I followed the instructions on Ubuntu's website and created an bootable USB, and when 15.04 loaded, I could not get a Wi-Fi connection. Being the first available release of 15.04, should I wait a couple more days and try again or should I assume that Wi-Fi is not available out-of-the-box with VividVerdet?
Answer: You will likely want to dual boot because there are still some driver issues. Namely around the discrete GPU and the webcam. I wrote a blog post about doing just this which you might find helpful [1], the last step explains how to get WIFI working.
[1] http://fromanegg.com/post/82251710943/how-to-install-ubuntu-on-a-mac-or-macbook
Comment: Your link appears to be dead. I can't see your post.
I own a 13" version the retina macbook pro, which does not offer dual-graphic cards. Having only the Intel Iris integrated graphics, would you advise installing 15.04?
Comment: Sorry about that, the site is back up. I haven't yet done the upgrade but others haven't reported any issues.


What is a cardinal basis spline?

Question: Wikipedia says:

the normalized cardinal B-splines tend to the Gaussian function

and writes them as "Bk".  Meanwhile, cnx.org Signal Reconstruction says:

The basis splines Bn are shown ... as the order increases, the functions approach the Gaussian function, which is exactly B∞.

but then says

as the order increases, the cardinal basis splines approximate the sinc function, which is exactly η∞.

Likewise, Signal Reconstruction with Cardinal Splines uses similar notation of ηn for "cardinal spline".
So which is it?  Does a "cardinal basis spline" approximate a Gaussian or a sinc?  "B-spline" and "basis spline" are the same thing, right?  Is there any relationship to this cardinal spline?
Answer: Roughly speaking ...
If you fix certain quantities (degree, knots, orders of continuity) then the set of all splines forms a vector space, which, of course, has several different bases.
Two common bases are the cardinal splines, and the b-splines.
It's true that "b-spline" is an abbreviation of "basis spline", but the vector space of splines has other bases, besides the b-splines. Confusing, I guess.
I wasn't aware of the limits as degree goes to infinity, but the statements sound plausible. Assuming you use the right knot sequences, I can see how the b-spline basis functions might tend to the Gaussian function, and the cardinal basis functions might tend to the sinc function.
Comment: The word "cardinal" is used in two different senses (unfortunately). I just discovered that some people use the term "cardinal b-spline" to refer to a b-spline whose knots are successive integers.

Cardinal basis splines are the things I mentioned in my answer -- they are the splines shown in your second set of pictures.

So, not the same thing.
Comment: Ok, so "cardinal B-spline" and "cardinal basis spline" are not the same thing?

What is a cardinal basis spline?


reading a file into stream in windows store App without using async/await

Question: I want to read a file from the assets into a stream, I currently use it as the following:
public async void LoadWidthOfUnicodesData()
{

    string dataFile = @"Assets\QuranData\Data_Font1.xml";
    StorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    StorageFile file = await InstallationFolder.GetFileAsync(dataFile);
    Stream readStream = await file.OpenStreamForReadAsync();
    DataContractSerializer ser = new DataContractSerializer(typeof(List<UniCodeWidth>));
    WidthOfUnicodes = (List<UniCodeWidth>)ser.ReadObject(readStream);
    for (int i = 0; i < WidthOfUnicodes.Count; i++)
    {
        WidthOfUnicodesDict.Add(WidthOfUnicodes[i].UniCode, WidthOfUnicodes[i].Width);
    }
}

The only problem with that, is that part is in my viewmodel, and as it's a non-blocking operation, when the VM initializes with the View as its DataContext, the constructor does what it's supposed to do to fill the view but I always get an exception at using the WidthOfUnicodesDict because it's not yet filled with the data.
What I want to do, is either make the reading to stream a synchronous method (without using async/await) which so far I don't know how to do it on windows store. or somehow make the VM constructor waits till this operation finishes and notifies it's done.
Comment: Have a look at [Stephen Cleary's article about `async` and constructors](http://blog.stephencleary.com/2013/01/async-oop-2-constructors.html).
Comment: If it's reading from a file, it's a blocking operation.
Answer: You can fetch a file without async/await semantics like this:
var file = Package.Current.InstalledLocation.GetFileAsync(Folder)
               .GetAwaiter()
               .GetResult();

I don't know how to get a stream, but you can get an IBuffer or read it as text, using FileIO:
string content = FileIO.ReadTextAsync(file).GetAwaiter().GetResult();
IList lines = FileIO.ReadLinesAsync(file).GetAwaiter().GetResult();
IBuffer buffer = FileIO.ReadBufferAsync(file).GetAwaiter().GetResult();

I've done this before and it doesn't cause any deadlocks.
Comment: But it will block the UI thread, which is why you should never do this.
Comment: When a question asks "How to do X?", sometimes the correct answer is "Don't do X, do Y instead, this is how."
Comment: @dcastro, looks like you are going through hoops and loops trying to avoid the disaster you're running into. Like @I3arnon said, `X.GetAwaiter().GetResult()` when applied to `Task` is the same as `X.Result`.
Comment: @svick *if* it is run on the UI thread, yes. But isn't that what the OP was looking for? To run it synchronously?
Comment: Why not simply `var file = .Result`
Comment: @PauloMorgado It seems both you and @I3arnon are under the false assumption that methods like `GetFileAsync` return a `Task`. They don't, they return an `IAsyncOperation`, which does not have a `Result` property. I'm not going through hoops, I'm simply retrieving the result of the operation. And what disaster am I running into?
Comment: @dcastro, than my question would be: why are you calling `X.GetAwaiter().GetResult()` instead of `X.GetResults() `?
Comment: @PauloMorgado I've tried it before, and it either lead to a deadlock or an exception. Can't remember, that was a while ago. I think it threw an exception, because it tried to retrieve the result of the operation immediately, but the results weren't available yet.


How to migrate a data type String to boolean?

Question: I have a class that has a parameter defined as a String, now I realized the type should be boolean, I would like to migrate the type from String to boolean.
I'm using Intellij and I have the option of migrating from a native type to another native type (e.g char --> int) but it does not work with String
Type Migration in Intellij does not have relevant info in this case.
Thanks.
Comment: This feature is working fine for me. Are you using the latest version of the IDE? What error are you running into?
Answer: You can migrate any type you like to any other type. It doesn't mean your code will be guaranteed work after any type migration though.
Consider this example.
private Class aClass = Class.class;

Here we have a Class object called aClass that stores a reference to the class Class. How confusing!
Since all classes in Java extend object. We can do a type migration from Class to Object, and we won't run into any errors with our code later.
private Object aClass = Class.class;

The above is still valid Java.
Now, if we want to convert say a String or char into a boolean, we'll get a popup saying it can't convert. We can click ignore so that it migrates the type, but now it will be invalid Java as you're trying to assign a char or String to a boolean type.
Here is a screenshot outlining this error:

IntelliJ doesn't modify the assignment to the variable, just its type. Correcting any compile errors as a result of migration is up to you.


undefined:1 undefined ^ SyntaxError: Unexpected token u in JSON at position 0

Question: This is my code, the data gets logged but then or mid-way the error happends.
The error message is
undefined:1
undefined
^

SyntaxError: Unexpected token u in JSON at position 0

function script() {
  request('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', function(error, res, body){
    for(let i = 0; i <= body.length; i++) {
      let obj = JSON.parse(body)
      request(`https://hacker-news.firebaseio.com/v0/item/${obj[i]}.json?print=pretty`, function(error, res, body){
        let myData = JSON.parse(body);
        if(myData && myData.title && myData.score && myData.id) {
          console.log('TITLE: ', myData.title)
          console.log('UPVOTES: ', myData.score)
          console.log(`https://news.ycombinator.com/item?id=${myData.id}`)
        }
      })
    }
  })
}

Comment: the value undefined can not be parsed ... so, body is undefined - common error ... you're accessing `body[body.length]`  (arrays start at index 0, as you know, so their length is obviously one greater than the last available index) since you check for `i <= body.length` ... remove the `=` and your code will work without error - I'd also put `let obj = JSON.parse(body)` before the for loop, so you don't unnecessarily repeat the same conversion
Comment: you are parsing the body until its length?
Comment: "the data gets logged" what data? why parse `let obj = JSON.parse(body)` lenght times?
Comment: @JaromandaX I switched back to `< body.length` and moved `let obj = JSON.parse(body)` before the loop and I'm still getting the same error as before.
Comment: @JaromandaX _"you're accessing `body[body.length]`"_ - There's no such (or `body[i]`) piece of code in OPs question...
Comment: Check the `error` of the inner `request(...)` which most likely will have an explanation for your problem.
Comment: @andreas, it's actually worse than I thought, OP is accessing `obj[i]` where obj is JSON.parse(body), so body is a STRING! wow!!!
Answer: You've probably wanted to parse the data and then iterate over it:
function script() {
  request('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty', function(error, res, body){
    let obj = JSON.parse(body)
    for(let i = 0; i < obj.length; i++) {
      request(`https://hacker-news.firebaseio.com/v0/item/${obj[i]}.json?print=pretty`, function(error, res, body){
        let myData = JSON.parse(body);
        if(myData && myData.title && myData.score && myData.id) {
          console.log('TITLE: ', myData.title)
          console.log('UPVOTES: ', myData.score)
          console.log(`https://news.ycombinator.com/item?id=${myData.id}`)
        }
      })
    }
  })
}

Comment: It works for me: https://runkit.com/fzs111/stackoverflow.com-a-61866927-8376184