How to prove that $H(S_1\cap S_2)\subset H(S_1) \cap H(S_2)$ and $H(S_1 \cup S_2) \supset H(S_1) \cup H(S_2)$

Question: I'm studying convex analysis and my task is to prove the following inclusions:

$S_1, S_2$ are non-empty sets in $\mathbb{R}^n$, and $H(S) $ defined as the convex hull  of set $S$.
Show that
$H(S_1\cap S_2)\subset H(S_1) \cap H(S_2)$
and
$H(S_1 \cup S_2) \supset H(S_1) \cup H(S_2)$
Can the inclusions be reversed? Explain why?

How should I proceed with a problem like this? I thought about using contradiction proof? What if I assume for example in the first task that there is a point $\textbf{x}_1 \in H(S_1\cap S_2)$, but $\textbf{x}_1\not\in H(S_1) \cap H(S_2)$ and show why this can not be? Is this the way to go? :)
Thank you for any help! =)
Comment: All you need to show is that the convex hull is inclusion-preserving, that is, if $S\subset T$, then $H(S)\subset H(T)$.
Comment: Thank you for your help @StefanHamcke =)
Answer: All you need to show is that the convex hull is inclusion-preserving, that is, if $S⊂T$, then $H(S)\subseteq H(T)$. The inclusions in your problem then follow easily.
In order to show that, in general, we don't have equality, consider $S_1=\{0,2\}$ and $S_2=\{1\}$, or $S_1=\{0\}$ and $S_2=\{1\}$.
Comment: @jjepsuomi: You're welcome :)
Answer: I think I got myself the first one so I'll add it here:
$$S_1 \cap S_2 \subset S_1$$
$$S_1 \cap S_2 \subset S_2$$
$$=>$$
$$H(S_1 \cap S_2) \subset H(S_1)$$
$$H(S_1 \cap S_2) \subset H(S_2)$$
$$=>$$
$$H(S_1 \cap S_2) \subset H(S_1) \cap H(S_2)$$
I think I can do the same with the second one:
$$H(S_1 \cup S_2) \supset H(S_1) \cup H(S_2)$$
$$<=> H(S_1) \cup H(S_2) \subset H(S_1 \cup S_2)$$
$$S_1 \subset S_1 \cup S_2$$
$$S_2 \subset S_1 \cup S_2$$
$$=>$$
$$H(S_1) \subset H(S_1 \cup S_2)$$
$$H(S_2) \subset H(S_1 \cup S_2)$$
so
$$H(S_1) \cup H(S_2) \subset H(S_1 \cup S_2)$$


How do I assign an empty matrix to elements of a cell array in MATLAB?

Question: I want to manipulate a cell array and make certain indices of the cell array contain the empty matrix []. I can't seem to figure out how to do this:
>> yy=num2cell(1:10)

yy =

  [1]    [2]    [3]    [4]    [5]    [6]    [7]    [8]    [9]    [10]

>> yy{1:2:end}=[]
??? The right hand side of this assignment has too few values to satisfy
 the left hand side.
>> yy(1:2:end) = []

yy =

  [2]    [4]    [6]    [8]    [10]

Bah! Can't seem to do what I want. I want to leave empty elements in the cell array, e.g.
  []    [2]    []    [4]    []    [6]    []    [8]    []    [10]

Any suggestions? My index vector could be arbitrary, and either in index form or boolean form, not necessarily [1 3 5 7 9].
Answer: What you can do is index the cell array (not the contents) using () and change each cell to an empty cell {[]}:
yy(1:2:end) = {[]};

An alternative is to use the DEAL function, but it looks a bit uglier:
[yy{1:2:end}] = deal([]);

Comment: I have to become "gintermediate" first. ;)
Comment: woohoo! gnovice comes through again. we're going to have to call you "gexpert"


Make change to config files on multiple servers using SSH

Question: Problem:
I'm trying to disable SSH password auth for multiple servers.
Which means I have to modify the sshd_config file.
From
#PasswordAuthentication yes

to
PasswordAuthentication no

I really don't wanna do it one by one. Is there any ways that I can distribute/modify the config file on multiple servers with a single command?
Assumptions you can make:

Those servers have same OS
I can broadcast the SSH command to multiple servers at once

Other notes:
I set the config file to listen different address and/or port on each server.
So this could not be done by downloading the updated config file from a central server.
I prefer a text replacement command to do the job
Comment: Given the additional constraint, the answer would very likely depend on whether you can ssh into different servers as root, or if it's possible to run sudo without password to obtain root privilege.
Comment: yes, I can ssh all those servers as root, and broadcast the command
Comment: Super lazy For SERVER in $(cat servers.txt);do scp sshd_conf root@$SERVER:/etc/ssh/sshd_conf;done
Answer: Look into configuration management tools like Puppet, Ansible or cfengine. They are helpful in the long run.
For a one-off, you could use Augeas, that make this change extremly easy, or even sed, which is present on most systems without further installs.
sed -i s/\#PasswordAuthentication\ yes/PasswordAuthentication\ no/ /etc/ssh/sshd_config

This can be sent in a simple ssh command:
ssh user@server sed ......

Comment: Nicer than my comment
Comment: And, in order to do it faster, install pssh (= parallell ssh) and use it to run the command - it'll give you nice output on where it worked and where it failed.


modal bottom sheet reusable class missing "State build" method

Question: I am trying to create a custom bottom sheet class to be re-usable, but it gives me the error of missing "State build" method. I know that I may include the @override method, but I have checked other responses like this, and I did not see the build method.
class ModalBottomSheet extends StatefulWidget {
  final Function()? onPressed;

  const ModalBottomSheet({Key? key, this.onPressed}) : super(key: key);

  @override
  State<ModalBottomSheet> createState() => _ModalBottomSheetState();
  }

  //error here
  class _ModalBottomSheetState extends State<ModalBottomSheet> {
   modal(context){
    showModalBottomSheet(
        context: context,
        isScrollControlled: true,
        backgroundColor: Colors.transparent,
        builder: (BuildContext context) {
          return Container(

            ),
          );
        });
      }
    }

EDIT:
class ModalBottomSheet {
void modal(context) {
Function(int)? onPressed;

showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (BuildContext context) {
      return Container(
        height: 200,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20), topRight: Radius.circular(20)),
        ),
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            children: [
          TextButton(
                onPressed: (1) {
                  onPressed?.call();
                },
                child: Text(
                  'CAMERA',
                ),
              ),

              TextButton(
                onPressed: (2) {
                  onPressed?.call();
                },
                child: Text(
                  'GALLERY',
                ),
              ),

This is the Main screen where to show the custom modal sheet:
ModalBottomSheet.modal(context,
                          onPressed: (index){
                            if(index == 1){
                              pickImage(ImageSource.camera);
                            }else{
                              pickImage(ImageSource.gallery);
                            }
                          });

Answer: You are extending the StatefulWidget, which requires you to override the build method. Instead, you can create a class or mixin that doesn't extend Widget, it will have a method that shows modal and requires BuildContext as a function parameter.
class ModalBottomSheet {
  void modal(context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return ...
      },
    );
  }
}

Edit:
You can also pass other parameters to this function, as void Function()? onPressed.
class ModalBottomSheet {
  static void modal(BuildContext context, void Function()? onPressed) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (BuildContext context) {
        return ...;
      },
    );
  }
}

Comment: ok nice. but can i still pass function onPressed? because now it gives me error
Comment: ok maybe just pass ```Function()? onPressed``` and then ```onPressed?.call()``` without the "widget" keyword
Comment: you pass it as function parameter `void modal(BuildContext context, Function()? onPressed)`
Comment: Thanks, nice explanation. However i changed the class as you suggested but when i try to access the class method using "ModalBottomSheet." i cannot display the method.
Comment: @Giovanni make the function static `static void modal()`, so you can access it as `ModalBottomSheet.modal()`
Comment: No actually it worked just now, passing the Buildcontext to ```modal```. but how can i access the ```onPressed``` function? Right now I wrote "ModalBottomSheet.modal(context)"
Comment: @Giovanni I edited the answer, now it include onPressed parameter as well.
Comment: Nice! works like a charms! Now i was able to pass index and pass function between different buttons. Thanks again!


Unity3D-How do I make a balance board?

Question: I'm making a test game, and I want to set a plane that tilts when the rolling ball I control with direction keys moves in that direction, kind of like a see-saw. Does anyone have any ideas for how to go about that?
Here's what I'm trying with code. I attatched it to the plane.
<code>public class Balance : MonoBehaviour {

    public float weight = 20f;
    Rigidbody rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.gameObject.name == "Player")
        {
            rb.AddForce(-transform.forward * weight, ForceMode.Acceleration);
            rb.useGravity = true;
        }
    }
}
</code>
New Ball Settings

Floor Collider
Comment: Can you create a gif of how it is behaving and post that?
Comment: Why are you setting useGravity on each trigger? That should be done in the Start function once. Also, post a screenshot that shows what's going on. Note that you can increase the mass of the rolling ball's Rigidbody
Comment: Ok. I posted the picture in the link Balance Board settings
Comment: Please read [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question) before attempting to ask more questions.
Comment: Also, this is **not a forum**, do not treat it like one.
Answer: What you would need to do is put the plane on a hinge in the center then enable gravity for the plain but not for the object that is the other side of the hinge.
Here is the documentation for the hinge joint, and here is a video tutorial on physics joints that covers hinges.
Comment: @user8048595 You don't. By adding force to the ball and rolling on the plane, the physics should handle that. Please give this a try before making further comments. If you are still lost, you can edit your question without what you have done and the issue it.
Comment: ok. How would I trigger the ball to add weight to a specific side of the plane?
Comment: I tried, but it's either doing nothing or sinks onto its side. I set the axis and anchor to the center. I just added the code Balance to my question.
Comment: You should not need your Balance script at all, it can be all done with the physics system with nothing special being done on via scripts.
Comment: Ok, I got rid of my script. and set the hinge in the center of the plane. The plan doesn't flip around, but it just doesn't do anything. Do I need to add some kind of weight in the ball script? Do I need to connect the center with an object?
Comment: if I dont check isKinematic on stage5, the ball will fall through it
Comment: If you are falling though the stage you are likely missing a collider for the floor or ball or both. Does your floor have a mesh collider?
Comment: My floor has a mesh collider and my ball has a sphere collider. Its just the ball that falls through the floor. I'm sure it has to do with the floor's rigidbody.
Comment: Its just the ball that falls through the floor. I'm think it has to do with the floor's rigidbody. The ball moves fine on the other floors.
Comment: I posted the ball and floor settings, I cant post two at once
Comment: You need to include a 3rd picture of the collider for the floor. Also, feel free to delete old comments, i have deleted mine.
Comment: Ok, Just added it

Unity3D-How do I make a balance board?


Copying Multi-Dimensional NSMutableArray

Question: I'm currently working on a Sudoku application, the numbers are stored within a Multi-Dimensional NSMutableArray of NSNumbers. I keep an array in my SudokuGridView, for displaying the numbers in the grid. When it comes time to solve the puzzle, I pass a [grid numberGrid] to a subclass of NSOperation I've created that solves the puzzle.
The grid's array is defined as a property as such:
@property (readonly) NSMutableArray *numberArray;

When passing it to the sudoku grid solver I go:
MESudokuSolver *solvePuzzleOperation  = [[MESudokuSolver alloc] initWithPuzzle: [grid numberArray]];

initWithPuzzle is defined as so:
- (id)initWithPuzzle:(NSMutableArray *)puzzleArray  {
    if(self = [super init]) {
        puzzle = [[NSMutableArray alloc] initWithArray: puzzleArray];
    }
    return self;
}

When I then convert the puzzle to a primitive int array to solve it, and then back into the puzzle NSMutableArray. What's funny, is that now, the grid's NSMutableArray now has the solution... Which means that somehow inside the MESudokuSolver the grid's array is being modified. So I did some investigation, the pointer to the array that is passed into the MESudokuSolver instance is different than the MESudokuSolver's puzzle NSMutableArray. Strange, right? I know.
Upon FURTHER investigation, the pointer to the NSNumbers inside the arrays with different pointers are actually the SAME.
To you StackOverflow, I ask, WTF?
Answer: When you initialise an array with the contents of the another array, the contents of both arrays will reference the same objects. What you want to do is perform a deep copy. This ensures that each array references its own copy of the object, so that if you modify the object in one array, it does not affect the object in the other array because they are actually different objects. This applies even to arrays of arrays. There are a number of approaches to performing deep copies. Since you want mutable copies of your mutable arrays inside your mutable array, it is a little trickier, but easy nonetheless:
// Implemented as a free function here, but this is not required.

NSMutableArray *MECopyGrid(NSMutableArray *outer)
{
    NSMutableArray *result = [[NSMutableArray alloc] initWithCapacity:[outer count]];

    for (NSMutableArray *inner in outer)
    {
        NSMutableArray *theCopy = [inner mutableCopy];
        [result addObject:theCopy];
        [theCopy release];
    }

    return result;
}

Beware also of NSNumber optimisations. Cocoa (and I assume Cocoa Touch also) caches a few different NSNumber instances. Since NSNumber instances are immutable, if you ask for [NSNumber numberWithInteger:1], Cocoa may give you a reference to an existing instance containing the same value. If you notice that NSNumber instance pointers are the same, it is likely because Cocoa has given you an old instance. This would save memory especially in situations like yours (without optimisations you would need 81 independent instances of NSNumber, but with optimisations you'll need at most only 9).
Comment: Thanks! I've never actually run into this issue before, probably because I've never worked with multidimensional NSArrays before.

If I could ask a quick question to clarify here... why is it that if you have a one dimensional array say of... NSStrings, that those strings are actually copied in memory and not modified directly from another instance?
Comment: @Matt Egan: I'm not exactly sure what you mean. If you have an array of immutable strings, they will likely never be copied in memory. Since nothing can modify an immutable string, a `copy` becomes a simple `retain`. If you create a copy of an array containing immutable strings, both arrays will contain references to the same immutable strings. The only time when modifying objects is cause for concern is when your array contains *mutable* objects. If you want an object to maintain mutable but you want nothing else to change it, you must get a `mutableCopy`.


foreach for JSON array , syntax

Question: my script is getting some array from php server side script.
result = jQuery.parseJSON(result);

now I want to check each variable of the array.
if (result.a!='') { something.... }
if (result.b!='') { something.... }
....

Is there any better way to make it quick like in php 'foreach' , 'while' or smth ?
UPDATE
This code ( thanks to hvgotcodes ) gives me values of variables inside the array but how can I get the names of variables also ?
for(var k in result) {
   alert(result[k]);
}

UPDATE 2
This is how php side works
$json = json_encode(array("a" => "test", "b" => "test",  "c" => "test", "d" => "test"));

Comment: If i'm not mistaken, you can access the attributes of each JSON Object by using it's name, like you would a property. e.g. `JSONObject.name` to get the attribute inside JSONObject that holds `{'name':'foo'}`
Answer: You can do something like
for(var k in result) {
   console.log(k, result[k]);
}

which loops over all the keys in the returned json and prints the values.  However, if you have a nested structure, you will need to use
typeof result[k] === "object"

to determine if you have to loop over the nested objects.  Most APIs I have used, the developers know the structure of what is being returned, so this is unnecessary.  However, I suppose it's possible that this expectation is not good for all cases.
Comment: you're going to want to square-bracket that. Edit: you fixed it.
Comment: yeah i actually made sure by trying in the console. ;)
Comment: that works. but 1 more problem, how can I get the names of those variables inside array ?
Comment: @david, is it an array, or an object literal?
Comment: @david, updated the answer -- `k` is the key, result[k] is the value.
Answer: Try this:
$.each(result,function(index, value){
    console.log('My array has at position ' + index + ', this value: ' + value);
});

Answer: You can use the .forEach() method of JavaScript for looping through JSON.

var datesBooking = [
    {"date": "04\/24\/2023"},
      {"date": "04\/25\/2023"}
    ];

    datesBooking.forEach(function(data, index) {
      console.log(data);
    });
Answer: Sure, you can use JS's foreach.
for (var k in result) {
  something(result[k])
}

foreach for JSON array , syntax


Opacity não funciona

Question: Tenho o seguinte código
HTML

        <

        >

     1
     2
     3

CSS
 * {
     margin:0;
     padding:0;
 }

 div.slideShow {
     position:relative;
     width:100%;
 }
 div.slideShow div.boxSlide {
     position:relative;
     width:100%;
 }
 div.slideShow div.boxSlide img {
     position:absolute;
     left:0;
     top:0;
     opacity:0;
     width:100%;
 }

 div.slideShow div.boxSlide img:first-child {
     opacity:1;
 }

  div.slideShow div.boxSlide div.anterior,
  div.slideShow div.boxSlide div.proximo {
     position:absolute;
     display:block;
     top:140px;
 }

 div.slideShow div.boxSlide div.anterior {
     left:100px;
 }
 div.slideShow div.boxSlide div.proximo {
     right:100px;
 }

div.slideShow div.boxSlide div.anterior span,
div.slideShow div.boxSlide div.proximo span{
     position: absolute;
     display:block;
     width:30px;
     height:30px;
}

div.slideShow div.boxSlide div.anterior span.boxSpan,
div.slideShow div.boxSlide div.proximo span.boxSpan {
     border:.1px rgba(0,0,0, .5) solid;
     background-color:rgb(200,200,200);
     opacity:0;
     z-index:1;
}

div.slideShow div.boxSlide div.anterior span.setaSpan,
div.slideShow div.boxSlide div.proximo span.setaSpan {
     line-height:30px;
     text-align:center;
     font-weight:bolder;
     cursor:pointer;
     z-index:2;
}

div.slideShow div.boxSlide div span.setaSpan::hover + span.boxSpan {
    opacity:1;
}

 div.slideShow div:nth-child(2) {
     position:relative;
     top:300px;
     width:100%;
 }

 div.slideShow div.contador{
     display:block;
 }

 div.slideShow div.contador span.contaSlide{
     display:inline-block;
     width:30px;
     height:30px;
     line-height:30px;
     text-align:center;
     background-color:rgb(200,200,200);
     cursor:pointer;
     opacity:.7;
 }

div.slideShow div.contador span.contaSlide::hover{
     opacity:1;
 }

Quando faço:
div.slideShow div.boxSlide div span.setaSpan::hover + span.boxSpan {
    opacity:1;
}

e
div.slideShow div.contador span.contaSlide::hover{
     opacity:1;
 }

Nenhum dos dois funciona.
Onde estou errando?
Comment: O que deveria acontecer exatamente e o que esta acontecendo?
Answer: Erro simples, use :hover não ::hover.

 * {
     margin:0;
     padding:0;
 }

 div.slideShow {
     position:relative;
     width:100%;
 }
 div.slideShow div.boxSlide {
     position:relative;
     width:100%;
 }
 div.slideShow div.boxSlide img {
     position:absolute;
     left:0;
     top:0;
     opacity:0;
     width:100%;
 }

 div.slideShow div.boxSlide img:first-child {
     opacity:1;
 }

  div.slideShow div.boxSlide div.anterior,
  div.slideShow div.boxSlide div.proximo {
     position:absolute;
     display:block;
     top:140px;
 }

 div.slideShow div.boxSlide div.anterior {
     left:100px;
 }
 div.slideShow div.boxSlide div.proximo {
     right:100px;
 }

div.slideShow div.boxSlide div.anterior span,
div.slideShow div.boxSlide div.proximo span{
     position: absolute;
     display:block;
     width:30px;
     height:30px;
}

div.slideShow div.boxSlide div.anterior span.boxSpan,
div.slideShow div.boxSlide div.proximo span.boxSpan {
     border:1px rgba(0,0,0, .5) solid;
     background-color:rgb(200,200,200);
     opacity:0;
     z-index:1;
}

div.slideShow div.boxSlide div.anterior span.setaSpan,
div.slideShow div.boxSlide div.proximo span.setaSpan {
     line-height:30px;
     text-align:center;
     font-weight:bolder;
     cursor:pointer;
     z-index:2;
}

div.slideShow div.boxSlide div span.setaSpan:hover + span {
    opacity:1;
}

 div.slideShow div:nth-child(2) {
     position:relative;
     top:300px;
     width:100%;
 }

 div.slideShow div.contador{
     display:block;
 }

 div.slideShow div.contador span.contaSlide{
     display:inline-block;
     width:30px;
     height:30px;
     line-height:30px;
     text-align:center;
     background-color:rgb(200,200,200);
     cursor:pointer;
     opacity:.7;
 }

div.slideShow div.contador span.contaSlide:hover{
     opacity:1;
 }

        <
        teste

        >
        teste

     1
     2
     3

Comment: :: é só para pseudo classes né?
Comment: na verdade hover é uma pseudo classe, :: é usado em pseudo elementos
Comment: é mesmo. Pode me ajudar em mais uma coisa: Descrição no final da pergunta
Comment: Isso só é possível com javascript, css ainda não é capaz de pegar o elemento pai (talvez na próxima versão), não estou com muito tempo agora, mas você pode abrir outra pergunta com essa questão, vão te responder rápido.
Comment: obrigado, vou fazer isso. Mas antes vou tentar com jQuery.
Comment: Se a resposta te ajudou você pode aceita-la, no canto superior esquerdo, isso ajuda o site e outros usuários. :)
Comment: Sim ajudou. Obrigado!

Opacity não funciona


How to display custom content when viewing node?

Question: I am using the Biblio module and I like the display mode (e.g. full, teaser).  I would like to tack on custom text and information when a user views the content below the display.  How do I append my own custom text in the current display?  When I go to "Manage Display", the custom fields are not shown.  It might be hard coded in the module.  What Drupal API call should I be looking for? Or better yet, I am perfectly willing to write my own module.  I just do not know where to start in adding my own additions to an existing display.
An example is the comment module.  When someone leaves a comment, then you can see the comment someone has written that is tied to the specific node and/or content type.  I am not talking about creating a user input form or input HTML field.
Answer: I resolved it by using hook_node_view() to append to the $node->content object.


Regex with multiple queries

Question: I am trying to test multiple conditions with a single regex.
My Regex:
^(?=.*no+\s+or+\s+no+\s+maybe).*

Sample test string :

Yes or No
Maybe yes or no
Maybe no or no
No or no Maybe
No maybe or No

When executed, it only matched "No or no Maybe".
The query should match as long as it finds "NO", "OR", "NO" and "MAYBE" (case insensitive) on the string
(Notice that there are 2 NOs. Treat the second NO as a separate variable. It should not match a string unless there are 2 NOs.)
Aside from "No or no Maybe", it should still match "Maybe no or no" and "No maybe or no".
I have also tried this one :
^(?=.*(?=.*no)(?=.*or)(?=.*no)(?=.*maybe)).*

Apparently it also matched Maybe yes or no
Comment: How you're selecting output. a bit explanation please
Comment: @CodeManiac I am not sure if I understand your comment correctly, so I edited it to "Matched" instead.
Comment: https://regex101.com/r/eRrBW9/1/ check this you want something like this ?
Comment: @CodeManiac, yes something like that. but "yes" is not a constant variable and I would prefer a different method instead
Comment: That is what i asked in first comment on what rules you're selecting your output. without knowing them can't tell you exact answer. i have seen a pattern of not including yes.
Comment: @CodeManiac ahh I understand. Basically, the query should match as long as it finds "no or no maybe" on the string.
Comment: Do you mean like this? `^.*(?:no maybe|maybe no) or no.*$` https://regex101.com/r/TWKBaF/1
Comment: @Thefourthbird it should still match "No or No maybe". Again, should match as long as it finds "no", "or", "no", "maybe" on the string.
Comment: So then it should find 4 out of 5 from your example data right instead of 2 because they all match No and Maybe. Or is it case sensitive?
Comment: @Thefourthbird i have posted 3 outputs from my original thread. If you are talking about "Maybe yes or no" then it should not be included as it only contains 1 no.
Comment: @GunjackSparrohw So like this then https://regex101.com/r/dVkXna/1
Comment: @Thefourthbird thanks for the update. unfortunately, "maybe no or no" was not matched on your regex. I have updated my thread to avoid further confusions.
Comment: @GunjackSparrohw Then you could use several lookarounds https://regex101.com/r/lQHUqe/1
Comment: @GunjackSparrohw Did that work for you?
Comment: @Thefourthbird hi there. thank you for the update! i am now trying to work out the use of the query on different scenarios (different set of words).
Answer: You could use lookarounds to check for your requirements and use word boundaries \b to prevent the words being part of a longer match:
^(?=.*\bno(?! maybe\b))(?=.*(?<!\bmaybe) no\b)(?=.*\b(?:no maybe|maybe no)\b)(?=.*\bor\b).+$

That will match

^ Assert the start of the string
(?=.*\bno(?! maybe\b)) Positive lookahead to assert no not followed by maybe using a negative lookahead
(?=.*(?<!\bmaybe) no\b) Assert that there is a no not preceded with maybe
(?=.*\b(?:no maybe|maybe no)\b) Assert that the string contains no maybe or maybe no
(?=.*\bor\b) Assert that the string contains or
.+ Match any character except a newline 1+ times
$ Assert the end of the string

Regex demo

Regex with multiple queries


Getting current time that changes dynamically after every statement is executed

Question: The question is very straight forward.
Observe the code below:
import time, datetime
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " This is a test"
time.sleep(5) # 5 seconds until next statement
print timer + " Test after 5 seconds, so the timer should've changed"

Results after executing the code:
13:22:07 This is a test
13:22:07 Test after 5 seconds, so the timer should've changed

As you see in the results, the timer is sleep the same.
I would've accepted it if we're talking about minutes here, but the number of seconds remained unchanged in the code results.
How would we go about using a timer that dynamically changes after executing one statement at a time?
Answer: When you assign datetime.datetime.now().strftime('%H:%M:%S') to timer variable current time assign to timer variable.
So after 5 second just reassign timer variable with current time[5 second later]
Try This One
import time, datetime
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " This is a test"
time.sleep(5) # 5 seconds until next statement
timer = datetime.datetime.now().strftime('%H:%M:%S')
print timer + " Test after 5 seconds, so the timer should've changed"

Comment: Besides the answers from the others, you might be more happy with time.clock() for exact measurements.
Answer: Don't use the timer again. Instead use datetime.datetime.now().strftime('%H:%M:%S') again. This will generate a new string with the time. Once you have assigned the string to timer, it will not change automatically.
The following should work:
import time, datetime
print datetime.datetime.now().strftime('%H:%M:%S') + " This is a test"
time.sleep(5) # 5 seconds until next statement
print datetime.datetime.now().strftime('%H:%M:%S') + " Test after 5 seconds, so the timer should've changed"

Answer: In you code, timer is nothing but a string containing the value of the current time when you ran the code. You are simply printing it out twice, with a 5 second sleep in between. But that will not change its value.
You need to rerun the line: datetime.datetime.now().strftime('%H:%M:%S') every time you want to refresh the time.


Learn to Program (Chris Pine) Answer explanation

Question: Chapter 7, first exercise at the end of the chapter (e-book) --> https://pine.fm/LearnToProgram/chap_07.html
I was able to get the code, but only once I set a variable and set it equal to something. I don't really understand why and would appreciate any explanation as to why you have to do this.
Here's my code:
puts "Tell me some of your favorite words-- one at a time, please!"

fave_words = []

word = '0'

while word != ''
     word = gets.chomp
     fave_words.push word
end

puts "Here are a few of your favorite words..."
puts fave_words.join(' ')
puts "Now in alphabetical order..."
puts fave_words.sort

Thanks in advance!
Comment: Without it, you would receive a `NameError` complaining that you are referencing an ``undefined local variable or method `word'``
Comment: What is your question?
Comment: Why I needed to set word equal to something (word = '0')
Answer: The condition for the loop to work (and to get into it for the first time mainly) is the word having a value different than an empty string. So it doesn't matter if you make it word = '0' or word ='any other string'. As long as you set it to something different than '' the loop clause will evaluate to true and the loop will start. As long as you provide a non empty input to it it will keep in the loop because the clause will remain evaluating to true.
Actually you don't even need to declare a variable outside of the loop. You could just do something like:
while true
   word = gets.chomp
   break if word.empty?
   fave_words.push word
end

So the loop starts immediately because eval(true) is truth. The loop will keep going until your input is an empty string, condition in which we break the loop.
Answer: word is always the input from the user and as long as it's a non-empty string the while loop functions. In order to get the ball rolling word is defined outside of the loop and set to a non-empty string, thus the loop executes.
When the user inputs nothing by pressing enter alone, the while loop condition fails and the loops ceases.


Find the polynomial $P(x)$ s.t. for any $a,b\in\Bbb C$ s.t. $a^2+b^2=ab$, $P(a+b)=6\big(P(a)+P(b)\big)+15a^2b^2(a+b)$.

Question:
Suppose that $P(x)$ is a polynomial such that
  $$P(a+b)=6\big(P(a)+P(b)\big)+15a^2b^2(a+b)$$
  for any complex numbers $a$ and $b$ satisfying $a^2+b^2=ab$, then find the polynomial $P(x)$.

I don't know how to even approach this one, it seems very complex. Your help is appreciated!
Comment: The answer is $P(x)=x^5$.  The key idea is to show that $$(x+1)^n-6(x^n+1)$$ is not divisible by $x^2-x+1$ for any integer $n\ge 0$.  And note also that $$(x+1)^5-6(x^5+1)-15x^2(x+1)=-5(x+1)(x^2-x+1)^2.$$
Comment: $P(0)=0$ (do you know why?)
Answer: In this solution, $P$ is assumed to be an entire function (which is more generalised than just being a polynomial).  Let $\omega_1,\omega_2$ be roots of $x^2-x+1=0$.
 We note that when $a=\omega_jt$ and $b=t$, we have $a^2+b^2=ab$, so that
$$P\big((\omega_j+1)t\big)-6\big(P(\omega_j t)-6P(t)\big)-15\omega_j^2(\omega_j+1)t^5=0\tag{1}$$
for $j=1,2$.
Suppose that
$$P(x)=\sum_{k=0}^\infty p_kx^k.$$
If $k\neq 5$, then the coefficient of $t^k$ of the LHS of $(1)$ is $p_k\cdot f_k(\omega_j)$, where
$$f_k(x)=(x+1)^k-6(x^k+1).$$
If $p_k\ne 0$, then $f_k(\omega_j)=0$.  For $k\geq 5$, we have
$$\big|(\omega_j+1)^k\big|\geq |\omega_j+1|^k=\sqrt{3}^k=9\sqrt{3}$$
and
$$\big|6(\omega_j^k+1)\big|\leq 6\big(|\omega_j|^k+1\big)=6\cdot 2=12.$$
Thus
$$\big|(\omega_j+1)^k-6(\omega_j^k+1)\big|\geq \big|(\omega_j+1)^k\big|-\big|6(\omega_j^k+1)\big|\geq 9\sqrt{3}-12>0\,.$$
For $k=0,1,2,3,4$, we can easily verify by hand that
$$(\omega_j+1)^k-6(\omega_j^k+1)\ne 0.$$
For $k=0,1$, this is trivial.  For $k=2$, we note that $(x+1)^2-6(x^2+1)=-5x^2+2x-5$ is not divisible by $x^2-x+1$.  For $k=3$, we note that $\omega_j^3=-1$ and $(\omega_j+1)^3\ne 0$.  For $k=4$, note that $$(\omega_j+1)^4=\big((\omega_j+1)^2\big)^2=(3\omega_j)^2=9\omega_j^2$$ and $$\omega_j^4=-\omega_j,$$ so $$(\omega_j+1)^4-6(\omega_j^4+1)=9\omega_j^2+6\omega_j-6\ne0.$$
Thus $\omega_j$ is not a root of $f_k(x)$ for any integer $k\geq 0$.  This is a contradiction, so $p_k=0$ for $k\ne 5$.
The coefficient of $t^5$ in $(1)$ is
$$p_5(\omega_j+1)^5-6(\omega_j^5+1)-15\omega_j^2(\omega_j+1).\tag{2}$$
Noting that
$$(x+1)^5-6(x^5+1)-15x^2(x+1)=-5(x+1)(x^2-x+1)^5,$$
we conclude that
$$(\omega_j+1)^5-6(\omega_j^5+1)-15\omega_j^2(\omega_j+1)=0.\tag{3}$$
Subtract $(3)$ from $(2)$ to get
$$(p_5-1)(\omega_j+1)^5=0.$$
Therefore $p_5=1$, so $P(x)=x^5$.


Manually calculating `false negative risk` (using Likelihood ratio and Bayesian analysis)

Question: The question is with reference to this paper: https://arxiv.org/pdf/1802.04888.pdf  and  https://royalsocietypublishing.org/doi/full/10.1098/rsos.171085
It give clearly how to calculate false positive risk or false discovery risk.
A real life example is also given on page 17-18
However, how can false NEGATIVE risk be calculated manually?
What exact formulae can we use?
Answer: Thanks for the link to my paper. I have been thinking of adding the false negative risk to my web calculator (but after 110 days of lockdown I'm having difficulty in concentrating).  Presumably it should be defined as
(false neg)/(false neg + true neg).
Incidentally, our web calculator at http://fpr-calc.ucl.ac.uk/ is down at the moment (a cock-up at UCL), but there is another copy at http://shiny.ieis.tue.nl/fpr_calc/
There are also later papers on the topic, in which I'm more explicit about the assumptions) at https://www.tandfonline.com/doi/full/10.1080/00031305.2018.1529622
and at https://royalsocietypublishing.org/doi/10.1098/rsos.190819
Comment: It's true that, for small enough p values, the log(FPR) vs log(observed p value) is more or less linear, but the position of the line will depend on all the values that you have to enter into the R scripts or the web calculator.  The web calculator was provided for those people for whom running an R script is "too cumbersome".  I doubt that it's possible to devise a simpler way of doing the calculations.
Comment: P-less-than method seems simple: LR = pval / power;  OR = priorORHo * LR; FDR = OR/(1+OR) . What are similar steps for P-equal method?
Comment: Look forward to your method for estimating `false negative risk`. Many drugs have been found to have `non-significant` effect against COVID-19. It will be important to know false negative risk for these studies.
Comment: Of course it's always possible that the drugs don't work. The prior probability of a random drug being effective for a viral infection must be very low.
Comment: These are not random agents. They have some prior study indicating their likely efficacy. I would put prior probability as 2/3 or 0.67
Comment: That seems much too high to me. But we are both guessing. That's why I suggest citing, along with the p value and CI, the FPR_50 ie the value for a prior of 0.5. That's the nearest we can get to equipoise.
Comment: I want to focus on how to calculate False `NEGATIVE` Risk. Same principles as FPR will need to be applied to `power`?
Comment: For `power` varying from 0.8 to .95, FPR_50 (a prior of 0.5), will be only slightly higher than the observed p value.  FPR_50 is 0.058 if p value is 0.05 and power is 0.8 . Not much difference. Difference is even lesser for higher power values. (I hope my calculation is correct)
Comment: That calculation is right only if you use the p-less-than method of calculation of the likelihood ratio. That method is wrong, or at least inappropriate, for interpretation of a p value for a single experiment.  Who consider p values that have not been observed?  If you use the p-equals  method to calculate the likelihood ratio, the FPR_50 is not 0.058, but it is 0.26 -far bigger. e.g. see Fig 2 in https://royalsocietypublishing.org/doi/full/10.1098/rsos.171085#d3e628https://royalsocietypublishing.org/doi/full/10.1098/rsos.171085#d3e628
Comment: Both methods of calculation are given by our false positive risk calculator, At present the usual URL, http://fpr-calc.ucl.ac.uk/  is offline (thanks to a cockup by UCL) but you can access a back up copy at http://fpr-calc.ucl.ac.uk/fpr_calc/
Comment: From the graph, it appears that, for P<0.05, FPR with p-equal method, is almost linear. Hence, for this part, if a simple formula can be given, everyone can easily use it. Its acceptability will also increase as the current method of using online calculator is quite cumbersome. IMHO.
Comment: @mso The explicit calculations are specified in the appendices of my papers.


Display different time from one field value

Question: I have field to display event start date and time. This field uses date module's widget. I need display time of event start for different time zones. For example:
Eventname - starttime for Tallin: 05.07.2015 01:54
Eventname - starttime for Boston: 05.07.2015 09:54 (+8 Hours)
How can I add +8 hours to date field value and display result on node?
Comment: Why don't you use user's timezone? so that each user will see event based on his/her own timezone?
Comment: Because I need display start time of some event on American's server for Russian users. This event is added on site with start time for Boston. I need autoconvert this time for Moscow time, but Boston's time also should be displayed.
Answer: Well you are better off writing a custom module or using a function that can swap out a timezone variable instead of manually calculating by adding 8 hours...
But if that's what you want here is one way of achieving this..
Create a node template for that content type or specific node (whichever suits your scenario).
In the template file you can use:
<code> <?php
    // Your date field. note the appended 'field_' at the start of the machine name.
    $date = new DateTime($content['field_YOUR_FIELD_MACHINE_NAME']['#items'][0]['value']);

    // Boston date field
    $boston_date = $date;
    $boston_date ->modify("+8 hours");
    $boston_date ->format("d.m.Y H:i");

    //Outputs your date field with 8 hours added to it.
    print 'Eventname - starttime for Boston: ' . $boston_date;
 ?>
</code>
Comment: Thank you for help! But this solution crashes my site without any error message. I don't know why(
Comment: Where are you placing the code? I tested my code on a fresh install of d7 and it works great with a node template.


How to associate User data with custom module?

Question: I'm thinking about a custom module where I need to save additional data (like user logs from other software, customer data, etc.) that'd go into a custom module user table.
How would I associate that with the user? Just the user ID?
Or is there anything else that I might want to save for uses that I might not yet know (Views, Domain Acess, Panels, Context, ...) or can I get all required data just be joining the UserID everywhere?
Comment: Have you checked [Feeds module] (https://www.drupal.org/project/feeds) already? It allows you to bring in external data and relate it to existing Drupal entities using an easy administration.
Comment: That is true - I played around with it. But I'm not certain whether it's enough. It can create Nodes but my data seems to be a bit more complex and it might be more reasonable to have it in an optimised table.
But having nodes would be nice of course.
Comment: I hear you. IMO using Feeds gives you the benefit of a robust and mature module that already does all the heavy lifting for you. I've done projects where the external data wasn't Fed in and it became a non-scalable headache after a while. Feeds has a lot of API flexibilty... check out this [tutorial] (https://www.drupal.org/node/622700) for many great tips and guides on how to implement your own customization.
Comment: In my opinion, Feeds would only be useful if the software from which you are drawing the information can export in a format Feeds natively uses. Otherwise, I think a custom module is better because you are then not constrained by any changes to the Feeds module or its API - any changes would require a rewrite of parts of your site, whereas a custom module only changes when you change it
Comment: The problem is the kind or amount of data I guess.
Should be similar like data mining/logs/analytics table. I estimate on average for 500 users, 200 nodes, every day - 100.000 a day, so 3.6 Mio per year. I'd like to use d3 etc. for visualisation (not Views). Where as .. I just read more about it and saw it would be possible to put the feeds into MongoDB and that could go a long way. Maybe that's the way to go.
Comment: @Chris, it seems like you answered your own question, you should answer it and accept it so it's off the unanswered list
Answer: As usual there are plenty of ways to do something with Drupal.
Of course it would be possible to create a content type and import it via Feeds but sometimes (in case it might become plenty of data) it could be better to use a different approach.
So far it seems I'd go with MongoDB, the appropriate module and get the data into the DB using JSON and try to relate that to the current user if or where needed. Due to the amount of data and the visualisation it seems to be better to go the Document DB way.


How can I tell what my parameter values are?

Question: Here's a snippet of my code-behind:
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;

//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("@StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("@EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}

if (MyPlatform != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MyPlatform", cboPlatform.SelectedValue));
}

if (MyManager != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MyManager", cboManager.SelectedValue));
}

if (MyAuditManager != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MyAuditManager", cboAuditorManager.SelectedValue));
}

if (MySampleTitle != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MySampleTitle", cboSampleTitle.SelectedValue));
}

if (MyAuditType != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MyAuditType", cboAuditType.SelectedValue));
}

if (MyLocation != "N")
{
cmd2.Parameters.Add(new SqlParameter("@MyLocation", cboLocation.SelectedValue));
}

try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");

// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSRptMenu"] = ds;

GridView_Reports.DataSource = ds;
GridView_Reports.DataBind();

So I'm stepping through this code and I get to
var adapter = new SqlDataAdapter(cmd2);

I highlight "cmd2" and it tells me what server it's looking at, what the command text is, etc...  It also tells me that there are 5 parameters selected for this particular case.
My question is; how can I tell which parameters are selected, and what their values are?  I've drilled down through just about every menu item and can't seem to find it.
Comment: you've added them to `Parameters`. What do you see when you look there?
Comment: Well, how about a defining `SqlParameterCollection` at the top of your code and add them if your conditions are `true` then check your collection at the end?
Comment: It says there are 5, but I can't find any menu item under it that says what those 5 are.
Comment: @JohnnyBones: I would expect that to be of type `SqlParameterCollection` which is expandable to show the items in the collection. Perhaps you could put a screenshot of what you are seeing there instead of the connection object (or as well as if you want).
Answer: If anyone else needs this info, I found it under:
cmd2 -->
  Parameters -->
    base -->
      base -->
        Non-Public members -->
          [System.Data.SqlClient.SqlParameterCollection] -->
             _items -->

That's where you can find the list of parameters, then under each parameter you can find its value.


Apply a theme to an activity in Android?

Question: I know how to apply a theme to a whole application, but where would I go to apply a theme to just a single activity?
Answer: You can apply a theme to any activity by including android:theme inside <activity> inside manifest file.
For example:

<activity android:theme="@android:style/Theme.Dialog">
<activity android:theme="@style/CustomTheme">

And if you want to set theme programatically then use setTheme() before calling setContentView() and super.onCreate() method inside onCreate() method.
Comment: What about disable theme? on a single activity
Comment: and in activity xml use `tools:context= ".YourAtivityName"` in the root
Comment: @Yousha Aleayoub: did you try just setting another theme?
Comment: No, but i just want to disable/remove the theme and make it basic... :)
Answer: To set it programmatically in Activity.java:
public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setTheme(R.style.MyTheme); // (for Custom theme)
  setTheme(android.R.style.Theme_Holo); // (for Android Built In Theme)

  this.setContentView(R.layout.myactivity);

To set in Application scope in Manifest.xml (all activities):
 <application
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To set in Activity scope in Manifest.xml (single activity):
  <activity
    android:theme="@android:style/Theme.Holo"
    android:theme="@style/MyTheme">

To build a custom theme, you will have to declare theme in
themes.xml file, and set styles in styles.xml file.
Comment: Why have you added two `android:theme` attributes?
Comment: What about disable theme? on a single activity
Comment: @Yousha Aleayoub, to disable the theme, create a blank theme in `styles.xml` and then use the syntax `android:theme=@style/MyBlankTheme`.
Comment: @Vineet Kaushik, `android:theme="@android:style/Theme.Holo"` is the syntax for adding an Android built-in theme.  `android:theme="@style/MyTheme"` is the syntax for adding a custom theme described in your `styles.xml` file.  In your actual `AndroidManifest.xml` file you would only use one or the other for each section, not both.
Comment: It seems putting more than one custom theme in the manifest don't work. If you add a theme at application level and a second at activity level, only the application one is used. I tried to add one theme for each activity with different "look" but without good result.
Answer: Before you call setContentView(), call setTheme(android.R.style...) and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).
Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)


Has there been an athlete to win a College Championship in two or more different sports?

Question: After asking one involving college sports, I want to know if there has been an athlete who was known for excelling in different sports ever won a championship in separate sports?
Comment: Division I only or are you also interested in Division II / III?
Comment: Well, generally Division I, but Division II and III is fine as well. I should have probably specified Division I, but any would be fine since it has been brought up.
Comment: I assume from the way your question is phrased that "different sports" means actual different activities, and an athlete who wins cross-country and track wouldn't answer this. Likewise different disciplines on the track (sprints/hurdles) aren't what you're looking for either?
Answer: Jim Thorpe won championships in football and ballroom dancing, an interesting combination. Surprisingly, he does not appear to have any victories in track, perhaps because there was no collegiate pentathlon or heptathlon.
https://en.wikipedia.org/wiki/Jim_Thorpe#College_career

[Thorpe] also competed in football, baseball, lacrosse and even ballroom
dancing, winning the 1912 intercollegiate ballroom dancing
championship.
...
In 1912 Carlisle won the national collegiate championship largely as a
result of [Thorpe's] efforts – he scored 25 touchdowns and 198 points during
the season, according to CNN's Greg Botelho.
Answer: Bob Rule of Cornell University was a goalie on the NCCA champion ice hockey team as well as a goalie on the championship lacrosse team
Source
Comment: Not getting the downvotes here. I've found confirmation (apart from the Cornell website linked to in the answer) that Mr. Rule was on both those teams and that they won their championships.
Comment: @GreenMatt I agree. I wonder if the issue is the specifics of "won a championship"? The Cornell site seems to imply that Mr. Rule, while on the two championship teams, did not play in the lacrosse championship (having been injured in the last game of the season) and it's not implied that he played in the hockey championship either. Seems like this comes back to a need for more specificity in the question.
Comment: @pjmorse: Possibly, although an injured player - especially one who made significant contributions to the team's season (and starting goalie certainly qualifies, IMO) - is usually considered part of a championship team, even if their injury prevents participation is the championship game/match/series. I wonder if "excelling" is part of the issue, since the selected answer mentions one of the most celebrated athletes of all time, while Bob Rule is unknown.
Answer: Jared Mitchell from LSU attained this feat.

2007 - Football
2009 - Baseball
Answer: Anthony Munoz won College National Championships at USC in 1978 for football and baseball.
Comment: Welcome to Sports Stack Exchange. Can you add a reference that verifies this answer?


Paired data comparison: What statistical method to use?

Question: I want to analyze the difference of two data collection rounds which took place in two different years with the same sample.
Companies were asked a few questions and afterwards the answers were analyzed into variables.
Now I want to compare these variables and outcomes, if they significantly differ.
What is the best statistical method to do this? I have paired data and an unbalanced panel ( in this two collection rounds, not each company answered all questions)
Thanks for your help!
Comment: The test you should use will depend on the shape of the data distributions. You might consider parametric tests like t-tests, or non-parametric tests like Mann-Whitney U test.
Answer: Comment:
If you want to do a paired test of companies across the two different years (call them $i=1,2)$, you
must use only companies $j = 1,2, \dots, n$ that responded in both years. Then find differences
$d_j = Y_{1j} - Y_{2j}.$
If the sample of differences $d_j$ is approximately normally distributed
then you can do a one-sample t test on the differences for $H_0: \delta = 0$ against $\delta \ne 0,$ where $\delta$ is the mean change in the population
of participating companies between the two years.
If the sample of differences is clearly not from a normal population, but is nearly symmetrical, you might use a one-sample Wilcoxon signed-rank test
instead of a t test.
[Data below are fictitious data sampled using R for purposes of demonstration; of course, your real data may differ.]
For example, suppose differences are in vector d in R, with numerical
and graphical summaries as below:
summary(d);  length(d);  sd(d)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-58.010 -11.270  -3.747  -2.641   4.093  41.582
[1] 100         # sample size
[1] 15.94684    # sample standard deviation

One hundred companies responded in both of the years. It seems that observations in the later year are larger (perhaps significantly larger), giving many negative differences.
boxplot(d, horizontal=T, col="skyblue2")

There are more boxplot ouliers in both tails than I would
anticipate from normal data, but the sample seems roughly
symmetrical.
Also a normal probability plot (quantile-quantile plot) of the
data is distinctly nonlinear.
qqnorm(d, datax=T);  qqline(d, datax=T, col="green3")

So, I choose the Wilcoxon SR test, which
rejects (5% level) the null hypothesis that the population is centered
at $0.$ The P-value is $0.032 < 0.05 = 5\%.$
wilcox.test(d)

        Wilcoxon signed rank test with continuity correction

data:  d
V = 1901, p-value = 0.03205
alternative hypothesis: true location is not equal to 0

Note: Fictitious data (Laplace distributed), used for illustration above, were sampled
in R as shown below:
set.seed(2021)
d = rexp(100, .1) - rexp(100, .1) - 1.5


Display extra information adjacent to system_settings_form() output

Question: I have a properly constructed set of data coming out of a call to system_settings_form().  How can I add to that data to display additional items on the form page?
I'm currently trying (and failing with):
// ...inside drupal_get_form callback
// $form has some form elements in it
$return =  system_settings_form($form);
if (!hay_problemas()){
    $return['warning'] = array(
        '#type' => 'div',
        '#class' => 'warning',
        '#markup' => 'WARNING:  Filesystem permission are broken'
    );
}
return $return;

Answer: I think this must be
// ...inside drupal_get_form callback
// $form has some form elements in it

if (!hay_problemas()){
  $form['warning'] = array(
    '#attributes' => array('class' => array('warning')),
    '#markup' => t('WARNING:  Filesystem permission are broken'),
    '#weight' => -10, //set position relative to other $form['key']
  );
}

return system_settings_form($form);

Comment: Nailed it.  Can you recommend a good tutorial for this type of work?
Comment: http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval for allowed form properties and http://drupal.org/node/206761 for module settings page, the best place is to see how other module implements their settings pages
Comment: Thanks, the first link was what i meant.  I more or less had a handle on the second part.
Comment: Also, take a look at `drupal_set_message()`, as it might be better to display warnings. See http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_set_message/7


Finding The Number Of The Solutions For $\cos x = \frac{x^2}{100}$

Question: Hello everyone how can I find the number of the solution to the equation:
$\cos x = \frac{x^2}{100}$ in real numbers?
I tried to convert it to function $y = \frac{x^2}{100} -\cos x$
and find all the cutting points with the x axis by find all the extreme points of y.
$y' = \frac{x}{50}+\sin x$
I found 1 minimum point in $(0,-1)$ because of that I know that the equation have
at least two solutions.
Comment: Hint : draw a graph. Find values of both side on the numbers 0 and π/2 . Also note that that both the functions are even. Also in the range 0 to π/2, check the behaviour of both sides, i.e increasing or decreasing. Last thing , check when the right side will cross the value of 1 , so that they stop intersecting.
Comment: What did you try?
Comment: Hint: can you find a lower and upper bound for the maximal value of x for which the equality holds for the _last_ time?
Answer: Making a rough plot will give you 6 solutions
Draw the graph of $\cos x$ , and notice that $\cos x\le 1$ , and ${x^2\over 100} > 1$ for all $x$ such that $|x| > 10$ , so there won't be any solution before $x=-10$ and after $x=10$ . Now , a rough plot of graph between $x=-10$ and $x=10$ , will give you 6 points of intersection.!
Comment: Never mind I understood your solution. Thank you very much!!!
Comment: Thank you but I didn't understand the last part.
Comment: Could you please elaborate exactly what you didn't understand ? I'll try to explain it better.


Active não ficando selecionado ao click

Question: Bom dia,
eu sei que deve ser uma coisa basica, mas estou tendo problemas com isso.
O site contem dois idiomas, ao clicar em uma bandeira, a linguagem do site muda e a bandeira referente a linguagem fica com cores, em quanto a outra bandeira fica em Preto e Branco, porem, quando eu clico em uma bandeira, ela fica selecionada e atualiza a pagina automaticamente, voltando para a outra bandeira.
Alguem poderia me ajudar?
HTML

               <a href="<?=URL_SITE?>/idiomas/changeLanguage/portugues">
                   <img id="br" class="active" src="<?=ICONES?>br-flag.png">

                <a href="<?=URL_SITE?>/idiomas/changeLanguage/espanhol">
                    <img id="es" src="<?=ICONES?>es-flag.png">

SCRIPT

CSS
.languages img{
         margin-left: 3px;
         filter: grayscale(1);
         -webkit-filter: grayscale(1);
      }

.languages img:hover, .languages img.active{
         filter: grayscale(0);
         -webkit-filter: grayscale(0);
      }

Comment: Qual é a linguagem que tens no servidor (imagino que PHP?)? A lógica que falta aqui pode ser feita no servidor. Se juntares ao link de cada imagem uma query string com por exemplo `?lang=br` no servidor podes ir buscar isso como um GET e renderizar as classes ou url de cada ficheiro png dependendo disso.
Answer: Uma vez que redirecionas para outra página/url não precisas de ter a lógica no cliente e podes fazer tudo no PHP. Mesmo o que tens agora em jQuery podes fazer no servidor.
Seria algo assim:
<?php
    $lang = $_GET['lang'];
?>

    <a href="<?=URL_SITE?>/idiomas/changeLanguage/portugues?lang=br">
        <img id="br" class="<?= $lang == 'br' ? 'active' : ''?>" src="<?=ICONES?>br-flag.png" />

    <a href="<?=URL_SITE?>/idiomas/changeLanguage/espanhol?lang=es">
        <img id="es" class="<?= $lang == 'es' ? 'active' : ''?>" src="<?=ICONES?>es-flag.png" />

Active não ficando selecionado ao click


Forecasting in intervals

Question: I have data in the interval of 5 years from 1975 to 2018 e.g. (1975-1979). (1980-1984) so on. I need to forecast the numbers in the future from 2018 to 2030 and 2040 in 5 years intervals also. what is the best method?
Answer: You don't really any some special method. Time-series data always has a frequency, for example, it could be milliseconds, minutes, hours, weeks, or years. In your case, the frequency is 5-year periods. If you have 5-year data and you need to predict next 5 years, just train a time-series model on it and it will out-of-the-box make a prediction for the 5-year periods.
The only limitation is that your data comes in predefined boxes. So if you are at time $t$ equal to the 1975-79 box, the $t+1$ would be the 1980-84 box. If for example, you would need to make a prediction for the years 1977-81, you can use linear interpolation and take the appropriate fractions from both boxes $3/5 \times x_t + 2/5 \times x_{t+1}$.
Since your data is relatively small, you should look into simple forecasting methods that work well for short time-series.
Comment: For a great introduction to forecasting, I recommend [*Forecasting: Principles and Practice* (2nd ed.) by Athanasopoulos & Hyndman](https://otexts.org/fpp2/)
and
[*Forecasting: Principles and Practice* (3rd ed.) by Athanasopoulos & Hyndman](https://otexts.org/fpp3/)
Comment: can you send me a method for ordinary time series analysis?
Comment: @kirellossaid see edit.

Forecasting in intervals


P-values vs Coefficient Values in GLM

Question: In the following excerpt, the author noted an association with the dependent variable based solely on the p-value and not the magnitude of the coefficient. Here is a link to the study.

I thought that the coefficients would tell us the magnitude of change in the dependent variable with a change in the feature; like a gradient. Why are Followers and Followees strong predictors if they have such small coefficients?
Comment: Please give a reference to this study in usual academic form or alternatively a stable and accessible URL.
Comment: If I changed a variable from being measured in mm to being measured in km (or from dollars to millions of dollars), the coefficient would change by six orders of magnitude, but the p-value would remain unchanged.
Comment: @NickCox I have added the URL.
Comment: Thanks. The .pdf there carries no standard bibliographic details but here they are: Bongwon Suh, Lichan Hong, Peter Pirolli, and Ed H. Chi. 2010. Want to be Retweeted? Large Scale Analytics on Factors Impacting Retweet in Twitter Network. In _Proceedings of the 2010 IEEE Second International Conference on Social Computing (SOCIALCOM '10)_. IEEE Computer Society, Washington, DC, USA, 177-184. DOI=http://dx.doi.org/10.1109/SocialCom.2010.33
Answer: Understanding the magnitude of the effect as expressed through the regression coefficient depends entirely on the scale on which the X variables are measured. Remember, the coefficient in a GLM model represents the change in Y for a one unit change in X. In this example, a number of the predictors are binary variables (those with the 'orNot' suffixes).  Thus, for these variables, a one unit change represents moving from the minimum value (0) to the maximum value (1). Variables such as Followers and Followees are continuous variables, and thus a one unit change in these X variables means something very different as they range from a minimum of zero to a maximum of (possibly) several thousand.
Accordingly, it is not possible to directly compare the estimated coefficients for different variables in a GLM model without taking into account the scale on which those variables are measured.
Comment: Agreed. I think it's consistent with that to point out that some rescaling of predictors would have been a very good idea in the study cited. **The coefficients of four predictors are given to just 1 sig. fig.**  as a side-effect of working with values $>> 1$. While it's perhaps unlikely that any one would want to use this particular equation for comparison, in other fields of science using other studies' results for prediction is important. Indeed it's a criterion of scientific or practical worth if a fitted model is of wider interest.
Comment: Indeed - I suppose it is possible that they did some rescaling in other tables in the paper, though without a reference it is impossible to tell!

P-values vs Coefficient Values in GLM


Understanding a part of the theorem from Ferguson's book

Question: The following images are part of a proof of a theorem in the Ferguson's seminal book "Mathematical Statistics-A decision theoretic approach".
I did not get some parts which uses certain concepts from Analysis.

The information given in the statement of the proof was that $S$ was closed from below, and bounded from below. It is fine when they say that $B$ is bounded below which is also obvious from the definition. So, there should be a g.l.b. for the set $B$, which is denoted by $b_0$.
Now why there should exist a sequence of points $\left(\mathbf{y^{(n)}}\right)$ in the risk set $S$  such that $\sum p_j y_j \to b_0$ ? Is $b_0$ a limit point of $B$? Is $B$ closed ? Even if this happen why $b_0$ which is greatest lower bound of $B$ should belong to $B$ ?
Next, I guess they apply Bolzano Weierstrass theorem to say that $\mathbf{y^{0}}$ is a limit point of the sequence $\left(\mathbf{y^{(n)}}\right)$. But why the last step $\sum p_j y_j^0 =b_0$ ?
Answer: Since $b_0=\inf B$, there exists a sequence $(\beta_n)_{n\geq 1}$ of elements of $B$ such that $\lim_n\beta_n = b_0$. As in the book, write $\beta_n = \sum_{j=1}^k p_jy_j^{(n)}$ where $(y_1^{(n)},\ldots,y_k^{(n)})\in S$.
Since $(\beta_n)_{n\geq 1}$ converges, it is bounded above by some $B$, hence for fixed $j$, we have $p_jy_j^{(n)}\leq \sum_{j=1}^k p_jy_j^{(n)}\leq B$. Since $p_j>0$, this yields $\forall n\geq 1,\; y_j^{(n)}\leq \frac B{p_j}$. Consequently, $(\mathbf y^{(n)})_{n\geq 1}$ is bounded coordinate-wise, hence bounded in $\mathbb R^k$. Applying Bolzano-Weierstrass gives some limit point $\mathbf y^{0}$ and a subsequence $(\mathbf y^{(n_m)})_{m\geq 1}$ such that $\lim_m\mathbf y^{(n_m)} = \mathbf y^{0}$. This implies convergence w.r.t each coordinate: $\lim_m y_j^{(n_m)} = y_j^{0}$.
Letting $m\to \infty$ in  $\displaystyle \sum_{j=1}^k p_jy_j^{(n_m)} =\beta_{n_m}$ yields $$\sum_{j=1}^k p_jy_j^{0} =b_0$$


Parsing Complex Json with Gson Java - Only nodes

Question: I have this Json structure and I need to get the information for "myId", "name", "adress1" and "city".
      {
        "InformationResponse":{
        "Id":"122212",
        "customerSessionId":"007",
        "Summary":{
        "myId":1234567,
        "name":"Casino",
        "address1":"13 Street",
        "city":"Las Vegas",
       },
...

I am using Gson (Java).
I created 3 Class (InformationResponse, Summary and Main)
public class Summary {

    private String myId;
    private String name;
    private String city;

    public String getMyId() {
        return myId;
    }
    public void setMyId(String myId) {
        this.myId= myId;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString(){
        return getMyId() + ", "+getName()+", "+getCity();
    }
}

MyObject.class
public class MyObject{

    private Summary summary;

    public Summary getSummary() {
        return address;
    }

    @Override
    public String toString(){
        sb.append("Summary="+getSummary()+"\n");
        return sb.toString();
    }
}

In the Main I can see my Json file and I am doing this:
// Get Gson object
Gson gson = new GsonBuilder().setPrettyPrinting().create();

// parse json string to object
MyObject myobject1 = gson.fromJson(json, MyObject.class);

But I have null everytime.
Thanks for your help!
Jean M.
Comment: Looks like you might have a class cast problem from MyObject to Hotel.
Comment: thanks but actually I did a mistake when I copy/paste. It is MyObject in my code. Edited
Answer: Try This          @SerializedName("Id")
               private String myId;
Answer: Gson requires a default no args constructor:
https://sites.google.com/site/gson/gson-user-guide#TOC-Object-Examples
Try adding a public no-args constructor to both your Summary and MyObject classes.
public Summary() {}
public MyObject() {}

Comment: From the docs: "While deserializing an Object, Gson needs to create a default instance of the class
Well-behaved  classes that are meant for serialization and deserialization should have a no-argument constructor"
Comment: I think its great that you read the docs, I do. But a) the docs are outdated b) again, gson doesn't require an explicit no-arg constructor. And c) this wasn't the op's problem because of that. The only time you would need to explicitly add a nullary constructor is if you had a class will a non-nullary constructor, preventing gson from calling `newInstance()` to instantiate the class via reflection


Is there any Windows library in node.js (like Windows.h in c++)

Question: I wanted to make a script which can move my cursor to a certain point on the screen and click or type something. Is there any way to do that with node.js?
I am aware that I can do that with c++ using <Windows.h> or <WinUser.h> headers. But I prefer using JavaScript so I was wondering is there any way to do that?
Answer: you can use with Node.js is the robotjs library. This library provides a simple, cross-platform way to control the mouse and keyboard using JavaScript.
npm install robotjs

Here is an example from its website:
// Move the mouse across the screen as a sine wave.
var robot = require("robotjs");

// Speed up the mouse.
robot.setMouseDelay(2);

var twoPI = Math.PI * 2.0;
var screenSize = robot.getScreenSize();
var height = (screenSize.height / 2) - 10;
var width = screenSize.width;

for (var x = 0; x < width; x++)
{
    y = height * Math.sin((twoPI * x) / width) + height;
    robot.moveMouse(x, y);
}
Keyboard
// Type "Hello World" then press enter.
var robot = require("robotjs");

// Type "Hello World".
robot.typeString("Hello World");

// Press enter.
robot.keyTap("enter");
Screen
// Get pixel color under the mouse.
var robot = require("robotjs");

// Get mouse position.
var mouse = robot.getMousePos();

// Get pixel color in hex format.
var hex = robot.getPixelColor(mouse.x, mouse.y);
console.log("#" + hex + " at x:" + mouse.x + " y:" + mouse.y);

For more details you can go with its documentation.
Answer: to can user robotjs lib
https://www.npmjs.com/package/robotjs
//Type "Hello World" then press enter.
var robot = require("robotjs");

//Type "Hello World".
robot.typeString("Hello World");

// Press enter.
robot.keyTap("enter");


bulk size text parameters in jenkins report error

Question: I have a build with a text parameters in Jenkins, when I input big data into text area and try to build, it comes

[TEST-save_txt_to_file] $ /bin/sh -xe /tmp/hudson3834163952953567847.sh
FATAL: command execution failed
java.io.IOException: Cannot run program "/bin/sh" (in directory "/var/lib/jenkins/workspace/TEST-save_txt_to_file"): java.io.IOException: error=7, Argument list too long
    at java.lang.ProcessBuilder.start(Unknown Source)
    at hudson.Proc$LocalProc.(Proc.java:244)
    at hudson.Proc$LocalProc.(Proc.java:216)
    at hudson.Launcher$LocalLauncher.launch(Launcher.java:763)
    at hudson.Launcher$ProcStarter.start(Launcher.java:353)
    at hudson.Launcher$ProcStarter.join(Launcher.java:360)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:91)
    at hudson.tasks.CommandInterpreter.perform(CommandInterpreter.java:60)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:19)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:814)
    at hudson.model.Build$BuildExecution.build(Build.java:199)
    at hudson.model.Build$BuildExecution.doRun(Build.java:160)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:593)
    at hudson.model.Run.execute(Run.java:1568)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:46)
    at hudson.model.ResourceController.execute(ResourceController.java:88)
    at hudson.model.Executor.run(Executor.java:237)
Caused by: java.io.IOException: java.io.IOException: error=7, Argument list too long
    at java.lang.UNIXProcess.(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 17 more
Build step 'Execute shell' marked build as failure
Finished: FAILURE

Is there any workaround? Thanks!
my ENV:
java.runtime.version    1.6.0_41-b02
org.jenkins-ci.main:jenkins-war:1.502
Comment: A typical workaround is to write the argument value to a file and then use an alternate command-line argument that can read all or some arguments form a file. Are you trying to do this already ? If not maybe that could work for your command.
Comment: Thank you. It won't help, my job is save_txt_to_file, which already got the error before I can write to a file.
Answer: This is caused by a linux limitation whereby the arguments can't exceed 128kb in size
See Linux Kernel constant: MAX_ARG_STRLEN
https://github.com/torvalds/linux/blob/master/include/uapi/linux/binfmts.h
Within Jenkins once you read from/to a variable where this value is exceeded, you will hit this error.
In my case, I had a github webhook that launched a Jenkins job and set a payload parameter to some string > than this limit. Attempting to read this parameter would throw this error.
In order to work around the problem, I have a child job that uses a rest-api call to read the value from parent
You can let the parent job throw a failure, but allow the child job to be launched in all cases.
Below is a slightly refined function I used to pull the information (Stripped out error checking and comments for brevity)
def get_parameter_value_from_parent():
    host = 'https://[YOUR_COMPANY].ci.cloudbees.com'
    this_build_url = os.environ.get('BUILD_URL')
    request_auth = (JENKINS_USER, JENKINS_TOKEN)

    url = '{0}/api/json'.format(this_build_url)
    parameter_name = 'payload'
    payload = ''

    #
    # Get the upstreamBuild number, and the upstreamUrl
    # so we can put together a link to the upstream job
    #

    response = requests.get(url, auth=request_auth)
    this_build = json.loads(response)

    build_number = ''
    short_url = ''
    actions = this_build['actions']
    for action in actions:
        if action.get('causes'):
            for cause in action.get('causes'):
                build_number = cause['upstreamBuild']
                short_url = cause['upstreamUrl']

    parent_url = '{host}/{short_url}{build}/api/json'.format(host=host,
            short_url=short_url, build=build_number)

    #
    # Now get the payload from the parent job by making REST api call
    #

    response = requests.get(parent_url, auth=request_auth)
    upstream_build = json.loads(response)

    actions = upstream_build['actions']
    for action in actions:
        if action.get('parameters'):
            for parameter in action.get('parameters'):
                if parameter['name'] == parameter_name:
                    value = parameter['value']
                    payload = value
                    return payload

    print 'Error: Unable to return payload from parent jenkins job: {0}'.format(parent_url)
    sys.exit(1)

Answer: I can get this to work for my purpose by first echoing the parameter value to a file, e.g.:
echo "${BIG_TEXT_PARAM}" > ${WORKSPACE}/BIG_TEXT_PARAM.txt

cat ${WORKSPACE}/BIG_TEXT_PARAM.txt

Note the use of double-quotes in the 'echo' command.
Comment: I got it working for >75KB, but when I get close to your value indeed it seems that linux itself has a limit that you can't really overcome anyway (http://www.cyberciti.biz/faq/linux-unix-arg_max-maximum-length-of-arguments/). I'd look next for maybe a different shell (than the standard one) that supports higher (or no) limits.
Comment: How big is your data? Mine is 132KB.


some examples of filtering the noise out of a data set

Question: I have a data set which measures 60 data points in a second (60Hz). Clearly, I do not really need all 60 points in one second since this only generates some noise.
ABOUT MY DATA:
So my data sets are primarily location/position data (x,y) coordinates that are obtained from a motion tracker. The motion tracker measurements are expected to have some noise in them (but nothing out of the ordinary). If I zoomed out of the graphs (to see the bigger picture, I am satisfied with the graphs). Zooming into time $t$ and $t+\delta$ would mean you are staring at the zigzag lines that may be attributed to errors. In the end, I would like to compute velocities, speeds, etc, without having to worry about the errors.
What are some examples of filtering techniques that would be applicable to this? I am pretty sure this would depend on the circumstances.
Thanks for your insights.
Comment: Please explain what information you're trying to get from this stream of data: that is the primary consideration in selecting a procedure to filter it.
Comment: I added a section on 'about my data'
Comment: There is a multitude of solutions, varying greatly in computational accuracy and complexity. If the errors are truly random and independent, then a good old least squares approach might serve you best. But it also depends on the "etc." what you want to calculate. Are you interested only in the "best" result (e.g. smallest variance) of all final variables or of a particular one? The hint at Kalman filtering is particularly useful; it is a very usable version of a least squares fit.And there are tons of library implementations, so you don't even have to implement it yourself.
Answer: From the short description you provided I would suggest that you look into Kalman filters.
I won't bother to give you the details here since there is plenty of literature available online, e.g. the usual first go to place is Wikipedia. There are also some good books, e.g. if you work with MATLAB, I can recommend the book "Kalman Filtering, Theory and Practice Using MATLAB" by M.S. Grewal and A.P. Andrews.
It might be that a Kalman filter is a bit of an overkill for your problem, simpler alternatives would be the good old low-pass filter or a moving average (or maybe a zero lag moving average if you don't process the data in real-time).
Answer: If you use just single points for estimation, you get large variance due to measurement errors.
If you use MA (moving average) in the form $\hat X_t = \Sigma^t_{t-\tau}{\gamma_iX_i}$, you get bias due to velocity of the object, unless you suppuse that you have Brownian Motion.
If you don't mind a lag, you can use some kind of MA like $\hat X_t=\frac{1}{3}X_{t-1} + \frac{1}{3}X_{t} + \frac{1}{3}X_{t+1}$; you can include more terms or use different coefficients (corresponding to different kernel).
If you need $\hat X_t$ at the moment  $t$, you have to estimate velocity from previous observations with something simple like OLS, and correct the $\hat X_t = \Sigma^t_{t-\tau}{\gamma_iX_i}$ formula for this velocity to get something like $\hat X_t = \Sigma^t_{t-\tau}{\gamma_i[X_i+ (t-i)\hat V_t]}$. The velocity estimate we used for the correction is just ad hoc. When you compute velocities for your original purposes, use $\hat X_t$.


Brand new bass, annoying fret buzz

Question: I know this question has come up multiple times here on this website, but I think that it's kind of strange to have fret buzz with a brand new bass. This happens most on the two middle strings, and I can only avoid the buzz by pressing the strings really hard, which makes it really hard to play fast. Maybe it's my technique that is wrong, because I don't think that a brand new bass wasn't calibrated.
Any opinions on this? is my technique or is the bass that is not calibrated?
Ps: this is the one http://www.thomann.de/pt/harley_benton_mb222t.htm
Comment: Can you take it back and exchange it for one that doesn't have buzz?
Answer: It could very well be set up quickly and to the manufacturer's specs which don't work for your type of playing, or was done in a rush to begin with.  This happens often, and adjustment (assuming you have a set of hex keys) is pretty easy.
The clue I'm going with is:

...This happens most on the two middle strings...

This really isn't that big of a deal.  If you're not encountering this on the outer strings then your neck is set well, and relief is good.  However, your inner two strings probably sit considerably (enough) closer to the fretboard causing the buzz.  The easy fix for this is an adjustment at the bridge to raise (you don't need much) the height of the string to match more of the fretboard radius.  Check out this video for adjustment.

If above doesn't solve the problem then I'm afraid you may just not be pressing hard enough (I can't judge your experience with bass right now).  I only get the feeling of this by the following statement:

...and I can only avoid the buzz by pressing the strings really hard...

To get a clear, loud note out of a fretted one, you may need to press a bit harder than you think (especially if you're starting out, and not used to the amount of pressure required by a bass).
If this is the case, you may want to look more into proper positioning of your thumb on the back of the neck to provide the right anchor point and applied pressure you're looking for.
EDIT: Considering it's a Harley Benton, the setup process was probably just not done properly, and a quick neck/bridge setup may all be all that's necessary.  Make sure this bass also has a straight neck (Excuse Guitar World's ads).
Comment: I don't know, if I had a brand new bass with fret buzz when I'm not playing that hard, I'd take it back either way. If the neck or frets are fine, then the store should have done a decent setup and I want a free setup. The last time I bought a guitar new from a store (as opposed to used or online), they pretty much insisted that they do a setup on it before handing it to me, probably to make sure I didn't want to take it back right after getting it home.
Comment: Oh the days of customer service!  Half the guitars at Guitar Center are unplayable!
Comment: If the problem goes away when pressing down the strings sufficiently hard, then it may in fact help to _lower_ the action, so it's easier to do that. It is indeed more typical that buzz is caused by _too low_ action, but in that case the buzz doesn't care how hard you press down on the strings, so if pressure helps then the issue is probably not that the action is too low.
Comment: I think the top half is the answer. If the neck cross section has a radius (is curved), but the bridge saddles are dead flat, then yeah, the middle two strings are closer to the fretboard. Raise them to mimic the radius, it won't take much.

Brand new bass, annoying fret buzz


Como obter o nome do objeto pai da propriedade Javascript

Question: Eu tenho o seguinte código:
 var teste = 'objeto': {
           version: '5.x.x',
           name:this[??]  // 'objeto'
        };

O que poderia ser feito para que a propriedade name tenha o mesmo nome do objeto a quem ele pertence (que no caso é objeto)?
Comment: A sintaxe que tens está errada, não podes dar nomes a objetos dessa maneira. Podes explicar melhor o que queres fazer?
Comment: Tem certeza que não é `{'objeto':{...}}`  ao invés de `'objeto':{...}`?
Comment: É isso mesmo, não me importei muito com a sintaxe porque o foco é o conceito, mas realmente propriedades em formato de string são apenas aceitas quando dentro de um objeto
Answer: Não existe nenhuma sintaxe especial para fazer o que você está querendo. Objetos em javascript não tem nenhum ponteiro pro "pai" (afinal, se houvesse daria pra notar uma diferença se um objeto está armazenado numa tabela, lista ou variável - seria uma grande dor de cabeça...)
Se o que você quer é evitar de escrever a string "objeto" duas vezes, algo que você pode fazer é por esse nome numa variável e atribuir campos dinâmicamente:
var myName = 'objeto';
var teste = {};
teste[myName] = {version: '5.x.x', name:myName}


Install lib files in red-hat from file

Question: One question about installing libs.
I have a RH 6.4, and I need some libs to be updated in the SO. I've been provided with the actual version, those are in file format  libicudata.so.36.0 libicui18n.so.36.0  libicuuc.so.36.0
Is there a way to install them by command and update dependencies? I've made a locate of those librarys, and previous versions exists on multipla places of the machine, not as simbolic links. That's why I want to be sure instead of just replacing.
Thanks
Answer: After trying, I've got a solution.
These external libraries needs to be copied on /usr/lib
Once they have been copied, you have to reload the libraries to make the new ones available
<code>ldconfig -n -v /usr/lib
</code>

Install lib files in red-hat from file


Resolve DNS Misconfiguration abuse complaint

Question: Today i received a abuse complaint about my dns server.
Translation courtesy of Froggiz

Hi,
The CERT-FR has been informed by one of his partner that one or more domain name server (DNS) below aren't validating the IP source of the transfert protocol of "zone AXFR"
ID,Domain,Name server,IP address,Country 329872,mydomain.com,ns1.mydomain.com.,220.127.116.11,FR 329872,mydomain.com,ns2.mydomain.com.,220.127.116.11,FR
Consequently, anyone is able to get the whole DNS records and hosted domain on this DNS.
You can find more informations and help in the following link: http://www.cert.ssi.gouv.fr/site/CERTA-2012-ACT-048/CERTA-2012-ACT-048.html
It is your responsibility to check the veracity of this information and take appropriate corrective measures
The CERT-FR stands at your disposal for more informations or advices

here is the complaint , its french!
Bonjour,
Le CERT-FR a été informé par l'un de ses partenaires que le ou les
serveurs de noms (DNS) ci-dessous n'effectuent pas de validation de
l'adresse IP source lors de l'utilisation du protocole de transfert de
zone AXFR :
ID,Domain,Name server,IP address,Country
329872,mydomain.com,ns1.mydomain.com.,126.96.36.199,FR
329872,mydomain.com,ns2.mydomain.com.,220.127.116.11,FR
Par conséquent, n'importe qui est en capacité de récupérer l'intégralité
des informations DNS du ou des domaines hébergés sur ce ou ces serveurs
de noms.
Vous pourrez trouver des informations complémentaires à l'aide du lien
suivant :
http://www.cert.ssi.gouv.fr/site/CERTA-2012-ACT-048/CERTA-2012-ACT-048.html
Il vous revient de vérifier la véracité de cette information et de
prendre les mesures de correction adaptées.
Le CERT-FR se tient à votre disposition pour toute information ou
conseil complémentaires.
Cordialement,

On my server for DNS i am using Bind9:
here its the my bind configuration:
//
// named.conf
//
// Provided by Red Hat bind package to configure the ISC BIND named(8) DNS
// server as a caching only nameserver (as a localhost DNS resolver only).
//
// See /usr/share/doc/bind*/sample/ for example named configuration files.
//

options {
    listen-on port 53 { 127.0.0.1; 18.104.22.168;}; ### Master DNS IP ###
#    listen-on-v6 port 53 { ::1; };
    directory     "/var/named";
    dump-file     "/var/named/data/cache_dump.db";
    statistics-file "/var/named/data/named_stats.txt";
    memstatistics-file "/var/named/data/named_mem_stats.txt";
    allow-query     { any;}; ### IP Range ###
   // allow-recursion {"none";};
    //allow-transfer{ localhost; 184.108.40.206; };   ### Slave DNS IP ###

    /*
     - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
     - If you are building a RECURSIVE (caching) DNS server, you need to enable
       recursion.
     - If your recursive DNS server has a public IP address, you MUST enable access
       control to limit queries to your legitimate users. Failing to do so will
       cause your server to become part of large scale DNS amplification
       attacks. Implementing BCP38 within your network would greatly
       reduce such attack surface
    */
    recursion no;

    dnssec-enable yes;
    dnssec-validation yes;
    dnssec-lookaside auto;

    /* Path to ISC DLV key */
    bindkeys-file "/etc/named.iscdlv.key";

    managed-keys-directory "/var/named/dynamic";

    pid-file "/run/named/named.pid";
    session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
    type hint;
    file "named.ca";
};

zone "mydomain.com" IN {
type master;
file "mydomain.com.zone";
allow-update { none; };
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

And my zone file :
$TTL 86400;
@ IN SOA ns1.mydomain.com. admin.mydomain.com. (
            2010062801 ; Serial
            10800 ; Refresh
            3600 ; Retry
            604800 ; Expire
            86400 ; Minimum
)

mydomain.com. IN NS ns1.mydomain.com.
mydomain.com. IN  NS  ns2.mydomain.com.
mydomain.com.       IN A 184.108.40.206
ns1.mydomain.com.   IN A 220.127.116.11
ns2.mydomain.com.   IN A 18.104.22.168
www.mydomain.com.   IN A 126.96.36.199
ftp.mydomain.com.   IN A 126.96.36.199
mail.mydomain.com.  IN A 220.127.116.11
*.mydomain.com.  IN A 188.8.131.52
mydomain.com.       IN MX 10 mail.mydomain.com.

I want know what i do wrong , and what should i do to resolve this issue
Thank in advance
Answer: You've removed the allow-transfer directive from your configuration, thus anyone in the world can download your entire zone file.
Whether this is a problem depends on whether you have a need to keep this information private.
Comment: thanks , now if i just uncomment `allow-transfer` its ok ? do you have any other security advice in my confg file ?
Comment: `allow-transfer  { none; };`
Comment: @JacobEvans what different `allow-transfer{ localhost; myServerIp; };` and `allow-transfer { none; };`
Comment: The only servers in your list should be slaves or none


Passando Parametros do HTML para o Javascript

Question: Boa tarde Galera!
Preciso passar parâmetros de um pequeno formulário HTML para uma função do Javascript mas já tentei de todas as formas e não funciona!
Onde estou errando?

function pessoa(nome) {
  this.nome = nome;

}

var pessoa1 = new pessoa(document.getElementById('nome'));

function mostrar() {
  document.getElementById('texto').innerHTML = pessoa1.nome;
}
<form>
  Qual é o seu nome? <input type="text" id="nome">

  <button id="btn-enviar" onclick="mostrar()">ENVIAR</button>
</form>

Comment: Talvez o evento `onsubmit` do form te ajude com essa tarefa. [w3schools](https://www.w3schools.com/jsref/event_onsubmit.asp)
Answer: Seu código tem muito erro estrutural.
Primeiro, nessa linha:
var pessoa1 = new pessoa(document.getElementById('nome'));

Você está atribuindo o elemento retornado por getElementById à propriedade  nome, da classe pessoa, e não o valor do elemento.
O correto seria document.getElementById('nome').value.
Mas aí tem outro problema: Se você quer atualizar o valor sempre que for clicado em mostrar, então você deveria fazer a criação da instância de pessoa quando mostrar fosse chamado.
Se definir isso fora da função, como você fez, o valor capturado seria apenas o que tivesse definido inicialmente.
Então, eu modifiquei seu código, deixei ele assim:

<form>
    Qual é o seu nome? <input type="text" id="nome">

    <button id="btn-enviar" onclick="mostrar(event)">ENVIAR</button>
</form>

Note que além de tudo, tive que usar o event.preventDefault(), pois o form faria que um submit fosse enviado. preventDefault() previne a ação padrão do elemento.
Dicas:

Se vai usar apenas eventos Javascript, não tem necessidade de usar a tag form. Um formulário com um botão dentro, sem especificar o type, vai fazer o navegador entender que você quer submeter o formulário. Se você clicar nele, a página provavelmente seria atualizada. Por isso usei o preventDefault dentro do form, mas sem o form nem seria necessário.

Evite usar onclick para chamar funções. Isso costuma deixar o código mais difícil de dar manutenção. Eu recomendaria a utilização de addEventListener.

Exemplo:
  function mostrar(e) {
     e.preventDefault();
     // resto do código
  }

  document.getElementById('nome').addEventListener('click', mostrar);

Veja uns exemplos aqui.

Se pessoa é um objeto simples, porque não usar um Object do próprio Javascript?

Talvez, no seu caso, fosse necessário apenas fazer isso:
var pessoa = {nome: null}

No final, eu deixaria assim:

var elTexto = document.querySelector('#texto');
var elNome = document.querySelector('#nome');

var pessoa = {nome: null};

document.querySelector('#botao').addEventListener('click', function (e) {
   e.preventDefault();
   pessoa.nome = elNome.value;
   elTexto.innerHTML = elNome.value;

   console.log(pessoa);
})
Qual é seu nome?
<input type="text" id="nome" />

<button id="botao">Enviar</button>

Comment: Dê o feedback sobre o porque do negativo. É importante pra sabermos o que pode ser melhorado na resposta.
Comment: cara! Sensacional!

Não espera essa AULA!

Mas criei dessa forma pq estou estudando orientação ao objeto =D
Comment: Com a sua ajuda consegui entender o codigo e atualizei dessa forma:

Answer: Usando seu código eu adicionei um name ao input e no onsubmit eu coloquei uma chamada para a função mostrar utilizando o call passando o this como parâmetro dessa forma o this da função mostrar será o proprio ObjectHTML form e assim eu consigo acessar o this.nome graças ao name colocado no input. O return false no onsubmit server para ele não enviar o formulario.

function mostrar(){
    alert(this.nome.value);
    document.getElementById('texto').innerHTML = this.nome.value;
}
<form onsubmit="mostrar.call(this); return false;">
  Qual é o seu nome? <input type="text" id="nome" name="nome">

  <button id="btn-enviar">ENVIAR</button>
</form>

Answer: Bom no java script é o seguinte, você faz essa função que vai pegar o conteudo do html, com innerHtml você vai escrever no html.

<from method="post">
<input type="text" name="texto" id="texto"/>

<input type="submit" onclick="getName()" value="Pegar Nome"/>
</form>

Depedendo da função pode por no body como onLoad.
Comment: Upvoted! Não entendi porque negativaram esta resposta, se está correta. Stack Overflow Português é desmotivador...