text:
Q: How to generate a random number in 1.18.1? I have fiddled around with a data pack which needs a random number. To get that, I have tried using emeraldfyr3's random function, which is quite outdated by now, but I have updated it to the best of my knowledge. However, when running the command, instead of a random number, it just always returns the current math_output value + 50. Any ideas on where the issue lies, how I could fix it and/or how I could get a random number perhaps with other, better methods?
#Change (lower, upper) to (lower, range)
scoreboard players set @s math_input1 50
scoreboard players set @s math_input2 10070
scoreboard players operation @s math_input2 -= @s math_input1
scoreboard players add @s math_input2 1

#Summon two entities to work with
summon minecraft:area_effect_cloud ~ ~ ~ {Duration:1,CustomName:'{"text":"math_random_kcjbc"}'}
summon minecraft:area_effect_cloud ~ ~ ~ {Duration:1,CustomName:'{"text":"math_random_kcjbc"}'}

#Generate a 31-bit random number by randomizing each bit
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 1
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 2
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 4
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 8
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 16
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 32
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 64
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 128
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 256
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 512
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 1024
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 2048
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 4096
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 8192
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 16384
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 32768
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 65536
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 131072
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 262144
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 524288
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 1048576
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 2097152
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 4194304
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 8388608
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 16777216
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 33554432
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 67108864
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 134217728
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 268435456
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 536870912
scoreboard players add @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1,sort=random] math_input1 1073741824

#Transfer random number and limit to given range
scoreboard players operation @s math_output = @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=0,limit=1] math_input1
scoreboard players operation @s math_output %= @s math_input2
scoreboard players operation @s math_output += @s math_input1

scoreboard players operation @s math_input2 += @s math_input1
scoreboard players remove @s math_input2 1

function srm_func:mechanics/main

kill @e[type=minecraft:area_effect_cloud,name=math_random_kcjbc,distance=..1]


text:
Q: Is there a tool that will combine a 32 bit + 64 bit application and pack them together in one 32+64 bit application In Windows 2008 R2 server (server core installation) wow64 is no longer a required component.
I can compile a 32 bit application using the same source code as a 64 bit application (with a few ifdefs here and there).
Is there a tool that puts both versions of my app in one executable so that my 32+64 bit application will run on a pure 32-bit Windows and a 64-bit only Windows?
Note that I am not talking about a packer because the packer itself will be either 32 or 64 bit.

A: No. An EXE's header is marked with the processor architecture supported by the code contained in the EXE. Use DUMPBIN.EXE -HEADERS  to explore.
EXE's report the "machine" type as:
x86: 0x14C
x64: 0x8664
ARM: 0x1C4
If you want to deploy your app, build a version for x86, a version for x64 (ARM comes later with Win8) and author a setup package (MSI) that can dynamically examine the architecture of the machine onto which you're installing the app, and lay down one or both of the apps. This is how, for example, Adobe are now distributing Flash x86 and Flash x64 in the latest Flash player download.
If you want to build a truly universal binary, build it in .NET and mark it as targetting "Any" CPU. Your app will then be JITted to the architecture of your machine (or the hosting process in the case of an add-in component).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Navigation bar not appearing? I am currently using a form building library called
Eureka(https://github.com/xmartlabs/Eureka)  and for some reason
whenever I build a form,the navigation bar is not appearing eventhough
my view controller is embedded in a navigation controller and it is
set to visible.Any help?  Here's my repo:
https://github.com/ariff20/iTutor
Code
class SignUpViewController: FormViewController ,UINavigationBarDelegate{

override func viewDidLoad() {
    super.viewDidLoad()

     let logButton : UIBarButtonItem = UIBarButtonItem(title: "RightButtonTitle", style: UIBarButtonItemStyle.Done, target: self,action: "multipleSelectorDone")

    self.navigationController?.navigationBar.hidden = false

    self.navigationItem.rightBarButtonItem = logButton
     form +++ Section("Your Basic Details")
        <<< NameRow()
            {
                $0.placeholder = "Your Name"
            }
        <<< EmailRow()
            {
                $0.placeholder = "Email"
            }
        <<< PasswordRow()
            {
                $0.placeholder = "Password"
            }
        <<< PhoneRow()
            {
                $0.placeholder = "Your phone no,Customers will see this"
            }

        +++ Section("Select your Expertise")
        <<< MultipleSelectorRow<String>
            {
                $0.title = "Choose your Subjects"
                $0.options = ["English","Mandarin","Maths","Science","Bahasa Malaysia"]

            }
            .onPresent { from, to in
                to.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Done, target: from, action:"multipleSelectorDone:")
        }
        <<< MultipleSelectorRow<String>
            {
                $0.title = "Choose your levels"
                $0.options = ["Standard 1-3","Standard 4-6","Form 1-3","Form 4-5"]

            }
            .onPresent { from, to in
                to.navigationItem.rightBarButtonItem = logButton}

        <<< MultipleSelectorRow<String>
            {
                $0.title = "Choose your pricing range"
                $0.options = ["RM30-RM40","RM40-RM60","RM60-RM80","RM80-RM100"]
            }
            .onPresent { from, to in
                to.navigationItem.rightBarButtonItem = logButton}
        +++ Section("Where can you teach?")
        <<< TextRow()
            {
                $0.placeholder = "State"
            }
        <<< TextRow()
            {
                $0.placeholder = "Town,ex:Near Shah Alam"
            }

    }
override func viewWillAppear(animated: Bool)
{
    super.viewWillAppear(true)
    self.navigationController?.navigationBarHidden=false

}

func multipleSelectorDone(item:UIBarButtonItem)
{

    navigationController?.popViewControllerAnimated(true)
}

OUTPUT
1

2

3

A: Xcode 8.3+
Click on the view controller and select the following option:
Editor > Embed in > Navigation Controller
That should do it.

A: You're presenting your ViewController like this:
let vc = storyboard!.instantiateViewControllerWithIdentifier("TutorSignUp") as! SignUpViewController
self.presentViewController(vc, animated: true, completion: nil)

so your SignUpViewController doesn't actually have a UINavigationController as a parent.
This will fix that:
let vc = storyboard!.instantiateViewControllerWithIdentifier("TutorSignUp") as! SignUpViewController
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: true, completion: nil)

A: You need new UINavigationBar in StoryBoard then you will @IBOutlet
@IBOutlet weak var NavigationBar: UINavigationBar!

and you will addSubvie  UINavigationBar
override func viewDidLoad() {
    super.viewDidLoad()

    self.view.addSubview(NavigationBar)


text:
Q: Exploding keys and values in a dictionary subset in Python I'm trying to create a way of exchanging the keys and values in a Pandas DataFrame of the USGS/WWF HydroBASINS dataset but only for a specific subset. My entire dataframe is roughly 500 000 rows long so I only want to perform this for key, value pairs that are relevant to an intial value.
Assuming that a DataFrame/Dictionary is structured as 'upstream' and 'downstream':
{1: [2, 3], 2: [4, 5, 6], 3: [7, 8]}

Therefore, 2 is downstream of [1], 4 is downstream of [1 and 2], 7 is downstream of [1, 3].
The challenging part is that I don't want to determine the relationships for all keys,values as this would take a very long time. For a large dataset of hydrological tributaries, depending on where one starts, this could lead to creating a dataframe that explodes with keys if the upstream values are collected and determined for all keys.
At the end of the day, when providing one key, I would like to have returned all the upstream keys. Expanding all values would resemble this:
{1: [], 2: [1], 3: [1], 4: [1, 2], 5: [1, 2], 6: [1, 2], 7: [1, 3], 8: [1, 3], ...}

Whereas I would rather simply return:
5: [1, 2]

I haven't had much luck working with DefaultDicts as some posts have suggested but this is probably because I'm not familiar enough with them.
UPDATE:
In order to better understand, the relevant fields of the data frame are 'HYBAS_ID': The ID number of the basin, 'NEXT_DOWN': The basin that it flows into, (and 'MAIN_BAS': The greater watershed ID (e.g. Mississippi, Saint Lawrence, James Bay, Rio Grande, etc.))
here's what the unoptimized code looks like:
def get_upstream_hydrobasins(basin_dataframe, basin_id):
    upstream_mask = basin_dataframe['NEXT_DOWN'] == basin_id
    iter_upstream = basin_dataframe[upstream_mask]['HYBAS_ID']
    return iter_upstream

basin_ID = <ID of some hydroBASIN>
df = pd.read_csv(table)
row_id = df['HYBAS_ID'] == basin_ID

# Some code to subset the number of potential sub-basins using regions
main_basin_id = df[row_id]['MAIN_BAS']
main_basin_mask = df['MAIN_BAS'] == main_basin_id.values[0]
main_basin_df = df[main_basin_mask]

all_basins = list(main_basin_df[row_id]['HYBAS_ID'].values)
for b in all_basins:
    tmp = get_upstream_hydrobasins(main_basin_df, b)
    if len(tmp):
        all_basins.extend(tmp.values)

I'm wondering if there is a better way to optimize this code.


text:
Q: Application displays a revolving Windows Logo on Windows Mobile I have created an application for quite old Windows Mobile 5 based handhelds using VS 2008, c# and .net core 2.0. Here is the, erm, code, which I use to show the problem:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;

namespace TestEmptyApp
{
    class Program
    {
        static void Main(string[] args)
        {
        while (true) { };  // ended by the debugger or device boot
        }
    }
}

I choose the "Smart Device Project" "Console Application" boilerplate. If I run it, a revolving image resembling the Windows logo (4 coloured patches, red, green, yellow, blue) appears on the display. I need the application to run entirely silent.
How can I get rid of the logo?


text:
Q: Elegant way to denote the following summation? For example, $$
\begin{align}
S_1&=\frac{x_1}{2},\\
S_2&=\frac{x_1}{2}-\frac{x_1^2}{6}\frac{1}{x_2},\\
S_3&=\frac{x_1}{2}-\frac{x_1^2}{6}\left(\frac{1}{x_2}+\frac{1}{x_3}\right)+\frac{x_1^3}{12}\frac{1}{x_2 x_3},\\
S_4&=\frac{x_1}{2}-\frac{x_1^2}{6}\left(\frac{1}{x_2}+\frac{1}{x_3}+\frac{1}{x_4}\right)+\frac{x_1^3}{12}\left({\frac{1}{x_2 x_3}+\frac{1}{x_2 x_4}+\frac{1}{x_3 x_4}}\right)-\frac{x_1^4}{20}\frac{1}{x_2 x_3 x_4},\\
&\cdots
\end{align}
$$I am trying to generalize this using $\sum$ and $\prod$ notation. My attempt: $$S_n=\sum_{i=1}^{n}{\frac{(-1)^{i-1}x_1^i}{i(i+1)}\sum_{2\le j_1\lt j_2\lt\cdots\lt j_{i-1}\le n}\prod_{k=1}^{i-1}\frac{1}{x_{j_k}}},$$ which still seems complicated. I wonder if there are more elegant expressions. :-)

A: One way is the express it as
$$ S_n := \frac1{x_1}\int_0^{x_1} \int_0^{t} \prod_{k=2}^n
   \left(1 - \frac{x}{x_k}\right) \, \text{d}x \, \text{d}t. $$
The clue is the appearance of elementary symmetric polynomials in the coefficients of $\,x_1^k$.

A: Probably not what you are after, but observing that $\dfrac1{x_k}, k=2,\cdots4$ are the roots of some polynomial
$$\left(z-\frac1{x_2}\right)\left(z-\frac1{x_3}\right)\left(z-\frac1{x_4}\right)=p_3z^3+p_2z^2+p_1z+p_0,$$
you have
$$S_4=\sum_{i=1}^4\frac{p_{4-i}}{i(i+1)}x_1^i.$$

You can also refer to the elementary symmetric polynomials notation.


text:
Q: Asymptotic Distribution of Minimum Uniform Random Variables I've been working on this problem for a while, and I've made some progress, but I'm still stuck on some parts. I was hoping to get some assistance with this!
Let $M_n = \min(X_1, ..., X_n)$ where $X_i$ are i.i.d Unif$(a,b)$.
First part is to find the distribution of $M_n$. This was quite simple, and I ended up getting the CDF as:
$F_M(m) = 0$ for $m ≤ a \\$
$F_M(m) = 1 - \left[ 1 - \dfrac{m-a}{b-a}\right]^n$ for $m \in (a,b] \\$
$F_M(m) = 1$ for $x > b$
Now that the CDF has been found, the next step is to find the asymptotic distribution of $P_n = n(M_n - a)$. This is the part I'm stuck on. I thought about working through and finding the distribution of $P_n$ by using $Pr(P_n ≤ t)$. But when I do this, I end up with the CDF of $P_n$ as $n \rightarrow \infty$ being 0 for all values of $t$, which I know is incorrect since the next part of the question relies on calculating confidence intervals. So, the asymptotic distribution for $P_n$ is needed, and shouldn't be 0.
Finally, once I get that asymptotic distribution of $P_n$, how can I go about calculating a confidence interval, given specific values say, $b=3$, $n=10$, and $M_n=1$.

A: First, note that you can simplify your problem by setting $a=0$ without loss of generality, which gets rid of $a$ as a parameter.
Let $z = nm$, then $m = z/n$ and, substituting,
$$F_Z(z) = 1 -\left[1-{z \over nb}\right]^n$$
for $0 < z < nb$.
Remembering our limits, specifically, the one relating $(1-x/n)^n$ to $e^{-x}$, we can write:
$$\lim_{n \to \infty}F_Z(z) = 1 - e^{-z/b}$$
which is the c.d.f. of an Exponential variate with mean $b$.
Some straightforward substitution gets us back to your problem:
$$\lim_{n \to \infty}F_{P_n}(p) = 1 - e^{-p/(b-a)}$$


text:
Q: How to create a custom font size in xaml using Xamarin, so that you can change font sizes depending on device? Is there are way to create a custom fontsize that would work the same as Micro or Small or Title that are already built into Xamarin. I want to be able to use it like the following:
<Label Text="Test" FontSize="MyFontSize"/>

I think it would be implemented something like the following inside my resource dictionary but it isn't working:
<FontSize x:Key="MyFontSize">
    <OnPlatform x:TypeArguments="FontSize">
        <On Platform="UWP">25</On>
        <On Platform="iOS">12</On>
    </OnPlatform>
</FontSize>

The error says:

"The type FontSize can not be found"

It's not a runtime error. It's just a green underline in the XAML editor.
Can it be done?

A: You need to use x:Double instead:
<OnPlatform x:Key="MyFontSize" x:TypeArguments="x:Double">
    <On Platform="UWP">25</On>
    <On Platform="iOS">12</On>
</OnPlatform>

And then reference the resource like this:
<Label Text="Test" FontSize="{StaticResource MyFontSize}"/>

Or you can specify it directly on the view:
<Label Text="Test">
   <Label.FontSize>
      <OnPlatform x:TypeArguments="x:Double">
          <On Platform="UWP">25</On>
          <On Platform="iOS">12</On>
      </OnPlatform>
   </Label.FontSize>
</Label>


text:
Q: assets look grainy/pixelated I'm using pretty high res graphics in my project. I've got different assets in my MDPI and HDPI folders. I've made sure that my manifest supports resizing, that it supports large screens, etc (though this shouldn't matter, at least not for resizing, as long as you declare a minsdk in the manifest.)
The problem is that, all of my assets look grainy and pixelated on devices I test them on. I've tested on a G2x (which is 480 x 800, I believe) and others and it always looks pixelated. When I compare the stock android buttons to my stretchable resources, for example, the difference is startling. My assets look terrible, but the stock android ones are sharp.
Anything I'm missing here to get assets to look good?

A: Solved! You must add a minsdkversion to the manifest, e.g. <uses-sdk android:minSdkVersion="4"/> even if you declare that <supports-screens android:resizeable="true" android:largeScreens="true"/> otherwise assets will look terrible.


text:
Q: How do I retrieve a sum of distinct values to list? The SQL table and model supporting my application is very similar to what I have displayed below.
Id | CustomerName | FruitName | Charge
_____________________________________
1  | Bob          | Banana    | 3.00
2  | Jill         | Apple     | 2.00
3  | Bob          | Apple     | 3.00
4  | Marvin       | Banana    | 1.00
5  | Sam          | Pear      | 4.00

[Key]
public int Id {get; set;}
public string CustomerName { get; set; }
public string FruitName { get; set;}
public string Charge {get; set;}

What I would like to do is pull the distinct FruitName and the Charge.Sum() and display it ToList() in my view.  Here is what I have tried
var fruitToList = (from f in db.fruit select f).ToList();
var test = fruitToList.GroupBy(x => x.FruitName).Sum(y => y.Charge).Select(z => z.First());
return View(test.ToList());

I know that the reason why it does not work is because Charge needs to be something like decimal.Parse(y.Charge) but I cannot figure out how to do it within the Sum() function. Should I be going about this a different way?

A: Weird that the charge is a string, but never the less, since the data is already in a list you can group by fruit name extract the charge as a decimal and sum the group
For example
//...

var test = fruitToList
    .GroupBy(_ => _.FruitName, _ => new { Charge = decimal.Parse(_.Charge) })
    .Select(g => new Fruit {
        FruitName = g.Key,
        Charge = g.Sum(f => f.Charge).ToString()
    });

//...

Which could also be simplified even more
var test = fruitToList
    .GroupBy(_ => _.FruitName, _ => decimal.Parse(_.Charge))
    .Select(g => new Fruit {
        FruitName = g.Key,
        Charge = g.Sum().ToString()
    });


text:
Q: PHP Mcrypt error: Cannot open source device I downgraded to PHP 5.2.8 from PHP 5.4.2 for a reason, I enabled the mcrypt extension, but when I run the function mcrypt_create_iv ($size, MCRYPT_DEV_RANDOM), it doesn't execute properly, and I get the following warning
Warning: mcrypt_create_iv() [function.mcrypt-create-iv]:Cannot open source device

Please how do I fix this issue? Thanks for any suggestion.

A: The issue occurred because MCRYPT_DEV_URANDOM was only supported on Windows as from PHP version 5.3.0, that is why it was working well until the downgrade.
I changed to MCRYPT_RAND which worked on previous versions and the problem was solved.

A:
Locate the file includes/CryptRandom.php. Find the following line
  (probably around line 285): $iv = mcrypt_create_iv( $rem,
  MCRYPT_DEV_URANDOM ); Change it to: $iv = mcrypt_create_iv( $rem,
  MCRYPT_RAND );

Source

A: Check the device file (if Linux):
/dev/random


text:
Q: Keyboard shortcut to navigate/cycle between visible windows on screen I have two windows(e.g a document and a browser). I have maximized them such that the document completely occupies the left half and the browser completely occupies the right half of the screen ( I do this easily with the keyboard shortcuts of Spectacle)
What is the keyboard shortcut to navigate quickly between these two visible windows?
Cmd + Tab is not ideal because if I use multiple virtual desktops(like workspaces in Linux) and I go to a third application there in another desktop, when I come back to the virtual desktop which contains my browser and document, Cmd + Tab brings in the third application to the mix.
Cmd+Space and then typing the application name(e.g the browser application or the document application) is the closest I could get to what I originally wanted.
Is there a software or configuration that I can use to get this functionality?

A: Those would be
Control+F4 - Move focus to the active (or next) window
Shift+Control+F4 - Move focus to the previously active window
If you have the "F keys as standard function keys" option disabled in System Preferences > Keyboard, enable it.

Or use Fn in addition to the above shortcuts.


text:
Q: Flutter: Condition [FieldPath([type]), == type ] already exists in this query I have the following code:
Query _cardsQuery = FirebaseFirestore.instance.collection('Cards');

StreamSubscription _stream;

String _selectedType;

 // This method is called after in initState() method
 void _getDataAndListen() {
   _stream?.cancel();
   _stream=_cardsQuery
          .orderBy('createdAt', descending: true)
          .snapshots()
          .listen((collection) => _fillData(collection));
  }

It works fine
But when I add new where to the _cardsQuery:
// This method is called after selecting the _selectedType
void _preparingQueryAndReListen() {
    if (_selectedType != null) {
      _cardsQuery = _cardsQuery.where('type', isEqualTo: _selectedType);
    }
    _getDataAndListen();
  }

The following error appears :

conditions .where((List item) => equality.equals(condition,
item))
.isEmpty': Condition [FieldPath([type]), ==, type] already exists in this query.

Where is the error in this code
Packages used in the code is : cloud_firestore
Any help, thank you

A: It sounds like you're calling _preparingQueryAndReListen multiple times. Each time the code takes the existing _cardsQuery and adds a condition on type. Since a query can only contain one condition on each specific field, this call correctly fails after the first time.
A simple fix based on the code you shared is to rebuild the query from scratch each time _preparingQueryAndReListen is called:
  void _preparingQueryAndReListen() {
    _cardsQuery = FirebaseFirestore.instance.collection('Cards');
    if (_selectedType != null) {
      _cardsQuery = _cardsQuery.where('type', isEqualTo: _selectedType);
    }
    _getDataAndListen();
  }


text:
Q: Unitary orbit of the Jordan matrices Let
$$
\mathcal{J}=\{A\in M_n(\mathbb{C}):\ A \text{ is a Jordan matrix}\}
$$
Then it is well-known that the similary orbit of $\mathcal{J}$ is all of $M_n(\mathbb{C})$.

What is the unitary orbit of $\mathcal{J}$? Is it dense?

It cannot be all of $M_n(\mathbb{C})$, because every matrix in $\mathcal{J}$ and its unitary conjugates have the property that eigenvectors corresponding to different eigenvalues are orthogonal to each other.

A: It cannot be dense except in the trivial case of $n=1$.  The (real) dimension of $U(n)$ is $n^2$ while the dimension of $Gl_n(\mathbb{C})$ is $2n^2$  Since $\mathcal{J}$ has dimension $n$ (in the sense that it's a union of the diagonal matrices together with unions of various Jordan blocks things of smaller dimension since we get to choose fewer eigenvalues), the $U(n)$ orbit through $\mathcal{J}$ has dimension at most $n^2+n$.
But $n^2 + n\leq 2n^2$ unless $n=n^2$, i.e., $n=0$ or $n=1$.

A: It is the set of $n \times n$ matrices $A$ such that there is an orthormal basis $\{u_j:\ j=1\ldots n\}$ that is the union of blocks $\{u_j:\ a \le j \le b\}$ where $u_a$ is an eigenvector of $A$ for some eigenvalue $\lambda$ and $A u_j = \lambda u_j + u_{j-1}$ for
$a+1 \le j \le b$.  Well, that's just restating the fact that the matrix for $A$ in this basis should be in Jordan form.
EDIT: here's a necessary condition, I'm not sure it's sufficient.  $A = B + N$ where $B$ is a normal matrix and $N$ a nilpotent matrix that commutes with $B$, and such that
$N^k (N^k)^*$ and $(N^k)^* N^k$ are orthogonal projections for each positive integer $k$.


text:
Q: ssh-agent rendered unusable after single use I'm using Ubuntu 18.04 on WSL (Windows 10 1803, Build 17134.112), and lately I've noticed an issue with ssh-agent.
When I start up a shell, before connecting to anything over SSH, I first call ssh-add. Then I go on connecting to something as usual. However, once I exit that SSH session to return to my own shell, I find that trying to open any SSH session prompts me for my passphrase, and ssh-add complains that the agent refused the connection.
In ps however, I find that the instance with the PID I've seen calling ssh-agent is still live. Checking the corresponding directory in /tmp also shows that the socket file still exists.
I'm confused why a live agent instance would suddenly refuse connections, and that only after exactly one use of the agent.

A: This seems to be caused by a bug in WSL, see this link for answer: https://github.com/Microsoft/WSL/issues/3183
In short, it seems to happen when ForwardAgent is set to yes.


text:
Q: Ordering in a foreach loop I trying to order a query inside a foreach loop. After looking around reasoning why its not displaying the results correctly I've read that the foreach will only run once for every user its found so its basically just ordering that one users updates.
$AllFriend = explode(",", $UserInfo['friends']);
                                array_push($AllFriend, $Username);

                                foreach ($AllFriend as $FriendSel) {

                                    $sql5 = "SELECT * FROM updates WHERE username = :username ORDER BY id DESC LIMIT 20";
                                    $DoQuery = $pdo->prepare($sql5);
                                    $DoQuery->bindValue(':username', $FriendSel);
                                    $DoQuery->execute();
while ($Updates = $DoQuery->fetch(PDO::FETCH_ASSOC)){

I have the friends in the database like "friend1, friend2, friend3" etc so I'm using array_push to add the users username in to be able to see their own updates to as you wouldn't add yourself as a friend.
What would I need todo to be able to get the updates ordering by ID.
I'm not wanting someone to just show me what todo and thats it as I want to learn so pointing me in the right direction would be great!
Thank you!

As an update, I've got an array what holds the usernames and have changed the query
 $FriendNames = array();

                                $AllFriend = explode(",", $UserInfo['friends']);
                                array_push($AllFriend, $Username);

                                foreach ($AllFriend as $FriendSel) {
                                    $FriendNames[] = $FriendSel;
                                }
                                $Addit = implode(",", $FriendNames);
 $sql5 = "SELECT * FROM updates WHERE username IN ('$Addit') ORDER BY id DESC";
                                $DoQuery = $pdo->prepare($sql5);                                $DoQuery->execute();
while ($Updates = $DoQuery->fetch(PDO::FETCH_ASSOC)) {

The $Addit variable is holding usernames like "friend1,friend2,friend3" etc although now my while loop is blank and showing no results. For what reason is this?
Thanks


text:
Q: Add meta tag to search results In the search results I use author_name=something in the url to restrict the results. The Problem is that domain.com/?s=searchterm and domain.com/?s=searchterm&author_name=something have the same meta tags. How can I add the author_name value to the meta tags?

A: Well I am asuming you want to amend the <title> tag?
Add this in functions.php
  add_filter('wp_title', 'my_custom_page_title');

  function my_custom_page_title($title) {
    global $s;
    if( isset($_REQUEST['author_name']) && is_search() ) {
            $title = 'Search Results for '.$s.' from author '.$_REQUEST['author_name'];
    }
    return $title;
  }

If $s returns blank replace that with $_REQUEST['s']


text:
Q: Reading and parsing from file in java. How can I get it to read and print the details for lion etc I am looking for some help with my code. I don't need to know the whole code... just trying to figure out how to read from a file in java. I can get it to read one line, but that's it. Any help appreciated. Thanks in advance.
Here is the text from the file I am trying to read from...
Details on lions
Details on tigers
Details on bears
Details on giraffes
Animal - Lion
Name: Leo
Age: 5
*****Health concerns: Cut on left front paw
Feeding schedule: Twice daily
Animal - Tiger
Name: Maj
Age: 15
Health concerns: None
Feeding schedule: 3x daily
package monitoringsystem;

import java.util.Scanner;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.BufferedReader;

import java.io.*;

public class MonitoringSystem {

/**
 * @param args the command line arguments
 * @throws java.io.IOException
 *
 */
public static void main(String[] args) throws IOException {
    Scanner scnr = new Scanner(System.in);
    Scanner inFS = null;

    FileInputStream animals = null;
    FileInputStream habitats = null;
    BufferedReader reader = null;

    String monitorChoice = "";
    String animalChoice = "";
    String habitatChoice = "";

    System.out.println("Would you like to monitor an Animal, Habitat, or exit?");
    monitorChoice = scnr.nextLine();

    if (monitorChoice.equals("Animal")) {
        System.out.println("Choose an animal to monitor: Lion, Tiger, Bear, or Giraffe.");

        animals = new FileInputStream("animals.txt");
        animalChoice = scnr.nextLine();

        File file = new File("animals.txt");
        BufferedReader br = new BufferedReader(new FileReader(file));

       String currentLine = br.readLine();
        while ((currentLine = br.readLine()) != null) {
            if (currentLine.contains(animalChoice)) {
                String nameline = br.readLine();
                String ageline = br.readLine();
                String feedline = br.readLine();
                System.out.println(currentLine);
                System.out.println(nameline);
                System.out.println(ageline);
                System.out.println(feedline);
            }

Now the only issue I have is getting it to omit the line with the ***** and skip to the feeding line. Again...Thanks in advance for any insight.

A: Here is a simple program to read from a file formatted as per your example
package animals;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Animals {
    public static class Animal {
        private String animalType;
        private String name;
        private String age;
        private String healthConcerns;
        private String feedingSchedule;
        public boolean isComplete() {
            return animalType != null && name != null && age != null && age != null && healthConcerns != null && feedingSchedule != null;
        }
        public void loadFrom(BufferedReader in) throws IOException {

            for(String line; !isComplete() && (line=in.readLine()) != null;) {
                line = line.trim();
                if (!line.isEmpty()) {
                    if (line.startsWith("Animal - ")) {
                        animalType = line.split(" - ")[1];
                    } else if (line.contains(":")) {
                        String[] fields = line.split(":");
                        switch(fields[0]) {
                            case "Feeding schedule":
                                this.feedingSchedule = fields[1].trim();
                                break;
                            case "Age":
                                this.age = fields[1].trim();
                                break;
                            case "Name":
                                this.name = fields[1].trim();
                                break;
                            case "Health concerns":
                            default:
                                this.healthConcerns = fields[1].trim();
                                break;
                        }
                    }
                }
            }
        }

        @Override
        public String toString() {
            return "Animal{" + "animalType=" + animalType + ", name=" + name + ", age=" + age + ", healthConcerns=" + healthConcerns + ", feedingSchedule=" + feedingSchedule + '}';
        }
    }
    public static void main(String[] args) throws FileNotFoundException, IOException {
        BufferedReader in = new BufferedReader(new FileReader(args[0]));
        List<Animal> animals = new ArrayList();
        Animal a = null;
        do {
            a = new Animal();
            a.loadFrom(in);
            if (a.isComplete()) {
                animals.add(a);
            }
        } while (a.isComplete());
        for (Animal animal : animals) {
            System.out.println(animal);
        }
    }
}

The output, given your input file looks like this:
package animals;
Animal{animalType=Lion, name=Leo, age=5, healthConcerns=Cut on left front paw, feedingSchedule=Twice daily}
Animal{animalType=Tiger, name=Maj, age=15, healthConcerns=None, feedingSchedule=3x daily}


text:
Q: LRC - Longitudinal Redundancy Check from sting I have to extract the LRC From :  "02 02 30 30 30 30 30 30 30 30 30 30 30 31 31 30 30 1c 35 32 33 1c 1c 2b 30 1c 39 34 36 1c 1c 1c 1c 1c 1c 1c 1c 1c 1c 1c 30 30 1c 1c 1c 1c 1c 1c 03" the corest answer must be : " 3B "
I tested the codes below but the result is wrong .
    public static byte calculateLRC(byte[] bytes)
    {
        int LRC = 0;
        for (int i = 0; i < bytes.Length; i++)
        {
            LRC -= bytes[i];
        }
        return (byte)LRC;
    }

    private static byte calculateLRC2(byte[] b)
    {
        byte lrc = 0x00;
        for (int i = 0; i < b.Length; i++)
        {
            lrc = (byte)((lrc + b[i]) & 0xFF);
        }
        lrc = (byte)(((lrc ^ 0xff) + 2) & 0xFF);
        return lrc;
    }

    public static char CalculateLRC3(string toEncode)
    {
        byte[] bytes = Encoding.ASCII.GetBytes(toEncode);
        byte LRC = 0;
        for (int i = 0; i < bytes.Length; i++)
        {
            LRC ^= bytes[i];
        }
        return Convert.ToChar(LRC);
    }

    public static byte calculateLRC4(byte[] bytes)
    {
        return bytes.Aggregate<byte, byte>(0, (x, y) => (byte)(x ^ y));
    }

I'm waiting for your answer, thank you!!

A: Looking at the Wikipedia article for LRC, it says the pseudocode for LRC is
Set LRC = 0
For each byte b in the buffer
do
    Set LRC = (LRC + b) AND 0xFF
end do
Set LRC = (((LRC XOR 0xFF) + 1) AND 0xFF)

This seems similar to your calculateLRC2 function, however you're doing + 2 instead of the + 1 prescribed above. Might that be the problem?


text:
Q: How to get notifications for changes to a file in ios? I am downloading a file using AFNetworking. But I am not able to keep track of my downloadOperation (i.e. viewController recieving completion callback is dismissed). Is there any api to track the file size changes to compare against the total file size.
I don't want to monitor filesystem changes like these answers:

*

*what-is-the-optimal-way-to-monitor-changes-in-a-directory-with-a-kqueue

*notification-of-changes-to-the-iphones-documents-directory
Can I use KVO to implement this type of behavior.

A: Your problem is a design issue. Your download operation is salient to multiple view controllers. The download is started and owned by a view controller that can go out of scope before the download completes.

*

*Change the download operation to a higher level controller object (like your app delegate). That way controllers can initiate downloads or view status of downloads. You may want to define a protocol that interested view controllers implement to allow you to call specific methods on those view controllers.

*Dispatch messages about your download operation to interested view controllers from that higher level controller.


text:
Q: How do i load my sample data to Azure data lake and visualize in Power Bi? I have a sample data (.CSV)  and I'm able to visualize the same in my Power Bi desktop by using get data->text file. I want to load the same data into Azure data lakes so that i can access it from  get data-> Azure data lake storage in my Power BI.
My azure data factory and my Power Bi accounts are trial ones. How do i load data into my azure data lake? When i try to do it it is asking for my git repository which is not necessary i suppose.

A: To get your sample data into the Data Lake, you can go into the Azure Portal, find the data lake object and find the 'Storage Explorer' option. That will open up a file manager like interface to allow folder creation and upload files.

You can also use Azure Storage Explorer to load the file.
To load the data in a continuing process, you can use Azure Data Factory. You haven't mentioned if your Data Lake is Gen 1 or Gen 2, but the MS Docs website give a good start on how to use a copy activity to push files to the data lake
Gen 1 - https://learn.microsoft.com/en-us/azure/data-factory/load-azure-data-lake-store
Gen 2 - https://learn.microsoft.com/en-us/azure/data-factory/load-azure-data-lake-storage-gen2


text:
Q: Fade out siblings on hover using jQuery I want to fade out sibling elements of a list when an li is hovered on and fade back when hovered off. I know this can be done using CSS but it won't work to the exact same degree as I'd like. How can I achieve this using jQuery?

@import url("https://fonts.googleapis.com/css?family=Anton");
body {
  background: #F4D35E;
}

ul {
  List-style: none;
  width: 1000px;
  margin: 0 auto;
  padding: 0px 100px;
}

ul li {
  display: inline-block;
  color: #DA4167;
  font-family: 'Anton', serif;
  font-size: 300px;
  margin: 0px 50px;
}

ul li:hover {
  color: white;
}

1

2

3

4

A: $('li').hover(
  function() {
    $(this).siblings().addClass('fade-out');
  },
  function() {
    $(this).siblings().removeClass('fade-out');
  }
);

Set the fade out style on .fade-out class.

$(document).ready(function() {
  $('li').hover(
    function() {
      $(this).siblings().addClass('fade-out');
    },
    function() {
      $(this).siblings().removeClass('fade-out');
    }
  );
});
@import url("https://fonts.googleapis.com/css?family=Anton");
body {
  background: #F4D35E;
}

ul {
  List-style: none;
  width: 1000px;
  margin: 0 auto;
  padding: 0px 100px;
}

ul li {
  display: inline-block;
  font-family: 'Anton', serif;
  font-size: 300px;
  margin: 0px 50px;
  color: rgba(218, 65, 103, 1);
  transition: color .2s;
}

ul li:hover {
  color: white;
}

.fade-out {
  color: rgba(218, 65, 103, .5);
}

1

2

3

4


text:
Q: Ascertain Google Streetview function existence Is there a way of ascertaining if a Google Streetview panorama is available from an Android application (i.e. using Java).
No alternatives seem to exist for PHP or Python or other server-side technologies.
The impact of calling Google Streetview where no panorama exists is simply a black screen and a "spinning thing".

A: I created a little hack for this. :)
strings.xml
<string name="html_streetview">    <![CDATA[
<html>
<head>
   <script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
 </head>
<body>
<script type="text/javascript">
 Android.echo();
 var testPoint = new google.maps.LatLng(%1$s, %2$s,true);
 var svClient = new google.maps.StreetViewService();
 svClient.getPanoramaByLocation(testPoint, 50,function (panoramaData, status) {
   if (status == google.maps.StreetViewStatus.OK) {
     Android.hasStreetview();
   } else {
     Android.hasNotStreetview();
   }
 });
</script>
</body>
</html>
]]>
</string>

now add a button for streetview on the activity and put this following code into the onclick method:
    if (webView == null) {
      webView = new WebView(this);
      webView.setVisibility(View.INVISIBLE);
      webView.getSettings().setJavaScriptEnabled(true);
      webView.addJavascriptInterface(new JavascriptCheck(this), "Android");
      webView.setWebViewClient(new WebViewClient() {
          public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
               Toast.makeText(this, "Streetview loading", Toast.LENGTH_SHORT).show();
               super.onReceivedError(view, errorCode, description, failingUrl);
                }
      });
    }

    Toast.makeText(this, "Streetview loading", Toast.LENGTH_SHORT).show();

    webView.loadDataWithBaseURL(baseurl,
      getString(R.string.html_streetview, latitude, longitude), "text/html", "UTF-8", baseurl);

And now the inner Class of the activity:
public class JavascriptCheck {
   private final Context context;

   public JavascriptCheck(Context context) {
      this.context = context;
   }

   public void echo() {
       Log.d("JavascriptChecker", "javascript called");
   }

   public void hasStreetview() {
       pushStreetviewState(true);
   }

   public void hasNotStreetview() {
      pushStreetviewState(false);
   }

   private void pushStreetviewState(final boolean hasStreetview) {
       Log.d("JavascriptChecker", hasStreetview);
       // TODO do your stuff needed here
   }
}

this a a rather bad workaround but probably can help. :)

A: Just to further on the excellent answer from alos, here is a script which will return you the angle needed so that streetview will launch pointed at the correct coordinates:
<string name="html_streetview_bearing"> <![CDATA[
<html>
<head>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
</head>
<body>
<script type=\"text/javascript\">
  var testPoint = new google.maps.LatLng(%1$s, %2$s,true);
  var svClient = new google.maps.StreetViewService();

  svClient.getPanoramaByLocation(testPoint,100,function (camera, status) {

  if(camera!=null) {

    var location = camera.location;
    var latLng = location.latLng;
    lat2 = latLng.lat();
    lon2 = latLng.lng();
    lat1 = testPoint.lat();
    lon1 = testPoint.lng();

    var dLon = lon1 - lon2;
    var y = Math.sin(dLon) * Math.cos(lat2);
    var x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
    var bearing = Math.atan2(y, x) * (180 / Math.PI);
    Android.setStreetviewAngle(bearing);

  }

  }
);
</script>
</body>
</html>
]]>
</string>

Note: The return value needs to be altered so that
bearing = (bearing + 180) % 360;

to give you the correct final value. I do this in native code.
UPDATED ANSWER: Now working on Android 3.0 and greater.

A: Thanks a bunch Alos and steemcb, I was stuck with street view showing the wrong property or a blank screen. I hope google comes out with a native android SDK, until then both your codes ROX!!
I had to make a few adjustments before I could use the code. Here is my implementation.
strings.xml
<string formatted="false" name="html_streetview">
<html>
  <head>
    <script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false\" type=\"text/javascript\"/>
  </head>
  <body>
    <script type=\"text/javascript\">
      var testPoint = new GLatLng(%1$s, %2$s);
      var svClient = new GStreetviewClient();

       svClient.getNearestPanoramaLatLng(testPoint,function(camera){
          if (camera !== null){
               lat2 = camera.lat();
               lon2 = camera.lng();
               lat1 = testPoint.lat();
               lon1 = testPoint.lng();

               dLon = lon1 - lon2;
               y = Math.sin(dLon) * Math.cos(lat2);
               x = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
               var bearing = Math.atan2(y, x) * (180 / Math.PI);
               //had to get rid of this line it was causing formatting exceptions
               // I moved this logic to the inner class
               //bearing = (bearing + 180) % 360;
               Android.setStreetViewAngle(bearing);
           }
           //had trouble with bearing taking long to calculate and end up with 0.0 value in the uri. So I put it in here after when bearing is calculated. Not pretty.. but it works for me
            svClient.getNearestPanoramaLatLng(testPoint, function (nearest) {
            if ((nearest !== null) && (testPoint.distanceFrom(nearest) <= 100)) {
              Android.hasStreetview(true);
            }
            else {
              Android.hasStreetview(false);
            }
           });
      });

</script>
  </body>
</html>
</string>

Private Inner Class
    private final Context context;
        private double bearing;

        public JavascriptCheck(Context context) {
          this.context = context;

        }

        public void hasStreetview(boolean hasStreetview) {
          if (hasStreetview) {
            String uri = "google.streetview:cbll=" + propDetailInfo.getLatitude() + "," + propDetailInfo.getLongitude() +
              "&cbp=1,"+ bearing + ",,1,1.0&mz=14";

            Utils.printDebug("URI: " + uri);
            Intent streetView = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
            startActivity(streetView);
          } else {
            Toast.makeText(context, "Sorry Streetview not available for this address", Toast.LENGTH_LONG).show();
          }
        }
        public void setStreetViewAngle(double bearing){
            bearing = (bearing + 180) % 360;
            this.bearing = bearing;
        }

        public void toast(String part) {
          Toast.makeText(context, part, Toast.LENGTH_SHORT).show();
        }

        }

A: A way to do that would be to use Google Street View Image API to check whether Google Street View exist or not.
https://developers.google.com/maps/documentation/streetview/
It returns an image with a different file size when Street View at a particular co-ordinates exist,than when it doesn't
http://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,%20-73.988354&fov=90&heading=235&pitch=10&sensor=false

You can compare these images and check if it exist or not.


text:
Q: Reading whitespace when asking user input C I'm having issues trying to read a white space character in C. What I want to do is read user input when asking for a first and last name.
So for example, I prompt the user to enter their name, they type in something like "Peter Smith". With that info, I want to write it to a file.
When it writes it to a file, the file only reads the last name "Smith". How can I read the whole string?
Here's how I asked:
printf("\nPlease enter your first and last name:  \n");
scanf("%[^\n]", name);
fgets(name, sizeof(name), stdin);

A: I don't think your problem lies in the snippet you posted. Here's an example program I wrote on my Linux system to try and pinpoint the issue:
#include <stdio.h>

int main()
{
    char name[128];
    int  num_scans = 0;
    FILE *out = fopen("name.txt", "w");

    if(out == NULL)
    {
        printf("Failed to open file for write.\n");
        return 1;
    }

    printf("\nPlease enter your first and last name:  \n");
    num_scans = scanf("%127[^\n]", name);

    if(num_scans < 1)
    {
        printf("Error reading name.\n");
        return 2;
    }

    fprintf(out, "%s\n", name);

    fclose(out);

    return 0;
}

This appeared to work for me:
$cat name.txt
Peter Smith

If you post the code you used to write the name to a file, that might reveal the source of the error.

A: The code is working correctly. The fgets call replaces the value you read for the first name.
You should stick to one scheme of input. When you switch between input paradigms "strange" things happen. (Technically they are exactly what is supposed to happen, but typical users tend to not be too precise about exactly how each function works, and what state the input stream is left in.)


text:
Q: Random Local Notification in background I want random Local Notification (Text and Sound) in every minute. I am using this below code:
self.randomIndex_text  = arc4random() % [self.array_motivation count];
self.randomIndex_alarm = arc4random() % [self.array_alarm count];
NSLog(@"text %d, alarm %d",self.randomIndex_text, self.randomIndex_alarm);

This code perfectly works for
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notif
{
notif.soundName = [NSString stringWithFormat:@"%@.mp3", [self.array_alarm objectAtIndex:self.randomIndex_alarm]];
    [self _showAlert:[NSString stringWithFormat:@"%@",[self.array_motivation objectAtIndex:self.randomIndex_text]] withTitle:@"Daily Achiever"];
}

Display alert from above code and on Ok of alert this below method call:
-(void)insert:(NSDate *)fire
{
    self.localNotification = [[UILocalNotification alloc] init];

    if (self.localNotification == nil)
        return;

    self.randomIndex_text  = arc4random() % [self.array_motivation count];
    self.randomIndex_alarm = arc4random() % [self.array_alarm count];
    NSLog(@"text %d, alarm %d",self.randomIndex_text, self.randomIndex_alarm);

    self.localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:refTimeIntrval];
    self.localNotification.timeZone = [NSTimeZone defaultTimeZone];
    self.localNotification.alertBody = [NSString stringWithFormat:@"%@",[self.array_motivation objectAtIndex:self.randomIndex_text]];
    self.localNotification.soundName = [NSString stringWithFormat:@"%@.mp3",[self.array_alarm objectAtIndex:self.randomIndex_alarm]];
    self.localNotification.alertAction = @"View";
    self.localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber]+1;
    self.localNotification.repeatInterval=NSMinuteCalendarUnit;

    NSLog(@"alertBody %@,soundName %@", self.localNotification.alertBody, self.localNotification.soundName);
    [[UIApplication sharedApplication] scheduleLocalNotification:self.localNotification];
}

but does not work in background. I just put this above random method in
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);
    bgTask = [application beginBackgroundTaskWithExpirationHandler: ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [application endBackgroundTask:self->bgTask];
            self->bgTask = UIBackgroundTaskInvalid;
        });
    }];

    dispatch_async(dispatch_get_main_queue(), ^{
        while ([application backgroundTimeRemaining] > 1.0)
        {
            UILocalNotification *localNotif = [[UILocalNotification alloc] init];
            if (localNotif)
            {
                self.randomIndex_text  = arc4random() % [self.array_motivation count];
                self.randomIndex_alarm = arc4random() % [self.array_alarm count];
                NSLog(@"tempmethod text %d, alarm %d",self.randomIndex_text, self.randomIndex_alarm);

                localNotif.fireDate = [[NSDate date] dateByAddingTimeInterval:refTimeIntrval];
                localNotif.alertBody = [NSString stringWithFormat:@"%@",[self.array_motivation objectAtIndex:self.randomIndex_text]];
                localNotif.soundName =[NSString stringWithFormat:@"%@.mp3",[self.array_alarm objectAtIndex:self.randomIndex_alarm]];
                localNotif.alertAction = NSLocalizedString(@"Read Msg", nil);
                localNotif.applicationIconBadgeNumber = 1;
                [localNotif setRepeatInterval:NSMinuteCalendarUnit];
                [application presentLocalNotificationNow:localNotif];

                NSLog(@"sound: %@, alertAction: %@, alerBody: %@, ref: %f, str_time: %@",localNotif.soundName, localNotif.alertAction, localNotif.alertBody, refTimeIntrval, str_Time);

                [self performSelector:@selector(bgmethodd) withObject:nil afterDelay:refTimeIntrval];
                break;
            }
        }
        [application endBackgroundTask:self->bgTask];
        self->bgTask = UIBackgroundTaskInvalid;
    });
    NSLog(@"smh: %d,%d,%d",self.seconds, self.minutes, self.hours);
    }
}

One more thing i noticed when i do debug that applicationDidEnterBackground call at one time only (i.e when application moves in background). After that no any method call till application open again but still i got notification text and sound continoulsy. But this text and sound is not random.
Please suggest me some idea and share your knowledge that from where this notification text and sound come when no any method call in background. And is it possible to make notification random in background.
Thanks in advance.

A: The first notification that you schedule when the app goes in background is repeating with interval NSMinuteCalendarUnit, and therefore the app shows only that notification every minute.
In order to get random alerts and sounds, the local notification needs to execute some code in background that will generate the next random sound and alert, which is not possible.
One way to do this is to schedule 64 (max) local notifications in advance with random sounds and alerts. When the user opens the app, you can see how many notifications were fired in background, and reschedule them.
To be sure that local notifications will be fired even if the user doesn't open the application during those 64 notifications, the last notification needs to be repeating with interval NSMinuteCalendarUnit. So after the first 63 notifications, you will lose the randomness, but if the user opens the app frequently this will not be a problem.


text:
Q: How can I give another user access to my Azure portal resources? I am trying to give other users access to my resources in the Azure portal. I am trying to add them as a Contributor, but it seems like they are not able to see the resources when they login to the Azure portal.
Here's the access control list for the VM:

Any ideas why they can't see the resource when they login to the portal?
They are a Contributor.

A: When you add a user to an Azure subscription, s/he is also added to the directory if s/he isn't already there. This is considered an "invitation" that must be accepted before the user can get access. Tell the person to check their email, if this is the first time the email address has been added to a subscription in the directory. (Note that personal subscriptions are usually created along with a new directory whereas company subscriptions are usually in the company's directory.)
After accepting the invitation, s/he will need to switch to the directory before the subscription will be visible. You can do that in the top-right, like Juunas mentioned in the comment above. Here's a link to the directory switcher: https://portal.azure.com/#menu/account.

A: Steps to reproduce-
As owner:
Go to Resource Group you want to give access to:
Go to IAM:
Go to 'Add ROLE ASSIGNMENTS'
Search the name you want to give access to:
Select the Role (Contributor in your case)
Click Add and they will recieve an email.


text:
Q: Dual booting Ubuntu & Windows from an encrypted disk I have a dual boot system with Windows 10 and Ubuntu 16.04. Windows is installed on sda1 and Ubuntu on sda5. Everything was working fine until I encrypted the whole disk from windows using Symantec PGP Desktop 10.
Now when I boot the computer, I get the Symantec login screen and after entering the username and password, I get the grub entries. I can log in to windows by choosing the appropriate entry from grub but if I choose Ubuntu, it doesn't boot shows the error
uncleared pch fifo underrun on pch transcoder a

I can see my Linux file system if I run ls (hd0,5)/ from the grub command line. This proves that the files are intact.
I tried these commands in the grub command prompt:
set root=(hd0,5)
linux /vmlinuz root=/dev/sda5
initrd /initrd.img
boot

This gives me another error saying
mounting /dev/sda5 on /root failed: No such device

Is there any way to boot Ubuntu without decrypting the whole disk?

A: Unfortunately, no, you'll have to decrypt your drive.
As mentioned in the manual for the Symantec software, a special kernel module is installed to allow the system to see and otherwise be aware of the fact that encryption is taking place. Therefore, everything throws an error and boot fails.
Windows is unaffected because it's aware that encryption is going on, and can handle it properly due to the proper drivers being installed and loaded in boot-time.
Apparently, Symantec's tools do support full disk encryption, as per their help. However, the encryption programs must be installed on all operating systems before encryption takes place. You may use either OS to actually run the decryption.
Therefore, to resolve this issue, just decrypt your drive. Then, install the Symantec program (same version) on Linux, and then re-encrypt from either operating system. Both OSes will have the required drivers/modules, and boot should run normally.


text:
Q: Wordpress plugin that allows tagging of pictures Is there a wordpress plugin that would allow you to tag a person? I'm using a buddypress theme and I'm not sure if there's plugin that would tag a picture to a user.
I've been looking in the internet but I can't find any. Hope someone would help.
Thanks! :)

A: I think this is what ur looking for
http://wordpress.org/extend/plugins/demon-image-annotation/


text:
Q: I get `this.getOptions is not a function` error when using coffee-loader on Rails 6.1 I created a brand new Rails app with Ruby 2.7.2 and Ruby on Rails 6.1.3:
rails new rails6

Then I installed the CoffeeScript compiler using the Rails command:
rails webpacker:install:coffee

But when i started the webpack-dev-server, he was unable to compile correctly:
                                      Asset       Size        Chunks                         Chunk Names
     js/application-30c16ea0138c526e20f5.js    515 KiB   application  [emitted] [immutable]  application
 js/application-30c16ea0138c526e20f5.js.map    579 KiB   application  [emitted] [dev]        application
    js/hello_coffee-5eba0c58c2666f949e88.js    395 KiB  hello_coffee  [emitted] [immutable]  hello_coffee
js/hello_coffee-5eba0c58c2666f949e88.js.map    444 KiB  hello_coffee  [emitted] [dev]        hello_coffee
                              manifest.json  710 bytes                [emitted]

ERROR in ./app/javascript/packs/hello_coffee.coffee
Module build failed (from ./node_modules/coffee-loader/dist/cjs.js):
TypeError: this.getOptions is not a function
    at Object.loader (/Users/iwan/dev/rails/rails6/node_modules/coffee-loader/dist/index.js:21:24)
ℹ 「wdm」: Failed to compile.

How to fix this issue?

A: I found that downgrading coffee-loader to the version 1.0.1 removed the error.
Edit package.json and change the version from
"coffee-loader": "^2.0.0",

to
"coffee-loader": "1.0.1",

Then run yarn install --check-files to apply the change.
Happy days!


text:
Q: undefined post error in http angular2 I am trying to post the data to database,but i am getting the error "cannot read the property 'post' of undefined".I am trying to learn angular2 can someone help me.
 import {Component} from '@angular/component'
 import {FormBuilder, Validators, ControlGroup, FORM_DIRECTIVES} from '@angular/common';
 import {HTTP_PROVIDERS, Http, Response} from '@angular/http';

 @Component({
   selector: 'profile-form',
   directives: [FORM_DIRECTIVES],
   templateUrl: './components/profile/profile.html',
   providers: [FormBuilder, HTTP_PROVIDERS]
 })
 export class Profile {
   data;
   form;

   constructor(private http: Http) {}
   onSubmit(): void {

     this.http.post(
         'http://localhost/a2server/index.php/profile/addprofile',
         JSON.stringify({
           firstname: 'bar',
           lastname: 'foo'
         }))
       .subscribe((res: Response) => {
         this.data = res.json();

       });
   }
 }


text:
Q: Incorrect syntax near the keyword 'SELECT'. Incorrect syntax near ')' when attempting using an inner select I've seen the error before for a different reason but how can I fix this?
INSERT INTO [dbo].[XXX] ([ID], [aaa], [bbb], [ccc])
VALUES (SELECT NEXT VALUE FOR dbo.S_SHIPPING_ID_SEQ, @aaa, @bbb, @ccc)

Thank you for the help

A: Just use insert . . . select.  No values is needed:
INSERT INTO [dbo].[XXX] ([ID], [aaa], [bbb], [ccc])
    SELECT NEXT VALUE FOR dbo.S_SHIPPING_ID_SEQ, @aaa, @bbb, @ccc;

Or, if you really like VALUES, use a subquery:
INSERT INTO [dbo].[XXX] ([ID], [aaa], [bbb], [ccc])
    VALUES (SELECT NEXT VALUE FOR dbo.S_SHIPPING_ID_SEQ), @aaa, @bbb, @ccc);

And, actually, this should also work:
INSERT INTO [dbo].[XXX] ([ID], [aaa], [bbb], [ccc])
    VALUES (NEXT VALUE FOR dbo.S_SHIPPING_ID_SEQ, @aaa, @bbb, @ccc);

But why not just declare ID to be an identity and use:
INSERT INTO [dbo].[XXX] ([aaa], [bbb], [ccc])
    VALUES (@aaa, @bbb, @ccc);


text:
Q: Firebase FCM error: Unregistered registration token I use cordova-plugin-fcm, and call its two functions onTokenRefresh, and getToken to get the FCM token of my device (Android). They both give me the same FCM token value, which used to work and my app used to receive notifications.
However now, I cannot send any notifications to the device anymore even from Firebase console which gives me this error:
Unregistered registration token

I haven't uninstalled the app or changed it. Why does it say this token is unregistered although getToken and onTokenRefresh seem to work and give me the same fcm token that I had from the beginning?


text:
Q: How to write those expressions in coffee script? I'm trying to rewrite a javascript application to coffee script. Though, I can't find how to transform those 2 expressions (I added what I tried beneath). Can you help me please ?
var config = require(path.join(__dirname, 'configs'))[env];
(What I tried) : config = require path.join __dirname, 'configs'[env]

server.use(require('node-compass')({mode: 'expanded'}));
(What I tried) : server.use require 'node-compass (
    mode: 'expanded'
)

Thanks for your help !

A: config = require(path.join(__dirname, 'configs'))[env]
server.use(require('node-compass') mode: 'expanded')


text:
Q: Chain rule for Newton-derivative I'm looking for properties of the Newton-derivative, defined as follows: A function $F \colon X \to Y$ is Newton differentiable at $x\in X$ if there exists $\varepsilon>0$ and a function $G\colon B_\varepsilon(x) \to L(X,Y)$ such that
\begin{align*}
\lim_{y\to0} \frac{\|F(x + y) -F(x) -G(x+y)[y]\|_Y}{\|y\|_X} = 0.
\end{align*}
$G$ is called Newton-derivative.  Can you provide me with a proof (or any reference) for a chain rule for this differential?
Actually, I need to know about the Newton-derivative of the function
\begin{align*}
L^2(\Omega) \ni u \mapsto \max(-1,\min(1,u)),
\end{align*}
which hopefully exists... Thanks a lot, Malte.


text:
Q: sudo not executing bashrc as expected Overall issue is when I log in, my prompt appears correctly formatted as per the /etc/bashrc but when I sudo to another user using bash, the prompt gets fubar'd.
Essential formatting in the /etc/bashrc
PROMPT_COMMAND='printf "\033]0;%s@%s:%s\007" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/~}"'

...and...
prompt_host=`/bin/hostname`

Sequence:
I log into my terminal as myuser.  My prompt is properly formatted as matching the /etc/bashrc above:
myuser@the.hostname.fully.qualified pwd :

Though the above implies my default shell program appears to be bash, I believe I'm using sh:
echo $SHELL     <---not very meaningful but I expect someone will ask me to run this
/bin/sh

ps -p `echo $$`
  PID TTY          TIME CMD
 7105 pts/2    00:00:00 sh     <---which looks to be an interactive shell (no dash)

ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
72338     9321  9320  0 01:07 pts/3    00:00:00 -sh   <---or is it a login shell????

./filethatsnotthere.sh
-sh: ./filethatsnotthere.sh: No such file or directory

And last, but not least...
getent passwd myuser
myuser:x:72338:25000:My Name:/home/myuser:/bin/sh

Also, it's apparent that the /etc/profile is being sourced because:
echo $prompt_host
the.hostname.fully.qualified

So looks like sh and that the /etc/profile is being sourced.  BUT this confuses me...
 ls -l `which sh`
lrwxrwxrwx. 1 root root 4 Jan 12  2018 /bin/sh -> bash

...sigh...But even if we go with the theory that I'm using sh, I then sudo to newuser using bash. newuser has a profile setup as newuser .bash_profile which sources newuser .bashrc which sources the /etc/bashrc.
But the prompt for newuser isn't working right and it's apparent that none of the newuser profile is run. It totally loses the hostname in the prompt
sudo -u newuser bash
newuser@ pwd         <---no hostname

I know NONE of the newuser profile is run because I put echo statements in them to confirm when they're run, and they don't display.  Even so, I've confirmed that newuser is truly running bash:
ps -f
UID        PID  PPID  C STIME TTY          TIME CMD
newuser  11717 11715  0 03:47 pts/1    00:00:00 bash

ps -p `echo $$`
  PID TTY          TIME CMD
11717 pts/1    00:00:00 bash

./filethatsnotthere.sh
bash: ./filethatsnotthere.sh: No such file or directory

The /etc/profile is not being run (which makes sense since this is an interactive, not login, shell):
echo $prompt_host
<crickets....>

BUT - neither is newuser's startup files in the /home/newuser directory...So, if I'm using sudo to a user with command bash, why isn't that user's bash profile files being sourced?  Since it's an interactive shell, even though the /etc/profile is not directly being sourced I would still expect the newuser's files to be run.

A: sudo can be configured to set $HOME to match the new user when switching users, or not to. In your case, it appears it is set to not switch $HOME. That can be useful when you want to switch to user accounts that are dedicated to specific service applications, but still want to keep using your personal shell configuration and other settings.
And ~/.bashrc is actually just a shorthand for $HOME/.bashrc.
So when you do sudo -u newuser bash, sudo switches the username to newuser but $HOME is still set to /home/myuser.
When bash attempts to execute ~/.bashrc, it has a slight problem: as newuser, it might have no access to read /home/myuser/.bashrc unless you have specifically granted that access. If you haven't, that is probably why .bashrc is getting skipped. Because $HOME is still set to /home/myuser, there will be no attempt to execute /home/newuser/.bashrc.
If you want sudo to set HOME=/home/newuser, you can:

*

*use the -H option with the sudo command: sudo -Hu newuser bash

*or add Defaults>newuser always_set_home to your sudoers file to automatically set the home directory when switching to newuser only

*or add Defaults:myuser always_set_home to sudoers file to automatically set the home directory to match the new identity when myuser is running any sudo commands

*or add Defaults always_set_home to sudoers file to force this behavior for all sudo commands on the system. (Some Linux distributions have this enabled by default.)

If you don't especially want to switch the home directory when switching users, then you'll need to make sure the new user can read your personal shell startup files instead.
The minimal permissions you'd need to allow for sudo -u newuser bash to run /home/myuser/.bashrc are:

*

*a search permission to /home/myuser

*a read permission to /home/myuser/.bashrc
If there is no convenient user group that would be common to both myuser and newuser, and ACLs are not available (i.e. traditional Unix-style permissions only), this would be the traditional way to do it:
chmod 711 /home/myuser          # i.e. directory permissions drwx--x--x
chmod 644 /home/myuser/.bashrc  # i.e. file permissions      -rw-r--r--

If ACLs are available for the filesystem containing your home directory, you could do this instead to grant the minimal necessary access:
setfacl -m u:newuser:x /home/myuser
setfacl -m u:newuser:r /home/myuser/.bashrc

If the permissions of the home directory were initially drwx------, after this command the permissions to /home/myuser would look like drwx--x---+. To check the complete ACL, use getfacl:
$ getfacl /home/myuser
getfacl: Removing leading '/' from absolute path names
# file: home/myuser
# owner: myuser
# group: myuser
user::rwx
user:newuser:--x
group::---
mask::--x
other::---


text:
Q: PHP preg_replace needs improvement Ok, I have a string as follows:
$disallowedBBC = 'abbr|acronym|anchor|bdo|black|blue|br|color|email|flash|font|ftp|glow|green|html|hr|img|iurl|li|list|ltr|url|quote';

And than a preg_replace on the actual string ($message variable) that should get rid of all bbc code that is not allowed according to the $disallowedBBC variable:
$message = preg_replace("/\[($disallowedBBC)[^]]*](.*?)\[\/($disallowedBBC)\]/is", "$2", $message);

But, for some reason, the [hr] tag is getting past this preg_replace.  So, in this case:
$message = '[hr]Test';

It outputs the [hr] tag, but should remove it.  What is wrong with my regex?
Basically...
How to change it so that it removes all [hr] and/or [hr]Test[/hr] altogether? But would also need to get rid of instances where [url=http://someurl.com]Some Url[/url].  And it should remove [color=red] from a string as follows: [color=red]Testing
For example, it needs to get rid of [{tag}] and if it has a closing tag [/{tag}], but if there is no closing tag, it needs to get rid of the opening tag, and vice versa.  It should be able to capture anything within the {tag} that is within the brackets as well, such as:  [quote author=Solomon time=7834783470]Just a quote here[/quote] Additional text here...
So, this should output:  Just a quote here Additional text here...

A: I think you need two preg_replaces.  One to first get rid of the pairs of [hr]...[/hr] and then a second to get rid of any remaining [hr]...
$message = preg_replace("/\[($disallowedBBC)[^\]]*](.*?)\[\/($disallowedBBC)\]/is", "$2", $message);
$message = preg_replace("/\[($disallowedBBC)[^\]]*]/is", "", $message);

I you try to do it in one step, then things like "abc[br]blahblah[hr]gak[/hr]def" will become "abcdef".  You might be able to do it if you can place restrictions on the blahblah portion.
You can, of course, combine these into one preg_replace call by using the array syntax (but remember that the order matters):
$patterns = array("/\[($disallowedBBC)[^\]]*](.*?)\[\/($disallowedBBC)\]/is",
                  "/\[($disallowedBBC)[^\]]*]/is", );
$replacements = array("$2", "");
$message = preg_replace($patterns, $replacements, $message);


text:
Q: How to comment in package-scripts.js to show up in package.json? Goal
I want to display comments of my nps commands from package-scripts.js in my package.json like this:

Tried
I actually don't know where the content of this overlay ("Run by the 'npm test' command") is coming from (vscode, npm, nps?). I've looked up all of their GitHub repositories without success.
I've tried to add comments the following way with no results:
// package-scripts.js
module.exports = {
  scripts: {
    /** Build image */
    build: "docker build"
  }
}

// package.json
{
  scripts: {
    "build": "nps build"
  }
}

Is it possible at all? How is the shown comment made?

A: This seems to work with:

*

*json schemas in your vscode settings or

*switching to jsonc mode in vscode

Both are documented here: https://code.visualstudio.com/docs/languages/json.
I suggest to extend the package.json schema https://json.schemastore.org/package to fit your needs, but i don't have any experience with displaying comments as tooltips in vscode.


text:
Q: Can transfinite induction be defined as axiom scheme in FOL on bin-tree structures? Transfinite induction requires a second order induction hypothesis. So, that can not be defined as axiom scheme in FOL.
However, if I look to Goodstein's theorem en the Hydra games, then they have to do with tree structures.
Suppose we have in FOL a binary tree. This has an element 0 and a predicate that makes a pair P(x,y). We have the expected definitions on these tree like structures.
Now, is it possible to define an axiom scheme on this binary tree structure, that is strong enough for transfinite induction (to proof Goodstein's theorem)? Or, is a second order induction hypothesis always necessary, even when when we start to make schemes on tree structures? And why?
Lucas
Edit:
I think my question was not fully clear yet.
If you have the natural numbers with the ordinals, you can make an axiom scheme as schoppenhauer suggests in the answer.
However, this requires definitions of ordinal. If you encode the ordinals in the natural numbers (using FOL + PA + addition and multiplication), you can not proof that these numbers are well ordered (I assume this base on the results of reverse mathematics). You need second order logic for that. So, the only option here is to define the ordinals as is and not base it on PA.
If we do so, we have defined the ordinals and the axiom scheme of transfinite induction and with that we should be able to prove Goodstein's theorem.
But, I am not so font on ordinals. So, my question is if it is possible to make a kind of induction axiom scheme on binary trees (instead of ordinal numbers), that is stronger than normal induction. FOL + these binary trees + binary tree induction axiom scheme, should be capable of proving Goodstein theorem.
I would like this, because I consider a binary tree as a much more simpler concept than ordinals.
I think this should be possible, based on the observation of the Hydra games which are based on Goodstein.

A: I'm struggling to figure out what is it that you actually want. You can consider induction on an arbitrary well-founded relation instead of an ordinal (and only on well-founded relations, as induction actually implies that the relation is well-founded). (This covers all the various special cases like transfinite induction, structural induction, $\in$-induction, and whatnot.) If the relation is reasonably encoded, its induction scheme should have the same proof-theoretic strength as induction on the ordinal which is the rank of the relation. Thus, the only thing you can achieve is to have ordinals represented nonuniquely by elements of a fancy, more complicated structure. As a matter of fact, this is what you do anyway, since e.g. in the usual representation of ordinals below $\varepsilon_0$ in arithmetic using Cantor normal form, ordinals are identified with certain trees. So the answer to your question appears to be "yes, just call them trees instead of ordinals".

A: Not sure whether I understand what exactly you mean. But transfinite induction is formally almost the same as "finite" induction, the only difference lies in the limit-ordinal-case. I.e. "finite" induction is $\varphi(0)\rightarrow\forall n(\varphi(n)\rightarrow\varphi(n+1))\rightarrow\forall n\varphi(n)$ while transfinite induction is $\varphi(0)\rightarrow\forall n(\varphi(n)\rightarrow\varphi(n+1))\rightarrow (n\in \mbox{Lim}\rightarrow\forall m \lt n (\varphi(m))\rightarrow\varphi(n))\rightarrow\forall n\varphi(n)$ (or just $\varphi(0)\rightarrow\forall n (\forall m\lt n(\varphi(m))\rightarrow\varphi(n))\rightarrow\forall n\varphi(n)$).
Of course, in higher order logic, you can quantify over $\varphi$. In first order logic, you will just put in infinitely many induction axioms, with $\varphi$ ranging over all formulas with one free variable. Thats why it is called "axiom scheme" rather than just "axiom", its a scheme to produce infinitely many axioms.
I hope I got your question right.

A: Assuming I understand your comment right, I don't know that binary trees are enough to get there, but arbitrary finite trees should certainly be.  One natural induction-esque principle on trees would be the Konig's lemmas; the weak version (WKL0) simply states that every infinite binary tree has an infinite path, while the strong version makes the same claim for an infinite tree where the nodes can have arbitrary (finite) degree.  According to Reverse Mathematics (or at least the Wikipedia page on it!), the 'proof ordinal' for WKL0 is just ωω, whereas that for ACA0 (which full Konig's lemma is equivalent to) is ε0.  So you may be able to derive a proof based on Konig's lemma, but it seems likely that binary trees may not have 'enough strength' to get you there.

A: Does the wiki article http://en.wikipedia.org/wiki/Structural_induction help?


text:
Q: I want to find $\lim\limits_{x\to 5}\frac{2^x-2^5}{x-5}$ without using l'Hopital's rule I want to solve this limit without using L'Hopital's rule:
$$\lim_{x\to 5}\frac{2^x-2^5}{x-5}.$$
And thanks.

A: First write $2^x$ as $e^{x \ln 2}$. Then let $x=5+t$ so that you get a limit as $t \to 0$. Now you should be able to use the standard limit $(e^z-1)/z \to 1$ as $z\to 0$.

A: $\lim_{x\to 5}\frac{2^x-2^5}{x-5}=\lim_{x\to 5}\frac{f(x)-f(5)}{x-5}=f'(5)$, where $f(x)=2^x$.  $f'(x)=\cdots$ so $f'(5)=\cdots$

A: In principle, you can use L'Hopital's Rule here because both numerator and denominator are differentiable, they both have a limit of $0$ as $x\to 5$, and the limit of the quotient $(2^x-2^5)'/(x-5)'$ exists as $x\to 5$.
Morally, however, you should not use L'Hopital's Rule; the reason is that in order to use L'Hopital's Rule, you need to know what the derivative of $2^x$ is. But the derivative of $2^x$ (at least, at $x=5$) is given precisely by the limit you are trying to do. It would be like using L'Hopital's Rule in order to find $\lim\limits_{\theta\to 0}\frac{\sin\theta}{\theta}$; the problem is that to use L'Hopital's Rule you need ot know the derivative of $\sin\theta$, and in order to know the derivative of $\sin\theta$ you most likely had to figure out this limit in the first place.
So it's a good thing that you don't want to use L'Hopital's Rule here. Instead, you need to recognize this limit as the limit that defines $f'(5)$ with $f(x)=2^x$, and solve it accordingly, whether using the Chain Rule (since $2^x = e^{\ln(2)x}$), or by some other similar method.

A: You could do this as well. Write $x = 5+h$. So as $x \to 5$, $h \to 0$. Therefore the required limit is
\begin{align*}
\lim_{h \to 0 } \frac{2^{5+h}-2^{5}}{h} &= 2^{5} \cdot \lim_{h \to 0}\Bigl[ \frac{2^{h}-1}{h}\Bigr] \\ &= 2^{5} \cdot M
\end{align*}
where $M$= Some value in $\log$. I forgot the formula.
ADDED: The formula is $$\lim_{x \to 0} \frac{a^{x}-1}{x} = \log{a}$$


text:
Q: lapply with nested list I have a nested list and I'd like to lapply as.data.frame on the deepest nesting level and then rbindlist (from data.table) everything. Here's what my data looks like:
a <- list(date="2017-01-01",ret=1:5)
b <- list(date="2017-01-02",ret=7:9)
lvl3 <- list(a,b)
lvl2 <- list(lvl3,lvl3)
lvl1 <- list(lvl2,lvl2,lvl2)

If I only had lvl3, I would to this to tranform into a data.frame and rbind the data:
rbindlist(lapply(lvl3,as.data.frame))
         date ret
1: 2017-01-01   1
2: 2017-01-01   2
3: 2017-01-01   3
4: 2017-01-01   4
5: 2017-01-01   5
6: 2017-01-02   7
7: 2017-01-02   8
8: 2017-01-02   9

How would I do that from lvl1 and rbind all nested data.frames? This does not work:
rbindlist(lapply(lvl1,as.data.frame))
Desired result contains 48 rows:
         date ret
 1: 2017-01-01   1
 2: 2017-01-01   2
 3: 2017-01-01   3
 4: 2017-01-01   4
 5: 2017-01-01   5
 6: 2017-01-02   7
 7: 2017-01-02   8
 8: 2017-01-02   9
 9: 2017-01-01   1
10: 2017-01-01   2
11: 2017-01-01   3
12: 2017-01-01   4
13: 2017-01-01   5
14: 2017-01-02   7
15: 2017-01-02   8
16: 2017-01-02   9
17: 2017-01-01   1
18: 2017-01-01   2
19: 2017-01-01   3
20: 2017-01-01   4
21: 2017-01-01   5
22: 2017-01-02   7
23: 2017-01-02   8
24: 2017-01-02   9
25: 2017-01-01   1
26: 2017-01-01   2
27: 2017-01-01   3
28: 2017-01-01   4
29: 2017-01-01   5
30: 2017-01-02   7
31: 2017-01-02   8
32: 2017-01-02   9
33: 2017-01-01   1
34: 2017-01-01   2
35: 2017-01-01   3
36: 2017-01-01   4
37: 2017-01-01   5
38: 2017-01-02   7
39: 2017-01-02   8
40: 2017-01-02   9
41: 2017-01-01   1
42: 2017-01-01   2
43: 2017-01-01   3
44: 2017-01-01   4
45: 2017-01-01   5
46: 2017-01-02   7
47: 2017-01-02   8
48: 2017-01-02   9

A: You can build your own recursive function, à la
f <- function(l) {
  data.table::rbindlist(lapply(l, function(x) {
    if(all(sapply(x, is.atomic))) as.data.table(x) else f(x)
  }))
}
f(lvl1)

This returns an ordinary data.table of 48 rows and 2 columns.
Also note that this works with lvl1, lvl2, and lvl3 without modifications.

A: @docendo's general solution is best, in my opinion, but if you know that it is only nested two-deep...
library(magrittr)

lvl1 %>%
  unlist(recursive=FALSE) %>%
  unlist(recursive=FALSE) %>%
  lapply(as.data.table) %>%
  rbindlist

From @lmo, here's the pipeless analogue (that doesn't require magrittr):
do.call(
  rbind,
  lapply(
    unlist(unlist(lvl1, recursive=FALSE), recursive=FALSE),
    as.data.frame
  )
)

A: There's probably more elegant ways, but combining data.table with nested foreach loops:
library(foreach)
library(data.table)

a <- list(date="2017-01-01",ret=1:5)
b <- list(date="2017-01-02",ret=7:9)
lvl3 <- list(a,b)
lvl2 <- list(lvl3,lvl3)
lvl1 <- list(lvl2,lvl2,lvl2)

o.3 <- foreach(i=1:length(lvl1)) %do% {
    o.2 <- foreach(j=1:length(lvl1[[i]])) %do% {
            o.1 <- foreach(k=1:length(lvl1[[i]][[j]])) %do% {
                as.data.table(lvl1[[i]][[j]][[k]])
            }
            rbindlist(o.1)
        }
        rbindlist(o.2)
    }

dat.final <- rbindlist(o.3)

A: I would go with the wicked package purrr. In particular:
library(purrr)

(rbindlist(lapply(simplify_all((rbindlist((lvl1 %>% at_depth(3,data.frame))))),rbindlist)))

     date ret
1: 2017-01-01   1
2: 2017-01-01   2
3: 2017-01-01   3
4: 2017-01-01   4
5: 2017-01-01   5
-----
44: 2017-01-01   4
45: 2017-01-01   5
46: 2017-01-02   7
47: 2017-01-02   8
48: 2017-01-02   9

A: An ugly nested lapply call with do.call will do the trick:
do.call(rbind,do.call(rbind,lapply(lvl1,function(x) lapply(x,function(y) do.call(rbind,lapply(y, function(z) as.data.frame(z)))))))
The output:
> do.call(rbind,do.call(rbind,lapply(lvl1,function(x) lapply(x,function(y) do.call(rbind,lapply(y, function(z) as.data.frame(z)))))))
         date ret
1  2017-01-01   1
2  2017-01-01   2
3  2017-01-01   3
4  2017-01-01   4
5  2017-01-01   5
6  2017-01-02   7
7  2017-01-02   8
8  2017-01-02   9
9  2017-01-01   1
10 2017-01-01   2
11 2017-01-01   3
12 2017-01-01   4
13 2017-01-01   5
14 2017-01-02   7
15 2017-01-02   8
16 2017-01-02   9
17 2017-01-01   1
18 2017-01-01   2
19 2017-01-01   3
20 2017-01-01   4
21 2017-01-01   5
22 2017-01-02   7
23 2017-01-02   8
24 2017-01-02   9
25 2017-01-01   1
26 2017-01-01   2
27 2017-01-01   3
28 2017-01-01   4
29 2017-01-01   5
30 2017-01-02   7
31 2017-01-02   8
32 2017-01-02   9
33 2017-01-01   1
34 2017-01-01   2
35 2017-01-01   3
36 2017-01-01   4
37 2017-01-01   5
38 2017-01-02   7
39 2017-01-02   8
40 2017-01-02   9
41 2017-01-01   1
42 2017-01-01   2
43 2017-01-01   3
44 2017-01-01   4
45 2017-01-01   5
46 2017-01-02   7
47 2017-01-02   8
48 2017-01-02   9


text:
Q: Remove the link to the upstream repository in Bitbucket Let's say I have a git repository parent in bitbucket. I fork parent to child (I guess Bitbucket implements this as a clone operation, but I am not sure). Now I commit changes to child. From time to time Bitbucket notifies me that the parent is behind child and asks me whether I want to sync them. I don't like this because in my case parent is a template repository for new projects, so changes in instantiated projects should never be pushed back to the template repository. How can I achieve this?

A:
I don't like this because in my case parent is a template repository for new projects, so changes in instantiated projects should never be pushed back to the template repository

Then don't fork it.

*

*Create a new empty repo on BitBucket

*clone your BitBucket template repo on your computer

*change the remote "origin" of your local repo to the new remote BitBucket repo you just created:
git remote set-url origin https://username@bitbucket.org/username/newrepo

*push to the new repo
git push -u origin master

That way, both BitBucket repos won't have any link between them, and BitBucket won't remind you of any merge to do between them.


text:
Q: C# MVC Web application SQL not working properly Currently I am facing issue in my web application.

*

*Background > This web application is working well for 4 to 5 years

Recently, I receive the error message return as below.
(Noted: My Code never changes since 2 to 3 years ago)
Unknown column ''' in 'where clause'
Below is my query. And the query work well when running in HeidiSQL
internal static readonly string GetTableSQL = @"  SELECT u.* FROM tableA u WHERE REPLACE(u.COLUMN_A,'\'','') IN (@CompanyCodes) "
** @CompanyCodes will pass as parameters
I use REPLACE because COLUMN_A value has a single quote. That's why I want to replace it.
On 17-Feb-2023, my application start throw this error.
One strange thing is, when ever the error is throw, I restart my IIS and App pool, then the application work well for may be 30 min, after that the error throw again until I restart again my IIS service.
I do notice that on 16-Feb-2023, there is one window update  on .NET Framework 3.5, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8 for Windows Embedded 8.1 and Windows Server 2012 R2 (KB5022733). But I am not sure does this error related to this window update.
http://support.microsoft.com/kb/5022733
I do try different method of code such as
Web application details:

*

*DB - Mariadb (MySQL)

*Web C# MVC

*Hosting Server: Windows server 2012 R2

*IIS 8

Does anyone know how to troubleshoot or what is the root cause ?
Please help. Much appreciate!

A: The error Unknown column ''' in 'where clause' is happening because you're using string concatenation to build your SQL query.
Instead of doing this, you should use DbCommand parameters to pass the values. With a library like Dapper, this would look something like:
using var connection = GetYourConnection();
var companyCodes = new[] { "CODE1", "CODE2", ... };
var results = connection.Query<CompanyObject>(
    "SELECT u.* FROM tableA u WHERE u.COLUMN_A IN @companyCodes"
    new { companyCodes });


text:
Q: PHP - Mysqli Connection open and close using object oriented way - MySQLi I am trying to find a way which does the following

*

*Object Oriented way

*Closing the connection efficiently

*closing a connection anyways
<?php

 define("HOST", "localhost");
 define("USER", "username");
 define("PASS", "password");
 define("DBNM", "database");

 class ConnectionTest extends mysqli {

    private $link;

    function __construct() {
        $this->link = new mysqli(HOST, USER, PASS, DBNM);
    }

    function getLink(){
        return $this->link;
    }

    function __destruct() {
        mysqli_close($this->link)
    }
 }
?>

To try to get to my objective

*

*Object Oriented way - Used a class

*closing connection efficiently - defined a function to close the connection

*closing a connection anyways - set the same function to be destructor of that class

As I am new to PHP, I would like to know:

*

*Is this technique proper?

*What complications could occur? or what are the disadvantages to this technique?

*Is there any improvement needed in this code?

A: Frankly, this class of yours makes very little sense as it effectively duplicates mysqli. All the things you want to achieve, are already implemented in mysqli:

*

*Object Oriented way - Mysqli is a class already.

*There is a function in mysqli to close a connection as well

*Which is closing a connection efficiently.

So I fail to see how is your class any better than mysqli.


text:
Q: CodeIgniter: I'm able to list the items but I can't load one My
Application/.htaccess
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]

Application/config/routes.php
$route['default_controller'] = "news";
$route['404_override'] = '';

Application/models/news_model.php
<?php
class News_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function get_news($slug = FALSE)
    {
        if ($slug === FALSE)
        {
            $query = $this->db->get('news');
            return $query->result_array();
        }

        $query = $this->db->get_where('news', array('slug' => $slug));
        return $query->row_array();
    }
}
?>

Applications/controlers/news.php
<?php
class News extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('news_model');
    }

    public function index()
    {
        $data['news'] = $this->news_model->get_news();
        $data['title'] = 'News archive';

        $this->load->view('templates/header', $data);
        $this->load->view('news/index', $data);
        $this->load->view('templates/footer');
    }

    public function view($slug)
    {
        echo $slug;
        $data['news_item'] = $this->news_model->get_news($slug);
        var_dump($data);
        if (empty($data['news_item']))
        {
            show_404();
        }

        $data['title'] = $data['news_item']['title'];

        $this->load->view('templates/header', $data);
        $this->load->view('news/view', $data);
        $this->load->view('templates/footer');
    }
}
?>

Applications/views/index.php:
<?php foreach ($news as $news_item): ?>
    <?php var_dump($news_item); ?>

<?php echo "
"; echo $news_item['title'] ?>

        <?php echo $news_item['text'] ?>

<a href="news/<?php echo $news_item['slug'] ?>">View article

<?php endforeach ?>

And Applications/views/view.php
<?php
echo '
'.$news_item['title'].'
';
echo $news_item['text'];

The problem is that I can see index (wich lists my news) but when I click on a slug link it tries to go to:
/news/slug1

And it fires a not found error..
What am I missing here?

A: Link should be:

<a href="/news/view/<?php echo $news_item['slug'] ?>">View article

A: Controller's index method should be:
public function index()
{
    $data['news'] = $this->news_model->get_news();
    $data['title'] = 'News archive';

    $this->load->view('templates/header', $data);
    $this->load->view('view', $data);
    $this->load->view('templates/footer');
}

and article link must be:

<a href="news/index/<?php echo $news_item['slug'] ?>">View article

A: Assuming your CI is in the /demo folder:
try this htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /demo/

#Needed for CodeIgniter
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|pub|tmp|robots\.txt)
RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>

Your action should be accessible at a url like:
http://localhost:8080/demo/news/view/slug-here
and NOT at:
http://localhost:8080/demo/news/slug-here


text:
Q: how to transform domain.com/news.php?post_id=56 into domain.com/news/post-56 How to rewrite URL bar like so:

http://domain.com/news.php?post_id=56

into

http://domain.com/news/post-56?

A: It need to be done in .htaccess fileThere is such thing as RewriteEngineand code can look something like that
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/([^/]+)/?$    news.php?post_id=$1 [NC,L]

in begining we turn on rewrite enginefirst two conditions check if there is no such file or folder - in your case newsthen we rewrite what is typed in to what we need in our system

A: You can do it by URL rewriting.
URL rewriting is asking server to call specific file/script on certain URL requests.
Depending on the software your server is running, you may already have access to URL rewriting modules. If not, most hosts will enable or install the relevant modules for you if you ask them very nicely.
Apache is the easiest system to get URL rewriting running on. It usually comes with its own built-in URL rewriting module, mod_rewrite, enabled, and working with mod_rewrite.

To do this,
You need to first create a text document called .htaccess to contain our rules. This would be placed in the root directory of the server. There may already be an .htaccess file there, in which case we should edit that rather than overwrite it.
Now your .htaccess file will look something like this,
RewriteEngine On    # Turn on the rewriting engine
RewriteRule    ^news/post-([0-9]+)/?$    news.php?post_id=$1    [NC,L]    # Handling post requests

[NC,L] - They are called Flags, that tell Apache how to apply the rule. In this case, we're using two flags. NC, tells Apache that this rule should be case-insensitive, and L tells Apache not to process any more rules if this one is used.

Above RewriteRule tell Apache to look for news.php file with post-id passed in news/post-([0-9]+)/ URL. Where [0-9] denotes any numeric vaue.
Learn more here: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/


text:
Q: Maven+Spring: Use resources of a module autowired by spring First: Sorry for the title but i was really not sure how to frase the question.
I have a maven project with several modules in it.
All the modules are really simple as they provide some special logic classes to the main Web-App module.
These logic classes are injected at runtime by spring.
Following is my Maven setup (abstracted for simplicity)

*

*core-module (provides interfaces and basic classes for all modules)

*algorithm-modules (modules which provide special algorithms, implement one of code-modules interfaces)

*web-app-module (Spring Web App, which uses the algorithms that register themselves as @Component, is dependent on core and algorithm modules)

Now the Problem:
The algorithm module has a resource - in this case a python script - which i want to execute on the systems Python interpreter. (resource/pythonscript.py)
All available Algorithm Classes (Implement Metric interface) are injected by spring in to the web-apps controller:
@Autowired
List<Metric> metrics;

Later the user chooses the algorithm he wants to execute:
metric.performCalculations(dataset);

This executes the logic that later tries to run the python script from the modules resource directory:
URL url = NXBetweennessCentrality.class.getResource("bc/betweenness_centrality.py");
logger.debug("URL: {}", url); //=> null

I tried sevaral combinations:
class.getResourceAsStream(resourcePath)
class.getClassLoader().getResources("")

basically everything from How do I load a file from resource folder? But i can't load this resource.
I heard of problems when trying to access resources of a maven dependencys project (Use a dependency's resources?), but in my case i execute the Class from the package which owns the resource - so there should be no problem, at least thats what i thought.
Can somebody point out my mistake? Is this not possible without some tricky workaround?

A: If you run the class standalone then it should work. Else if you running as webapp using war then your resources should also get bundled inside your war. Since you have multiple modules, you might be packaging the modules which have your python resources as JAR and could have added that dependency to webapp module. At this point your resources which present the JAR module wont get bundled inside war.

A: ex:

a.b.c.NXBetweennessCentrality.class.getResource("");

that's mean  NXBetweennessCentrality packge
  WEB-INF/classes/a/b/c

in your code url is null

URL url =a.b.c.NXBetweennessCentrality.class.getResource("bc/betweenness_centrality.py");

meaning
  WEB-INF/classes/a/b/c/bc/betweenness_centrality.py

if your py file under the resources
you can try root "/" path in your web application

getResource("/bc/betweenness_centrality.py");

Correct me if I'm wrong ,thx.

A: So i managed to make it work using the maven script from https://stackoverflow.com/a/6448530/760952
Now all resources from all sub-modules are copied to the web-app resources directory before packaging the war.
This is ok for me, because all the modules can keep their own resources and you don't need to configure anything when adding new resources or new modules.