How to Implement Logical OR constraint in CPLEX Python

Question: How can I implement a constraint like x[0,0] == 0 OR x[0,0] >= 2 in CPLEX Python MP?
Seems like a job for semiinteger but semiinteger_var_matrix() is not available in the version of CPLEX Python I am using in Watson Studio DO environment.  I could use semiinteger_var_list() which is available but would like to do via logical OR constraint to teach myself.  I tried x[0,0] != 1 but MP doesn't handle NE.  So I figured that I could do it the logical OR constraint shown above. Looked at the doc and the source of docplex.mp.model yet cannot figure out how to do this.  I am in the early stages of learning CPLEX Python.
Answer: Let me give you a small example with the bus story:
from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

for v in mdl.iter_integer_vars():
   print(v," = ",v.solution_value)

print()
print("with nb buses 40 less than 3 or more than 7")

mdl.add((nbbus40<=3) + (nbbus40>=7) >=1)

mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

which gives
nbBus40  =  6.0
nbBus30  =  2.0

with nb buses 40 less than 3 or more than 7
nbBus40  =  7.0
nbBus30  =  1.0

NB: You may also write
from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

for v in mdl.iter_integer_vars():
   print(v," = ",v.solution_value)

print()
print("with nb buses 40 less than 3 or more than 7")

option1=mdl.binary_var(name='option1')
option2=mdl.binary_var(name='option2')

mdl.add(option1==(nbbus40<=3))
mdl.add(option2==(nbbus40>=7))

mdl.add(1==mdl.logical_or(option1,option2))

mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value)

Many other tiny docplex Python examples at https://www.linkedin.com/pulse/making-optimization-simple-python-alex-fleischer/
Comment: You could have a look at https://stackoverflow.com/questions/58853258/how-to-use-continuous-variables-for-if-then-constraints-on-docplex-python
Comment: pretty late comment but do you confirm that this doesn't work (in docplex at least) if the variables are continuous and not anymore integers?
Answer: True, semiinteger_matrix does not exist. But semiinteger_dict does. So you can do something like
x = model.semiinteger_var_dict((i, j) for i in range(I) for j in range(J))

and after that you can reference the variables as x[0,0] etc.
Answer: The classic formulation, assuming also an upper bound u looks like:
introduce fresh binary variable b

post

x <= u * b
x >= l * b

In your case l=2.
The value of u is problem-dependent and it's important to make it as small as possible for a better relaxation. (an introductory blog-post on the topic)


Curious about effect of recursion of a method

Question: I have written an instance method which uses recursion to find a certain solution. It works perfectly fine except the time when I'm exiting the if-elif block. I call the function itself inside IF block. Also, I have only one return statement. The output from the method is weird for me to understand. Here is the code and the output:
def create_schedule(self):
    """
    Creates the day scedule for the crew based on the crew_dict passed.
    """
    sched_output = ScheduleOutput()
    assigned_assignements = []
    for i in self.crew_list:
        assigned_assignements.extend(i.list_of_patients)

    rest_of_items = []
    for item in self.job.list_of_patients:
        if item not in assigned_assignements:
            rest_of_items.append(item)

    print("Rest of the items are:", len(rest_of_items))

    if len(rest_of_items) != 0:
        assignment = sorted(rest_of_items, key=lambda x: x.window_open)[0]
        # print("\nNext assignment to be taken ", assignment)
        output = self.next_task_eligibility(assignment, self.crew_list)
        if len(output) != 0:
            output_sorted = sorted(output, key=itemgetter(2))
            crew_to_assign = output_sorted[0][1]
            assignment.eta = output_sorted[0][4]
            assignment.etd = int(assignment.eta) + int(assignment.care_duration)
            crew = next((x for x in self.crew_list if x.crew_number == crew_to_assign), None)
            self.crew_list.remove(crew)
            crew.list_of_patients.append(assignment)
            crew.time_spent = assignment.etd
            self.crew_list.append(crew)

            self.create_schedule()
        else:
            print("*" * 80, "\n", "*" * 80, "\nWe were not able to assign a task so stopped.\n", "*" * 80, "\n", "*" * 80)

            sched_output.crew_output = self.crew_list
            sched_output.patients_left = len(rest_of_items)

    elif not rest_of_items:
        print("Fully solved.")
        sched_output.crew_output = self.crew_list
        sched_output.patients_left = 0

    print("After completely solving coming here.")
    return sched_output

This was the output:
Rest of the items are: 10
Rest of the items are: 9
Rest of the items are: 8
Rest of the items are: 7
Rest of the items are: 6
Rest of the items are: 5
Rest of the items are: 4
Rest of the items are: 3
Rest of the items are: 2
Rest of the items are: 1
Rest of the items are: 0
Fully solved.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.
After completely solving coming here.

What I don't understand is that as soon as my list rest_of_items is empty, I assign data to sched_output and return it. However, print statement is being executed for the same number of time as recursion was done. How can I avoid this?
My output is perfectly fine. All I want to do is understand the cause of this behaviour and how to avoid it.
Comment: As a side note, you've written an "instance method", or just a "method"; a "class method" is a special thing (usually decorated with `@classmethod`) which is meant to be called on the class itself, rather than on objects that are instances of that class.
Comment: @abarnert fixed. Apologies.
Comment: In the future, please try to provide a [mcve] -- the **shortest possible code**, with everything needed for someone else to run it themselves, that illustrates a given question.
Comment: @CharlesDuffy Noted. I'll follow the guide. Thanks. :)
Comment: Run this through a debugger and it will be clear why you are seeing this output
Answer: The reason it's printing out 11 times is that you always call print at the end of the function, and you're calling the function 11 times. (It's really the same reason you get Rest of the items are: … 11 times, which should be a lot more obvious.)
Often, the best solution is to redesign things so instead of doing "side effects" like print inside the function, you just return a value, and the caller can then do whatever side effects it wants with the result. In that case, it doesn't matter that you're calling print 11 times; the print will only happen once, in the caller.

If that isn't possible, you can change this so that you only print something when you're at the top of the stack. But in many recursive functions, there's no obvious way to figure that out without passing down more information:
def create_schedule(self, depth=0):
    # etc.
    self.create_schedule(depth+1)
    # etc.
    if not depth:
        print('After completely solving come here.')
    returns sched_output

The last resort is to just wrap the recursive function, like this:
def _create_schedule(self):
    # etc.
    self._create_schedule()
    # etc.
    # don't call print
    return sched_output

def create_schedule(self):
    result = self._create_schedule()
    print('After completely solving come here.')
    return result

That's usually only necessary when you need to do some one-time setup for the recursive process, but here you want to do some one-time post-processing instead, which is basically the same problem, so it can be solved the same way.
(Of course this is really just the first solution in disguise, but it's hidden inside the implementation of create_schedule, so you don't need to change the interface that the callers see.)
Comment: Cool, This makes sense. Thanks for explanation. I'll implement this.
Answer: As you call your create_schedule function within itself before the function finishes, once it has gotten to the end and doesn't need to call itself again, each function ends, and hits the "After completely solving coming here.", at the end of the function.
This means that each function, after calling itself, is still running - just stuck at the line where it calls itself - until they have all completed, which is when the paused functions can finish their task, printing out your statement.
Comment: Does that also mean each function also call `return sched_output`?
Comment: Yes, @RyanCyrus, but they do nothing with the returned value.
Comment: Is it a normal behaviour? Can it be improved?
Comment: To improve it, you could work upon what @abamert has done, and copy the function into another one with a different name, which is called by the original function, and have the print statement only happen in the original function, or have the print statement after where you call this method in the first place. This would also mean that none of them `return sched_output` if you only include it in the original. Refer to @abermert's answer to see this in action.
Answer: You have print("After completely solving coming here.") at the end of your recursive function. That line will be executed once for each recursion.
Consider this simple example, which recreates your issue:
def foo(x):
    print("x = {x}".format(x=x))
    if x > 1:
        foo(x-1)
    print("Done.")

Now call the function:
>>> foo(5)
x = 5
x = 4
x = 3
x = 2
x = 1
Done.
Done.
Done.
Done.
Done.

As you can see, on the final call to foo(x=0), it will print "Done.". At that point, the function will return to the previous call, which will also print "Done." and so on.


Arzela-Ascoli and adjoint of compact operator compact

Question: I have seen in this thread a nice answer where it is shown that Thread
that the adjoint operator of a compact operator is compact by using the Arzela Ascoli theorem. Unfortunately, there is one thing I do not understand: It is not shown that $(f_n)_n$ is closed, so why is this sequence compact then? It is only shown that it is equicontinuous and bounded but not closed and since we derive from Arzela Ascoli that there is a convergent subsequence we probably need compactness.
I should point how we formulated Arzela Ascoli: Let $M \subset C(S)$ where $S$ is a compact set, then $M$ is compact iff: $M$ is bounded, closed and equicontinuous.
Thank you in advance for every helpful comment.
Answer: If you let $\mathcal{F} = \{ f_n | n\in \mathbb{N} \}$ then this set is not necessarily closed, as you say. However, it has compact-closure and so the sequence $f_n$ converges to a point in $\overline{\mathcal{F}}$ though not necessarily to a point in $\mathcal{F}$ itself.


Total number of unique n-element sets from a base of unique elements

Question: I have searched for the answer for this on the site (and on the Internet) and have not found the answer. I do apologize if this is answered and I do not have the vocabulary to ask or search for the question properly.
I am trying to determine a mathematical method for determining how many unique n-element sets can be made from a base group of elements when each element can be used only once per set.
For instance, take the numbers 0, 1, 2, 3, 4, 5, 6
0, 1, and 21 are invalid because they are not complete sets.
012, 013, 014, 015, 016, 023, 024, 025, 026, etc. are all valid.
020 is not because it uses element 0 twice.
Given the valid sets above:
  021, 102, 210 are invalid (duplicates) because they use the same elements as 012.
I have determined by brute force that the answer to this for 3 element sets out of 7 unique elements is 35.
012, 013, 014, 015, 016, 023, 024, 025, 026, 034, 035, 036, 045, 046, 056, 123, 124, 125, 126, 134, 135, 136, 145, 146, 156, 234, 235, 236, 245, 246, 256, 345, 346, 356, 456
For 3 element sets out of 5 unique elements (0, 1, 2, 3, 4) is 10.
012, 013, 014, 023, 024, 034, 123, 124, 134, 234
I would like to be able to calculate the answer to this problem for any combination of base elements, and n-element sets. Using the brute force approach I am using would be impractical for large sets from very large numbers of elements.
Answer: The number of $k$-element subsets of an $n$-element set is often denoted by $\binom{n}{k}$.   There are other notations for the same numbers, for example ${}^nC_k$, and variants. One formula for $\binom{n}{k}$ is
$$\binom{n}{k}=\frac{n!}{k!(n-k)!}.$$
Here $m!$  denotes the product of all the integers from $m$ down to $1$. So for example $5!=5\cdot 4\cdot 3\cdot 2\cdot 1=120$.
Example: We do the calculation for the number of ways to choose $3$ objects from $7$. By definition, this is $\binom{7}{3}$, which is $\frac{7!}{3!4!}$. We could calculate $7!$ (it is $5040$), but there is a shortcut.
Note that $7!=7\cdot 6\cdot 5\cdot 4!$. Thus $\frac{7!}{3!4!}=\frac{7\cdot 6\cdot 5\cdot 4!}{3!4!}$. By cancellation, this is $\frac{7\cdot 6\cdot 5}{3!}$. But $3!=6$, so we get $35$.
For more information, please google Binomial Coefficients, and Pascal Triangle. Wikipedia has good writeups.
Comment: Thank you for this answer. I will give this a look. I'm not seeing where m/m! is coming from (or what the ! in the formula denotes for that matter), but that I am sure is my fault for not having enough math skill to get this in the first place (first year college algebra). I guess it was wishful thinking to believe that it would be something simple where I plug in 7 and 3 and do a couple operations and end up with 35. At least that does not jump out at me.
Comment: I will add the calculation in the answer, since writing math in comments is more awkward.
Comment: I had not encountered the '!' symbol in mathematics before so I had looked that up. Good to have one more tool in my maths-bag. That and your example solved it for me. Thank you so much!
Comment: Also, thank you for the references to Binomial Coefficients and Pascal Triangle. These are both interesting reads. Another step forward in knowledge, another step forward in skill!
Comment: You are welcome. Your comment reminded me to do what I should have done already, which is to do at least one explicit computation.


How to fix Flutter "A RenderFlex overflowed by.." issue when keyboard opens

Question: I get a A RenderFlex overflowed by 161 pixels on the bottom. issue in my Flutter app when the keyboard opens and I don't know why. I'm using a SingleChildScrollView with a fixed height to the container. Also I tried it with resizeToAvoidBottomInset: false, on Scaffold. No success.
I think that the problem has something to do with the included Pin Code Field on this page. But there I have no columns or something else... also I open this widget a ModalBottomSheet (https://pub.dev/packages/modal_bottom_sheet)
Here is my code structure:
Widget build(BuildContext context) {
    return Scaffold(
        body: SingleChildScrollView(
      child: Container(
        height: Get.height,
        color: Get.theme.colorScheme.primary.withOpacity(.03),
        padding: EdgeInsets.all(50),
        child: ListView(
          shrinkWrap: true,
          physics: ClampingScrollPhysics(),
          children: [
            EntryGuestbookHeading(),
            SizedBox(height: 50),
            Obx(() {
              if (entryGuestbookController.isCheckingCode.value == true) {
                return Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      LoadingSpinner(),
                      SizedBox(height: 15),
                      Text("search_for_guestbook",
                              style: TextStyle(fontWeight: FontWeight.bold))
                          .tr(),
                      SizedBox(height: 50),
                    ],
                  ),
                );
              } else {
                return Container();
              }
            }),
            PinCodeField(
              guestbookCodeController: guestbookCodeController,
            ),
            EntryGuestbookActions(),
          ],
        ),
      ),
    ));
  }

EntryGuestbookHeading Widget
Widget build(BuildContext context) {
    return Container(
      padding: context.isTablet
          ? EdgeInsets.only(left: 150, right: 150, top: 100)
          : null,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Lottie.asset("assets/animations/key.json",
              height: Get.height / 8, repeat: false),
          SizedBox(height: 15),
          Container(
            child: Text(
              "open_guestbook",
              style: Get.theme.textTheme.headline3,
              textAlign: TextAlign.left,
            ).tr(),
          ),
          SizedBox(height: 15),
          Text(
            tr("enter_entry_code"),
            style: Get.theme.textTheme.bodyText1,
          )
        ],
      ),
    );
  }

PinCodeField Widget
Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 25),
      child: Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          padding: context.isTablet
              ? EdgeInsets.only(left: 150, right: 150, bottom: 150)
              : null,
          child: PinCodeTextField(
            backgroundColor: Colors.transparent,
            appContext: context,
            length: 5,
            focusNode: focusNode,
            autoDisposeControllers: false,
            obsecureText: false,
            textCapitalization: TextCapitalization.characters,
            animationType: AnimationType.slide,
            autoFocus: true,
            enableActiveFill: true,
            pinTheme: PinTheme(
              shape: PinCodeFieldShape.box,
              borderRadius: BorderRadius.circular(5),
              fieldHeight: 50,
              fieldWidth: 40,
              inactiveColor: Colors.grey,
              inactiveFillColor: Colors.transparent,
              selectedColor: Get.theme.colorScheme.primary,
              selectedFillColor: Get.theme.colorScheme.primary,
              activeColor: Get.theme.colorScheme.primary,
              activeFillColor: Get.theme.colorScheme.primary,
            ),
            animationDuration: Duration(milliseconds: 300),
            controller: widget.guestbookCodeController,
            onCompleted: (v) {
              entryGuestbookController.checkEntryCode(v).then((success) {
                if (success == false) {
                  setState(() {
                    guestbookCodeController.text = "";
                  });
                  focusNode.requestFocus();
                }
              });
            },
            onChanged: (value) => null,
          ),
        ),
      ),
    );
  }

EntryGuestbookActions Widget
Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(bottom: 15),
        child: ConstrainedBox(
            constraints: BoxConstraints(
                minWidth: MediaQuery.of(context).size.width - 50),
            child: FlatButton(
                child: Text("cancel",
                        style: TextStyle(
                            color: Get.theme.colorScheme.onBackground))
                    .tr(),
                onPressed: () {
                  Navigator.of(context).pop();
                })));
  }

The autofocus is set to true. If the keyboard opens, I get the overflow error. Where is the issue in my code? Thanks in advance for your help!
Comment: Have you got any workaround for it?
Answer: Scaffold(
resizeToAvoidBottomPadding: false, )

Comment: Please read my topic. I've tried this already. It does not work. Btw: `resizeToAvoidBottomPadding ` is deprecated. We should use `resizeToAvoidBottomInset ` instead. Source: https://api.flutter.dev/flutter/material/Scaffold/resizeToAvoidBottomPadding.html
Answer: I think now the flutter has updated its properties, and using
Scaffold (
  resizeToAvoidBottomPadding: false,)

would work as we expect.
Answer: Try to wrap the widget that causes this error with Flexible or Expanded widget. This may solve your problem.
Comment: Flexible does not solve the multithreading/Future problem.
Answer: I had the same error, I was working on a Signup page and this problem occurred. I just wrapped the first container with a singleChildScrollView, and then wrapped it to the Center Widget, and it worked.


Using AfterUpdate event on a control in one subform to requery a control on another subform

Question: I have an Access 2010 database set up with using the native Navigation Form interface feature.
Using this very helpful table, I've been able to use vba on multiple ocassions to reference forms throughout my database. However I seem to be having difficulty in this one instance.
On the Navigation form I have a number of main tabs. Clicking on one of the main tabs brings up a number of sub-tabs that have various forms attached to them.
On one of these sub-tabs, I have a main form (main) attached to it. There is a subform (subform1) within that main form containing a control text box (control1). Within subform1 there is another form (subform2) containing an unbound text box (control2) displaying a value that is calculated using a TempVar.
I want to use the AfterUpdate event on control1 to requery subform2 in order to update the calculation in control2, or simply requery control2.
Using Refresh and/or Requery on the AfterUpdate event for control1 does not do anything to control2.
Currently I have a button on subform2 that users can click which refreshes the form and updates the value in control2. The user can also hit F5 and refresh all the forms with the same result.
My goal is to take away the manual aspect and have the AfterUpdate event for control1 to update control2.
Any help would be much appreciated as I haven't been able to find anything online that works and I've been kicking tires at the problem for over a month now.
**** UPDATE **** I did not correctly describe the layout of my forms. subform1 and subform2 are actually both nested under main. subform2 is NOT nested under subform1 as I originally described above.
Comment: As I understand Navigation form, only one subform is active and available at a time. Review this discussion http://www.accessforums.net/showthread.php?t=32053. I use a Tab control instead.
Comment: I agree a tab control is the way to go here. If you avoid it because of the lower performance, review [this thread](https://www.pcreview.co.uk/threads/increasing-speed-load-subforms-on-tabs-only-when-tab-clicked.1149237/). If performance is not an issue, a tab control is just more flexible.
Comment: Have done a little more digging into navigation controls, and the entire subform should requery as you switch tabs (tested in Access 2016, only the active subform is loaded, and gets unloaded as soon as you navigate to another sub. Thus requerying a control on another sub should not be necessary. Can you specify the exact issue?
Comment: Thanks to both of you for the quick replies. I've explored the link you provided and attempted a few suggestions to no avail. RE: Tab control, unfortunately I'm very far into the project and don't want to have to migrate everything into  a tab control interface. I would have to re-test everything as well. This particular issue just isn't worth it...I also like the look of the Navigation Form. That being said if anyone has anything further to add please do so. I will be away for a few days so my non-response is not indicative of anyone's input. I'll explore June's link further upon my return.
Comment: Sorry I didn't get back earlier. I had some more pressing matters upon my return. @Erik, you are correct that the subform should requery when switching tabs, however I would like the control2 to requery when control1 is updated. Switching tabs is more work than my current solution. I'm guessing that I wouldn't have the issue if my description of the problem was initially correct. I have updated my question as I realized I posted inaccurate information. This update might make more sense. My apologies.
Answer: Wow. Now I feel like an idiot. Tackling my problem again with the update I provided above allowed me to solve it.
All I needed to do was requery subform2 by referencing it this way:
[Forms]![HOME]![NavigationSubform].[Form]![subform2].[Form].Requery
Where "HOME" is the name of my Navigation Form.
For anyone with the same issue that hasn't renamed their Navigation Form I believe the syntax would be:
[Forms]![Navigation Form]![NavigationSubform].[Form]![subform2].[Form].Requery
Thank you to @Erik von Asmuth and @June7 for your patience and help.


Text wrapping inconsistent in Firefox 3 on PC only

Question: This is a recurring problem I have in Firefox 3.0. It seems when I keep refreshing sometimes it wraps, sometimes it doesn't. When it doesn't wrap, I can adjust the window size and the sIFR'd element will snap to its correct size. I need my elements to wrap on load, based on the width of it's container.
I have the most current 'nightly build' of sIFR 3.0.
I want to sIFR a h2 tag. The h2 tag is enclosed in a div, and both have set widths.

This is a recipe title

In my sifr.js file, I have the following parameters set:
forceWidth = true;
fitExactly = true;
preventWrap = false;

My .sifr.CSS file looks like this:
@media screen {
  .sIFR-active .recipe-title h2 { width:455px; font-size:16px; text-transform:uppercase; }
}

And my normal CSS file looks like this:
.recipe-title, .recipe-title h2 { width:400px; }

Everything else seems to work in all other browsers except for FF3 on PC only. Is this a known bug?
Answer: sIFR may be initializing too early. Easiest fix is to set sIFR.useDomLoaded = false; before sIFR.activate(), which will wait until page load before replacing the elements.
You can also look into using sIFR.useStyleCheck = true; which needs a bit more CSS but will wait until the CSS has loaded.
Answer: I'm pretty sure it's text-transform:uppercase enlarging the word width after the flash width has been set
I've been trying to figure a solution to this for some time
Comment: This is causing my pain too.  Tried both useStyleCheck and useDomLoaded without success.
Comment: I fixed my problem by being able to set a fixed width on my replaced element.
Answer: For the common user... make sure that you set your width and height of the div container for your object or image.   Firefox will wrap any text following if these values are not set.
Answer: A possibility is that you might need to specify a height on the element. IE7 can have a similar problem.
Answer: Is sIFR.activate() located in the sifr.js file or the sifr-addons.js file?
Answer: Per Mark's advice, uncommenting sIFR.useStyleCheck = true; just before sIFR.activate() worked for me.
Robert, sIFR.activate() is found in sifr.js.


multi fields search query for elasticsearch golang

Question: I have a situation where I need to do elastic search based on multi-field. For Example: I have multiple fields in my postindex and I want to apply condition on four these fields (i.e. userid, channelid, createat, teamid) to meet my search requirement. When value of all these fields matched then search query displays results and if one of these is not match with values in postindex then it display no result.
I am trying to make a multifield search query for go-elasticsearch to search data from my post index. For the searcquery result four field must match otherwise it display 0 hit/no-result.
Comment: Could you give some samples for the what are you searching on the fields? Maybe you can give something like :
`userid = 1 AND channelid = 5 AND createat > 2022-01-01 AND teamid = 1` Is this what your are doing?
Comment: I think you are looking for bool query but according to your answer I will write a answer here.
Comment: @hkulekci Thank you of your response.
This is sample like : `userid = mcqmycxpyjrddkie9mr13txaqe AND channelid = dnoihmrinins3qrm6bb9175ume AND createat > 1672909114890 OR teamid = qomrg11o8b8ijxoy8hrcnweoay`.
note: create time store in mili
Comment: In here you need to use bool query but you need to be a little bit more clear on OR part. Could you share with some paranthesis for the OOR part? Something like, `(userid = 1 AND channelid = 1 AND createat > 2022-01-01) OR (teamid = 1)`. is this right?
Comment: @hkulekci `(userid = 1 AND channelid = 1 AND createat > 2022-01-01) OR (teamid = 1)` is right one. I need to use bool query for this condition.
Answer: So, I think you need to write a following query :
GET postindex/_search
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "userid": {
                    "value": "mcqmycxpyjrddkie9mr13txaqe"
                  }
                }
              },
              {
                "term": {
                  "channelid": {
                    "value": "dnoihmrinins3qrm6bb9175ume"
                  }
                }
              },
              {
                "range": {
                  "createat": {
                    "gt": 1672909114890
                  }
                }
              }
            ]
          }
        },
        {
          "term": {
            "teamid": {
              "value": "qomrg11o8b8ijxoy8hrcnweoay"
            }
          }
        }
      ]
    }
  }
}

In here, there is a bool query with should in parent scope, which is like OR. And inside the should there is another bool query with must which is like AND. We can also write the query shorter, but this will be better for you to understand.
Comment: Thank you for your response. Can you convert it in go request/code?
@hkulekci


Mostrar resultado de uma lista do servlet em pagina JSP

Question: Preciso capturar um nome do input, fazer a consulta no banco de dados e retornar o resultado em uma pagina jsp.
Eu quero mostrar o resultado em um pequeno trecho da pagina JSP, no caso misturar o texto da pagina JSP com o resultado que quero capturar.
Pagina jsp com o input

Nome: <input type="text" name="nome" />

Cpf: <input type="text" name="cpf" />

<input type="submit" name="enviar" value="Enviar" />
<input type="reset" name="limpar" value="Limpar" />

</form>

Lista
PrintWriter out = response.getWriter();

 SessionFactory factory = new Configuration().configure().buildSessionFactory();
 Session session = factory.openSession();
 session.beginTransaction();

 List<Pessoa> listForm = new ArrayList<>();

 listForm = session.createQuery("from Pessoa where cpf like '%"+cpf+"%' and nome like '%"+nome+"%'").list();

 int tamanho = listForm.size();

 for(int i=0;i<tamanho;i++){
     Pessoa pessoa = listForm.get(i);
     out.println(pessoa.getId()+" - "+ pessoa.getNome());

 }

Answer: A partir do objeto HttpServletRequest, você pode recuperar a session e adicionar os atributos que desejar exibir na view.
Por Exemplo:(Servlet)
protected void doPost(HttpServletRequest request, HttpServletResponse
response) {

    List<String> nomes = new ArrayList<>();

    request.getSession().setAttribute("nomes", nomes);
    response.sendRedirect("/view");
}

Para exibir os atributos na view, é uma boa prática neste caso, usar EL(Expression Language) e JSTL(JSP Standard Tag Library).
Para usar JSTL você deve baixar o jar e adicionar dentro da pasta lib ou adicionar a dependência no pom.xml caso use maven.
https://mvnrepository.com/artifact/javax.servlet/jstl/1.2
Na sua JSP você deve importar a biblioteca JSTL
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

E por fim, para mostrar a lista do exemplo na view, podemos combinar el e jstl.

     <c:forEach items="${nomes}" var="nome">

 ${nome}

     </c:forEach>

Links Úteis
https://www.tutorialspoint.com/jsp/jsp_standard_tag_library.html
https://docs.oracle.com/cd/E19798-01/821-1841/gjddd/index.html


erro ao criar botão de like simples

Question: pessoal tou tentando criar um botão simples de like que simplesmente adiciona +1 em uma tabela na col like, ignorando que pode clicar mais de uma vez e que está sujeito a invasão pois é só um teste. Do jeito que ta agora ele me devolve os seguintes erros:

Undefined index: tipo in
  Undefined index: tab in
  Undefined index: estado in C:\wamp64\www\novo\logado\locais\coleta2.php
  Undefined variable: varsql in
  mysqli_query(): Empty query in

A pagina php que faz o like atualizar redireciona pra mesma pagina que está o botao, pordem essa apgina recebe valores de outra pagina, por isso acho que está esses erros, mas tentei já mandar os mesmo dados pelo like.php mas continua dando problema. se alguem puder ajudar com o codigo ou dar uma outra sugestão para fazer um botão que adiciona +1 numa coluna referente a um id especifico.
insira o código aqui<?php

        ob_start();

      $tipo =$_GET["tipo"];
      $tab = $_GET["tab"];

      include "coleta2.php";
      $conexao = mysqli_connect("127.0.0.1","root","","db_tcc") or die ("Não foi possível se conectar com o servidor.");

        echo "<meta charset='utf-8' />";

        switch($tipo){
            case "0":
                    $varsql = "SELECT * FROM $tab ORDER BY likes DESC";
                    break;

            case "1": case "2": case "3":
                    $varsql = "SELECT * FROM $tab WHERE TIPO='$tipo' ORDER BY likes DESC";
                    break;
    }

      function Like() {
   $updd = "";
  $x = 0;
        if ($x == 0) {
          $x = $like + 1;
          $updd = "UPDATE $tab set likes = '$like'+1 where ID = '$id'";

        } else {
          $x = $like - 1;
          $updd = "UPDATE $tab set likes = '$like'-1 where ID = '$id'";

        }
        mysqli_query($conexao, $updd);
       }

       $carregar_guias = mysqli_query($conexao, $varsql);

echo "
";

      while ($linha = mysqli_fetch_array($carregar_guias))
      {
        $id = $linha["id"];
        $blob = $linha["foto"];
        $nome = $linha["nome"];
        $desc = $linha["descricao"];
        $like = $linha["likes"];

       $img = imagecreatefromstring($blob);

        ob_start();
        imagejpeg($img, null, 80);
        $data = ob_get_contents();
        ob_end_clean();

        echo "

";
        echo "".  htmlentities(utf8_encode($nome), 0, "UTF-8")."	";
        echo " <form name='like' method='get' action='like.php?            tab=$tab&id=$id'><INPUT TYPE='submit' VALUE='Curtir' ></form>
        $like

";

          echo '';

        echo "

".  htmlentities(utf8_encode($desc), 0, "UTF-8")."

";

      }
      echo "
";
    ?>

pag like.php
<?php

$id =$_GET["id"];
      $tab = $_GET["tab"];
      $tipo = $_GET["tipo"];

$conexao = mysqli_connect("localhost","root","","db_tcc") or die ("Não foi possível se conectar com o servidor.");
$updl = "UPDATE $tab set likes = likes +1 where id = '$id'";
mysqli_query($conexao, $updl);

header('location:din.php');

?>

Answer: Tente remover as seguintes linhas da função like:
 $x = $like + 1;

$x = $like - 1;

e colocar isso:
 if($x == 0){
      $updd = "UPDATE $tab set likes = likes + 1 where ID = '$id'";

    } else {
      $updd = "UPDATE $tab set likes = likes - 1 where ID = '$id'";

    }
    mysqli_query($conexao, $updd);

erro ao criar botão de like simples


How do you make an element in a SwiftUI loop full screen? Like Apple's, App of the day

Question: Here's a gif of what I currently have
Trying a bunch of things here, like offset and zIndex but they don't change the position, I'm looking for something like absolute position in css to make the card full screen.
    var body: some View {
    VStack {
        Text("")
    }
    .frame(minWidth: 0, maxWidth: .infinity)
    .frame(height: show ? UIScreen.main.bounds.height : 200)
    .zIndex(show ? 1 : 0)
    .background(/*@START_MENU_TOKEN@*/Color.blue/*@END_MENU_TOKEN@*/)
    .cornerRadius(show ? 0 : 20)
    .padding(show ? 0 : 30)
    .offset(y: show ? 0 : viewState.height)
    .animation(.easeInOut(duration: 0.3))
}

Answer: You may want to use GeometryReader instead, combining with edgesIgnoringSafeArea like this:
struct ContentView: View {

    @State var show = false

    var body: some View {
        GeometryReader { geo in
            VStack { Text("") }
                .frame(minWidth: 0, maxWidth: .infinity)
                .frame(height: self.show ? geo.size.height : 200)
                .background(/*@START_MENU_TOKEN@*/Color.blue/*@END_MENU_TOKEN@*/)
                .cornerRadius(self.show ? 0 : 20)
                .padding(self.show ? 0 : 30)
                .offset(y: self.show ? 0 : 0)
                .animation(.easeInOut(duration: 0.3))
                .onTapGesture {
                    self.show.toggle()
            }
        }.edgesIgnoringSafeArea(.all)
    }
}

Output:

Note That This was just an answer to the original question and original provided code, If you like to embed the card in another way like using ScrollView, you should consider some changes to the original code of course. For example:
struct CardView: View {
    @Binding var show: Bool

    var body: some View {

        Rectangle()
            .foregroundColor(.blue)
            .cornerRadius(self.show ? 0 : 20)
            .padding(self.show ? 0 : 30)
            .animation(.easeInOut(duration: 0.3))
    }
}

extension Int: Identifiable { public var id: Int { self } }

struct ContentView: View {

    @State var show = false

    var body: some View {
        GeometryReader { geo in
            ScrollView {
                VStack {
                    ForEach(0..<1) { item in
                        CardView(show: self.$show)
                            .frame(height: self.show ? geo.size.height : 200)
                        .onTapGesture { self.show.toggle() }

                    }
                }
            }
        }.edgesIgnoringSafeArea(.all)
    }
}

Comment: Thank you so much for your help @mojtaba-hosseini! I can replicate your animation with one card, but when it's a ScrollView with a loop of cards, it doesn't apply, any thoughts?

`ScrollView {
                            ForEach() { item in
                                Card(item: item)
                            }
                        }`

The card component doesn't animate full screen in this case
Comment: [Output for me when in a loop](https://i.stack.imgur.com/8o8RT.gif).
Comment: Because geometry represents the parent view. When you embed it in another view, you should consider that geometry data changes accordingly. I have added another example for you. Hope it will giude you the achieve what you need.


Resumo de Posts no WordPress

Question: Preciso que o tamanho do resumo dos post na minha frontpage seja diferente do tamanho do resumo da pagina onde é exibido todos os posts(home.php).
No meu arquivo functions.php eu coloquei o seguinte código:
//adiciona um novo tamanho de resumo de posts
function novo_tamanho_do_resumo($length) {
    return 15; //15 palavras
}
add_filter('excerpt_length', 'novo_tamanho_do_resumo');

O problema deste código é que o resumo ficou com 15 palavras em todas as páginas, no entanto eu preciso que em frontpage.php seja 15 palavras, e que em home.php tenha 100 palavras.
Answer: Quando você cria uma action para um determinado hook, dentro desta função podem existir verificações para o que você precisar e retornar o valor de acordo.
No seu caso você pode fazer:
//adiciona um novo tamanho de resumo de posts
function novo_tamanho_do_resumo ( $length ) {

    if ( is_frontpage() ) { // ou qualquer outro if pra verificar em qual página está

        return 15; //15 palavras

    } else if ( is_home() ) {

        return 100; //100 palavras

    } else {

        return 55; //valor padrão

    }

}
add_filter( 'excerpt_length', 'novo_tamanho_do_resumo' );

Comment: tentei fazer desta forma, porém esta caindo sempre no segundo "if ( is_home() )" ficando em ambas as páginas 100 palavras... meu código esta exatamente como o seu, apenas corrigi a função is_frontpage() para is_front_page(), pois estava dando um erro de função indefinida.
Answer: Para solucionar este problema eu fiz assim:
criei a seguinte função no arquivo functions.php
function cropText($texto, $limite){
    if (strlen($texto) <= $limite) echo $texto;
    echo array_shift(explode('||', wordwrap($texto, $limite, '||'))) . " [...]";
}

e na minha frontpage.php eu chamo o conteúdo do post e limito os caracteres assim:
<?php cropText(get_the_content(), 120); ?>

Desta forma o resumo na frontpage terá sempre 120 caracteres enquanto o resumo da pagina de posts continua com o padrão de 55 palavras.

Resumo de Posts no WordPress


O que são e como funcionam os valores de width max-content e min-content?

Question: Recentemente me deparei com esses dois valores para o width de um elemento, no entanto não entendi como usa-los e para que servem...
Isso é o que diz a documentação da Mozilla, mas eu não entendi:
max-content A largura intríseca preferida. (width: min-content)
                      ------------------------------------------------
min-content A largura intríseca mínima preferida. (width: max-content)
                      -------------------------------------------------------------
Fonte: https://developer.mozilla.org/pt-BR/docs/Web/CSS/max-width

O que seriam essas valores de fato, e como os elementos se comportam com eles?
  Esses valores já são aceitos por todos os browsers?

Se possível gostaria de um ou dois exemplos didáticos :)
Answer: Recomendo ler este artigo.
Primeiro, esta imagem exemplifica bem o funcionamento de min e max content para width(texto em inglês):

Agora, um código que produz resultado semelhante ao da imagem, baseado no conteúdo disponível em MDN Web Docs:
CSS:
p.douradinho-max {
  background: gold;
  width: -moz-max-content;
}

p.douradinho-min {
  background: gold;
  width: -moz-min-content;
}

HTML:

A comunidade Mozilla produz diversos softwares incríveis.

Aqui, a largura assume o valor necessário para agrupar todo o texto em uma linha, ou seja, o valor máximo do conteúdo.

A comunidade Mozilla produz diversos softwares incríveis.

Aqui, a largura assume o valor da maior palavra da frase("comunidade"), assim, o valor mínimo de largura necessário para agrupar toda a frase.

Resultado:
Comment: Neto está meio confuso o texto... Olha isso *O tamanho menor que uma caixa pode levar que não leva ao estouro que poderia ser evitado escolhendo um tamanho maior.* Não me ajudou muito... E os exemplos que vc linkou são sobre max-width e min-width, não sobre `width: min-content` e `width: max-content`
Comment: Neto nesse caso te sugiro editar a sua resposta remover os exemplos que estão equivocados nela, rever os texto traduzidos acredito pois não fazem sentido está difícil de entender-los. E coloque os novos exemplos direito como código na resposta, use o ícono ao lado do ícone da imagem para incluir o código na sua resposta. Assim fica mais claro e a resposta preserva o conteúdo caso o link externo pare de funcionar
Comment: O texto não ajudou muito, se vc puder explicar o funcionamento dos novos exemplos ai sim ficaria algo interessante. Pois a duvida é entender como esses atributos funcionam quando aplicados no elemento. Só um código como exemplo sem explicação alguma não ajuda muito


How could I cut off text after a keyword?

Question: So say I would write something like <break> and it would show everything before <break> out of
$text = "I like apple pies<break>Do you like Apple pies?";

So it should only output
I like apple pies

Answer: $text = "I like apple pies<break>Do you like Apple pies?";

list($result) = explode('<break>',$text,2);

Comment: `list($result) = explode('',$text,2);` is more efficient, especially if the string is long after the `` mark (php doesn't have to search the whole string).
Comment: <3, big duh on my part. Especially like the elegance of using `list()`
Answer: As a function:
function BeforeBreak($input)
{
    return stristr($input, '<break>', true);
}

Note this functionality requires PHP 5.3.0.
stristr documentation
Comment: Please note that this will perform a case-insensative search for ``. The function would be a great idea, +1.
Comment: This is done to accept `` as well, but use `strstr` instead if the case sensitivity is important.
Answer: Try this:
$text = "I like apple pies<break>Do you like Apple pies?";
$texplode = explode('<break>',$text);
echo $texplode[0];

read up on php explode()
Answer: $good = substr( $bad, 0, strpos( $bad, "<break>" ) );

Answer: this will give you what you want:
<?
   $output = strstr($text, '<break>', true);
?>

if you have multiple occurrences it's a good idea to use
<?
   $text = 'a<break>b<break>c<break>d';
   $output = explode('<break>', $text);

   // the output will be
   // array('a', 'b', 'c', 'd');
?>

Comment: Please note that you will need to have PHP 5.3.0 installed to be able to use the `before_needle` parameter. Nice answer though, +1.


Laravel Migration is auto-incrementing all numeric columns. Why is this?

Question: Hello I am currently trying to set up a migration in Laravel and am running into the issue to that all of my numeric columns are being set to autoincrement.
Test Migration:
Schema::create('sublobbies', function (Blueprint $table) {
    $table->increments('id');
    $table->tinyInteger('sub', 2)->default(1);
    $table->tinyInteger('anothertable', 2)->default(1);
    $table->tinyInteger('anothertable2', 2)->default(1);
});

Besides the fact, that I am getting an Invalid default value error (im assuming due to the auto increments), I noticed that everything is being set to auto increment:
Syntax error or access violation: 1067 Invalid default val
  ue for 'sub' (SQL: create table `sublobbies` (`id` int unsigned not null au
  to_increment primary key, `sub` tinyint not null default '1' auto_increment
   primary key, `anothertable` tinyint not null default '1' auto_increment pr
  imary key, `anothertable2` tinyint not null default '1' auto_increment prim
  ary key) default character set utf8mb4 collate utf8mb4_unicode_ci)

Is this the natural behavior of Migrations or am I just missing something? How do I turn auto_increment off?
Comment: Laravel doesn't support specifying lengths of integer fields because many databases don't utilize it.  MySQL, for instance, only uses integer lengths as a read length.  It will store `100` in a TINYINT(1).
Comment: @Devon Oh okay, I see!
Answer: Schema::create('sublobbies', function (Blueprint $table) {
    $table->increments('id');
    $table->tinyInteger('sub', 2)->default(1); // remove the , 2
    $table->tinyInteger('anothertable', 2)->default(1); // remove the , 2
    $table->tinyInteger('anothertable2', 2)->default(1); // remove the , 2
});

the second spot in the tinyInteger() function is a boolean you are setting to true should just be
Schema::create('sublobbies', function (Blueprint $table) {
    $table->increments('id');
    $table->tinyInteger('sub')->default(1);
    $table->tinyInteger('anothertable')->default(1);
    $table->tinyInteger('anothertable2')->default(1);
});

Adding this for reference:

tinyInteger(string $column, bool $autoIncrement = false, bool $unsigned = false)

https://laravel.com/api/4.2/Illuminate/Database/Schema/Blueprint.html#method_tinyInteger
Comment: So how do I specify a length like on the strings?
Comment: You don't https://stackoverflow.com/questions/25772759/schema-builder-length-of-an-integer


I need a way of checking a URL is valid given an input

Question: I am trying to do some validation checks on inputs, which I'm having some issues with.
I need to be able to check that the url entered is valid, return it's boolean value. If true it allows it to be assigned as myURL, else it will give me the JOptionPane message and stop. These will be checked from fields of entered data. This is part of a larger project, so any and all input is welcomed and appreciated.
public String SetURL (String a) {
if (ValidateURL(a)) {
  myURL = a;
}
else {
  JOptionPane.showMessageDialog (null, "Sorry the URL: " + SetURL() + " is an invalid URL",
                                 "Incorrect Information", JOptionPane.INFORMATION_MESSAGE);
}

}
  public Boolean ValidateURL () {
//Some code here to check the validation and return a true of false

}
Comment: You first have to decide/define what it means for a URL to be "valid"
Answer: You need to create both a URL object and a URLConnection object. The following code will test both the format of the URL and whether a connection can be established:
try {
    URL url = new URL("http://www.yoursite.com/");
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}

in your case, the catch will give you the JOptionPane message and stop, and you can even tell the user if it is because it's malformed or unavailable
Comment: Thanks for the amazing response time. would replacing yoursite with my input work? If this formats, like follows?

    try {
    URL url = new URL(a);
    URLConnection conn = url.openConnection();
    conn.connect();
} catch (MalformedURLException e) {
    // the URL is not in a valid form
} catch (IOException e) {
    // the connection couldn't be established
}
Comment: I get an error stating that it cannot find the Symbol URL.I tried a similar solution earlier and I got an error also.
Comment: are you using eclipse ?, you should check if you imported the right packages : import java.net.URL;
import java.net.URLConnection;
Comment: I'm using DR Java, and I certainly did not add the packages! So that would be why. Not sure why it occurred to me to get the packages for the IO and Malformed but not that... Compiles fine now. Tried in a seperate file and works a treat!
Thank you for this help!
Answer: You can to use regex and the Java Matcher class.
Here is a good regex: (http:(?![^"\s]*google)[^"\s]+)["\s]
and here is the documentation on Matcher.
Comment: Thank you for the response, I used the above method however.


Change Drupal URL

Question: I use cpanel and ftp (filezila)
I don't know much about drupal. I believe i am using v.6
I have an old website made in drupal: www.oldwebsite.com
I don't want to delete my oldwebsite but change to www.oldwebsite.com/drupal
So I have then www.oldwebsite.com free to put whatever.
Easy?
How and where do i acess the files to change such a thing? thanks!
Answer: I believe in order to switch Drupal from using no sub directory to instead use on, you only need to:

Copy all of the files into the sub directory e.g. /drupal. This can be done with FTP (or SSH)
Edit the file .htaccess and uncomment the line 103(RewriteBase /drupal). Make sure the rewrite base is the same as the name you gave your subfolder above
Optional extra, ensure all your content is linked correctly as any hard coded links in content are will now no longer work, or better yet, use a module like pathologic to ensure links never break

Change Drupal URL


degree field extension by a power of transcendental element

Question: Basic field theory exercise:
Let $K$ be a field and $x \in K$ transcendental.
Firstly I need to prove that $x^n$ is transcendental too. I proved that the map $ev_{x^n}:K[T] \longrightarrow K[x]$ is injective as a consequence of the injectivity of $ev_x$.
Now I need to show that $[K(x):K(x^n)]=n$
I'm still a bit confused by the definition of $K(x):=\{ \frac{f(x)}{g(x)}:f(T),g(T) \in K[T] \} \cong \{ \frac{f(T)}{g(T)}: f,g \in K[T] \}=K(T)$.
I see that every element of $K(x):=\{ \frac{f(x^n)}{g(x^n)}:f(T),g(T) \in K[T] \}$ is "associated to an element of degree multiple of $n$ in K(T)".
I believe that basis of $K(x)$ over $K(x^n)$ looks like $B:=\left(\frac{f(x)}{g(x)}, x \cdot \frac{f(x)}{g(x)},x^2 \cdot \frac{f(x)}{g(x)},..., x^{n-1} \cdot \frac{f(x)}{g(x)} \right)$. Since $x^k=x^{k'} \iff k=k'$ linear independence should be clear. Showing that $<B>=K(x)$ looks more complicated but would anyway follow from $|B|=n$.
If I'm not mistaken the solution is pretty much there but I'm still quite confused so I would really appreciate any hint on how to make it more formal.
Answer: Recall that if $F/E$ is an extension such that $F = E(\alpha)$ for some $\alpha \in F$, then $F/E$ is a finite extension whenever $\alpha$ is algebraic over $E$; moreover, if $p(T) \in E[T]$ is the minimal polynomial of $\alpha$ over $E$, then $[F:E] = m := \deg p(T)$ and $1,\alpha,\dots,\alpha^{m-1}$ is a $E$-basis for $F$.
Now, notice that $K(x) = K(x^n)(x)$,  and so it suffices to find an irreducible monic polynomial $p(T) \in K(x^n)[T]$ with $n$-degree such that $p(x) = 0$. In fact, you can consider $p(T) := T^n-x^n$, and once you have shown that $p(T)$ is irreducible, it follows that a $K(x^n)$-basis for $K(x)$ is given by $1,x,\dots,x^{n-1}$.
Comment: Thank you. I see that $q \notin K(x^n)[T]$. I do not see why there cannot be any other factor of higher degree since only considering the zeroes of $p$ isn't enough to conclude irreducibility in general...
Comment: I can't show that $T^n-x^n$ is irreducible. Its only zero is $x \notin K(x^n)$, does that bring me anywhere? Thank you!
Comment: @VerzaJr. Try to show that the polynomial $q(T)$ such that $p(T) = (T-x)q(T)$ is not in $K(x^n)[T]$.


Outra opção ao uso do @ no PHP?

Question: Não me sinto muito confortável tendo que utilizar o @ antes de algumas variáveis e sessões quando faço condições, para evitar erro de Unexpected Index que acontece quando a variável ou sessão não foi inicializada anteriormente.
Queria saber se não há algum meio de que eu possa setar, num arquivo de topo da minha aplicação por exemplo, uma configuração pro PHP automaticamente fazer isso para todas variáveis e sessões? De repente algum outra solução?
Comment: @gmsantos Porque minha pergunta foi editada e minha saudação removida? Não lembro de ter lido algo que proíba isso, desculpe se eu estiver errado, mas achei desnecessária sua a interferência...
Comment: Na prática estaria tirando algo que não é bom e trocando por algo pior. O certo é corrigir e precaver-se de erros comuns e previsíveis. O inibidor de erros @ é usado para casos bastante específicos como funções que retornam erros inexperados que não podem ser controlados pela configuração de erros.
Comment: @DirtyOldMan esse tipo de saudação é considerada um ruído. Um dos *slogans* do SOPT é [Faça perguntas, obtenha respostas, sem distrações](http://pt.stackoverflow.com/tour). Mais detalhes nessa [resposta do meta](http://meta.pt.stackoverflow.com/a/52/4751).
Comment: Me desculpe se pareci intrusivo, mas tenho o costume de [fazer esse tipo de edição](http://pt.stackoverflow.com/users/4751/gmsantos?tab=activity&sort=revisions) :)
Answer: O @ não é uma boa pratica, apesar de poder ser usada, o recomendável para fazer verificações de variáveis é o isset.
O isset diferente do array_key_exists (que também pode ser usado conforme o exemplo do Ricardo) suporta verificações multidimensionais e também pode-se verificar mais de uma variável ao mesmo tempo, por exemplo:

Verificando arrays multidimensionais:
<?php
$test = array('a' => 1);

var_dump(isset($test['a']['b'])); //Retorna bool (false)
var_dump(isset($test['a']));      //Retorna bool (true)

Verificando mais de uma variável ao mesmo tempo:
<?php
$a = 1;
var_dump(isset($a)); //Retorna bool (true)
var_dump(isset($a, $b)); //Retorna bool (false) por que $b não existe

ou
<?php
$a = array('test' => 1);
$b = array('foo'  => 2);

var_dump(isset($a['test'])); //Retorna bool (true)
var_dump(isset($a['test'], $b['test'])); //Retorna bool (false) por que $b['test'] não existe

O isset também suporta stdClass (ou variáveis de uma classe)
Detalhes sobre o isset:

Não é uma função, ele é um construtor
Se a variável for NULL ou FALSE ele irá retornar false, como no exemplo:
<?php
$a = NULL;
var_dump(isset($a)); //Retorna bool (false)

empty vs isset
Acaso não for verificar varias variáveis ao mesmo tempo, como no exemplo já citado com isset (isset($a, $b, $c, $d, $e)), você pode usar o empty, que além de verificar se a "variável existe" ele também verifica se ela é vazia em caso de strings por exemplo. Situações que empty irá retornar TRUE:

"" (uma string vazia)
0 (quando for um numero inteiro igual a zero)
"0" (zero como string)
NULL
FALSE
array() (uma array vazia)
var $var; (Quando uma variavel é declarada em uma classe, mas não tem valor, pois é NULL)

O problema da pergunta
Como suprimir todas notificações de variáveis não declaradas sem usar o @? Neste caso eu recomendaria a usar o isset e criar variáveis normais, como por exemplo:
$variavelA = empty($_SESSION['varA']) ? NULL : $_SESSION['varA'];
$variavelB = empty($_SESSION['varB']) ? NULL : $_SESSION['varD'];
$variavelC = empty($_SESSION['varC']) ? NULL : $_SESSION['varC'];
$variavelD = empty($_SESSION['varD']) ? NULL : $_SESSION['varD'];

Se parecer trabalhoso, você pode usar um loop com foreach ou for, é um pouco gambiarra admito, mas existem diferentes maneiras de se fazer o processo, está é apenas uma e vai depender de como está o seu código:
$keys_in_session = array('a', 'b', 'user', 'ultimaatividade');

foreach ($keys_in_session as $k => $v) {
    if (empty($_SESSION[$v])) {//Acaso a variável não exista na sessão ele cria ela como o valor `NULL` para que você possa usa-la sem ocasionar
        $_SESSION[$v] = NULL;
    }
}

Consideração sobre o uso
Apesar do exemplo com foreach, eu pessoalmente recomendo usar apenas o isset e o empty combinado com if ou com operadores de comparação ternários:
echo 'Resposta: ', ( empty($_SESSION['message']) ? 'sem resposta' : $_SESSION['message'] );

Ambiente de desenvolvimento vs Ambiente de produção
Como já citado na outra resposta, o uso de error_reporting é uma boa pratica para o ambiente de produção e desenvolvimento.

Ambiente de produção é aquele que se entende no momento que o software já é utilizado para "produzir algo", em outras palavras, quando o site já está no ar.
Ambiente de desenvolvimento é aquele de quando você está desenvolvendo o software em um local aonde não afete o servidor/site ou seja na sua máquina por exemplo.

Eu pessoalmente sempre uso em ambiente de desenvolvimento todas notificações de erro "ligadas":
<?php
//No topo do script
error_reporting(E_ALL|E_STRICT);

No ambiente de produção sempre desligo todos erros:
<?php
//No topo do script
error_reporting(0);

Porém não é possível determinar todas falhas que possam ocorrer e todas situações, então como saber que erros ocorreram? Para isto temos 3 funções que podemos usar combinados, error_get_last(), set_error_handler e register_shutdown_function, assim você pode gravar os erros em um arquivo .txt por exemplo e consultar este arquivo para verificar quando a falha ocorreu, veja um exemplo nesta outra resposta:
https://pt.stackoverflow.com/a/34818/3635

Nota: Não é por que você vai desligar as mensagens de erro que você não deve usar isset ou empty, procure usar o E_ALL|E_STRICT para detectar possíveis falhas do código e depois corrigi-las.
Comment: +1 Essa deveria ser marcada como a resposta correta. Falou sobre `error_reporting` em desenvolvimento e falou sobre `isset` para checar as variáveis. Não é boa prática usar o `@` para evitar os Notices.
Answer:
Com esta solução você verifica se a chave do array session (ou qualquer outro) existe.

if (array_key_exists("login", $_SESSION)) {
    echo "O Usuario esta logado";
}

Com esta solução não será exibido mais notices como o Unexpected Index (é o que a pergunta pede) porem não resolve do Unexpected Index.

Para configurar o php.ini para não exibir as mensagens de notificação você deve deixar da seguinte forma:
error_reporting  =  E_ALL & ~E_NOTICE

Outra forma é colar esta linha no arquivo inicio do arquivo .php:
ini_set("display_errors", "0");

Outra forma é colar esta linha no arquivo inicio do arquivo .php:
error_reporting(E_ALL ^ E_NOTICE); // ira reportar todos esceto os `notices`.

Comment: Neste caso serão suprimidas as informações de erro, o que não é uma boa prática no ambiente de desenvolvimento.
Comment: @RodrigoSpeller Mas foi justamente isto que o autor perguntou.
Comment: Foi adicionado um código que verifica se a chave do $_SESSION existe antes de usa-la inibindo assim o erro.
Answer: Segue o arquivo session_defs.php para ser incluído no setup do código. Neste arquivo criei a função session_def, que define o valor padrão para a variável de sessão caso ela ainda não tenha sido definida.
Arquivo session_defs.php
<?php
function session_def($name, $value) {
    // isset: Informa se já variável foi iniciada antes
    if (!isset($_SESSION[$name]))
        return $_SESSION[$name] = $value; // Se não foi iniciada,
                                          // inicia com o valor padrão
    return $_SESSION[$name];
}

// Cria a sessão ou resume a sessão atual.
// A partir deste ponto a variável $_SESSION é definida com os valores
// que já foram definidos anteriormente.
session_start();

// Define os valor padrão para as variáveis de sessão que não foram iniciadas
// com session_start.
session_def('item1', 12345);
session_def('item2', true);
session_def('item3', 'string');

?>

Uso
<?php
require_once 'session_defs.php';
?><!doctype html>

    <meta charset="utf-8">

<?php
var_dump($_SESSION);
?>

Comment: Sua resposta é boa, mas não explica o ponto importante, o isset, considere editá-la.
Comment: Editada. Caso tenha restado dúvida sobre o uso da função isset, a documentação do PHP é bem completa [ http://php.net/manual/pt_BR/function.isset.php ].
Answer: Normalmente esse erro undefined index é causado por problemas no $_POST ou $_GET.
Você pode executar o comando extract(); no início do código. Assim todas as variáveis já entram de forma automática, sem precisar chamar $_POST ou $_GET.
Basta inserir no início do código:
extract();
Esse artigo explica detalhadamente a solução pro erro:
https://www.homehost.com.br/blog/notice-undefined-index-php/

Outra opção ao uso do @ no PHP?


Principal bundle (or torsor) for a diagonalizable group over a torus

Question: Let $T$ be an algebraic torus and $G$ a diagonalizable group; both are over an algebraically closed field $k$ of characteristic $0$ (take $k=\mathbb C$, if you like).
I am trying to understand principal $G$-bundles $P\to T$ over $T$, but I'm getting conflicting conclusions from two perspectives.

From what I've read (e.g. pg 11-13 here: https://arxiv.org/pdf/2009.08675.pdf), the total space $P$ is given by
$$P=\operatorname{Spec}_T\left(\bigoplus_{m\in\Gamma} \mathcal L^{\otimes m}\right)$$ where $\Gamma$ is the character group of $G$ (so $\Gamma$ is a finitely generated abelian group) and $\mathcal L$ is a product of line bundles on $T$ indexed by generators for $\Gamma$ (some possibly torsion, if $\Gamma$ has torsion).
But line bundles on $T$ are all trivial, so $\color{red}{\text{I think we just have (?)}}$

$$\begin{align}\operatorname{Spec}_T\left(\bigoplus_{m\in\Gamma} \mathcal L^{\otimes m}\right) = \operatorname{Spec}_T\left(\bigoplus_{m\in\Gamma} \mathcal O_T^{\otimes m}\right) = \operatorname{Spec}(k[T][\Gamma]) &= \operatorname{Spec}(k[T]\otimes_k k[\Gamma])\\&= T\times G.\end{align}$$

This seems to imply that every principal $G$-bundle over $T$ is trivial.

On the other hand, consider the following example. Take $G=\{1,-1\}$ (i.e. $\mu_2$) as a subgroup of $T=\mathbb G_m$ (rank $1$ torus). Then we have an exact sequence
$$1 \to G \to T \xrightarrow{t\mapsto t^2} T \to 1$$
where the map $T\to T$ via $t\mapsto t^2$ is a principal $G$-bundle over $T$. This should not be trivial, since $T\not\cong T\times G$ in this case (i.e. the exact sequence does not split).
This seems to contradict the above approach.

My question is: can anyone explain where I've gone wrong? Is one of the approaches correct and the other incorrect?
Edit: I think in the first approach the $\mathcal O_T$-algebra structure will depend on the torsion in $\Gamma$. For example, if $\Gamma=\mathbb Z/2$, then this $\mathcal O_T$-algebra structure will depend on a choice of isomorphism $\mathcal O_T^{\otimes 2}\to\mathcal O_T$. If this is right, then I guess it comes down to understanding these isomorphisms and how they give different $\mathcal O_T$-algebra structures, which is still confusing to me.
Comment: I think you might benefit from more carefully studying what torsors are. For instance, a $\mu_n$-torsor on some $X$ corresponds (in reasonable situations) to equivalence classes of pairs $(\mathscr{L},\iota)$ where $\mathscr{L}$ is a line bundle on $X$ and $\iota\colon \mathscr{L}^{\otimes n}\to \mathcal{O}_X$ is an isomorphism, where two pairs $(\mathscr{L}_i,\iota_i)$ are equivalent if there exists an isomorphism $f\colon \mathscr{L}_1\to \mathscr{L}_2$ such that $\iota_2\circ f^{\otimes m}=\iota_1$.
Comment: In particular, if $\mathrm{Pic}(X)=0$, then $\mathscr{L}$ is abstractly isomorophic to $\mathcal{O}_X$. But, note that the isomorphisms $\iota$ can then just be identified with $\mathcal{O}_X(X)^\times$, and the equivalence relation then means that $\mu_n$-torsors are classified by $\mathcal{O}_X(X)^\times/(\mathcal{O}_X(X)^\times)^n$. In particular, if $X=\mathbb{G}_{m,k}$ where $k$ is algebraically closed, then $\mathrm{Pic}(X)=0$, but $\mathcal{O}(X)^\times/(\mathcal{O}_X(X)^\times)^n=(k^\times T^\mathbb{Z})/(k^\times T^\mathbb{Z})^n$ which is precisely $\mathbb{Z}/n\mathbb{Z}$.
Comment: This shouldn't be shocking as (at least in reasonable situations) $\mu_n=\mathbb{Z}/n\mathbb{Z}$ and so $H^1(X,\mu_n)=H^1(X,\mathbb{Z}/n\mathbb{Z})=\mathrm{Hom}(\pi_1(X),\mathbb{Z}/n\mathbb{Z})$. We see then that $\mathbb{Z}/n\mathbb{Z}$ is coming from the automorphisms of the $n$-fold cover $\mathbb{G}_{m,k}\xrightarrow{t\mapsto t^n}\mathbb{G}_{m,k}$ as you already observed.
Comment: By the way, the total space is of the $G$-bundle is not what you write -- what is the fiber of that map look like? For instance while it is true that the group of $\mathbb{G}_m$-torsors is isomorphic to $\mathrm{Pic}(X)$ the isomorphism doesn't take $\mathscr{L}$ to $\mathscr{L}\to X$ (i.e. doesn't take the invertible sheaf to the associated geometric line bundle). Indeed, the latter is actually a $\mathbb{G}_a$-bundle. Instead, the total space of the associated $\mathbb{G}_m$-bundle is $\underline{\mathrm{Isom}}(\mathscr{L},\mathcal{O}_X)$ (the 'frame bundle') and is isomorphic to
Comment: $\mathscr{L}-\{0\}\to X$ (i.e. the geometric line bundle minus the zero section).
Comment: @AlexYoucis thanks for all the responses. Indeed, this choice of isomorphism $\mathcal L^{\otimes n}\to \mathcal O_X$ makes sense to me as the extra piece of data needed. However, I do believe that the form of the total space that I have written is correct (e.g. it is used in the reference I gave above). I did write it in a very simplified form, which may have been confusing.
Comment: @AlexYoucis if you'd like to put your original comment (or whatever information you'd like to add) as an answer, I will accept.
Answer: Just to get this off the unanswered list, I will elaborate on my comment above.
Your mistake was in the understanding of the total space of a $\mu_{n,X}$-torsor as $\underline{\mathrm{Spec}}\left(\bigoplus_{i=0}^{n-1}\mathscr{L}^{\otimes i}\right)\to X$ where $\mathscr{L}$ is an $n$-torsion element of $\mathrm{Pic
}(X)$. Namely, how are you thinking of a $\bigoplus_{i=0}^{n-1}\mathscr{L}^{\otimes i}$ as a quasi-coherent $\mathscr{O}_X$-algebra? Namely, the multiplication here should be obtained via the natural maps
$$\mathscr{L}^{\otimes a}\otimes \mathscr{L}^{\otimes b}\to \mathscr{L}^{\otimes(a+b)},$$
but, of course, as we only consider $\mathscr{L}^{\otimes i}$ for $i=0,\ldots,n-1$ what you really need is a map like
$$\mathscr{L}^{\otimes a}\otimes \mathscr{L}^{\otimes b}\to \mathscr{L}^{\otimes(a+b\mod n)}.$$
This is doable as $\mathscr{L}^{\otimes n}\cong \mathscr{O}_X$, but not canonically so. In fact, you need to fix an isomorphism $\iota\colon \mathscr{L}^{\otimes n}\xrightarrow{\approx}\mathscr{O}_X$ and then from this structure one can actually give $\bigoplus_{i=0}^{n-1}\mathscr{L}^{\otimes i}$ the structure of a quasi-coherent $\mathscr{O}_X$-algebra.
Let us call this algebra structure $\mathscr{A}(\mathscr{L},\iota)$. Then, one can check that the isomorphism class of $\mathscr{A}(\mathscr{L},\iota)$ only depends on the following equivalence relation on the pair $(\mathscr{L},\iota)$: $(\mathscr{L}_1,\iota_1)\sim (\mathscr{L}_2,\iota_2)$ is there exists an isomorphism $f\colon \mathscr{L}_1\xrightarrow{\approx}\mathscr{L}_2$ such that $\iota_2\circ f^{\otimes n}=\iota_1$. In this way, using $H^1(X,\mu_{n,X})$ to denote the isomorphism classes of $\mu_{n,X}$-torsors, one gets a map
$$\{(\mathscr{L},\iota)\}/\sim\, \longrightarrow\, H^1(X,\mu_{n,X}).$$
This is actually an isomorphism of groups where one defines a group structure on the source in the obvious way: $(\mathscr{L}_1,\iota_1)\otimes (\mathscr{L}_2,\iota_2)=(\mathscr{L}_3,\iota_3)$ where $\mathscr{L}_3=\mathscr{L}_1\otimes\mathscr{L}_2$, and $\iota_3$ is the composition of
$$(\mathscr{L}_1\otimes\mathscr{L}_2)^{\otimes n}\xrightarrow{\text{natural}}\mathscr{L}_1^{\otimes n}\otimes \mathscr{L}_2^{\otimes n}\xrightarrow{\iota_1\otimes\iota_2}\mathscr{O}_X\otimes\mathscr{O}_X\xrightarrow{\text{natural}}\mathscr{O}_X.$$
There are several ways to prove this assertion, let me list two here.

You can first prove that the association of $\mathscr{L}$ of the sheaf $\underline{\mathrm{Isom}}(\mathscr{O}_X,\mathscr{L})$ (which associates to an $X$-scheme $T$ the isomorphisms $\mathscr{O}_T\to \mathscr{L}_T$) is actually an isomorphism $\mathrm{Pic}(X)\to H^1(X,\mathbf{G}_{m,X})$ -- this is classical, for instance see here. One can then deduce the result for $\mu_{n,X}$ by tracing through the long exact sequence in cohomology obtained from the Kummer sequence $1\to \mu_{n,X}\to\mathbf{G}_{m,X}\to\mathbf{G}_{m,X}\to 1$.
A more conceptual reason (which also handles the case of $\mathbf{G}_{m,X}$-torsors) is to see that $\mathscr{A}(\mathscr{L},\iota)$ represents the scheme $\underline{\mathrm{Isom}}((\mathscr{O}_X,\iota_0),(\mathscr{L},\iota))$ where $\iota_0\colon \mathscr{O}_X^{\otimes n}\xrightarrow{\approx}\mathscr{O}_X$ is the obvious map. One then wins from the general yoga that if $\mathcal{S}$ is any stack over a site $\mathcal{X}$, and any $x$ is any object of $\mathcal{C}_T$ (for $T$ an object of $\mathcal{X}$) then the association $y\mapsto \underline{\mathrm{Isom}}(x,y)$ is an isomorphism $\mathrm{Tw}(x)\to H^1(T,\underline{\mathrm{Aut}}(x))$. Here $\mathrm{Tw}(x)$ is the (isomorphism classe) of objects of $\mathcal{C}_T$ which are locally isomorphic to $x$ (i.e. the 'twists'). Why is this relevant here? Well, line bundlesform a stack, and therefore so do pairs
$(\mathscr{L},j)$ where $j\colon \mathscr{L}^{\otimes m}\to \mathscr{O}_X$. Note then that $\{(\mathscr{L},\iota)\}/\sim$ is precisely $\mathrm{Tw}((\mathscr{O}_X,\iota_0))$. But, what is $\underline{\mathrm{Aut}}(\mathscr{O}_X,\iota)$? It's precisely $\mu_{n,X}$!


How to make a one to many connection between Netlify CMS and Gatsby

Question: I'm using Netlify CMS on a gatsby site. I used the netlify CMS relation widget on my post collection to reference the title field of my author collection, so...
- {label: "Author", name: "author", widget: "relation", collection: "authors", searchFields: ["title", "firstName", "lastName"], valueField: "title"}

That works well but when I do a query in my GraphiQL window the only available field is author, with a single string, how do I access all the frontmatter of a particular author?
Answer: Making the connection in Netlify turns out to just be the first step. Then you need to configure your gatsby-node.js file to make those relationships on build. The end result allows you to make a query on the posts that has a nested author. Here's the whole setup.
First the netlifyCMS config.yml which I have in static/admin
backend:
  name: git-gateway
  branch: development

media_folder: "static/images/uploads" # Media files will be stored in the repo under static/images/uploads
public_folder: "/images/uploads"

    collections:
  - name: "blog" # Used in routes, e.g., /admin/collections/blog
    label: "Blog" # Used in the UI
    folder: "src/pages/blog/posts" # The path to the folder where the documents are stored
    create: true # Allow users to create new documents in this collection
    slug: "{{year}}-{{month}}-{{day}}-{{slug}}" # Filename template, e.g., YYYY-MM-DD-title.md
    fields: # The fields for each document, usually in front matter
      - {label: "Layout", name: "layout", widget: "hidden", default: "blog"}
      - {label: "Author", name: "author", widget: "relation", collection: "authors", searchFields: ["title", "firstName", "lastName"], valueField: "title"}
      - {label: "Title", name: "title", widget: "string"}
      - {label: "Publish Date", name: "date", widget: "datetime"}
      - {label: "Featured Image", name: "thumbnail", widget: "image"}
      - {label: "Body", name: "body", widget: "markdown"}
  - name: "authors"
    label: "Authors"
    folder: "src/authors"
    create: true
    slug: "{{slug}}"
    fields:
      - {label: "Layout", name: "layout", widget: "hidden", default: "author"}
      - {label: "Full Name", name: "title", widget: "string"}
      - {label: "First Name", name: "firstName", widget: "string"}
      - {label: "Last Name", name: "lastName", widget: "string"}
      - {label: "Position", name: "position", widget: "string"}
      - {label: "Profile Picture", name: "profilePicture", widget: "image"}
      - {label: "Email", name: "email", widget: "string"}

Then at the bottom of my gatsby-node.js file.
exports.sourceNodes = ({ boundActionCreators, getNodes, getNode }) => {
    const { createNodeField } = boundActionCreators;

    const postsOfAuthors = {};
    // iterate thorugh all markdown nodes to link books to author
    // and build author index
    const markdownNodes = getNodes()
        .filter(node => node.internal.type === "MarkdownRemark")
        .forEach(node => {
            if (node.frontmatter.author) {
                const authorNode = getNodes().find(
                    node2 =>
                        node2.internal.type === "MarkdownRemark" &&
            node2.frontmatter.title === node.frontmatter.author
                );

                if (authorNode) {
                    createNodeField({
                        node,
                        name: "author",
                        value: authorNode.id,
                    });

                    // if it's first time for this author init empty array for his posts
                    if (!(authorNode.id in postsOfAuthors)) {
                        postsOfAuthors[authorNode.id] = [];
                    }
                    // add book to this author
                    postsOfAuthors[authorNode.id].push(node.id);
                }
            }
        });

    Object.entries(postsOfAuthors).forEach(([authorNodeId, postIds]) => {
        createNodeField({
            node: getNode(authorNodeId),
            name: "posts",
            value: postIds,
        });
    });
};

And lastly in gastby-config.js you need to add the mapping.
    mapping: {
        "MarkdownRemark.fields.author": "MarkdownRemark",
        "MarkdownRemark.fields.posts": "MarkdownRemark",
    }

Which gives you the ability to make a query like tis...
query AllPosts {
  allMarkdownRemark (
    filter: { fileAbsolutePath: {regex : "\/posts/"} },
    sort: {fields: [frontmatter___date], order: DESC}
  ){
    edges {
      node {
        fields {
          author {
            fields {
              slug
            }
            frontmatter {
              title
              firstName
              lastName
              profilePicture

            }
          }
          slug
        }
        frontmatter {
          title
          date(formatString:"MMM DD 'YY")
          thumbnail
          layout
        }
        excerpt
      }
    }
  }
}

Comment: Do you know if this approach is still valid? I've followed this answer and could only get the author id returned through GraphQL explorer... I can't see to access the authors fields.
Comment: Can you share with me how a relation is being displayed on the .md file? I'm working with a local server and I'm being unable to find an example


Using Web-Workers in stand alone V8 Javascript Engine

Question: I tried to adopt the shell.cc sample from the V8 distribution package for my own purposes.
I want to spawn a web-worker to execute a long-running script, and execute:
<code>var myWorker = new Worker("my_task.js");
</code>
But I receive the following error message:
<code>(shell):1: ReferenceError: Worker is not defined
var myWorker = new Worker("my_task.js");
                   ^
ReferenceError: Worker is not defined
    at (shell):1:20
</code>
Is there a way to activate Web Workers in the V8 Engine?
Thank you in advance for any help on this issue!
Answer: I think you'd use the Child Process library for node or one of the other libraries that implements threading.  As far as I know, web workers are a browser thing, not part of the standard node.js implementation and if you want that sort of API, you would need to use a third party library that implements something like that API.
Other useful references:
Lightweight Web Worker API implementation with native threads
Concurrency on Node Discussion
Web Worker implementation in node
Answer: Too late though: But for any one still searching for it:
Check d8.cc file in v8 source code , it exposes Worker Template:
Comment: How to use these templates?


using specifics when making linear regression models in r

Question: I am not really sure what catagory this goes under but I have a data set and I want to test the association between test results (response) and 3 catagorical variables (SEX) and (INFARCTS) and (LACUNE) these 3 are all binary
so essentially I want to produce a linear model of test results for Males and females that have Infarcts
and
test results for males and females that lacunes
i dont know if this makes sense but any help would be great
thanks in advance
Comment: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1                            please check this link on how to ask a good question. i would be glad to help. :-)
Answer: That's should work. If you have more then two categories you need to dummy code your categories. But with only two just use 0 and 1 and run the regression normally as long as your dependent variable is continuous. If the dependent variable is binary as well, you'll need to do a logistic regression.


How to combine the data in 2 columns without removing the empty cells in between the columns in google sheet?

Question:
Hi everyone,
I want to combine column B and column D in column F. The formula that I used in column F is:
=query({B2:B1000;D2:D1000}, "select * where Col1 is not null ")
I used where Col1 is not null in the Query because I want to avoid the empty cells start from cell B14 onwards. However, it removed the empty cell in between column B (cell B7 & B8) as well. May I know how should I modified my query function so that it includes the empty cells in between column B and column D.
The desired output should be like this:

Any help will be greatly appreciated!
Answer: You can either use closed ranges in the formula:
={B2:B13; D2:D6}

or, if you want to use open ranges, try something like
={INDIRECT("B2:B"&max(FILTER(row(B2:B), len(B2:B)))); INDIRECT("D2:D"&max(FILTER(row(D2:D), len(D2:D))))}

and see if that works?