SwiftUI - Observable Object initiated from Swift class does not update @ObservedObject on ContentView()

Question: The ObservableObject class is being instantiated from both the ContentView() as well as another Swift class. When a function of the ObservableObject class is run by the Swift class, it does not update the @ObservedObject of the ContentView().
I am aware that this is due to me instantiating the ObservableObject class twice. What is the best practice to utilise @ObservedObject when the Observable Class is not/cannot be instantiated by the ContentView().
I haven't found a way to make @EnvironmentObject work with Swift classes.
I could use a global variable and run a Timer() to check for changes to it. However, this feels like an ugly way to do it?!?
Please see example code below. Please run on a device, to see the print statement.
<code>
import SwiftUI

struct ContentView: View {

    @ObservedObject var observedClass: ObservedClass = ObservedClass()

    // The callingObservedClass does not exist on the ContentView, but is called
    // somewhere in the app with no reference to the ContentView.
    // It is included here to better showcase the issue.

    let callingObservedClass: CallingObservedClass = CallingObservedClass()

    var body: some View {

        VStack {

            // This Text shall be updated, when
            // self.callingObservedClass.increaseObservedClassCount() has been executed.

            Text(String(observedClass.count))

            Button(action: {

                // This updates the count-variable, but as callingObservedClass creates
                // a new instance of ObservedClass, the Text(observedClass.count) is not updated.

                self.callingObservedClass.increaseObservedClassCount()
            }, label: {
                Text("Increase")
            })
        }
    }
}

class CallingObservedClass {

    let observedClass = ObservedClass()

    func increaseObservedClassCount() {

        // Returning an Int here to better showcase that count is increased.
        // But not in the ObservedClass instance of the ContentView, as the
        // Text(observedClass.count) remains at 0.

        let printCount = observedClass.increaseCount()
        print(printCount)
    }
}

class ObservedClass: ObservableObject {
    @Published var count: Int = 0

    func increaseCount() -> Int {
        count = count + 1
        return count
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

</code>
Edit: I suppose my question is how do I get data from a Swift class and update a SwiftUI view when the data changes when I am unable to instantiate the Swift class from the SwiftUI view.
Answer: A possible solution to this is to chain the ObservableObject classes. Unfortunately, as of iOS 13.6 this does not work out of the box.
I found the answer via:
How to tell SwiftUI views to bind to nested ObservableObjects
Adjusted & functioning example:
<code>// Add Combine

import Combine
import SwiftUI

struct ContentView: View {

    @ObservedObject var callingObservedClass: CallingObservedClass = CallingObservedClass()

    var body: some View {

        VStack {

            // Calling the chained ObservableObject

            Text(String(callingObservedClass.observedClass.count))

            Button(action: {

                self.callingObservedClass.increaseObservedClassCount()
            }, label: {
                Text("Increase")
            })
        }
    }
}

class CallingObservedClass: ObservableObject {

    // Chaining Observable Objects

    @Published var observedClass = ObservedClass()

    // ObservableObject-chaining does not work out of the box.
    // The anyCancellable variable with the below init() will do the trick.
    // Thanks to https://stackoverflow.com/questions/58406287/how-to-tell-swiftui-views-to-bind-to-nested-observableobjects

    var anyCancellable: AnyCancellable? = nil

    init() {
        anyCancellable = observedClass.objectWillChange.sink { (_) in
            self.objectWillChange.send()
        }
    }

    func increaseObservedClassCount() {
        let printCount = observedClass.increaseCount()
        print(printCount)
    }
}

class ObservedClass: ObservableObject {
    @Published var count: Int = 0

    func increaseCount() -> Int {
        count = count + 1
        return count
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>
I am interested on how to access Swift Class data and update an SwiftUI view if ObservableObject-Chaining is not an option.
Please answer below if you have a solution to this.


" _typeof is not defined" when loading m3u8 file using hls.js

Question: I am trying to load my m3u8 files that i have saved on my aws s3.
My code looks like this:
    var video = document.getElementById('video');
    var videoSrc = "https://my-file-link.m3u8";
    if (Hls.isSupported()) {
      console.log("creating");
      var hls = new Hls();
      console.log("loading");
      hls.loadSource(videoSrc);
      console.log("attaching");
      hls.attachMedia(video);
      console.log("finished");
    }
    else if (video.canPlayType('application/vnd.apple.mpegurl')) {
      video.src = videoSrc;
    }

      <video id="video"></video>

But the files are not loading, and the logs look like this:
creating
loading
attaching
finished
Uncaught ReferenceError: _typeof is not defined
    at enableLogs (...)
    at ...

If I comment out hls.attachMedia(video); the error disappears(the files obviously don't load).
I am trying to view the video from Chrome, and my site is using npm.
I still do not have a full understanding of CORS  headers, but I am guessing CORS is not the issue as the video is able to play from here.
What is causing this issue, and how can I make my video play on my site?
Is there anything else I need to share?
Answer: I just had to add controls to the video tag like so:
<video class="live-player" id="video" controls></video>

And it worked...
Any clue as to why? They do not seem to be adding controls in the examples here:
https://github.com/video-dev/hls.js/


wwwroot content prefixed by controller name

Question: I have a Login page that isn't loading any CSS at all. It is because the page is looking for the following:

My wwwroot folder has the structure css/login/login.css, however the page is trying to prefix this with the name of the Controller (AuthController). The Page's header simply looks like so:

    <meta charset="utf-8">
    <title>My Webpage</title>

    <link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/login/login.css">

My Controller is just in a folder named Controllers and my View is in a structure like so: Views/Auth/.
I am not using a _Layout page as of yet.
I haven't seen this before and I cannot workout why it is prefixing the Controller name to the content in wwwroot.
Answer: Try setting your style to
    <link rel="stylesheet" href="~/css/login/login.css">

Similar to how you can refer to relative paths (eg: ../css/login/login.css) you can in Razor you can refer the virtual root path using the ~ operator.
Generally I find ~ more useful as you can change the location of your view and still refer to the same location.
Comment: I just tried this a few seconds before seeing this answer. It worked. Could you give a small explanation on why this works then I'm happy to accept it as an answer.


Prime Number Generator: $n\cdot2^n - 1$?

Question: I ran into the following sequence:

$$f_n=n\cdot2^n-1.$$

Apparently, for $n>1$, $f_n$ will yield a prime number. It will not list all of them, however.
My question is: Is this true for all $n$?
I currently have a program running that has thus far checked that it is true for all $n\leq49$. What do you guys think?
Comment: I suggest you check your program.
Comment: By the way, $4\cdot 2^4-1=63$.
Comment: @Josue Why didn't you try some values for yourself? You'd have had an answer right away!
Comment: I agree, and I apologize for not having done that to begin with. :/ I guess I just have this thing for programming where, in my excitement, I do it blindly and without much prior thought. I checked its validity by hand for the first two cases or so, and upon seeing that it worked, I jumped straight into the coding... had I done just one more number!
Answer: Here is a list of numbers $1\leq n\leq 100$ for which $n2^n-1$ is not prime:
$$1,4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,$$
$$ 25, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45,$$
$$46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65,$$
$$66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 82, 83, 84, 85, 86, 87,$$
$$88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100.$$
Comment: That is, for 94 out of 100 possible values of $1\leq n\leq 100$, the quantity $n2^n-1$ is not prime.
Answer: These are called Woodall numbers.  See https://oeis.org/A002234 and references given there.
It is conjectured that infinitely many Woodall numbers are prime, but this is still very much an open question.
Comment: That's interesting! I just found out that $n\cdot2^n+1$ are called *Cullen* numbers. o.o
Comment: Wow! oeis.org looks like a legacy archive, but indeed is useful collection
Comment: Why do you call it "legacy"?
Comment: Looks old style (so my remark was for the appearance - sorry if I confused with that remark)
Answer: Your program apparently needs work.  Let $n=2^{2k}$.  Then $f_n=2^{2k}\times2^{2^{2k}}-1=2^{2k+2^{2k}}-1=(2^{k+2^{2k-1}}+1)(2^{k+2^{2k-1}}-1)$.
So $f_n$ is composite for all positive integer powers of 4.
Answer: $16\times 2^{16}-1$ is divisible by $5$.
This is because $2^4 = 16 = 1 \mod 5$.
In general, for every odd prime $p$, for $n = (p-1)^2, \ n2^n - 1$ is divisible by $p$.
Comment: $4 \times 2^4 - 1 = 63$
Comment: @SivaramAmbikasaran: True :-) I started with trying to find one divisibly by $5$ for some reason.
Comment: That's interesting. I must've messed up my programming. Thanks for the counterexample.
Answer: $n = 4$ is the first value for which $f_n$ isn't prime.
$4 \times 2^4 - 1 = 63 = 3^2 \times 7$
Answer: Notice that if $n = 2^{2a}$ for some positive integer $a,$ then $n2^{n}- 1$ is never prime, because $n 2^{n}-1 = 2^{ 2a+2^{2a}} -1,$ which is divisible by $3$ as $2^{2m}-1$ is divisible by $3$ for any positive integer $m.$


Is the set of all nonnegative real numbers bounded using the metric space definition?

Question: I'm looking at the definition of the bounded set on Wikipedia, which says:

A subset S of a metric space $(M, d)$ is bounded if it is contained in a
  ball of finite radius, i.e. if there exists $x \in M$ and $r > 0$ such that
  for all $s \in S$, we have $d(x, s) < r$.

If I let $M = \mathbb{R}$ and $S$ be the set of all nonnegative real numbers, does that mean it's not bounded by the definition? I'm struggling to construct a ball to contain $S$.
If so, that's a bit counter-intuitive to me, since $S$ is bounded from below (by $0$). Can someone please verify whether or not I'm right?
Answer: Let $a\in S$. Let $r > 0$.
Then $B_r(a)$ is the "ball of radius $r$ around $a$", and in this case it corresponds to the interval $(a-r, a+r)$.
But clearly $a+r+1 \in S$, while $a+r+1 \not\in B_r(a)$. Because $a$ and $r$ were arbitrary, this shows that $S$ isn't contained in any ball, so it's not bounded.
Answer: As you say, $S = [0,+\infty)$ is bounded from below. This is weaker than being bounded, and the easiest example to see this is actually $S$. If it were bounded, we could take an interval $(-M,M)$ with $M > 0$ such that $S \subseteq (-M,M)$. This is false,  since $M+1$ is in $S$ but not in $(-M,M)$. Therefore, $S$ is not bounded.
Comment: I meant that to be a parenthesis, I've edited it accordingly. Thanks!


Error when creating PDF from ASP.NET report

Question: I'm trying to programmatically create a pdf file from ASP.NET report. When I run the program it throws the following error:

Error occurred during report processing. Loading this assembly would
  produce a different grant set from other instances. (Exception from
  HRESULT: 0x80131401)

I already tried adding
<code><trust level="Full">
</code>
to my applications web.config and reset the IIS.
Any other ideas?
Comment: You need to add more details. Describe how you're creating the PDF.
Comment: Make sure that you build the PDF in memory, and not on a local drive.  Need to see some code.
Answer: Reinstalling ReportViewer 2005 SP2 and then IIS reset solved my problem.


Selected file gets reset after clicking on +Add More button

Question: am implementing a form and in that form it requires that two form element should be coming under one Add more button, so user can add any number of fields.
Here is the code which i am using to create a form.
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  $form['description'] = array(
    '#markup' => '
' . t('This example shows an add-more and a remove-last button. The AJAX version does it without page reloads; the non-js version is the same code but simulates a non-javascript environment, showing it with page reloads.',
      array('!ajax' => url('examples/ajax_example/add_more'), '!multistep' => url('examples/ajax_example/add_more_no_js')))
    . '
',
  );

  $form['#tree'] = TRUE;
  $form['names_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('People coming to the picnic'),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  for ($i = 0; $i < $form_state['num_names']; $i++) {
    $form['names_fieldset'][$i]['name'] = array(
      '#type' => 'textfield',
      '#title' => t('Name'),
    );
    $form['names_fieldset'][$i]['surname'] = array(
      '#type' => 'textfield',
      '#title' => t('SurName'),
    );
    $form['names_fieldset'][$i]['filedepot_file'] = array(
      '#type' => 'managed_file',
      '#title' => t('Choose a file'),
      '#size' => 22,
      '#process' => array('_module_my_file_element_process'),
    );
  }
  $form['names_fieldset']['add_name'] = array(
    '#type' => 'submit',
    '#value' => t('Add one more'),
    '#submit' => array('ajax_example_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'ajax_example_add_more_callback',
      'wrapper' => 'names-fieldset-wrapper',
    ),
  );
  if ($form_state['num_names'] > 1) {
    $form['names_fieldset']['remove_name'] = array(
      '#type' => 'submit',
      '#value' => t('Remove one'),
      '#submit' => array('ajax_example_add_more_remove_one'),
      '#ajax' => array(
        'callback' => 'ajax_example_add_more_callback',
        'wrapper' => 'names-fieldset-wrapper',
      ),
    );
  }
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );
  if ($no_js_use) {
    // Remove the #ajax from the above, so ajax.js won't be loaded.
    if (!empty($form['names_fieldset']['remove_name']['#ajax'])) {
      unset($form['names_fieldset']['remove_name']['#ajax']);
    }
    unset($form['names_fieldset']['add_name']['#ajax']);
  }

  return $form;
}

/**
 * Callback for both ajax-enabled buttons.
 *
 * Selects and returns the fieldset with the names in it.
 */
function ajax_example_add_more_callback($form, $form_state) {
  return $form['names_fieldset'];
}

/**
 * Submit handler for the "add-one-more" button.
 *
 * Increments the max counter and causes a rebuild.
 */
function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
}

/**
 * Submit handler for the "remove one" button.
 *
 * Decrements the max counter and causes a form rebuild.
 */
function ajax_example_add_more_remove_one($form, &$form_state) {
  if ($form_state['num_names'] > 1) {
    $form_state['num_names']--;
  }
  $form_state['rebuild'] = TRUE;
}

function _module_my_file_element_process($element, &$form_state, $form) {
    $element = file_managed_file_process($element, $form_state, $form);
    $element['upload_button']['#access'] = FALSE;
    return $element;
}

Now after adding file when i click on +Add More button at that time all the fields retains their values but filefield gets reset.
Here i am hiding the upload button so that file will be uploaded when user submits the form.
After filing on fieldset when i click on +Add more button at that time selected files doesn't come in the appropriate form fields, where as other fields retains their values.
How can i fix the code so that selected file remains as it is in the respected fields.
Answer: Problem is in $form_state['rebuild'] = TRUE; in your ajax_example_add_more_callback().
From my experience it sometimes is needed, and sometimes mess up values. So you could try to avoid it (point 1) or save values in a safe place before you rebuild, restore them after you rebuild (point 2).

Way I prefer to do it, if feasible, is to prevent submit on a button that's supposed. I used $form_state['triggering_element'] in form building function to detect AJAX calls and decide what needs to be updated.
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  if ( $form_state['triggering_element'] == MY_AJAX_ADD_BUTTON ) {
    $form_state['num_names']++;
  }

That way you are not rebuilding form, so data has no opportunity to get discarded.
The way that would require less changes to you is to save already filled values in some kind of cache inside your add more submit handler, and then set them as defaults in form building function.
function ajax_example_add_more($form, &$form_state, $no_js_use = FALSE) {
  // (...)
  $form['names_fieldset'][$i]['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
    '#default' => _mymodule_read_from_cache($i, 'name'),
  );
  // (...)
}

function ajax_example_add_more_add_one($form, &$form_state) {
  $form_state['num_names']++;
  $form_state['rebuild'] = TRUE;
  _mymodule_save_to_cache($form_state['values']);
}

This would require you to write _mymodule_save_to_cache() and _mymodule_read_from_cache() functions, but that's a way to prevent value loss during form rebuild. Not nice, maybe, but works.
Comment: Can you please describe little more, as i am not able to get your answer..
Comment: @mohit_rocks Added pseudocode samples
Comment: without writing `$form_state['rebuild'] = TRUE;` i am not able to get several instances of form. i.e. i can't get the output after pressing add more button.
Comment: @mohit_rocks from my experience `$form_state['rebuild'] = TRUE;` sometimes is needed, and sometimes mess up values. So my answer, point 2, can be read as: "save values in a safe place before you rebuild. Restore them after you rebuild". Makes sense?
Comment: How can i save the files as these are not yet uploaded . Actually problem is with files only rest of things are working perfectly


Using react-router with react portals?

Question: I'm implementing an app with plenty of tables that works with the react-router perfectly, reading the URL query etc.
Now I need to put one of the tables inside a modal (I'm using AntUI Modal component for this purpose). From this table I can change the URL query in the browser by using history:
import createHistory from 'history/createBrowserHistory';

export const history = createHistory()
...
history.push({ search: 'my search here' });

The problem is that the URL changes are not visible for the table inside the modal. I've tried wrapping the component in withRouter HOC but it did not help, so I assume that the problem is that the modal is not laying inside the <Router> component.
Can it be easily fixed? Or maybe my whole thought process is wrong?
Answer: If anyone is going to face a similar issue - just pass the router props (match, location, history) directly to the children of Modal component.
Comment: Have you found a solution to using `` directly without the [fallback of manually pushing to history](https://stackoverflow.com/questions/57357366/how-to-use-link-react-router-inside-mui-popover?noredirect=1&lq=1#comment101202045_57357366)?

Using react-router with react portals?


Can't call method from constructor

Question: Calling private/public method from constructor in the same class gives me an error

Uncaught TypeError: this.setEventHandler is not a function
      at Object.Init (Init.ts:4)
      at :3:16

export class Init {

constructor(private connectBtn: HTMLElement) {
    this.setEventHandler();
}
public setEventHandler() {
    this.connectBtn.onclick = (e) => {
        this.openConnectWindow();
    }
}
private openConnectWindow() {
    console.log("OPEN SESAME")
}
}

This is the compiled javascript
var Init = (function () {
function Init(connectBtn) {
    this.connectBtn = connectBtn;
    this.setEventHandler();
}
Init.prototype.setEventHandler = function () {
    var _this = this;
    this.connectBtn.onclick = function (e) {
        _this.openConnectWindow();
    };
};
Init.prototype.openConnectWindow = function () {
    console.log("OPEN SESAME");
};
return Init;
}());

Edit: This is for a library.
I tried putting var mylib = new MyLibraryName() but I only get "MyLibraryName is not a constructor".
I start the root object with webpack
output: {
    path: path.join(__dirname, "lib"),
    filename: outputFile,
    library: libraryName,
    libraryTarget: "umd",
    umdNamedDefine: true
},

Comment: Show me how you create `Init` class instanses
Comment: Its going to be a library so i just type MyLibraryName.Init
Comment: var ele = document.getElementsByClassName('dropdown-toggle')[0];
MyLibraryName.Init(ele)
Answer: Change the methods you are calling from other methods to this
export class Init {

constructor(private connectBtn: HTMLElement) {
    this.setEventHandler();
}

public setEventHandler = () => {
    this.connectBtn.onclick = (e) => {
        this.openConnectWindow();
    }
}

private openConnectWindow = () => {
    console.log("OPEN SESAME")
}
}

Comment: Could you tell us why is this necessary?
Comment: Yes, it works like charm, but why should I use this? It changes my syntax. Is there any way we can configure something to make it work on both ways?

Can't call method from constructor


Selection of informative examples of majority class for undersample using SVM

Question: I have this idea in mind, but I am not sure how to implement it. Suppose I have an imbalanced data that I want to down-sample instances of majority class, such that it becomes equal in size to the minority class.
I want to use SVM to select from majority class, it's class support vector(s) and examples near distance such support vectors until majority class examples equal the minority examples.
For example:

In the above figure, we have 8 instances of class 1  and 5 instances of class 0 before undersampling. After under-sample, we have 5 instances of class 1  and 5 instances of class 0 so the classes are balanced.
Can someone offer guide how this can be done?
Answer: Firstly, don't undersample unless you have vast amounts of data and need to undersample for computational reasons.
Rather than resampling, use different values of the C hyper-parameter for each class instead.  This is equivalent to resampling, but without throwing away any data (just down-weighting it).  For details see my paper (with Mrs Marsupial)
G. C. Cawley and N. L. C. Talbot, Manipulation of prior probabilities in support vector classification, In Proceedings of the IEEE/INNS International Joint Conference on Neural Networks (IJCNN-2001), pp. 2433-2438, Washington, D.C., U.S.A., July 15-19 2001.(www,pdf)
There were several other papers written on this topic at about the same time, but that was the easiest for me to find.  Most modern implementations of the SVM will support this.
However, the reason for changing the C parameters or resampling is not because of the imbalance, but because false-positive and false negative errors have different costs.
The approach you intend to take is unlikely to work because as soon as you delete some support vectors, that will change the solution simply because the support vectors are necessary to define the optimal hyperplane.  This means you will be invalidating much of the theory on which the SVM is based.  So I would advise against it.
I don't think SVMs have difficulties with imbalanced learning tasks, and if it is assigning everything to the majority class, it is quite likely that that is the optimal solution for equal false-positive/false-negative costs (see my related question here).
Comment: Many thanks for the detailed answer, I will study the paper cited about. However, I'm not deleting the support vectors, instead selecting the support vectors (and example near the support vectors for majority class) into the training set. In my case, I consider each class to have equal misclassification cost (no such as as concept of interest, only that for data collection reason, one class is under-represented).
Comment: @arilwan From the question "Suppose I have an imbalanced data that I want to down-sample instances of majority class, such that it becomes equal in size to the minority class." resampling the data that way is equivalent to changing the misclassification costs.  It is not clear *why* you are downsampling if the misclassification costs are equal.
Comment: May be my words are misleading, but what I mean is that there is not such thing as concept as concept of interest here. Detection of each class is important, only data for data collection reason, one class is under-represented.
Comment: Sorry @arilwan that does not really explain why you want to downsample.


Looking for python errno.ECONNREFUSED or ConnectionRefusedError

Question: I am looking for either of the above two Exceptions but cannot find them. In my existing errno I only have ECONNRESET.
I found a comment about python 3 (maybe time to upgrade?) and ConnectionRefused Error (here) but I cannot find the library that contains it.
Any help would be appreciated.
Thanks!
Comment: possible duplicate of [Catch "socket.error: \[Errno 111\] Connection refused" exception](http://stackoverflow.com/questions/14425401/catch-socket-error-errno-111-connection-refused-exception)
Answer: I see errno.ECONNREFUSED in the socket module.
ECONNREFUSED is not an exception though.  socket throws an exception of type socket.error, and sets the errno field of the exception to tell you what kind it was.  So you would do the following to check for ECONNREFUSED
import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
    sock.connect(('myhost', port))
except socket.error as sock_err:
    if(sock_err.errno == socket.errno.ECONNREFUSED):
        print "Connection was refused"

You can also see this in the answer by Martijn Pieters
Comment: Ok. I'm a bit confused: what is my import? socket? socket.error? what do I put in the except clause? Nothing seems to give me access to errno.ECONNREFUSED. Unless I do: except socket.error:
                    if socket.errno.ECONNREFUSED
Comment: @goggelj I've updated the answer to hopefully help you


Is there a way to change the command for running go tests when using VS Code

Question: I am working on a Go project using Visual Studio Code as my IDE and Doppler for managing secrets. Normally, to run my application with Doppler secrets, I use the following command:
doppler run -- go run main.go

However, I encounter a challenge when trying to run my Go tests. The default test run commands in Visual Studio Code are not prefixed with doppler run, which means my tests cannot access the secrets managed by Doppler.
Is there a way to configure Visual Studio Code to automatically use doppler run when executing Go tests? This is essential for ensuring that my tests have access to the necessary environment variables set by Doppler.
I've considered modifying the test configuration in launch.json, but I am unsure how to integrate Doppler into this process. Specifically, I am looking for a solution that allows me to run tests from the Visual Studio Code interface (e.g., using the 'Run Test' or 'Debug Test' options in the editor) with Doppler secrets injected.
Any suggestions or examples of how to set this up would be greatly appreciated.
I couldn't find any examples in the documentation of overriding the default test command, like I have done previously with the jest vscode extension
Comment: How abou using this extension? https://docs.doppler.com/docs/vscode-extension
Answer: Assuming you're using the Go extension for VS Code and want to continue doing your tests through it, I think not. It contributes a go.testFlags setting, but I didn't see a setting for adding a "wrapper command". What you could try do is write a task or a launch config that runs the specific command you want. You may find variables of use if you want to make those tasks more reusable.


Cron runs in all server instances

Question: We are facing really big issue with the cron. Our site is running on 2 ec2 instances under the load balancer. We have lot of cron tasks which are performed every day. But the problem comes when the cron run, during this time all instances start processing the cron jobs, and site will not be accessible for the users. Here all the instances are sharing the same db including the staging instances(another 2 instances). I don't understand that, why all instance's CPU utilization is going high when cron run(all 4 instances).
Because of this behavior, what we are planning now is, to move the cron to a separate server, there it will perform all the jobs. But I'm not sure how I can achieve this.
How can I move the cron job to a separate server?
Answer: Instead of moving cron, you need to look into what parts of cron are so CPU itensive and why it takes such a long time to complete.
You can start by logging executed tasks, how when they start, finish and a comment about what they do.
Comment: My question is not only about the CPU usage, Why all instances are running the cron tasks?. This is what giving me the headache. I just want to run the cron taks in one instance.
Comment: Do you have any idea about how to run the cron in one instance.
Comment: It all depends on SQL since cron creates its locks in SQL:
SELECT * FROM from variable WHERE name like "cron%";

Are you running on single SQL database on both instances?
Comment: Yes, All the instances are sharing the same DB.

Cron runs in all server instances


Vue.js com Electron: imagens não são carregadas. "Images and other types of assets omitted"

Question: Acabei de configurar um projeto com Vue.js e Electron usando Electron Builder e ao rodar npm run electron:serve (vue-cli-service electron:serve) o logo do Vuetify (logo.png) que está na pasta "assets" não é carregado.
No console do terminal aparece o erro "Images and other types of assets omitted". Mas porque está sendo omitido? Alguma ideia de qual é a configuração envolvida?
No console do electron aparece o erro: "Failed to load resource: the server responded with a status of 404 (Not Found)". A URL buscada é http://localhost:8080/.

Log completo do console do node:
PS C:\Users\Lucas_Pletsch\OneDrive\own-time> npm run electron:serve
npm WARN config global `--global`, `--local` are deprecated. Use `--location=global` instead.

> firstname.lastname@example.com electron:serve
> vue-cli-service electron:serve

 INFO  Starting development server...

 DONE  Compiled successfully in 4442ms                                                                                08:07:14

  App running at:
  - Local:   http://localhost:8080/
  - Network: http://192.168.1.105:8080/

  Note that the development build is not optimized.
  To create a production build, run npm run build.

|  Bundling main process...

 DONE  Compiled successfully in 2178ms                                                                                08:07:17
  File                      Size                                                  Gzipped

  dist_electron\index.js    801.57 KiB                                            175.88 KiB

  Images and other types of assets omitted.
  Build at: 2022-07-25T11:07:17.323Z - Hash: a01c9d543f7732d458ce - Time: 2178ms

 INFO  Launching Electron...
(node:20408) ExtensionLoadWarning: Warnings loading extension at C:\Users\Lucas_Pletsch\AppData\Roaming\own-time\extensions\ljjemllljcmogpfapbkkighbhhppjdbg:
  Unrecognized manifest key 'browser_action'.
  Unrecognized manifest key 'update_url'.
  Permission 'contextMenus' is unknown or URL pattern is malformed.
  Cannot load extension with file or directory name _metadata. Filenames starting with "_" are reserved for use by the system.
(Use `electron --trace-warnings ...` to show where the warning was created)
> Images and other types of assets omittedImages and other types of assets omitted
    insira o código aqui

Package.json:
[![{
  "name": "own-time",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "electron:build": "vue-cli-service electron:build",
    "electron:serve": "vue-cli-service electron:serve",
    "postinstall": "electron-builder install-app-deps",
    "postuninstall": "electron-builder install-app-deps"
  },
  "main": "background.js",
  "dependencies": {
    "core-js": "^3.8.3",
    "vue": "^3.2.13"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "electron": "^13.0.0",
    "electron-devtools-installer": "^3.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.0.3",
    "vue-cli-plugin-electron-builder": "~2.1.1",
    "vue-cli-plugin-vuetify": "~2.5.1"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": \[
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    \],
    "parserOptions": {
      "parser": "@babel/eslint-parser"
    },
    "rules": {}
  },
  "browserslist": \[
    "> 1%",
    "last 2 versions",
    "not dead",
    "not ie 11"
  \]
}

    insira o código aqui][1]][1]

O logo é importado no App.vue:
Comment: Poderia mostrar o código de onde você importa essa imagem/logo ?
Comment: @VictorBier coloquei.
Answer: Acabei recriando o projeto, e após ter criado o app (vue create meuapp) e adicionado o electron builder (vue add electron-builder), adicionei o vuetify (antes eu tinha feito isso antes do electron builder)e aí carregou certo com vuetify.


Save Japanese characters into MySQL

Question: I am using PHP for executing a MySQL update sentence with Spanish, English and Japanese characters.
But i'm not able to save Japanese characters into the database.  How should I proceed?

Database has utf8_general_ci collation.

$strSQL = "UPDATE table SET value = '" . addslashes($strValue) . "'";
$strSQL = utf8_decode($strSQL);
mysqli_query($cnn, $strSQL);

With addslashes I can get apostrophes to be saved into the database.
With utf8_decode I can get Spanish characters to be saved into the database.
Comment: You absolutely should not be using `addslashes`, use `mysqli_real_escape_string`. You also should not use `utf8_decode`, you need to make sure you are using UTF-8 as your database and page encoding. You can find information on how to use UTF-8 in PHP online (phptherightway.com)
Comment: If you still have trouble after implementing the changes suggested by Andrea and and Max Base, see if [_this_](https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored) helps.
Answer: Why you proccess utf8_decode() the sql query?

Look at http://php.net/manual/en/function.utf8-decode.php for details about utf8_decode()

You have to check a few things.
Whether there is a problem in your database and tables Or in your PHP script.

Database :
CREATE DATABASE test DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Table Charset :
CREATE TABLE test.table
(
    id INT NOT NULL AUTO_INCREMENT,
    text VARCHAR(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

Connection :
SET NAMES utf8;

E.g :
$mysqli = new mysqli("localhost","my_user","my_password","test_db");
$mysqli->set_charset("utf8");

OR
$link = mysqli_connect("localhost","my_user","my_password","test_db");
mysqli_set_charset($link,"utf8");

Configure the encoding charset of server :

With PHPMyAdmin , Choose UTF-8 when you login.

PHP Script :
header('Content-Type: text/html;charset=UTF-8');

Apache Config (/etc/httpd/conf/httpd.conf) :
AddDefaultCharset UTF-8

Apache .htaccess file :
AddCharset UTF-8 .htm
AddCharset UTF-8 .html
AddCharset UTF-8 .php

PHP Config (/etc/php.ini) :
default_charset = "utf-8"

MySQL Config (/etc/my.cnf ) :
[client]
default-character-set=utf8

[mysqld]
default-collation=utf8_unicode_ci
character-set-server=utf8
default-character-set=utf8
init-connect='SET NAMES utf8'
character-set-client = utf8

User values :

e.g : $_GET , $_POST

You can use mb_convert_encoding() for convert your strings to UTF-8.

Useful Links :

PHP inserting Japanese string to utf8 table as something else, but still reads it successfully

http://es2.php.net/manual/en/mysqli.set-charset.php

Select MySQL rows with Japanese characters

http://php.net/manual/en/function.mysql-set-charset.php

https://www.w3schools.com/php/func_mysqli_set_charset.asp

PHP mysql charset utf8 problems

https://medium.com/@adamhooper/in-mysql-never-use-utf8-use-utf8mb4-11761243e434

https://dev.mysql.com/doc/refman/8.0/en/faqs-cjk.html

https://www.experts-exchange.com/questions/24742133/How-to-insert-a-japanese-character-into-mysql-database.html

Save Japanese characters into MySQL


How to correctly use cookies? (Twig and cache context)

Question: In my current project I need to alter node templates depending on previously visited landing page. My idea is that, when a visitor visits one of these landing pages, a cookie will be set, and subsequent node templates will be altered depending on that cookie.
I've got three view pages serving as entry points for my visitors:
myproject.com/tv
myproject.com/mobile
myproject.com/infopoint
In theme preprocess I'm checking/setting a cookie and assigning a template variable. The Twig templates do minor modifications depending on that variable:
function MYTHEME_preprocess(array &$variables, $hook) {
  $router = \Drupal::routeMatch();

  if ($route = $router->getRouteObject()) {
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    $view_display_plugin = $route->getOption('_view_display_plugin_id');

    if ($view_id && $view_display_plugin === 'page') {
      if ($view_id == 'slide') {
        user_cookie_save(['device' => 'tv']);
        $variables['MYTHEME']['device'] = 'tv';
      }
      elseif ($view_id == 'tile' && $display_id == 'mobile') {
        user_cookie_save(['device' => 'mobile']);
        $variables['MYTHEME']['device'] = 'mobile';
      }
      elseif ($view_id == 'tile' && $display_id == 'infopoint') {
        user_cookie_save(['device' => 'infopoint']);
        $variables['MYTHEME']['device'] = 'infopoint';
      }
    }
  }

  // user_cookie_save prefixes all cookie names with 'Drupal.visitor.'
  if (isset($_COOKIE['Drupal.visitor.device']) &&
    in_array($_COOKIE['Drupal.visitor.device'], ['tv', 'mobile', 'infopoint'])) {
         // I'm doing design modifications in my Twig templates depending on this variable
        $variables['MYTHEME']['device'] = $_COOKIE['Drupal.visitor.device'];
    }
  }
}

In services.yml I've activated the cookies cache context
parameters:
  renderer.config:
    required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site', 'cookies:Drupal.visitor.device']

In my Twig templates I've got multiple code pieces like this:
{% if MYTHEME.device == 'tv' %}

{% else %}

{% endif %}

Sadly the code doesn't really work. On the entry pages, the device theme variable is always correct, but the cookie is not updated (seems as if only first uncached hit sets the cookie. I even have the weird situation that cookie and twig variable aren't equal.). On node templates the theme variable isn't set correctly at all.
Any ideas how to get the code above working?
PS: Due slow views with geo-distance calculations disabling cache is not an option, I need to provide cached pages also for anonymous users.
Comment: _I need to provide cached pages also for anonymous users_ Then you'll need to turn off the Internal Page Cache module. Dynamic Page Cache can still be enabled, but the former is only for use in situations where exactly the same content gets served to every anonymous user
Comment: I thought providing a proper cache context saves me from disabling the Internal Page cache? However, I disabled the internal page cache, but it still doesn't fully solve the problems. It looks as if the cookie is "one step behind" (e.g. visiting mobile - infopoint - infpoint shows mobile - mobile - infopoint)
Comment: No, internal page cache ignores cache contexts. Yes, there's no cookie on the first request (you haven't set it yet). Then you send it, and it comes back populated with the next request, assuming the UA sends it
Answer: I've updated the code in the question, the code is now working. It was almost complete, I had made some simple mistakes though:

Even when providing a proper cache context, you still need to disable the Internal page cache module. Only Internal dynamic page cache module is allowed.
user_cookie_save() prefixes the cookie name with Drupal.visitor. This is  the real name you'll also see in your browser's dev console. But when checking for cookie names in PHP, dots and spaces are converted to underscores. That means using user_cookie_save(['mycookie' => 'some_value']); creates a cookie with a "real" name of Drupal.visitor.mycookie, but in PHP

your template/module code needs to check
if ($_COOKIE['Drupal_visitor_mycookie'])
and you also have to use the underscore name in services.yml
required_cache_contexts: ['cookies:Drupal_visitor_device', '...other_stuff...']

Don't set the cookie value and check that updated cookie value in the same request:
user_cookie_save(['mycookie' => 'new_value'])
will immediatly update the cookie in the client browser, but PHP code in the same request like
if ($_COOKIE['Drupal_visitor_mycookie'])
will still return the original value from the previous request.
Comment: I used this example too. I would love to see some documentation on the parameters.renderer_config.required_cache_contexts - this fixed the main issue for me. But I want to know how to set it dynamically from a custom module (if that is even possible).


Wordpress 301 redirect. From Cloudfront to LoadBalancer - AWS

Question: Problem:
When entering the example.com domain it does a 301 redirect to the LoadBalancer address (loadbalancer.xx.xx.com). The site should be served from the original domain address.
My Infrastructure:

ECS (Dockefile)(port 80) -> LoadBalancer(port 80) -> CloudFront(port
443) -> example.com

e.g. when I first launch the application, seeing the wordpress configuration screen redirects me immediately to

example.com/wp-admin/install.php ->301-> loadbalancer.xx.xx.com/wp-admin/install.php

How I tried to fix it:

I cleaned the .htaccess file completely and unfortunately that didn't help
I added this to wp-config-docker.php

define('WP_HOME', getenv_docker('WP_HOME', ''));
define('WP_SITEURL', getenv_docker('WP_SITEURL', ''));

Now when I go to example.com it redirects me to

example.com/wp-admin/install.php

which is correct. After filling out the install form, it again runs a 301 redirect to loadbalancer.

https://example.com -> http://loadbalancer.xx.xx.com

I checked the database. I dumped it to file.sql and inside I don't see, any entry like "loadbalancer.xx.xx.com".

Here is my code:
Wordpress from the official site: https://github.com/docker-library/wordpress/tree/940a0d35951a0917622c35acc92b38b1db3c730f/latest/php8.2/apache
ECS Terraform Definition (like docker-compose):
<code># ECS Task Definition
resource "aws_ecs_task_definition" "woocommerce_task" {
  depends_on = [ aws_efs_access_point.wp_content ]
  family                   = var.task_family
  network_mode             = var.network_mode
  requires_compatibilities = var.task_compatibilities
  cpu                      = var.task_cpu
  memory                   = var.task_memory
  execution_role_arn       = aws_iam_role.ecs_execution_role.arn
  task_role_arn           = aws_iam_role.ecs_task_role.arn
  container_definitions = jsonencode([
    {
      name      = var.container_name,
      image     = "${var.ecr_repository_url}:${var.container_image_tag}",
      # user = "33:33",
      user = "0:0",
      essential = true,
      mountPoints: [{
        "sourceVolume": "wp-content",
        "containerPath": "/var/www/html/"
        # "containerPath": "/var/www/html/wp-content/"
      }],
      environment = [
        {
          name  = "WORDPRESS_DB_NAME",
          value = var.db_name
        },
        {
          name  = "WORDPRESS_DB_HOST",
          value = "${var.db_host}:3306"
        },
        {
          name  = "WORDPRESS_DB_USER",
          value = "XXXX"
        },
        {
          name  = "WORDPRESS_DB_PASSWORD",
          value = "XXXX"
        },
        {
          name  = "TAR_OPTIONS",
          value = "--no-same-owner"
        },
        # {
        #   name  = "WP_HOME",
        #   value = "https://example.com"
        # },
        # {
        #   name  = "WP_SITEURL",
        #   value = "https://example.com"
        # }
      ],
      portMappings = [{
        containerPort = var.container_port,
        hostPort      = var.container_port,
        protocol      = "tcp"
      }],
      logConfiguration = {
        logDriver = "awslogs",
        options = {
          "awslogs-group"         = aws_cloudwatch_log_group.ecs_logs.name,
          "awslogs-region"        = var.aws_region,
          "awslogs-stream-prefix" = "ecs"
        }
      }
    }
  ])
</code>
LoadBalancer Terraform:
<code>resource "aws_lb" "nan_lb" {
  name                       = var.lb_name
  internal                   = false # Set to false if you want to expose the load balancer to the internet. Cloudfront need it.
  load_balancer_type         = "application"
  security_groups = [aws_security_group.allow_all.id]
  enable_deletion_protection = false
  subnets                    = [var.subnet_a_id, var.subnet_b_id]
  access_logs {
    bucket  = aws_s3_bucket.lb_logs.id
    enabled = true
  }
}
</code>
Cloudfront Terraform:
<code># CloudFront Distribution Configuration
resource "aws_cloudfront_distribution" "cloudfront_dist" {
  depends_on   = [aws_wafv2_web_acl.nan_web_acl]
  provider     = aws.east
  aliases      = [var.domain_name, "www.${var.domain_name}"]
  http_version = "http2and3"
  web_acl_id   = aws_wafv2_web_acl.nan_web_acl.arn
  # https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html
  price_class = "PriceClass_100"

  origin {
    domain_name = aws_lb.nan_lb.dns_name
    origin_id   = "nan_lb"

    custom_origin_config {
      http_port                = 80
      https_port               = 80
      origin_protocol_policy   = "http-only"
      origin_ssl_protocols     = ["TLSv1.2"]
      origin_keepalive_timeout = 5
      origin_read_timeout      = 30
    }
  }

  enabled             = true
  is_ipv6_enabled     = true
  comment             = "CloudFront distribution for nan-woocommerce"
  default_root_object = "index.php"
  # default_root_object = "index.html"

  default_cache_behavior {
    allowed_methods  = ["GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"]
    cached_methods   = ["GET", "HEAD", "OPTIONS"]
    target_origin_id = "nan_lb"
    compress         = true

    forwarded_values {
      query_string = true
      query_string_cache_keys = ["*"]

      headers = ["Origin"]

      cookies {
        forward           = "whitelist"
        whitelisted_names = ["comment_*", "wordpress_*", "wp-settings-*"]
      }
    }

    viewer_protocol_policy = "redirect-to-https"
    min_ttl                = 0
    default_ttl            = 300
    max_ttl                = 31536000
  }
  ..........
  ..............
</code>
Question:
Does anyone perhaps know where the problem us and how to solve it?
Comment: What happens when you uncomment the `WP_HOME` and `WP_SITEURL` environment variables in the task definition, and redeploy?
Answer: For future.
There were two problems.

Bad caching in Cloudfront. I disabled the cache and then adjusted it. After that, I didn't have CSS styles.

CSS styles were not loaded because my LoadBalancer had port 80 instead of 443.


How to show parent objects attribute in gridview? ASP.NET

Question: Lets say i've got an employee table, and a company table. Every employee belongs to a company, so there is a foreign key column in the employee table on the company table.
I've created a gridview component on the default.aspx, for the employee and bound it to the database table with an sqldatasource. So I can see all the data, but i would like that instead of the company_id field, the gridview would show the companys name, which the user belongs to.
How to do that?
Answer: You should deal with it in data layer, not UI. Use SQL Join in SelectCommand property of SqlDataSource.
More about SQL Join types:
http://www.w3schools.com/sql/sql_join.asp
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html


Proof that Compact set is Closed and Bounded

Question: I came across the following problem while reading Spivak's Calculus on Manifolds.

Prove that a compact subset of $\mathbb{R}^n$ is closed and bounded.

The definition of an open set in the book is a set $A$ in which for all $x \in \mathbb{A}$, there exists an open rectangle $U$ such that $x \in U \subset A$. The definition of a closed set is a set $A$ in which $\mathbb{R}^n - A$ is open. The definition of a compact subset of $\mathbb{R}^n$ is a set $A$ in which for all open covers of $A$ (that is, collections of open sets that cover $A$), there exists a finite subcover of $A$. The boundary of a set $A$ is defined as the set of all points $x\in A$ such that for all open rectangles $U$ that contain $x$, $U$ contains points inside $A$ and outside $A$.
I attempted proof by contradiction first, asking myself a characteristic of not closed sets. Then I realized that if a set $A$ is closed, then $A$ must contain the boundary. I came up with the following proof

If $B$ is an open set and $x \in \text{Boundary}(B)$, then for all open rectangles $C$ such that $x\in C$, $C$ contains points of both $B$ and $\mathbb{R}^n - B$. This implies that $x \not\in B$. If $A$ is closed, then $\mathbb{R}^n - A$ is open, so the boundary of $A$ is not in $\mathbb{R}^n - A$, implying that the boundary of $A$ must be in $A$.

Now using this, I came up with a proof for the problem.

Let $A$ be a compact set. First, we show that $A$ must be bounded. Suppose that $A$ is not bounded. Then any finite open cover will only cover a finite volume, so this cannot hold. Now suppose that $A$ is not closed. Then there exists some $x$ in the boundary of $A$ such that $x$ is not in $A$. Now consider an open rectangle $U_1$ that contains $A$. Because an open rectangle is open, we must have that there exists some open rectangle $U_2$ that contains $x$ and is contained in $U_1$. By induction, we can show that there is a chain of open rectangles such that,
  $$x \in \cdots \subset U_3 \subset U_2 \subset U_1.$$
  Now let $V_k = U_k + \text{Boundary } U_k$, which is closed.
  Then the open cover
  $$ \{U_1 - V_3, U_2 - V_4, U_3- V_5, \dots \}$$
  has no finite subcover since taking any cover out will exclude some boundary of an open rectangle.

The above argument could be made more rigorous. However, is the reasoning completely valid? Also, what is a simpler solution to the problem?
Answer: I think that your argument is simple enough, though it has some holes. First, you claim that any finite open cover has finite volume. This may not be true if the open sets are unbounded. Instead, construct an open cover (Say, the rectangle of side lengths all 1 centered at $x$ for all $x\in A$) which contains only bounded open sets. Then there still must exist a finite subcover. Then this argument works (assuming you can prove that bounded open sets have finite volume, and that finite volume implies boundedness). Perhaps an easier way than volume is to go back to the definition of boundedness. If your finite subcover is $\{U_1,...,U_n\}$, and for $x,y\in U_i$, $d(x,y)<1$, then for $x,y\in A$, the triangle inequality implies $d(x,y)\leq 2n$. This requires a little work, but it is not too hard.
For closed, this looks pretty good, but make sure that $V_{n+1}\subset U_n$. As stated right now, you could have $U_1=U_2=U_3=...$ so that $U_1-V_3=\emptyset$, so the cover you construct would not really be a cover.
Answer: Alternatively you could use a similar construct and collapse both cases ($A$ is open and $A$ is unbounded) into the same case. Your construct in the first case is basically that you construct a covering of "shells" around a limit point outside $A$, where each "shell" is essential to cover $A$.
The same can be done with the unbounded case in which you just use ever larger and smaller rings around the origin to cover the whole space (except for the origin for which we throw in a ball around).
If we for example let the "shells" be anulli we have that a finite subcovering will again be contain inside an anulli (since we have a minimial inner radius and a maximal outer radius). The subcover of the space will consequently be bounded.
For the case where $A$ is not closed we can build a sequence of annuli round a limit point outside $A$ in which case we find that a finite subcover of $A$ will have a inner radius and consequently leaving a bit around $x$ out.


Is there exist an additive but unbounded function?

Question: I just learned that the function that is additive and bounded near $0$ on Real has the only form of $f(x)=cx$, where $c$ is a constant number. We say that a function $f$ is additive iff $f(x+y)=f(x)+f(y), \forall x, y \in \mathbb{R}$. We say it is bounded near $0$ iff there exists $a>0$ and $M>0 $ such that if $|x|<a$, then $|f(x)|<M$. I wonder whether there exist an additive function but is unbounded everywhere?
Any assistance is greatly appreciated!
Comment: A strange example can be made the following way. Consider R as a vector space over Q. It has a Hamel basis (this follows from the axiom of choice); take any coordinate function corresponding to this basis. It is additive by definition, but it is clearly not of the form `c x` (as it's values are rationals), so it is unbounded.
Comment: I was thinking of the same example.  I wonder if one exists without (any form of) AC.
Comment: @lisyarus make it an answer?
Comment: @Tom sure, made an answer.
Answer: A non-constructive example of an unbounded additive function can be achieved as follows.
Consider $\mathbb{R}$ to be a vector space over $\mathbb{Q}$ (a continuum-dimensioned one). By the axiom of choice, it has a Hamel basis. Take any of the coordinate functions corresponding to this basis. It is additive as any coordinate function, but it cannot be represented as $f(x) = c x$, as it's codomain is $\mathbb{Q}$, consequently, it is unbounded.


WebRequest.Create throws "Value cannot be null. Parameter name: str" exception

Question: I wrote a wrapper around HttpWebRequest with the constructor :

<code>    public MyHttpRequest(string requestUrl)
    {
        this.webRequest = (HttpWebRequest)WebRequest.Create(requestUrl);
    }
</code>

when I pass a vaild url that works in IE :

http://www.google.co.il/search?q=%D7%A9%D7%9E%D7%A8+%D7%97%D7%A1%D7%95%D7%9F&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

I get

System.ArgumentNullException occurred
    Message="Value cannot be null.\r\nParameter name: str"
    Source="mscorlib"
    ParamName="str"
    StackTrace:
         at System.Security.Permissions.FileIOPermission.HasIllegalCharacters(String[] str)
         at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
         at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)
         at System.Uri.ParseConfigFile(String file, IdnScopeFromConfig& idnStateConfig, IriParsingFromConfig& iriParsingConfig)
         at System.Uri.GetConfig(UriIdnScope& idnScope, Boolean& iriParsing)
         at System.Uri.InitializeUriConfig()
         at System.Uri.InitializeUri(ParsingError err, UriKind uriKind, UriFormatException& e)
         at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
         at System.Uri..ctor(String uriString)
         at System.Net.WebRequest.Create(String requestUriString)

Why is that ? how do i fix it ?
Comment: Which version of the .NET Framework did this occur on?

I tried it with v3.5, and it did not give me the exception.
Comment: This looks like a bug. Can you post thiss question on the Microsoft NCL support group (http://social.msdn.microsoft.com/forums/en-us/ncl)
Comment: .NET 3.5
i submitted the post to MS NCL
Answer: Unescape the url, then try again.
Comment: How to escape: http://stackoverflow.com/questions/6519222/unescape-an-escaped-url-in-c-sharp


Can I add 2 encrypted strings together and decrypt them?

Question: I have 2 methods to generate 2 different data and need to save them in one encrypted file.
Can I achieve this by adding encrypted stringA + encrypted stringB, then decrypt them later?
Or
I have to encrpt stringA -> save as file -> read the file & decrypt to stringA ->
stringA + stringB -> encrypt ?
NB, I am using Rijndael(AES) and someone suggested using customerized stream, will it work?
Any thoughts?
Many thanks~
Answer: If you're using ECB (electronic code book), then it should be possible (assuming they use the same encryption key), because each block is decrypted independent of other blocks. If you're using CBC (cipher block chaining) this will not work because each block is encrypted using data from the previous block. However, using ECB is way less secure than CBC.
Answer: If you encrypt each separately, and know the length of each block of encrypted text, you can decrypt them later individually.
Something like this format would probably work:
<code>Message1Length
Message1Content
Message2Content
</code>
Read the Message1Length number of bytes into the message and store it as encryptedMessage1 or something.  Then read from that point to the End of File and store it as encryptedMessage2.  Then decrypt them both individually.
Answer: It depends on which encryption algorithm you use. For block ciphers in ECB mode, it would work - but ECB mode is considered very insecure exactly because of this (it makes certain kinds of attack on the cipher very easy).
Comment: Hey Michael - I'll upvote your answer if you upvote mine. :-)


flow type error on type State and type Props

Question: I am using flow, and mostly things are working out, but I am catching this error in my linting on something as trivial as this:
 type Props = {
  actions: object,
  products: object,
 };

 type State = {
   email: string,
   name: string
 };

 class SomeComponent extends Component {
  // etc..
 }

The linting errors show right after the "type" keyword and the error is:
"Expecting newline or semicolon"
Answer: There are 2 possibilities that I see here:
1) object should be capitalized (Object)
2) You are not using eslint-plugin-flowtype
Comment: you sure it should be "Object", I thought object, string, boolean are acceptable and preferred. No?
Comment: 100% sure. To be even more specific, it's recommended that you use [sealed object types](https://flow.org/en/docs/types/objects/) and not plain Objects, because almost any variable in JavaScript inherits from Object. You can try it for yourself [here](https://flow.org/try/): Attempting to use lowercase `object` will throw the exception `identifier `object`. Could not resolve name`. Note that lowercase `string` and `boolean` are indeed preferred.
Comment: hmm, interesting. I am not catching any errors with lowercase, so I never noticed. Interesting.. thanks for the info. I will turn my object in Object! :-)
Answer: This may seem silly, but I had to go into IntelliJ IDEA -> Preferences -> Languages & Frameworks -> JavaScript and change JavaScript language version to Flow (was previously React JSX). I was already using eslint-plugin-flowtype, and was wondering why it was not working.


matrices with nullspace the complement of the range

Question: I've been studying Linear Algebra Done Right by Axler.  I've noticed some matrices pop up over and over again with an interesting property: if $V$ is a finite-dimensional vector space and $T \in \mathcal{L}(V)$ is this particular kind of operator, then
$$
V = \operatorname{null} T \oplus \operatorname{range} T.
$$
If an inner product is lying around, this is always true of normal operators, for which
$$
\operatorname{null} T = (\operatorname{range} T)^\perp,
$$
and for any operator $T$ in a vector space it is always true of the operator $T^{\operatorname{dim} V}$.  It's also true of invertible operators and projection operators!  But having this property does not imply that an operator is normal, or is invertible, or is the $\operatorname{dim} V$-th power of another operator.
Is there a name for the set of operators with the property $V = \operatorname{null}T \oplus \operatorname{range}T$?
Answer: In case it wasn't clear: Suppose $T$ satisfies the condition given in the question.
If $0$ is an eigenvalue of $T$, its algebraic multiplicity must equal its geometric multiplicity, i.e. when put into Jordan normal form, the Jordan blocks for eigenvalue $0$ are each $1 \times 1$.
Sanity checking that your examples satisfy this condition:

Normal matrices are diagonalizable, so the Jordan blocks each have size $1 \times 1$.
Similarly, orthogonal projections are symmetric, and are therefore diagonalizable.
Raising an $m \times m$ zero-eigenvalue Jordan block to the $m$th power (or higher) yields the zero matrix. So the zero-eigenvalue Jordan blocks of $T^{\dim V}$ each are $1 \times 1$.
Invertible operators have no zero eigenvalues so the condition holds vacuously.
Comment: The statement above that **if 0 is an eigenvalue of $T$, then its algebraic multiplicity equals its algebraic multiplicity** is false.
Comment: @SheldonAxler Could you clarify why it is false? I am mainly trying to say that the Jordan blocks for the eigenvalue $0$ must all be $1 \times 1$, and the other answer also agrees with this. In this case, the geometric multiplicity (number of Jordan blocks) equals the algebraic multiplicity (number of zeros on the diagonal).
Comment: @MorganRodgers Thanks, I've updated my answer to make this clearer.
Answer: I doubt there is a special name for operators $T:V\to V$ with $V=\ker T\oplus\operatorname{im} T$.  When $V$ is finite dimensional, one can characterize these operators as those $T$ with the property that $T^2(v)=0\Rightarrow T(v)=0$ ($T^2=T\circ T$).  Another way to say this is that the Jordan form decomposition for $T$ has one block, which is diagonal, or no block, for the eigenvalue $0$.  Edit: I stated the Jordan form alternative incorrectly.  I should have said every Jordan block for the eigenvalue $0$ is $1\times 1$.
To see that this characterization is valid, we show that for any vector space $V$, the condition $T^2(v)=0\Rightarrow T(v)=0$ is equivalent to the condition that $\ker T\cap\operatorname{im} T=0$.  Assume first that $T^2(v)=0\Rightarrow T(v)=0$ and $x\in \ker T\cap\operatorname{im} T$. Then $x=T(v)$ for some $v\in V$ and so $T^2(v)=T(x)=0$, whence $x=T(v)=0$.  Conversely, if $\ker T\cap\operatorname{im} T=0$ and $T^2(v)=0$, then $T(v)\in \ker T\cap\operatorname{im} T$, whence $T(v)=0$.  The equivalence with $V=\ker T\oplus\operatorname{im} T$ in the finite dimensional case now follows from the dimension formula.
I don't see any better characterization of such operators and that makes me think there isn't a special name for such operators.


Building a model for research question

Question: The question of interest is whether the relationship between A and B is the same for each level of Type. The data is in long format and looks somewhat like this...

A is a numerical variable and so is B. Type is a factor with 4 levels...
I'm trying to answer the question in R and so far I've come up with this model
lm(A ~ B + Type + B:Type, data = sample)
Running anova on this, I can say that there is an interaction term between B & Type due to the low p-value on the interaction term, which would mean that since the effect of B depends on Type, the relationship of A~B is dependent on Type. But I feel that there is a better way to build a model for this question.
Any help would be greatly appreciated!
Comment: Welcome to CV. You would be much more likely to get a response if you carefully stipulate your research question(s) rather than the oblique manner you've used here.
Comment: If possible, can you also explain the reason for this feeling? What led you to think so? It may give clues as to what needs to be explained.
Answer: The model you have fitted is an appropriate one* for investigating whether the lines differ.
A non-zero interaction says whether the slopes are different. (The coefficient for Type itself relates to a difference in intercept.)
*(as long as the assumptions under which your p-value was calculated were reasonably close to true)
However, it doesn't show you much about how big the effect is -- a statistically significant effect may be very small. As such, I'd seek to visualize the effect by plotting both the data and the fitted pair of regression lines (each colored by "Type").

Building a model for research question


Efficient algorithm for computing Vandermonde determinant

Question: The determinant of Vandermonde matrix
$$V=\left[\begin{matrix}
1 & x_1 & x_1^2 & \cdots & x_1^{n-1} \\
1 & x_2 & x_2^2 & \cdots & x_2^{n-1} \\
1 & x_3 & x_3^2 & \cdots & x_3^{n-1} \\
\vdots & \vdots & \vdots & \ddots & \vdots \\
1 & x_n & x_n^2 & \cdots & x_n^{n-1} \\
\end{matrix}\right]$$
can be represented as a product of pairwise differences between $x_i$s:
$$\det(V)=\prod_{i<j}x_j-x_i.$$
Is there an algorithm that computes this determinant more quickly than by trivially multiplying those $O(n^2)$ differences?
Comment: See the on-line MDPI document entitled (somewhat strangely) "Recursive matrix calculation paradigm by the example of structured matrix" by Jerzy S. Respondek
Answer: In this answer, I will provide a sub-quadratic algorithm.
Assumptions & Definitions

Let $\mathbb{F}$ be some field
Let $M(n)$ be the cost of a polynomial multiplication algorithm over $\mathbb{F}.$ And suppose that :
$$
2M(\tfrac{n}{2})  \le M(n)
$$

We will define $\Phi(x_1,\dots,x_n)$ as the determinant of the Vandermonde matrix $V:$
$$
V=\begin{pmatrix}
1 & x_1 & \dots & x_1^{n-1} \\
1 & x_2 & \dots & x_2^{n-1} \\
\vdots & \vdots& \ddots &\vdots \\
1& x_{n} & \dots & x_{n}^{n-1}
\end{pmatrix}
$$

Algorithm

Let $n\in\mathbb{N},$ and let $m=\lfloor \tfrac{n}{2} \rfloor$

Let $\boldsymbol{x}\in \mathbb{F}^n.$

We will assume that $x_1,\dots,x_n$ are pairwise distinct as otherwise, $\Phi(\boldsymbol{x})=0.$

1. Recursion
We have the following:
$$
\begin{align*}
\Phi(\boldsymbol{x}) &=  \prod_{1\le i<j \le n} x_j-x_i \\
&= \Phi(x_1,\dots,x_m) \times \Phi(x_{m+1},\dots,x_n) \times \prod_{i=1}^{m}\prod_{j=m+1}^{n}x_j-x_i  \\
&=\Phi(\boldsymbol{x}') \times \Phi(\boldsymbol{x''}) \times  \chi(\boldsymbol{x}',\boldsymbol{x''})
\end{align*}
$$
Where $\boldsymbol{x}'=(x_1,\dots,x_m)$ and $\boldsymbol{x}''=(x_{m+1},\dots,x_n)$
2. Calculating $\chi$
Now we arrived to two recursive calculations of $\Phi$ plus one evaluation of the term:
$$
\chi(\boldsymbol{x}',\boldsymbol{x}'')=\prod_{i=1}^{m}\prod_{j=m+1}^{n}x_j-x_i
$$
This term has to be efficiently calculated to get a sub-quadratic complexity. Fortunately, This is in fact possible
To demonstrate this, We will define the polynomial $H$ as follows:
$$
H(t)=\chi(\boldsymbol{x}',t)=\prod_{i=1}^{m}t-x_i
$$
Now it is very clear that $\chi(\boldsymbol{x}',\boldsymbol{x}'') = \prod_{j=m+1}^{n} H(x_j).$ And with that, we only have to evaluate the polynomial $H$ at the $n-m$ points. This can be done in $\mathcal{O}(M(n) \log n)$ using fast multi-point evaluation
3. Complexity
Now, let $T_n$ the cost of Algorithm 1 at the worst-case scenario:
$$
T_n = T_{m} + T_{n-m} + \mathcal{O}(M(n) \log n)
$$
With that, we can easily deduce that:
$$
T_n = \mathcal{O}\left(M(n)\cdot  (\log n)^2\right)
$$
If $\mathbb{F}$ allows a $\mathcal{O}(n \log n)$ polynomial multiplication algorithm (FFT-based), we get:
$$
T_n= \mathcal{O}(n (\log n)^3)
$$


pgadmin font size all messed up

Question: pgadmin font size all messed up one day I wake up! I tried
a. restart unclesoft
b. re-install pgadmin
c.add 'qt.conf'
None of above helped.
Answer: oh... After struggled for hours. CTRL with "-" (Minus) like a crazy man bring it back...
(I tried that very first go didnt work. You have to repeat this like crazy)
Comment: Try CTRL + 0 (zero), which is the usual way apps reset zoom to default.
Comment: How do you make it larger, I have de opposite problem
Comment: perhaps "CRTL +" ?
Comment: "Ctrl +" and "Ctrl 0" worked for me on Windows (11). Think you have to click on the right panel to get it to work, as didn't first time, till I found this and persevered.
Answer: This can be tricky as CTRL with "+" or "-" does not work when using the symbols from the keypad.
Using CTRL and "+" or "-" from the keyboard (next to backspace) works without issues (Using pgAdmin version 4.7).
Answer: For Mac, "command +/-". Thx
Answer: Increase the text size on the screen (pgAddmin4):

variant 1 : ⌘ %
variant 2 : Shift ⌘ %
if both variants do not work,
then: "pgAddmin4" -> "Reset Layout", then try option 1 or 2

Change the size of texts on the screen: ⌘ -
Tested MacBook Pro, macOS Ventura 13.6

pgadmin font size all messed up


Seletor CSS para tabelas

Question: Estou fazendo uma refatoração em um código e tem um regra CSS que está mudando o display de todas tabelas. Uma tabela em específico está visualmente quebrada por conta dessa alteração. Como ainda não vi todo o código, temo que se eu sobrescrever esta regra possa quebrar outras estruturas que são dependentes dela. Existe algum seletor CSS que eu consiga dizer: "Pegue todas as tabelas exceto as com classe .tabela-isolada" ?
table, thead, tbody, th, td, tr {
    display: block;
}

Answer: Você pode usar o pseudo-seletor :not assim:
:not(.tabela-isolada)

Como tem vários estilos, e quer excluir pela tabela, vai ficar um pouco extenso:
table:not(.tabela-isolada),
:not(.tabela-isolada) > thead,
:not(.tabela-isolada) > tbody,
:not(.tabela-isolada) > * > th,
:not(.tabela-isolada) > * > td,
:not(.tabela-isolada) > * > tr {
    display: block;
}

Referência na MDN - note pela MDN, que o suporte desse seletor não é amplo, principalmente se falando de IE
Comment: +1 Ficaria mais fácil visualizar se houvesse quebra de linha nas vírgulas :)
Comment: @LeandroAmorim: também acho, editei a resposta. =D
Answer: Acho que o que você quer seja isso:
table, thead, tbody, th, td, tr:not('.tabela-isolada') {
    display: block;
}

:not() é uma pseudo-class de negação.

Obs: Não é suportada por todos os browsers, como especificado no MDN

Referências:

MDN
css-tricks
Answer: Vamos por partes, esse código
table, thead, tbody, th, td, tr {
    display: block;
}

está colocando diplay block em todos esses elementos:

table
thead
tbody
th
td
tr

Usando o padrão do w3 para ter o efeito "original" da tabela você teria que fazer algo assim:
table.tabela-isolada { display: table !important; }
table.tabela-isolada tr { display: table-row !important; }
table.tabela-isolada thead { display: table-header-group !important; }
table.tabela-isolada tbody { display: table-row-group !important; }
table.tabela-isolada tfoot { display: table-footer-group !important; }
table.tabela-isolada col { display: table-column !important; }
table.tabela-isolada colgroup { display: table-column-group !important; }
table.tabela-isolada td,
table.tabela-isolada th { display: table-cell !important; }
table.tabela-isolada caption { display: table-caption !important; }

E para não ter problemas de sobrescrita de propriedade insira esse CSS posterior ao que coloca o display: block .
Comment: +1 pela solução que funciona em browsers antigos.

Seletor CSS para tabelas


Generating functions word problem(balloons)

Question: Find the generating function for the number of ways to create a bunch of n balloons selected from white, gold, and blue balloons so that the bunch contains
at least one white balloon, at least one gold balloon, and at most two blue balloons. How many ways are there to create a bunch of 10 balloons subject to these
requirements?
So I have $$\frac{x^2}{(1-x)^2} \cdot \frac{(1-x^3)}{1-x}$$ and I have no idea where to go from here. Have a test on this material in the morning so any help would be greatly appreciated.
Comment: I'd start by assuming one gold and one white since you're given that as a precondition and then concentrate on the blues in the remaining eight.
Comment: HINT at least two is the same as not zero or one
Comment: HINT HINT find your combinations forumla
Comment: Yeah, that guy is most likely in my class. Looks like he deleted the question. I've looked at that and still have no idea what to do. I know I need to find the coefficient of x^10 but I don't know a general way to accomplish it without counting the ways to get x^10 one by one.
Answer: You have $$(x^2-x^5)\frac{1}{(1-x)^3}$$
We have the generating function $$\frac{1}{(1-x)^3}=\sum_{n\ge 0} {n+2\choose 2}x^n$$
Multiply by $x^k$ gives $$x^k\frac{1}{(1-x)^3}=\sum_{n\ge 0}{n+2\choose 2}x^{n+k}$$
We reindex using $m=n+k$ to get $$x^k\frac{1}{(1-x)^3}=\sum_{m\ge k}{m-k+2\choose 2}x^m$$
We do this twice, for $k=2$ and $k=5$, then subtract.  The result is
$$(x^2-x^5)\frac{1}{(1-x)^3}=\sum_{m\ge 5}{m-2+2\choose 2}-{m-5+2\choose 2}x^m + \sum_{m=2}^4{m-2+2\choose 2}x^m$$
Hence your answer (for $m\ge 5$) is ${m\choose 2}-{m-3\choose 2}$.  You want $m=10$, so ${10\choose 2}-{7\choose 2}=24$.
Comment: Where did the generating function come from?
Comment: The first line is from the original post. "I have no idea where to go from here."
Comment: Or did you mean the second line?  That's a [standard formula](https://en.wikipedia.org/wiki/Generating_function#Ordinary_generating_functions).


If $B$ is an algebra, $X \subseteq B$ and $A$ the smallest subset that extends $X$, then $A= \bigcup_{n < \omega} A_n$

Question: I need to prove the next thing:
Let $\textbf{B} = \langle B, (b_i)_{i \in I}, (g_j)_{j\in J} \rangle$. Let $X \subseteq B$ and let $A$ be the smallest subset of $B$ which extends $X$ and is closed in $\textbf{B}$. Then $A= \bigcup_{n < \omega} A_n$ where $A_0 = X \cup \{ b_i : i \in I\}$ and $A_{n+1}= A_n \cup \bigcup_{j \in J}g_j[A^{n_j}_n]$.
So, I know I need to prove both inclusions.
For the first one, $ \bigcup_{n < \omega} A_n \subseteq A$. I need to do it by induction, $A_n \subseteq A$. Let $A_0 = X \cup \{ b_i : i \in I\}$, but I don't know how to justify that it is. I mean, it "clearly" is a subset, because of the way it is constructed, but I don't know how to formally explain that, I would really appreciate the help.
Now, As inductive hypothesis, assume $A_n \subseteq A$. As $A_\{n+1\}= A_n \cup \bigcup_{j \in J}g_j[A^{n_j}_n]$. Again, I have the notion: I know that $A_n$ is a subset by hypothesis, and I know that the other elements are also part of the subset because of the form it has, but again, I am stuck when I try to write it in a formal way, and I feel like I might be missing details.
For the other part of the inclusion, I have that $A \subseteq \bigcup_{n < \omega} A_n$. As $\bigcup_{n< \omega} A_n$ is a closed subset of $B$, and it contains $X$, it implies that $A \subseteq \bigcup_{n< \omega} A_n$, but in this case I know I'm missing on the details, but I have issues figuring them out. I would really appreciate your help in working this proof out. I'm working on improving my writing abilities so I really appreciate input on how to express things the best way possible. Thank you very much.
Answer: First recall the definition of closed: A subset $A \subseteq B$ is closed in $\def\B{\mathbf B}\B$ if

(1) $b_i \in A$ for $i \in I$.

That is $A$ contains all constants of the algebra $\B$.

(2) $g_j[A^{n_j}] \subseteq A$ for all $j \in J$, here $n_j$ is the arity of the operation $g_j$, that is $g_j \colon B^{n_j} \to B$.

That is $A$ is closed under all operations $g_j$.
To show that $A_0 \subseteq A$, note that as $A$ is closed, we have $\{b_i \colon i \in I\} \subseteq A$ by (1) above, as $X \subseteq A$ by definition of $A$ we have $A_0 \subseteq A$.
Now suppose $A_n \subseteq A$. By (2) above, for each $j \in J$ we have $g_j[A_n^{n_j}] \subseteq g_j[A^{n_j}] \subseteq A$, as $A_n \subseteq A$, we have $A_{n+1} = A_n \cup \bigcup_j g_j[A_n^{n_j}] \subseteq A$.
For the other inclusion, your idea is right: If we can show $\bigcup_n A_n$ is closed in $\B$, we are done (as $\bigcup_n A_n$ contains $X$ and $A$ is the smallest closed subset which contains $X$).
For (1), note that for each $i \in I$, we have $b_i \in A_0 \subseteq \bigcup_n A_n$. For (2), let $j \in J$ and $a_1, \ldots, a_{n_j} \in \bigcup_n A_n$. Then there are natural numbers $k_l$ such that $a_l \in A_{k_l}$ for each $l$. Let $ k = \max_l k_l$. As $(A_n)$ is increasing, we have $a_l \in A_k$ for each $l$. But now
$$ g_j(a_1, \ldots, a_{n_j}) \in g_j[A_k^{n_j}] \subseteq A_{k+1} \subseteq \bigcup_n A_n $$
hence $\bigcup_n A_n$ is closed.
Comment: Thank you very much for this answer, it was very clear and the way you stated things helped me not only understand what had to be done, but also the right way to express it.


How do I disable a constructor for only a particular method in Codeigniter?

Question: I have more than 30 methods in this User Controller.I don't want to create another controller just for this single method.
class User extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        if(empty($_SESSION['userid'])){
            $error['error'][] = "Please LogIn";
            echo json_encode($error);
            exit;
        }
    }

    public function index(){
    }

    public function get_public_pages(){

    }

}

I don't want the constructor function to run when accessing get_public_pages method.How can I do it?
Comment: you can try vinod's answer but **constructor** will always initialize else you can try moving your code in a `pre-controller hook` and check, but that would be an overkill.
Comment: Use codeigniter session instead of $_SESSION['userid']
Comment: Thanks but that is not the problem here! :)
Answer: Try this,
public function __construct(){
  parent::__construct();
  $method = $this->router->fetch_method();

  if(empty($method ) && $method != 'get_public_pages'){
    if(empty($_SESSION['userid'])){
        $error['error'][] = "Please LogIn";
        echo json_encode($error);
        exit;
    }
 }
}

Comment: I just want to disable section for this get_public_pages method.
I'm not using codeigniter sessions!
Comment: http://stackoverflow.com/questions/6833830/why-does-codeigniter-store-its-sessiondata-in-a-cookie
Comment: Nice solution, Worked well for me.


how to convert a char array into string in java

Question: this is my porter stemmer program....i got the output in char array in stem() function....and i tried to convert that into string...but it takes the older value and not the new one.that is for example-"looking" is stemmed to give "look"....."look" is in char array (b[c] in stem ()) but while converting it into string takes the value "looking"
    package file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.StringTokenizer;
import java.util.Vector;

/**
 *
 * @author sky
 */

public class stemmer {

    public static String line1,line,element,sentence,str;
  private char[] b;
   private int i,     /* offset into b */
               i_end, /* offset to end of stemmed word */
               j, k;
  private static final int INC = 50;
                     /* unit of size whereby b is increased */

   public stemmer()
   {
        //b = new char[INC];
      i = 0;
      i_end = 0;
   }

   /**
    * Add a character to the word being stemmed.  When you are finished
    * adding characters, you can call stem(void) to stem the word.
    */

   public void add(char ch)
   {
         System.out.println("in add() function");
       if (i == b.length)
      {
          char[] new_b = new char[i+INC];
         for (int c = 0; c = b.length)
      {
         char[] new_b = new char[i+wLen+INC];
         for (int c = 0; c < i; c++)
             new_b[c] = b[c];
             b = new_b;
      }
      for (int c = 0; c < wLen; c++)
          b[i++] = w[c];
   }
public void addstring(String s1)
{
  b=new  char[s1.length()];
  for(int k=0;k<s1.length();k++)
  {
         b[k] = s1.charAt(k);
  //System.out.println(b[k]);
  }
  i=s1.length();
}
   /**
    * After a word has been stemmed, it can be retrieved by toString(),
    * or a reference to the internal buffer can be retrieved by getResultBuffer
    * and getResultLength (which is generally more efficient.)
    */
   public String toString() { return new String(b,0,i_end); }

   /**
    * Returns the length of the word resulting from the stemming process.
    */
   public int getResultLength() { return i_end; }

   /**
    * Returns a reference to a character buffer containing the results of
    * the stemming process.  You also need to consult getResultLength()
    * to determine the length of the result.
    */
   public char[] getResultBuffer() { return b; }

   /* cons(i) is true <=> b[i] is a consonant. */

   private final boolean cons(int i)
   {  switch (b[i])
      {  case 'a': case 'e': case 'i': case 'o': case 'u': return false;
         case 'y': return (i==0) ? true : !cons(i-1);
         default: return true;
      }
   }

   /* m() measures the number of consonant sequences between 0 and j. if c is
      a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
      presence,

         <c><v>       gives 0
         <c>vc<v>     gives 1
         <c>vcvc<v>   gives 2
         <c>vcvcvc<v> gives 3
         ....
   */

   private final int m()
   {  int n = 0;
      int i = 0;
      while(true)
      {  if (i > j) return n;
         if (! cons(i)) break; i++;
      }
      i++;
      while(true)
      {  while(true)
         {  if (i > j) return n;
               if (cons(i)) break;
               i++;
         }
         i++;
         n++;
         while(true)
         {  if (i > j) return n;
            if (! cons(i)) break;
            i++;
         }
         i++;
       }
   }

   /* vowelinstem() is true <=> 0,...j contains a vowel */

   private final boolean vowelinstem()
   {  int i; for (i = 0; i <= j; i++) if (! cons(i)) return true;
      return false;
   }

   /* doublec(j) is true <=> j,(j-1) contain a double consonant. */

   private final boolean doublec(int j)
   {  if (j < 1) return false;
      if (b[j] != b[j-1]) return false;
      return cons(j);
   }

   /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
      and also if the second c is not w,x or y. this is used when trying to
      restore an e at the end of a short word. e.g.

         cav(e), lov(e), hop(e), crim(e), but
         snow, box, tray.

   */

   private final boolean cvc(int i)
   {  if (i < 2 || !cons(i) || cons(i-1) || !cons(i-2)) return false;
      {  int ch = b[i];
         if (ch == 'w' || ch == 'x' || ch == 'y') return false;
      }
      return true;
   }

   private final boolean ends(String s)
   {

       int l = s.length();
   int o = k-l+1;
      if (o < 0)
          return false;
      for (int i = 0; i < l; i++)
          if (b[o+i] != s.charAt(i))
          return false;
      j = k-l;
      return true;
   }

   /* setto(s) sets (j+1),...k to the characters in the string s, readjusting
      k. */

   private final void setto(String s)
   {  int l = s.length();
      int o = j+1;
      for (int i = 0; i < l; i++)
          b[o+i] = s.charAt(i);
      k = j+l;
   }

   /* r(s) is used further down. */

   private final void r(String s) { if (m() > 0) setto(s); }

   /* step1() gets rid of plurals and -ed or -ing. e.g.

          caresses  ->  caress
          ponies    ->  poni
          ties      ->  ti
          caress    ->  caress
          cats      ->  cat

          feed      ->  feed
          agreed    ->  agree
          disabled  ->  disable

          matting   ->  mat
          mating    ->  mate
          meeting   ->  meet
          milling   ->  mill
          messing   ->  mess

          meetings  ->  meet

   */

   private final void step1()
   {

       if (b[k] == 's')
      {  if (ends("sses")) k -= 2; else
         if (ends("ies")) setto("i"); else
         if (b[k-1] != 's') k--;
      }
      if (ends("eed")) { if (m() > 0) k--; } else
      if ((ends("ed") || ends("ing")) && vowelinstem())
      {  k = j;
         if (ends("at")) setto("ate"); else
         if (ends("bl")) setto("ble"); else
         if (ends("iz")) setto("ize"); else
         if (doublec(k))
         {  k--;
            {  int ch = b[k];
               if (ch == 'l' || ch == 's' || ch == 'z') k++;
            }
         }
         else if (m() == 1 && cvc(k)) setto("e");
     }

   }

   /* step2() turns terminal y to i when there is another vowel in the stem. */

   private final void step2() { if (ends("y") && vowelinstem()) b[k] = 'i'; }

   /* step3() maps double suffices to single ones. so -ization ( = -ize plus
      -ation) maps to -ize etc. note that the string before the suffix must give
      m() > 0. */

   private final void step3() { if (k == 0) return; /* For Bug 1 */ switch (b[k-1])
   {
       case 'a': if (ends("ational")) { r("ate"); break; }
                 if (ends("tional")) { r("tion"); break; }
                 break;
       case 'c': if (ends("enci")) { r("ence"); break; }
                 if (ends("anci")) { r("ance"); break; }
                 break;
       case 'e': if (ends("izer")) { r("ize"); break; }
                 break;
       case 'l': if (ends("bli")) { r("ble"); break; }
                 if (ends("alli")) { r("al"); break; }
                 if (ends("entli")) { r("ent"); break; }
                 if (ends("eli")) { r("e"); break; }
                 if (ends("ousli")) { r("ous"); break; }
                 break;
       case 'o': if (ends("ization")) { r("ize"); break; }
                 if (ends("ation")) { r("ate"); break; }
                 if (ends("ator")) { r("ate"); break; }
                 break;
       case 's': if (ends("alism")) { r("al"); break; }
                 if (ends("iveness")) { r("ive"); break; }
                 if (ends("fulness")) { r("ful"); break; }
                 if (ends("ousness")) { r("ous"); break; }
                 break;
       case 't': if (ends("aliti")) { r("al"); break; }
                 if (ends("iviti")) { r("ive"); break; }
                 if (ends("biliti")) { r("ble"); break; }
                 break;
       case 'g': if (ends("logi")) { r("log"); break; }
   } }

   /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */

   private final void step4() { switch (b[k])
   {
       case 'e': if (ends("icate")) { r("ic"); break; }
                 if (ends("ative")) { r(""); break; }
                 if (ends("alize")) { r("al"); break; }
                 break;
       case 'i': if (ends("iciti")) { r("ic"); break; }
                 break;
       case 'l': if (ends("ical")) { r("ic"); break; }
                 if (ends("ful")) { r(""); break; }
                 break;
       case 's': if (ends("ness")) { r(""); break; }
                 break;
   } }

   /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */

   private final void step5()
   {   if (k == 0) return; /* for Bug 1 */ switch (b[k-1])
       {  case 'a': if (ends("al")) break; return;
          case 'c': if (ends("ance")) break;
                    if (ends("ence")) break; return;
          case 'e': if (ends("er")) break; return;
          case 'i': if (ends("ic")) break; return;
          case 'l': if (ends("able")) break;
                    if (ends("ible")) break; return;
          case 'n': if (ends("ant")) break;
                    if (ends("ement")) break;
                    if (ends("ment")) break;
                    /* element etc. not stripped before the m */
                    if (ends("ent")) break; return;
          case 'o': if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
                                    /* j >= 0 fixes Bug 2 */
                    if (ends("ou")) break; return;
                    /* takes care of -ous */
          case 's': if (ends("ism")) break; return;
          case 't': if (ends("ate")) break;
                    if (ends("iti")) break; return;
          case 'u': if (ends("ous")) break; return;
          case 'v': if (ends("ive")) break; return;
          case 'z': if (ends("ize")) break; return;
          default: return;
       }
       if (m() > 1) k = j;
   }

   /* step6() removes a final -e if m() > 1. */

   private final void step6()
   {  j = k;
      if (b[k] == 'e')
      {  int a = m();
         if (a > 1 || a == 1 && !cvc(k-1)) k--;
      }
      if (b[k] == 'l' && doublec(k) && m() > 1) k--;
   }

   /** Stem the word placed into the Stemmer buffer through calls to add().
    * Returns true if the stemming process resulted in a word different
    * from the input.  You can retrieve the result with
    * getResultLength()/getResultBuffer() or toString().
    */
   public void stem()

   {
       //System.out.println(i);
        k = i - 1;
      if (k > 1)
      {
          step1();
          step2();
          step3();
          step4();
          step5();
          step6();
      }
      for(int c=0;c<=k;c++)
      {
         // System.out.print(b[c]);

      }
      str=new String(b);
 //System.out.println(str);
      sentence+=str+" ";
   System.out.println(sentence);

      i_end = k+1; i = 0;
   }
   public static void main(String[] args)
   {
         stemmer s = new stemmer();

       try
       {
     BufferedReader  br = new BufferedReader(new FileReader("D:/output.txt"));
     BufferedWriter output = new BufferedWriter(new FileWriter("D:/output1.txt"));
     String separator = System.getProperty("line.separator");
       while ((line = br.readLine()) != null)
            {
                    StringTokenizer st2 = new StringTokenizer(line, "\n");

                    while (st2.hasMoreElements())
                    {
                        String line1 = (String) st2.nextElement();
                        System.out.println(line1);
                        StringTokenizer st3 = new StringTokenizer(line1, " ");
                       // String sentence= new String();
                     while (st3.hasMoreTokens())
                     {
                        element=st3.nextToken();
                        s.addstring(element);
                        s.stem();
                      }
     output.append( separator+sentence);
     sentence="";
                    }
            }
        output.close();
       }

     //System.out.println(element);

//      s.addstring(element);
//      s.stem();
//      s.addstring("walks");
//      s.stem();
      //System.out.println("Output " +s.b);

       catch(Exception e)
       {

       }
}
}

Comment: This question is very confusing. We've no idea what `i` is, or what the various step methods do, or what the expected output is. Please read http://tinyurl.com/so-list
Comment: With more infos it will be easier to answer
Comment: Please write an SSCCE: http://sscce.org/
Answer: To convert char array to String use following statement:
String str=new String(char[]);

See the docs.
Comment: When providing code, it's preferable that that code should work, e.g. `char[] arr = {'a', 'b'}; String str = new String(arr);`.


Taxonomy Terms node count of different content type

Question: Hi I have a issue for which I searched everywhere but not getting any solution,
I have two content types Store and Deals with the following fields
Store is having the fields
1.Store-title
2.Logo
3.Categories--> Added as a taxonomy term field.
4.Outlets

When I am adding a node of type store I am selecting the corresponding category terms with it and saving.
Other content type Deal having the fields
1.Title
2.Store-title---> This field is of content type Store and is added here as a node reference.
3.Outlets

When I am adding a node of type deal I am selecting a store here( In deals content type, store-title is added as a node-reference), and selecting its outlets.

Issue:
I need a counter on the category terms, the counter should be based on  number of deals added to that particular store node on respective categories.

Hope you understand the issue,
I have seen the issue of same type where node counter is displayed but they show the count of nodes of the same content type where that taxonomy term is added like here http://www.brightwebsitedesign.com/how-to-use-views-aggregator-to-create-taxonomy-term-count-block,
But I have a bit different,  taxonomy is added to stores, but I need the count of deals( another content type) on the taxonomy term.
If you still need more clarification please let me know.
This is very urgent
Any help would be much appreciated!
Answer: You can achieve this with help of an additional relation. If you are following view creation from the post mentioned by you

After selecting ' Taxonomy term: Content with term ' add another relation and choose the node referenced field - reverse and choose Require this relationship. (in your case 2.Store-title---> This field is of content type Store and is added here as a node reference)
Now you will get your count of deals
Comment: Great it worked fine, but I am not able to maintain the hirarchy parent-child relationship, so that I can made it accordion type. Also I want the empty categories to be shown, this way they got hidden.
Comment: Maintaining the hierarchy here is must for me, I tried some modules like tree view, term reference tree, Hierarchical Select Taxonomy, but unfortunately not able to do.


Drupal 8 Webform Composite fieldset

Question: Is there a way to add fieldsets inside of a custom composite? Not looking to add anything repeatable, just simply group the fields together.
This get's the fieldset to show but I don't know how to add fields as children.
<code>$elements['grouped_fields'] = [
  '#type' => 'fieldset',
  '#title' => t('Grouped Fields')
];
</code>
Answer: Place the fields inside of the fieldset:
<code>$elements['grouped_fields']['field1'] = [
  '#type' => 'textfield',
  '#title' => t('Field 1'),
];
$elements['grouped_fields']['field2'] = [
  '#type' => 'textfield',
  '#title' => t('Field 2'),
];
// ...
</code>
Comment: Boom! You rock.

Drupal 8 Webform Composite fieldset


How to pass multiple variable and auto redirect to another php file?

Question: If want to pass multiple variables in save.php
header('Location: save.php?id_no='.$id_no.'?f_name='.$f_name.'?l_name='.$l_name.);

Comment: put in cookies and access them in next page..if not logged in
if after logged in then use Sessions
Answer: Change from
header('Location: save.php?id_no='.$id_no.'?f_name='.$f_name.'?l_name='.$l_name.);

to
header('Location: save.php?id_no='.$id_no.'&f_name='.$f_name.'&l_name='.$l_name);

Answer:
You have extra . dot at last
Also using multiple ? question mark is wrong use & ampersand
Use " instead of ' to process php variable which do not need . dots to concatenate

Simply try like this
header("Location: save.php?id_no=$id_no&f_name=$f_name&l_name=$l_name");