Handling Database related projects among teams members

Question: We are a team of 10 members. We are developing a project with php and mysql. To keep the code in Sync we use SVN. but major of our configurations and content are stored in DB. So how can we keep the DB also in sync with all users. Which is the best method in handling such projects in teams ?
Answer: I assume you look for a solution for syncronising database-related changes between developers and software versions (i.e. field changes, table changes), not changed data itself.
A good solution for this is Liquibase:

Liquibase is an open source (Apache 2.0 Licensed),
  database-independent library for tracking, managing and applying
  database changes. It is built on a simple premise: All database
  changes are stored in a human readable yet trackable form and checked
  into source control.
Comment: does it sync the Data changes also?
Comment: No it doesn't. If you want to synchronize data between different database servers, other tools are better suited for this. So what is it, database changes or data changes?
Comment: - its data changes inside the table.
Comment: Then you should use a tool to synchronize the data. If you want the data really fast, maybe use MySQL Replication. If the data is more static, use batch driven Synchronization (p.e. mysql_dump). If you want different kind of data, maybe use configuration files to populate your tables like your projects needs it.


What are the differences between normal and hard mode?

Question: It's somewhat obvious that enemies take more of a beating in Guacamelee!'s hard mode, and I seem to recall some bosses' attacks being changed to undodgeable. What other differences are there, if any?
Answer: Bosses had new tricks.
X'Tabay has 2 smaller platforms instead of one large one in her dimension swap. Her final phase also has three images instead of two.
Flame Face summons much harder minions to deal with while you fight him.
Javier seems to be noticeably faster in hard mode.
Calaca don't seem any different, other than dealing more damage.
AFAIK nothing else.


AbstractControl.value[data] is retuning undefined in Custom Validator using AbstractControl?

Question: I'm trying to write cross-field -validation using Abstract Control.
control.value[start] is showing undefined. kindly help me on solving.
working code is here.
app.component.html

export class AppComponent {
  form: FormGroup;
  rangeStart = new FormControl('', {
    validators: [this.MyAwesomeRangeValidator('rangeStart')],
  });
  rangeEnd = new FormControl('', {
    validators: this.MyAwesomeRangeValidator('rangeEnd'),
  });
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      rangeStart: this.rangeStart,
      rangeEnd: this.rangeEnd,
    });
  }

  MyAwesomeRangeValidator(rangeStart: string): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const start = control.value[rangeStart];
      const end = control.value;
      console.log('start', start, 'end', end);
      let re = /^[1-9]\d*$/;
      if (re.test(start) && re.test(end)) {
        return null;
      } else if (re.test(start) && !re.test(end)) {
        return null;
      } else if (!re.test(start) && re.test(end)) {
        return null;
      } else {
        return {
          range: true
        };
      }
    };
  }
}
<form [formGroup]="form">
  <input formControlName="rangeStart" placeholder="Range start" type="number">
  <input formControlName="rangeEnd" placeholder="Range end" type="number">
</form>

 Valid: {{ form.valid ? '' : '' }}

working code
Answer: You are trying to get property 'rangeStart' from string.
const start = control.value[rangeStart];, where control.value is a string. If you want to validate few fields at once then you should put validator to the FormGroup.
export class AppComponent {
  form: FormGroup;
  rangeStart = new FormControl('', {
    validators: [this.MyAwesomeRangeValidator('rangeStart', 'rangeEnd')],
  });

  rangeEnd = new FormControl('', {
    validators: this.MyAwesomeRangeValidator('someField_1', 'someField_2'),
  });

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      rangeStart: this.rangeStart,
      rangeEnd: this.rangeEnd,
    });
  }

  MyAwesomeRangeValidator(
    startControlName: string,
    endControlName: string
  ): ValidatorFn {
    return (formGroup: FormGroup): ValidationErrors | null => {
      const start = formGroup.get(startControlName).value;
      const end = formGroup.get(endControlName).value;

      console.log(formGroup, 'start', start, 'end', end);

      let re = /^[1-9]\d*$/;

      if (!re.test(start) && !re.test(end)) {
        return { range: true };
      }

      return null;
    };
  }
}

UPD: added dynamic form controls names
Comment: ,thanks for your answer.is there a way that I can use if for another formcontrols as well.(custom validator applicable to multiple formcontrols)
Comment: you can pass form controls names as arguments into validator. For your logic you can do this: https://stackblitz.com/edit/ng-cross-validation-qsiqn2?file=app/app.component.ts
Comment: ihttps://stackblitz.com/edit/ng-cross-validation-qsiqn2?file=app%2Fapp.component.ts. this code is not matching the condition  if (!re.test(start) && !re.test(end)) {
        return {range: true};
      }
.
Comment: `MyAwesomeRangeValidator(): ValidatorFn {
    return (formGroup: FormGroup): ValidationErrors | null => {
      const start = formGroup.get('rangeStart').value;
      const end = formGroup.get('rangeEnd').value;
      console.log(formGroup, 'start', start, 'end', end);
      let re = /^[1-9]\d*$/;

      if (!re.test(start) && !re.test(end)) {
        return {range: true};
      }

      return null;
    };
  }
}` this is matching the condition, but it is taking formControls, can we make it dynamic,to use to for other formcontrols as well, where it should satisfy the condition
Comment: sorry, i'm not really sure about your goal, but try this: https://stackblitz.com/edit/ng-cross-validation-qsiqn2?file=app/app.component.ts =)


org-agenda-bulk-action B + tag selection does not offer completion

Question: org-agenda-bulk-action B + tag selection does not offer completion. I use Ido completion. The tag completion for individual agenda items works in org-agenda mode.
Disabling Ido does not help.
Any idea if bulk tag selection completion is implemented at all?
Answer: It seems to be partially implemented.  If you set org-tag-alist,
you'll be offered these tags when running the bulk action (after reloading the original Org buffers).  Unlike org-set-tags, org-agenda-bulk-action does not generate the tags based on the tags in the Org buffer if org-tag-alist is nil.  (At first glance, I don't see any reason why it couldn't be extended to do this.)
Comment: Thank you @Kyle Meyer. Can I ask you to have a look at my related question here: [link](http://stackoverflow.com/questions/28535230/org-use-fast-tag-selection-quote-auto-breaks-tab-completion-non-ascii-tag). It explains the reasons I'm not using `org-tag-alist`.


Is there a power-management like OpenSuse?

Question: In OpenSuse there is a applet for choosing different energy-profiles for your notebook. Are there any tools/applets that will enable those features for ubuntu?
Answer: Battery Applet/Indicator
This is designed as a replacement for the original battery indicator which will give you more information and options including 4 power levels

Power Save
Ondemand
Normal
Performance

It shows the charge level of your battery and whether you are using the battery or mains. It can be used as an indicator or a gnome applet so can be used on Ubuntu 11.04, 10.10 and older
To install you will need to add there ppa
 - ppa:iaz/battery-status
A guide for adding additional ppa sources is available here -
what is a ppa and how do I use them - after you have aded it an updated your system you can install battery-status from the Software Centre by searching for it.
Hope this helps
Comment: This sounds exactly for what I'm searching for. I remember, that the CPU-Load-indicator has nearly the same functionality. But I will give a try. Thanks a lot.
Answer: Ubuntu's power management utility has 2 different profiles (AC and battery) you can change these things from System -> Preferences -> Power Management . But as for a quick switcher nothing that I know of exists in official repositories.
Answer: The below link provides details of installing Battery applet which also come with power profiles. check out
http://www.omgubuntu.co.uk/2011/02/battery-applet-status-ubuntu/


GE Dryer, Model GTDX100EM1WW Burnt Wiring

Question: White wire connecting to the door switch has burned through and detached from the connector head. There are also burn marks on the dryer drum.
I know at least temporarily fixing this is merely stripping the wire, crimping it to a new connector, and plugging it in... But why did this happen and how can I prevent it?
Answer: It looks as if the red connector in the first photo may not be the original, but a past DIY repair. I may be wrong, too.
Either way the wire should have a retaining clip close to the connection. The plastic grate in photo 1 most likely has a clip close to the terminal. If not zip tie the wires to a stable part of the dryer.
This most likely occurred due to vibration and the wire not being secured. If necessary solder the spade terminal to the wire for the most secure connection.


How to overwrite styles which having :root

Question: I want to overwrite styles which defined with :root pseudo-class.
I have css like below:

<!DOCTYPE html>

    <title></title>

hello world

I want to display color green instead of red. How can i overwrite the styles
Comment: Same as with any other, there is nothing special about the `:root` pseudo class in this regard. But your second selector doesn't match anything, because the `html` element doesn't have any `div` _children_.
Answer: html > div > p does not select your element because there is a body element between the html and the div.
html > body > div > p does select your element, but the specificity is lower than :root p, which has a pseudo-class.
The trick is easy: two pseudo-classes are more specific than one. Use :root:root p

:root p {
  color: red;
}
:root:root p {
  color: green;
}

hello world

Answer: use div > p instead of html > div > p
        div > p {
          color: green!important;
        }

JSFIDDLE
Answer: Try to this:

:root p{
          color: red !important;
        }

:root div > p{
      color: green !important;
}

hello world


How to convert memoryview to bytes?

Question: How do I convert a Python memoryview to bytes?
For example:
>>> convert(memoryview(b"test"))
b"test"

Answer: Python's memoryview has a tobytes() method that allows you to do just that. You're also able to call bytes() on the object.
Keep in mind that converting a memoryview object to bytes copies the data, and you're able to use memoryview in most places either way. I wouldn't suggest you to convert.
Comment: thanks! cryptography doesn't accept memoryview objects
Comment: Well then, send a patch to cryptography ;-)
Comment: Saying "you're able to use memoryview in most places either way" is not realy true - you can't do any operation on memoryview (like strip, find, ..) and in most cases I have to convert even if I don't want to.
Comment: @Jan you can use them in most places. Why are you stripping a bytes object?
Comment: @Jan Bytes are not meant to hold text lines, you're not really supposed to process whitespaces on the bytes object as you ignore the character encoding. The case of ASCII bytes, while prevalent, is quite unique and should be treated as so. Remember - processing strings is the job of str. Copying should be and can be avoided in most cases.
Comment: @Jan my friend, GStreamer is off topic. You realize your example is very specific to a library that broke backwards compatibility. Not everything is utf-8. Windows uses mainly utf-16, and  attempting to `.strip()` a utf-16 byte sequence can blow up your program. If you wish to do any sort of text processing on a byte sequence, you should count on the specific case of utf-8, and moreover I wouldn't use bytes anyway, but a bytearray. If you convert it to bytes in your case you're slowing down your code considerably, and taking twice the memory.
Comment: @jan And yes, there is such a thing as meant to hold. You wouldn't use strings to hold integers and you wouldn't use a byte sequence to hold a dictionary. Dictionaries, integers and text can be represented as bytes, but I prefer the dict type as it's meant for it, don't wish to reinvent addition operations on bytes, and don't wish to change all my code once a new encoding is introduced. Saying that GStreamer on Debian 11 doesn't work well, and everything is bytes are two sentences that completely miss the point, and are off topic.
Comment: @Bharel - I'm really sorry for the whole debate, It's hugely offtopic and I was just reacting because I felt like you were attacking me because I used bytes (which is/was beyound my control) so I felt I have to explain myself, but that serves no point. I propose I'll delete my comments and you can delete your reactions to me.
Comment: @Bharel - I'm deleting my off-topic comments, if you want to discuss it with me - i made a chat room: https://chat.stackexchange.com/rooms/info/134045/removing-clarification-of-off-topic-comments-on-memoryview-bytes?tab=general

How to convert memoryview to bytes?


C variable assignment issue

Question: I think the title does not suit well for my question. (I appreciate it, if someone suggests an Edit)
I am learning C with "Learn C The Hard Way.". I am using printf to output values using format specifiers. This is my code snippet:
#include <stdio.h>

int main()
{
    int x = 10;
    float y = 4.5;
    char c = 'c';

    printf("x=%d\n", x);
    printf("y=%f\n", y);
    printf("c=%c\n", c);
    return 0;
}

This works as I expect it to. I wanted to test it's behavior when it comes to conversion. So everything was ok unless I made it to break by converting char to float by this line:
printf("c=%f\n", c);

Ok, I'm compiling it and this is the output:
~$ cc ex2.c -o ex2
ex2.c: In function 'main':
ex2.c:13:3: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
printf("c=%f\n", c);
^

The error clearly tells me that It cannot convert from int to float, But this does not prevent the compiler from making an object file, and the confusing part is here, where I run the object file:
~$ ./ex2
x=10
y=4.500000
c=c
c=4.500000

As you can see printf prints the last float value it printed before. I tested it with other values for y and in each case it prints the value of y for c. Why this happen?
Comment: @πάνταῥεῖ: We tag questions, not answers.
Comment: @user3061142: Why not do some basic research?
Comment: Please do not tag spam C questions with the C++ tag
Comment: @πάνταῥεῖ there are no C++ headers included in the question, it's still tag spam as the question is pure C
Comment: @Mgetz The correct answer (undefined behavior) applies to [std::printf()](http://en.cppreference.com/w/cpp/io/c/fprintf) as well. I have rolled back your edit.
Comment: @chris can you tell what does undefined behavior mean please?
Comment: OK, I see! Yes it's not really c++ :P ...
Comment: since the `int` argument doesn't corrupt the memory contents of where the `double` argument was before, there are 2 logical possibilities: (a) a fantastic coincidence of same bitpatterns, or (b) not overlapping location.
Answer: Your compiler is warning you about the undefined behaviour you have. Anything can happen. Anything from seeming to work to nasal demons. A good reference on the subject is What Every C Programmer Should Know About Undefined Behavior.
Normally, int can convert to double just fine:
int i = 10;
double d = i; //works fine

printf is a special kind of function. Since it can take any number of arguments, the types have to match exactly. When given a char, it is promoted to int when passed in. printf, however, uses the %f you gave it to get a double. That's not going to work.
Here is how one would implement their own variadic function, taken from here:
int add_nums(int count, ...)
{
    int result = 0;
    va_list args;
    va_start(args, count);
    for (int i = 0; i < count; ++i) {
        result += va_arg(args, int);
    }
    va_end(args);
    return result;
}

count is the number of arguments that follow. There is no way for the function to know this without being told. printf can deduce it from the format specifiers in the string.
The other relevant part is the loop. It will execute count times. Each time, it uses va_arg to get the next argument. Notice how it gives va_arg the type. This type is assumed. The function needs to rely on the caller to pass in something that gets promoted to int in order for the va_arg call to work properly.
In the case of printf, it has a defined list of format specifiers that each tell it which type to use. %d is int. %f is double. %c is also int because char is promoted to int, but printf then needs to represent that integer as a character when forming output.
Thus, any function that takes variadic arguments needs some caller cooperation. Another thing that could go wrong is giving printf too many format specifiers. It will blindly go and get the next argument, but there are no more arguments. Uh-oh.
If all of this isn't enough, the standard explicitly says for fprintf (which it defines printf in terms of) in C11 (N1570) §18.104.22.168/9:

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

All in all, thank your compiler for warning you when you are not cooperating with printf. It can save you from some pretty bad results.
Comment: Thank you for your full complete answer
Answer: Since printf is a varargs function, parameters cannot be converted automatically to the type expected by the function. When varargs functions are called, parameters undergo certain standard conversions, but these will not convert between different fundamental types, such as between integer and float. It's the programmer's responsibility to ensure that the type of each argument to printf is appropriate for the corresponding format specifier. Some compilers will warn about mismatches because they do extra checking for printf, but the language doesn't allow them to convert the type -- printf is just a library function, calls to it must follow the same rules as any other function.
Answer: Here is a very general description, which may be slightly different depending on the compiler in use...

When printf("...",a,b,c) is invoked:

The address of the string "..." is pushed into the stack.
The values of each of the variables a, b, c are pushed into the stack:
Integer values shorter than 4 bytes are expanded to 4 bytes when pushed into the stack.
Floating-point values shorter than 8 bytes are expanded to 8 bytes when pushed into the stack.
The Program Counter (or as some call it - Instruction Pointer) jumps to the address of function printf in memory, and execution continues from there.
For every % character in the string pointed by the first argument passed to function printf, the function loads the corresponding argument from the stack, and then - based on the type specified after the % character - computes the data to be printed.

When printf("%f",c) is invoked:

The address of the string "%f" is pushed into the stack.
The value of the variable c is expanded to 4 bytes and pushed into the stack.
The Program Counter (or as some call it - Instruction Pointer) jumps to the address of function printf in memory, and execution continues from there.
Function printf sees %f in the string pointed by the first argument, and loads 8 bytes of data from the stack. As you can probably understand, this yields "junk data" in the good scenario and a memory access violation in the bad scenario.

C variable assignment issue


Sharepoint in MVC

Question: I have been trying to get my MVC C# code to connect to my sharepoint server. I have tried everything and I keep getting this error no matter what I try.

The Web application at [http://myserver/] could not be found. Verify
  that you have typed the URL correctly. If the URL should be serving
  existing content, the system administrator may need to add a new
  request URL mapping to the intended application.

This is my code:
<code>string strUrl = "http://myserver/";
using (SPSite site = new SPSite(strUrl))
{
}
</code>
Comment: We're going to need more information than this.  Have you tried adding a new request URL mapping, as the error message states?
Comment: +1 for nickname, wait for some binary code..
Comment: @Robert Yes I have tried URL mapping. I'm am hoping I did it correctly, I am new to this. Also if I type (http://myserver/) into the browser the page will load.
Answer: Note that SPSite/SPWeb only work on a Server that has SharePoint installed and is part of the Farm. It may work on non-Sharepoint machines, but this is officially unsupported and certain operations may throw exceptions.
Generally, external connectivity to SharePoint is done through Web Services or (since 2010) through the Client Object Model.
Answer: Make sure that you target your binary as 64-bit with .Net framework 3.5, otherwise it will throw this error. Also as other answers has stated; to use the object model like this require that the code is executed on a server in the farm.
Comment: I have tried to use .NET 3.5 and set the target as 64-bit, but when I do I get a bunch of errors and I cannot compile. Also, I am running my code on the server that way I can use the server object model. None of these fixes will fix my problem.
Comment: Ok, but until you manage to compile and run your code 64-bit, 3.5, your error will continue.
What kind of error are you getting when trying to compile?
Comment: Some of the dll's cannot compile to 64bit.
Answer: Use the Client Object Model to connect (assuming you are using SharePoint 2010).  If you want to use the server object model (which you are using in your code sample), the MVC app will need to be running on the same server that SharePoint is running on.

Sharepoint in MVC


Can't boot Ubuntu 12.04 from external Hard Drive using Mac

Question: Recently, I upgraded the RAM and hard drive on my Early 2008 Macbook to improve the performance. Rather than throw away the old hard drive, I bought an enclosure for it to turn it into an external hard drive, and, since all the data was migrated to my new drive, I decided to install Ubuntu on it for funsies (note: I am a near-total Ubuntu n00b).
My first attempt to install Ubuntu didn't work (it gave me errors about not being able to find the BIOS or something), but my second attempt finished successfully (can't remember what, if anything, I did different).
However, when I plug the external drive into my Macbook, it gives me a message saying it can't read the disk. Moreover, when I go into the Startup Manager (i.e.: what you get when you turn on the Macbook while holding the option key), the external drive is not one of the  available startup disks. I thought this might be because I have an older Macbook, so I tried booting it with my mom's Late 2011 Macbook, and got the same results. Then I tried booting it through my dad's Dell laptop that runs Windows 7, and that time it worked. This is really counter intuitive to me, since the hard drive originally came from a Macbook, so if anything you'd think it would be less compatible with the Windows laptop than the Macbook.
In case it helps, here's a link to a picture of how I set up the partition table while doing the install (not shown there is the fact that I checked the "Format?" box next to the /boot partition, since it gave me a warning when I tried to continue the installation without doing so)

Anyone have any clue at all? If it helps, the hard drive I'm using is a 120GB 5400-rpm Serial ATA hard disk drive.
Comment: Maybe because the drive is formatted to **ext4**. Mac cannot read drives in this format. Try formatting it in the **ext3** format and then reinstall Ubuntu.
Comment: Tried that, still having the same problem. Did a bit of Googling, and it seems Mac OSX Lion can't read any of the ext file system formats. However, you've still helped me by cluing me in to what the cause of the problem is. I've done some searching, and it seems that my best options are either rEFIt or some sort of FUSE-based solution to make my Mac read/write ext filesystems. Unless someone here knows a better way?
Answer: First of all your drive needs to be formatted with the GUID partition table (changed by clicking the options button when partitioning in Disk Utility),
Why because Intel Macs can only boot from GUID hard drives. Second you should be able to boot using rEFIt, but rEFIt must be installed on a External drive E.G. CD, USB etc, and not on the internal Hard Drive as rEFIt supports booting from ext formatted hard drives


RegEx for capturing specific alphanumeric pattern

Question: I have this string and I want to know how extract the "10-K_20190304_29_1_20190515" part.
"nCABALLERO MARIA\r\n10.1-K\r\n10-K_20190304_29_1_20190515\r\n6204 DEPORTES SANTIAGO - PEÑALOLÉN"

I've tried this, .+(?<=_).+, but it brings me more characters that I need.
How do I solve this problem?
Answer: Here, we like to start with a simple left and right boundary and collect our desire data and save it in a capturing group ($1). Let's start with:
[0-9]{2}-.+[0-9]{8}

and lets add our capturing group:
([0-9]{2}-.+[0-9]{8})

DEMO

const regex = /[0-9]{2}-.+[0-9]{8}/gm;
const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

RegEx
If this expression wasn't desired, it can be modified or changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:

If we wish to add more boundaries, we can certainly do so, depending on how our possible inputs might look like. For example, this expression has more boundaries:
([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})

DEMO

const regex = /([0-9]{2}-[A-Z]+_[0-9]{8}[0-9_]+.+?[0-9]{8})/gm;
const str = `nCABALLERO MARIA\\r\\n10.1-K\\r\\n10-K_20190304_29_1_20190515\\r\\n6204 DEPORTES SANTIAGO - PEÑALOLÉN`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Comment: Thank you very much for the answer, but in the full text there's more numbers and it doesn't recognise how I need it. Thats why I've match it with a _ because it only appears in the code. Please if you know how cut the entire code matching by _ it would be amazing.
Comment: Thanks for your help, I hope this helps someone else. I resolved by my own; When it brings to me: "15317029-0_20190102_29_1_20190515\r", I just: strCodigoPdf = strCodigoPdf.Substring(0,strCodigoPdf.Length()-0).Trim
Answer: You can also use split to extract the "10-K_20190304_29_1_20190515" part.
text.Split({"\r\n"},StringSplitOptions.None)(2)


Would I need to replace this whole tub if I were to tile the surround?

Question: I noticed that the tub and surround look like they go together. Does that mean I have to replace both of them if I wanted to do a tiled surround?
Comment: The tub and surround look like a typical one piece unit in which case the answer is yes. However, it's hard to tell from the pic if it is one piece. It appears there may be a seam just above the back of the tub in which case you may be able to pull out the surround and replace it with tile.
Answer: Probably not (have to replace the tub, that is), though you won't know for sure until you remove the surround. The surround probably just lays over top of the flange on the tub, though it may be attached to the tub.  One you have the surround removed, you can re-evaluate.  You may find that you have to build the wall out a bit to match the tub flange, and provide a water proof backer (cement board) in order to mount the tiles properly.
Here's typical installation.  Picture is from FamilyHandyman.com


evaluating button clicks java

Question: I have the following code:
for (int i = 0; i < dynamicVariable; i++) {
    String tmpString = myArray[i];
    JToggleButton tButton = new JToggleButton(tmpString);
    myJPanel.add(tButton);
    tButton.addActionListener(this);
}
JButton go = new JButton("go");
myJPanel.add(submit);

Where I create x amount of buttons and add them to my panel. What I now need to do is, when the user selects the correct buttons and hits go. I evaluate all the selected buttons. If they are all right, then print true, otherwise print false. If they select all the correct answers except one, then it should evaluate to false. I just have no idea how to evaluate each button selected inside the actionPerformed() method.
Answer: Put all the buttons into a List or array, then iterate over this when the go button is clicked
private List<JToggleButton> listOfButtons;
//...
listOfButtons = new ArrayList<>(dynamicVariable);
for (int i=0; i<dynamicVariable;i++){
    String tmpString= myArray[i];
    JToggleButton  tButton = new JToggleButton (tmpString);
    listOfButtons.add(tButton);
    myJPanel.add(tButton);
    tButton.addActionListener(this);
}
JButton go= new JButton("go");
myJPanel.add(submit);
//...

// ActionListener of go button
public void actionPerformed(ActionEvent evt) {
    for (JToggleButton btn : listOfButtons) {
        if (btn.isSelected()) {
            // Evaluate the state, set some flags
            // get funky tonight
        }
    }
    // Evaluate the final state once you know what
    // buttons are actually selected
}

Comment: adding to an array wouldn't work would it? I need to check which buttons are selected once i hit go, this just adds the buttons to an array
Comment: Sorry, see update. Once you have the buttons in a `List` or array, then you can use that `List` or array to simply iterate over at some time in the future (assuming you make that `List` or array an instance field, which is implied in the example)
Answer: You should first map the correct values for each button, then if the user clicks on the Go button, then iterate over the buttons, checking for each button if it is correctly toggled on or off.
In short:

First we define the correct answers as a map with each toggle button bound to a boolean indicating whether the statement is correct or not;
Then we add all toggle buttons to the panel;
Then we add a listener to the Go button, which determines whether the selected button is correctly pressed or left unpressed.

Here's the code:
// Put all values into a map. If the mentioned fruit has the mentioned
// color, then the answer is correct.
private Map<JToggleButton, Boolean> correctAnswers = new HashMap<JToggleButton, Boolean>() {{
    put(new JToggleButton("A strawberry is red"), true);
    put(new JToggleButton("A banana is blue"), false);
    put(new JToggleButton("A lemon is yellow"), true);
    put(new JToggleButton("An orange is orange"), true);
}};

void init() {
    for (JToggleButton button : map.keySet()) {
        // button.setActionListener(this); // The toggle buttons themselves
        // do not need to have a listener, do they? Only when the user clicks
        // "go", then the buttons should be evaluated, right?
        myJPanel.add(button);
    }
    JButton submitButton = new JButton("go");
    submitButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent event) {
            boolean wrong = false; // It's all good now, until a wrong
            // answer is found.

            // Iterate over all entries of our map.
            for (JToggleButton button : this.buttons.keySet()) {
                // Check if the selection state of the toggle button is
                // equal to whether the answer is yes or no.
                if (button.isSelected() != this.buttons.get(button)) {
                    // A button is pressed while it should not be pressed
                    // OR vice versa. Let's mark that at least one button
                    // is incorrect.
                    wrong = true;
                }
            }

            // We found at least one incorrect button.
            if (wrong) {
                // DO SOMETHING
            }
        }
    });
    myJPanel.add(submitButton);
}

I haven't tested this code, but it should work.
Comment: using ideas from both answers I have this code http://pastebin.com/Jy82WqkG I have two questions, is this code on the right track? if yes what I now need to do is that if ever a button clicked is false the boolean will always stay false

evaluating button clicks java


Creating table in mysql but the error keeps poping up , what am i doing wrong?

Question: ![CREATE TABLE ELEB(
ccode integer primary key,
cname varchar(20),
add varchar(25),
oldmr integer,
newmr integer,
unit integer,
tbill integer);][1]
Answer: CREATE TABLE ELEB
(
ccode int primary key,
cname varchar(20),
add varchar(25),
oldmr int,
newmr int,
unit int,
tbill int
)


Is it normal for acrylic caulk to dissolve?

Question: I didn't want to purchase a new shower door kit as we plan on remodeling the bathroom in the next five or so years, so I had to deal with the horrible old existing sliding doors and track.  The bottom track is not just an edge with a small guide for the hanging doors; it has two tracks that run it's entire length.  It is a pain to clean as the shower enclosure is not quite level, so water accumulates on the low side.  Below is an image similar to the style of bottom track:

I drilled an additional drain hole to allow more water out near the low side, but I still have to deal with the joint between the track and the vertical side piece.  I didn't want to mess with silicone sealant as the clean up is a pain so I used ACE Hardware brand tile and tub acrylic caulk, which has worked great around the sinks in my kitchens and bathrooms.
I let the caulk cure for three days as stated on the tube and I noticed that in that low corner where water is standing for many hours after taking a shower, it is dissolving.  Any thoughts on why this is happening?  Is this to be expected?  Will silicone stick to the acrylic caulk?  Can I dry it out and use silicone on top of the corner now to get me by for several years?  Would a marine epoxy be a better solution in that corner?
Answer: Acrylic caulks and paints, etc. are water-based. If you can clean them up easily with water than that's a pretty good sign that they are water-soluble.
Your caulk should be water-proof if fully cured. If you applied the caulking very thick or if the temperature is cool, it could take longer than the specified time to cure. Also, I don't think these are designed to be used in a situation of standing or pooling water.

"Will silicone stick to the acrylic caulk? Can I dry it out and use silicone on top of the corner now to get me by for several years? Would a marine epoxy be a better solution in that corner?"

You should have used 100% silicone. If you can find an epoxy that is flexible, then that might also be an option. That joint should not be solid/rigid.
Since you don't want to redo it, you should wait longer to see if it is just not fully cured. If still no good, you can try silicone over the acrylic caulk to help prevent it from dissolving. However, since that is just going to be a thin layer instead of a full bead it will be hard to guarantee a good seal.
Comment: The issue is the fact that I can't get to the corner in question.  It is at the corner of track and I can barely even get my finger in there.  The track is so poorly designed but I did not want to spend money on a new door kit that I might not use in a few years.  I went through so much work to prep the area and I can't imagine doing it again for this setup.  It simply isn't nice enough to devout that kind of time too yet again.  My guess is that 3 days simply wasn't enough time or it to cure.
Comment: At this point, I am not going to tear it all down and clean it up again to start over.  The bathroom, nor the shower, are the nice enough to warrant this.  I can't just take the bottom track off either, as the vertical sides prevent that.
Comment: Update:

I dried the area for two days, reapplied the same caulk, and let it cure for 4 days.  It not very thick, I figure maybe a quarter inch in the corners and only the size of a dime.  After a week of standing water, it is dissolving again.  I purchased a tube of 100% silicone to see if that will work.


django query is slow, but my sql query is fast

Question: I have a very simple vie in my django application
def notProjectsView(request):
context = {
    'projects':notProject.objects.all(),
    'title':'Not Projects | Dark White Studios'
}
return render(request, 'not-projects.html', context)

When I removed the context it ran fast, but it's a simple query and shouldn't be so long, the database also doesn't have a lot of records, it has 1 project and in the template I query project.notProjectImage.all which could cause an n+1 issue but I removed that part to test it and it was still slow
Django debug toobar shows a ~50ms sql query while the actual request in the time tab is over 15 seconds
Comment: try this https://stackoverflow.com/a/69113435/7865368
Answer: So, you have eliminated the DB query as  the reason it's slow. You need to look elsewhere. Is it slow when you test the view (using the Django test framework to GET html or POST data and check html response)? Then you've eliminated something happening in the browser, like a misbehaving script or framework. Which leaves the project's Python code, or something wrong with the machine it is running on. Is something  looping far more than it ought to? Or is your developer machine page-thrashing because it is  short of RAM?
(Oh, and where is the DB located? Developers usually host it on the machine they are developing with, but if it's cloud-based, look at the performance of the internet connection and possibly of the service itself).
Always work like Sherlock Holmes. "Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth."
BTW I recently traced occasional slowness on my developer machine to a bug in the (Cinnamon/Linux) GUI. That was of course the last place I though to look until I had eliminated absolutely everything else.


Windows Phone store app have link, but can't be found

Question: Few days ago i'm upload my app in th store. Everything worked fine,I got the message the app was accepted. Yesterday I got the working URL for Windows 10 && URL for Windows Phone 8.1 and earlier (before 404 page not found). But still can't found my app in the store.
The other strange part was, that I can't found my another app in the store (just disappeared). Another app was found on the first day after appearance in store.
ps: status - in the store
pss: sorry, bad english
Comment: Offtopic. Not a programming question. We are not general microsoft tech support.
Answer: Wait few more days .. the MS store was acting a bit funny in the past few days, the download stats were not up-to-date ...if it still does not appear, contact MS support


Skyrim will not launch?

Question: I fired up Steam to launch Skyrim.  Now when I press play from the splash screen it just disappears and then shows the splash screen again.
How can I see what is going wrong?  How can I fix it?
Comment: Have you verified the game integrity? (Steam right-click option)
Comment: @NickT - I was not getting elevation prompts and I tried running in admin mode too.
Comment: possible duplicate of [Skyrim launcher keeps prompting for elevation, but never launches](http://gaming.stackexchange.com/questions/39468/skyrim-launcher-keeps-prompting-for-elevation-but-never-launches)
Comment: @NickT Different problem, same resolution.
Comment: How is the problem different at all, the UAC settings may be different, but other than that it's the exact same symptoms.
Comment: Your computer could be configured differently for UAC.  How did you run a game in "admin mode"; if you used a Steam shortcut (e.g. on the desktop or in your start menu), it would just run the client with elevated privileges, not the game that it in turn launches.
Answer: Have you tried verifying the game's integrity? It sounds like something might have gotten corrupted, and rather than crashing, the launcher is recovering (though not giving you an error message to let you know something's wrong).
Comment: Note: After doing this, my Up and Down look sensitivity was shot.  (Took me pulling my mouse down a lot of times to move just a tiny bit.)  I adjusted  my fMouseHeadingYScale to 1.3200 and it seemed to work beter.  (Note I had modified this previously.)
Comment: @Vaccano There was [another question](http://gaming.stackexchange.com/questions/39577/is-there-a-way-to-prevent-steam-from-overwriting-my-configuration-changes-when-i) about Skyrim updates messing with your configs. I'd follow the answer there to prevent this from happening again.

Skyrim will not launch?


no tables are added to database when using code first approach in Entity Framework 6

Question: I have a need to add 2 tables to an exsisting database using Entity Framework 6. I have created the classes/tables in code, added DBSets in a new custom DBContext file, added a configuration and then I run the application. But the tables are not added to the database, what could be wrong here?
        public class TiDataDbContext : DbContext
    {
        public DbSet<TiData> TiDatas { get; set; }
        public DbSet<TiDataLanguage> TiDataLanguages { get; set; }

        public TiDataDbContext() : base("name=TestServerDB")
        {
        }

        public static void Initialize()
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<TiDataDbContext, TechDataMigrationsConfiguration>());
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //Manage auto update database
            var update = true;
            if (update)
                Database.SetInitializer(new MigrateDatabaseToLatestVersion<TiDataDbContext, TiDataMigrationsConfiguration>());
            else
                Database.SetInitializer<TiDataDbContext>(null);

            modelBuilder.Entity<TiDataLanguage>()
                .HasKey(tdl => new { tdl.Id, tdl.LanguageId, tdl.TiDataId });

            modelBuilder.Entity<TiDataLanguage>()
                .HasRequired(tdl => tdl.TiDatas)
                .WithMany(td => td.TiDataLanguages)
                .HasForeignKey(tdl => tdl.TiDataId);
        }
    }

config

    internal sealed class TiDataMigrationsConfiguration : DbMigrationsConfiguration<TiDataDbContext>
    {
        public TiDataMigrationsConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            MigrationsDirectory = "Migrations";
            AutomaticMigrationDataLossAllowed = true; // Needed to be able to update tables
        }

        protected override void Seed(TiDataDbContext context)
        {
            context.TiDatas.Create();
            context.TiDataLanguages.Create();
            context.SaveChanges();
        }
    }

    [Table("Demo.TiData")]
    public class TiData
    {
        public int TiDataId { get; set; }

        public string Name { get; set; }

        public string Unit { get; set; }

        public ICollection<TiDataLanguage> TiDataLanguages { get; set; }
    }

    [Table("Demo.TiDataLanguage")]
    public class TiDataLanguage
    {
        public int Id { get; set; }
        public int LanguageId { get; set; }
        public int TiDataId { get; set; }

        public string Name { get; set; }

        public string Unit { get; set; }

        public TiData TiData { get; set; }
    }

global.asax

TiDataDbContext.Initialize();

Answer: Try to add EnsureCreated method in constructor:
public TiDataDbContext() : base("name=TestServerDB")
{
    Database.EnsureCreated();
}


Is it possible to pass properties as parameters

Question: If this sounds too impossible, pls dont down vote :) Just my quirk that I wonder if ever I can pass a property as the parameter to a function to get some result.
For eg.
void delete_button_click ()
{
    foreach (DataGridViewRow row in dgvRecords.SelectedRows)
        dgvRecords.Rows.Remove(row);
}

And suppose
void delete_all_button click ()
{
    foreach (DataGridViewRow row in dgvRecords.Rows)
        dgvRecords.Rows.Remove(row);
}

Can I write the above two codes in one function since the only difference is SelectedRows and Rows. Something like this:
void button_click (/*DataGridView property rows*/)
{
    foreach (DataGridViewRow row in dgvRecords.rows)
        dgvRecords.Rows.Remove(row);
}

And call it
{
   button_click(DataGridView.Rows);
   //and
   button_click(DataGridView.SelectedRows);
}

Another eg.,
decimal GetAmount1(User usr)
{
    decimal sum = 0;
    foreach (DataGridViewRow row in dgvRecords.Rows)
    {
        Tuple<User, User, Notification, Acknowledgment> tup = (Tuple<User, User, Notification, Acknowledgment>)row.Tag;
        if (tup.Item1 == usr)
            sum += tup.Item4.Sum;

    }
    return sum;
}

and
decimal GetAmount2(User usr)
{
    decimal sum = 0;
    foreach (DataGridViewRow row in dgvRecords.Rows)
    {
        Tuple<User, User, Notification, Acknowledgment> tup = (Tuple<User, User, Notification, Acknowledgment>)row.Tag;
        if (tup.Item2 == usr)
            sum += tup.Item4.Sum;

    }
    return sum;
}

The only difference in above codes are just a property. So is this available:
decimal GetAmount(User usr, Tuple<User, User, Notification, Acknowledgment>.Property Item)
{
    decimal sum = 0;
    foreach (DataGridViewRow row in dgvRecords.Rows)
    {
        Tuple<User, User, Notification, Acknowledgment> tup = (Tuple<User, User, Notification, Acknowledgment>)row.Tag;
        if (tup.Item == usr)
            sum += tup.Item4.Sum;

    }
    return sum;
}

And call :
{
     GetAmount(usr, Tuple<User, User, Notification, Acknowledgment>.Item1)
     //and
     GetAmount(usr, Tuple<User, User, Notification, Acknowledgment>.Item2)
}

??
Comment: possible duplicate of [How can I pass a property of a class as a parameter of a method?](http://stackoverflow.com/questions/1178574/how-can-i-pass-a-property-of-a-class-as-a-parameter-of-a-method)
Answer: Your first example is can be solved by just using a normal parameter:
The signature of a method to remove rows would be:
void RemoveRows (IList rows)
{
    foreach (var row in rows)
        dgvRecords.Rows.Remove(row);
}

and call it with:
RemoveRows (DataGridView.Rows);
//or
RemoveRows (DataGridView.SelectedRows);

The second example requires the use of a Func<T, TResult> which allows you to define what property you want to select.
So your GetAmount() method siganture becomes:
decimal GetAmount(User usr, Func<Tuple<User, User, Notification, Acknowledgment>, User> selector)
{
    decimal sum = 0;
    foreach (DataGridViewRow row in dgvRecords.Rows)
    {
        Tuple<User, User, Notification, Acknowledgment> tup = (Tuple<User, User, Notification, Acknowledgment>)row.Tag;
        if (selector(tup) == usr)
            sum += tup.Item4.Sum;

    }
    return sum;
}

and you would call it:
GetAmount(usr, tuple => tuple.Item1);
//or
GetAmount(usr,  tuple => tuple.Item1);

Comment: Not at all. My suggestion is to think of the simplest thing first, frequently it's the right way to go :)
Comment: Terrific! Exactly what I wanted. I think I shouldn't ashamed of posting any crazy question, a solution might still exist in the language :)
Comment: nawfal: woops, thats because `IEnumerable` doesn't have a `.Remove()`. It seems that `IList` defines the `.Remove()` method. I've updated the answer.
Comment: Now how am I supposed to call the method? I tried this: `RemoveRows (dgvRecords.Rows)` which gives compilation error. I tried this: `RemoveRows((IList)dgvRecords.Rows)` but I get runtime error saying such a cast is not valid.
Comment: @nwfal: hmm, sry. Try my latest update. It seems that the IList is not generic. Try just leaving it as a plain `IList` and by using the `var` keyword, we don't really care what the type of `row` is. Also, what is the compilation error you get?
Comment: What a coincidence, I just got that done exactly now!! Compilation error was something like DataGridViewRowCollection argument doesnt match with IEnumerable
Comment: In the code, it doesnt matter if it is IEnumerable or IList, Both Works
Answer: You don't really need a projection to solve the first problem, but for the sake of argument of wanting to select a property, you can pass in a projection to allow the caller to select the property, for example in your first set of methods, you could do.
   void DeleteRows(DataGridView dgv, Func<DataGridView, IEnumerable> projection)
   {
        foreach (DataGridViewRow row in projection(dgv))
            dgv.Rows.Remove(row);
   }

Or, alternatively using generics:
   void DeleteRows<TCollection>(DataGridView dgv, Func<DataGridView, TCollection> projection) where TCollection : IEnumerable
   {
        foreach (DataGridViewRow row in projection(dgv))
            dgv.Rows.Remove(row);
   }

Then you can call it like:
   // delete all rows
   DeleteRows(dgvRecords, d => d.Rows);

   // delete only selected rows
   DeleteRows(dgvRecords, d => d.SelectedRows);

That is, in any case where you want to pass in a property dynamically, instead pass in a Func<...> that takes in the object and returns the property you want.  This is very similar how LINQ creates such generic algorithms by allowing the caller to specify the projections on which to query the data.
Of course, if you have public methods taking in delegates, make sure they are non-null before invoking them.  If they're private methods under your control, it's not as big of an issue if you control all the calls to them.
UPDATE For example 2:
decimal GetAmount(User usr, Func<Tuple<User, User, Notification, Acknowledgement>, User> projection)
{
    decimal sum = 0;
    foreach (DataGridViewRow row in dgvRecords.Rows)
    {
        Tuple<User, User, Notification, Acknowledgment> tup = (Tuple<User, User, Notification, Acknowledgment>)row.Tag;
        if (projection(tup) == usr)
            sum += tup.Item4.Sum;

    }
    return sum;
}

And call:
GetAmount(user, t => t.Item1);

Or
GetAmount(user, t => t.Item2);

That one's a bit uglier because of the large Tuple but still works.
Comment: That's so nice.. What will be the code similarly for the second example in my question? I find it a bit different
Comment: Thanks.. let me mark this as answer since you came up first with an answer.
Comment: This doesn't work. I mean the first example. The reason is `DataGridViewRowCollection` and `DataGridViewSelectedRowCollection` are different
Comment: @nawfal: You can use `IEnumerable` then, all you need to do is be able to iterate over the collection, and both implement `IEnumerable` and both contain `DataGridViewRow`.  I'll edit the answer.
Comment: @nawfal: Thanks for the heads-up, corrections always welcome!
Comment: :) Your second method using TCollection looks a bit verbose. I dunno the advantage of it though..
Answer: You can do this with reflection, but I wouldn't recommend it. Here is an example of getting a properties "getter" and working with it:
    int someFunction(Element instance, string propertyName)
    {
        MethodInfo prop = typeof(Element).GetProperty(propertyName).GetGetMethod();
        if (prop.ReturnType != typeof(int))
        {
            throw new Exception("Type of property does not match expected type of int");
        }
        return (int)prop.Invoke(instance, null);
    }

Again, I would not recommend doing anything like this unless you had a better reason than mentioned above. If you do something like this, you should try hard to cache the MethodInfo object so you don't need to recreate it every time.
Answer: This is @Alastair Pitts method, but I change the code a bit to get it working.
 void RemoveRows (IEnumerable rows)
 {
     foreach (DataGridViewRow row in rows)
         dgvRecords.Rows.Remove(row);
 }

And call it
RemoveRows ((IEnumerable)dgvRecords.Rows);
//or
RemoveRows ((IEnumerable)dgvRecords.SelectedRows);

I had tried with IEnumerable<> as pointed out by Alastair but it wouldnt work. It's not possible to cast a non-generic to a generic. IEnumerable is in the System.Collections namespace and not in the System.Collections.Generic namespace like IEnumerable<>. Nevertheless, I'm marking his as the answer.


How do I deal with random effects terms specified in formula?

Question: This is my following script:
library(lme4)
library(RColorBrewer) # needed for some extra colors in one of the graphs
library(lmerTest)# to get p-value estimations that are not part of the standard lme4 packages
lear<-read.csv("C:/Users/Liat/Documents/R/liat_data.csv")
colnames(lear) = c("participant","examiner", "date", "sex", "age", "age_group", "Hearing_status", "compression", "first 5", "last 5", "learning")
names(lear)

model <- lme4::lmer( learning ~ sex+age+Hearing_status,data = lear)
summary(model)

I get the following error: Error: No random effects terms specified in formula
what should I do?
Answer: Depending on what variable you want to specify as your grouping variable, you need to add in a | to your equation. For example, if you wanted to group your participants by  do the following model<- lme4::lmer(learning~ sex+(sex | <id variable>)+age+Hearing_status, data=lear)
Check out the documentationlme4 cran documentation


How to place v-text-field error message in vuetifyjs?

Question: I have v-text-field and I can't able to display the error message out of v-text-field dom position. in vuetify documentation there is not reference to this issue.
Is it possible to have the error message near the input?
Actual:

Expected:

<template>
  <v-app>
    <v-content>
      <playground></playground>
      <v-text-field
        style="width:120px;"
        class="numer"
        :rules="[rules.required, rules.min, rules.max]"
        v-model="numValue"
        type="number"
        append-outer-icon="add"
        @click:append-outer="increment"
        prepend-icon="remove"
        @click:prepend="decrement"
      ></v-text-field>
      {{numValue}}
    </v-content>
  </v-app>
</template>

The code in codesandbox
Answer: I know I'm late but if someone needs help:
Put this field inside a form.
<v-form ref="form">
 <v-text-field
    style="width:120px;"
    class="numer"
    :rules="[rules.required, rules.min, rules.max]"
    v-model="numValue"
    type="number"
    append-outer-icon="add"
    @click:append-outer="increment"
    prepend-icon="remove"
    @click:prepend="decrement"
 ></v-text-field>
</v-form>

Then call anywhere on template:

Validate it!

Or on the functions:
methods: {
    foo() {
       this.$refs.form.validate()
    }
}


FLEX: Is there a way to return multiple tokens at once

Question: In flex, I want to return multiple tokens for one match of a regular expression.  Is there a way to do this?
Answer: The way I've been doing this is to create a queue of to-be-returned tokens, and at the beginning of yylex(), check for tokens and return them.
Answer: Do you mean all matches? Are you using regex functions or string functions? Use the global flag.
As for flex, I don't think you can do that. You test for a match with one pattern at a time so that's probably out of scope. Why'd you want that? As an optimization? Scoping issues?
Comment: To be honest, I am fairly new to flex and I am not sure.  I thought I was using a combination of regular expressions and string matching.

Here is an example
"("      { return L_PAREN; }
{INT}       { yylval.Int = atoi(yytext); return INT; }

What I want is to be able to return two tokens at once.
Answer: Usually, this is handled by a parser on top of the scanner which gives you much cleaner code.  You can emulate that to some degree with states:
%option noyywrap

%top {
#define TOKEN_LEFT_PAREN    4711
#define TOKEN_RIGHT_PAREN   4712
#define TOKEN_NUMBER        4713
}

%x PAREN_STATE
%%
"("         BEGIN(PAREN_STATE); return TOKEN_LEFT_PAREN;
<PAREN_STATE>{
   [0-9]+   return TOKEN_NUMBER;
   ")"      BEGIN(INITIAL); return TOKEN_RIGHT_PAREN;
   .|\n     /* maybe signal syntax error here */
}
%%
int main (int argc, char *argv [])
{
  int i;

  while ((i = yylex ()))
    printf ("%d\n", i);

  return 0;
}

but this will get very messy as soon as your grammar gets more complex.
Comment: Fascinating.  I'm sure at one point this answer had a score of 10 or more for many years, but in the past, hmmm, six months it has gone negative without any indication why.


ReactiveForm for dynamically updated form entries

Question: How to check status of myform in component to check if all the fields are filled or not?
HTML:

      {{question.question}}
                <select required >
                  <option selected disabled="disabled">Option</option>
                   <option *ngFor="let option of question['options']">{{option}}</option>
                </select>

Question JSON coming from API:
 this.questions =  [
        {
          question: 'What is your age?',
          options: ['20', '30', '40']
        },

        {
          question: 'How much quantity?',
          options: ['1','2','3']
        }]

Comment: You're probably going to want to start here: https://angular.io/guide/user-input
Comment: @Brandon rather here : https://angular.io/guide/form-validation
Comment: And giving the dynamic side of the form, I would also suggest this : https://angular.io/guide/dynamic-form
Comment: How do I instantiate the formgroup for the array of select boxes?
Comment: See the thing is that i want the form's status changes to check if it is valid and then update a boolean value.
this.myform.statusChanges
      .distinctUntilChanged()
      .startWith(this.myform.status)
      .subscribe((status: string) => if(status=="Valid") {!booleanValue});
  }
But i think my form is not instantiated properly so my code never goes inside the statuschange
Comment: Of course your form isn't instanciated, your selects don't have a `formControlName` attribute.
Comment: @trichetriche can you help with that
Comment: I already gave you a link about reactive forms, and I frankly don't want to make a course to you right now ... Go ahead and read the link I gave you, and if you have trouble during your reading, make a question and refer me to it !
Comment: Sure @trichetriche. I went through the links and i created dynamic formControlName with the index. But there is only one part that iam stuck with. Instantiating myform, I tried it like this
this.myform == new FormGroup({}); But inside the formgroup how do i add the formarray for the select boxes
Comment: You have to make a `QuestionBase` [as explained here](https://angular.io/guide/dynamic-form#question-model). Once you have done that, you will be able to create a form group with `QuestionControlService`, as explained right under the first link I gave you in this comment.
Answer: If you use ReactiveForm, you need use a FormArray
A FormArray can be of FormControl or a FormGroup
FormArray of FormControls
constructor(private fb:FormBuilder) {}
ngOnInit() {
    //We create an array of FormControl, each question a FormControl
    let data:FormControl[]=this.questions.map(q=>new FormControl());

    this.myform=this.fb.group({
      questions:new FormArray(data)
    })
}
//the .html

      {{questions[i].question}}
      <select required [formControl]="question" >
         <option value="null" disabled="disabled">Option</option>
         <option *ngFor="let option of questions[i].options">{{option}}</option>
      </select>

{{myform?.value |json}}

If we use an array of formGroup we change some things
constructor(private fb:FormBuilder) {}
ngOnInit() {
    //we create and array of FormGroup
    let data2:FormGroup[]=this.questions.map(q=>this.fb.group({
      option:null
    }));

    this.myform2=this.fb.group({
      questions:new FormArray(data2)
    })
}

        {{questions[i].question}}

        <select required formControlName="option" >
           <option value="null" disabled="disabled">Option</option>
           <option *ngFor="let option of questions[i].options">{{option}}</option>
        </select>

  {{myform2?.value |json}}

Aclaration:@FrontEndDeveloper. One thing is the array question that we use to make the questions.(Perhafs I must be choose other names to the variables), other thing is the value of the form. The value of myform1={questions:["20","1"]}, the value of myform2={questions:[{option:"20"},{option:"2"}]}.
When we create an array of FormControl (or an array of FbGroup) I used map, equally I can do some like
let data:FormControl[]=[];
data.push(new FormControl());
data.push(new FormControl());

or
let data2:FormGroup[]=[];
data2.push(this.fb.group({
          option:null
        }));
data2.push(this.fb.group({
          option:null
        }));

Generally we have some data to initialize the form. (an object with some data) that we get from a dbs
//Imagine we have mydata{name:"A",options=["20","1"]}
//we can map this data to create the form
let data:FormControl[]=this.mydata.options.map(q=>new FormControl(q));
//or
   let data2:FormGroup[]=this.mydata.options.map(q=>this.fb.group({
          option:q
        }));

//Imagine we have mydata{name:"A",options=[{option:"20"},{option:"1"}]}
//we can map this data to create the form
let data:FormControl[]=this.mydata.options.map(q=>new FormControl(q.option));
//or
   let data2:FormGroup[]=this.mydata.options.map(q=>this.fb.group({
          option:q.option
        }));

Comment: @FrontEndDeveloper, I extended my answer, to make more clear the concept.About your question, If your questions are Observable of, you must subscribe the observable, and create the form In the function subscribe, not in ngInit
Comment: write console.log(questions), to see that you're receiving
Answer: This would help you to understand reactive form basic functionalities.
https://stackblitz.com/edit/objects-equality-check-edhyk5?file=src/app/app.component.ts
It will help to understand:
1. FormBulder,
2. FormGroup,
3. Form Value changes etc.
Comment: Hi please follow the link:https://stackblitz.com/edit/objects-equality-check-reactive-forms?file=src/main.ts


Javascript Object Assign and Structural Sharing

Question: I've been experimenting with concepts of immutability with javascript objects. I was wondering if the following code example implements what I believe is known as "Structural Sharing" (see: https://www.youtube.com/watch?v=e-5obm1G_FY&start=1123).
const objectFirst = {
  key1: 1,
  key2: 2
}

const updateObject = (lastObject) => {
  const updatedObject = {...lastObject, ...{ key2: 4 }}  // Object.assign({}, lastObject, { key2: 4 })
  return updatedObject
}

const objectNext = updateObject(objectFirst)

objectNext is now { key1: 1, Key2: 4 } and objectFirst is unchanged. But has key1 been duplicated? Or, is their now essentially a reference to key1's location in memory shared by both objects?
I'm basically just asking if this approach implements some sort of "Structural Sharing"? One could see that if this were not the case, then it would lead to significant memory bloat.
Comment: No this is not that. You can verify that by changing `objectFirst.key1` and see if it reflects in `objectNext`.
Comment: Both objects have distinct `key1` properties. There's no property sharing in any visible way, though one  never knows what goes on internally.
Comment: For structural sharing you need a tree-like data structure. The simplest tree is an unary tree, where each node has one or no child. You guessed it, it is a single linked list I am talking about. When you implement such a list you will notice that prepending is a cheap operation, whereas appending is an expensive one. Therefore balanced trees are used for the latter.
Answer: No, because 1 is stored as a simple value on objectFirst, not a reference to an object, so when you do {...objectFirst} you're copying the value of objectFirst.key1 to objectNext.key1.
However, if objectFirst.key1 was an object instead, then the shallow copy would copy the object reference instead of creating a new object. As a result, objectFirst.key1 and objectNext.key2 would both reference the same object.
const objectFirst = {
    key1: 1,
    key2: 2,
    sharedObject: {foo: 'original string'}
}
// we make a shallow copy with a different key2 value.
const objectSecond = {...objectFirst, key2: 4};

// changing a value in objectSecond doesn't affect objectFirst
objectSecond.key1 = 100;
console.log(objectFirst.key1); // 1

// but sharedObject is shared
objectSecond.sharedObject.foo = "new string";
console.log(objectFirst.sharedObject); // {foo: "new string"}

Answer: console.log(objectFirst['key1'] === objectNext['key1']); // true

console.log(objectFirst['key2'] === objectNext['key2']); // false

This means objectFirst and objectNext share the key1 property.
Comment: I don't think so, because `key1` is not reference value


Display text and score above players character (mc 1.16.3)

Question: I have tried to display a score value and a text above the player character/ under the name but all my attempts have failed (ish).
The score value i want to display is the player Xp level. I did it by running this command:
<code>/execute as @a[limit=1,sort=random] store result score @s level run data get entity @s XpLevel 1
</code>
The text i want to show is the players rank. The higher level the player has the better rank for exemple if the player is in level 6 > 9 the player has iron rank... I did this by running example this command:
<code>/execute as @a[level=6..9] run tag @s add iron_rank
</code>
Now i just want to display the level and rank above the players character/ under the name.
My Idea was to display the level score was to simply display the score belowname with this command:
<code>/scoreboard objectives setdisplay belowName level
</code>
But when i switched to third person i couldn´t see the score under my name/over the character for some reason.
My idea to display the rank was to summon and then teleport an small and invisible armor stand with a custom name at the player. This works but the armor stand can be in the way for the player if you want to interact with something above you!

<code>/summon armor_stand ~ ~ ~ {Invisible:1b,Invulnerable:1b,PersistenceRequired:1b,NoBasePlate:1b,NoGravity:1b,Small:1b,CustomName:"{\"text\":\"Rank: iron\",\"color\":\"gray\"}",Tags:[iron_rank]},CustomNameVisible:1b
</code>

<code>/execute as @a[limit=1,sort=random,tag=iron_rank] at @s run tp @e[type=minecraft:armor_stand,tag=iron_rank] ~ ~1.5 ~
</code>

I also tried this with the level score but it has the same problems and it will require 1 command block per level! (The rank also require 1 command block per rank but it will be like 10 ranks but infinit levels)
I want it to look something like this.
Comment: Are you playing on multiplayer? According to the [Minecraft Wiki](https://minecraft.gamepedia.com/Scoreboard#Display_slots), you can't see the `belowName` display slot in singleplayer.
Comment: I was testing in singleplayer but the map this is for is both singleplayer and multiplayer1
Answer: You could either use teams or the marker tag for the armor stand.  The marker tag removes the hitbox. For the teams you can have prefixes and suffixes.  You can do it with mcstacker at https://mcstacker.net/
you have to create the team first then you can edit the team prefixes and suffixes.  As well I suggest making a team if you use the armor stands marker tag to prevent collision.  For teams you would I think have to use execute if commands to assign teams for each level and rank.
below is the command for summoning the armor stand
<code>/summon armor_stand ~ ~ ~ {Marker:1b}
</code>
as well you can add tags for other things.
I suggest using mcstacker for command generation.
summary:
1: team prefixes and suffixes using the /team command
2: the marker nbt tag for armor stands
3: use mcstacker https://mcstacker.net/
your welcome.
Comment: Thanks a lot for the help, it works.
Comment: @zombie1111 Your welcome!


C++ Object Oriented Design

Question: class Allegro {};

class Input
{
private:
    Allegro allegro1
};

class Graphics
{
private:
    Allegro allegro2
};

class Game
{
private:
    Input keyBoardinput;
    Graphics Gamegraphics;
};

In the input I need access to Allegro functions related to the user keyboard input. In the Graphics class,I want only functions that will enable me to draw things on the screen, like shapes etc. However the Game class also needs access to Input and Graphics functions while the game is playing.Any ideas on how I can improve the design. I know I can remove the Graphics and Input classes and have all the Allegro functions inside Game class, because what I want to do is to separate implementation and logic and to also avoid long classes that do too many things.
Comment: There is no question here. There is nothing to improve, what you have so far is so little that there's no way to tell what might be wrong with it. What you have posted is clearly OOP, but it's such a small example that it's impossible to point out anything good *or* bad about it.
Comment: I need to make a design decision, the question is, is there any better way of achieving a similar objective, an example having only the game and Allegro class, and inserting an interface between them. I this way better than having composition relationships illustrated in the code? Is it a good idea/design to have two objects composed on one object?
Comment: No, a single massive Allegro class wouldn't be better, as you stated in your question, for the reasons you stated in your question. Beyond what you already say you know, there is no way to tell you anything useful based on the stub of code you posted.
Answer: Obviously, Graphics and Input should be talking to the same Allegro class. So you should do that: create the Allegro class instance, then use that instance in the constructors for Graphics and Input.
Answer: Your Game class should  create the instance of Allegro and the same instance should be passed to Input and Graphics, and the latter two will simply hold the reference of the instance.
class Game
{
    Game() : allegro(/*..*/), keyBoardinput(allegro), Gamegraphics(allegro) {}
private:
    Allegro allegro; //actual instance
    Input keyBoardinput;
    Graphics Gamegraphics;
};

Note that the order of members in Game is important. allegro should be declared before keyBoardinput and Gamegraphics. This makes sure that allegro is created before the rest two, and then you pass allegro (the fully created instance) to the constructors of Input and Graphics.
And then make sure that Input and Graphics hold the reference of allegro which is passed from Game. Don't make a copy of allegro:
class Input
{
public:
    Input(Allegro & allegro) : allegro1(allegro) {}
private:
    Allegro & allegro; //reference  - not copy!
};

class Graphics
{
public:
    Graphics(Allegro & allegro) : allegro1(allegro) {}
private:
    Allegro & allegro; //reference - not copy
};

Note that all of these classes make use of member-initialization-list which is also very important here.

C++ Object Oriented Design


What could be causing my sink and dishwasher to back up?

Question: My sink backs up when running water for 3 min. Also into dishwasher.
It's also a double sink.
On the other hand, my dishwasher also backs up into sink.
This causes a disgusting smell through my home.
Especially in the bathroom and my bedroom.
I do have a basement, and when water backs up into sink ..it also backs up out of floor drain downstairs.
I had snake run through and it's not appearing to be stopped up.
New pipes were put in under sink and it didn't help.
Please give me something I can do.
I'm a single woman trying to figure this out.
Comment: Note that you can't snake from the basement drain - this will do nothing since it is its own branch.  You need to snake from the main down or from the street to house.
Answer: It really sounds like the drain line blockage is beyond the place where the basement drain exits the foundation and goes off to either the public sewer system or private septic system. Could be broken underground line, line filled in with tree roots seeking water through joints or holes in the piping, or sediment / deposits in the line that have restricted its flow.
Probably the best way to troubleshoot this type of problem is to use a inspection camera that is slid through the pipe on the end of a long cable with a camera display at the end. Some professional plumbers have these for sewer inspection. It may also be possible to rent one and use it yourself but then you do not get the experienced eye of the operator knowing what nuances to look for.
Comment: Well the OP may very well have drain blockage after the sink trap since the sink/dishwasher backup. However since the basement floor drain also backs up it is indicative of multiple problems.
Comment: I was thinking it was a little after the trap.  I had an issue with old iron in my kitchen very similar to hers.  It was about $20 of pvc vs $400 plumber.
Comment: To add, I've had this happen in a past house where the cause was problems with the septic system itself. In some places your septic field slows goes from being loose soil to becoming dense and hard overtime. Mild cases you can have it aerated where they take a machine that blasts foam beads into the ground to help keep the soil from hardening as well as loosening up the soil, but when it's too for gone they have to dig up the field. (hard soil acts like a plug at the end of the pipe)
Answer: The problem is in the street, or at least towards it, as Michael suggests. If you snaked it yourself I doubt it made it all the way to the street. If it was professionally snaked, start making phone calls to whoever did it and to the city.
Jerseyville Sewage Plant. Call them and tell them your problem persists even after having your main line professionally snaked. If this is the wrong place perhaps they can point you in the right direction to contact your Streets and Sanitation department.


Problems with foundation 6 grid on img overlay in react

Question: I am using the foundation 6 xy grid for the first time and am having difficulties aligning three images which have a text overlay at the bottom of each image. I struggling to get the background of the text to fill the full width of the image while making it responsive, 100% width of the newsArticle__pCont class is greater than the parent cell which I don't understand. Below is the closest that I have got (which isn't very close)
class News extends Component {

    renderArticlePreview(article) {
        if(articleCount <= 2) {
            articleCount++;
            return (

{article.title}

            )
        }
    }

    render() {
        const { news } = this.props;

        return (

                        { news.map((article) => this.renderArticlePreview(article)) }

        )
    }
}

export default News;

.scss
@import './Helpers.scss';

.newsArticle {

    .newsArticle__cont--firstThree {
        position: relative;
    }

    .newsArticle__title {
        text-align: center;
        font-size: 24px;
        font-weight: 500;
        color: #000000;
    }

    .newsArticle__title--overlay {
        font-size: 16px;
        font-weight: 500;
        color: #FFFFFF;
        text-align: center;
        margin-bottom: 0px;
    }

    .newsArticle__pCont {
        background-color: rgba(0, 94, 154, 0.75);
        height: 45px;
        position: absolute;
        bottom: 0px;
        z-index: 10;
        width: 100%;
    }

    @include screen(sm-only) {
        .newsArticle__img {
            margin-top: 10px;
        }
    }

    @include screen(md) {
        .newsArticle__img {
            margin: 10px;
        }

        .newsArticle__p {
            margin: 10px;
        }
    }
}

Answer: So the reason your text right now is too large is because it is

position absolute (which takes it out of the flow, so it's not being
contained by the padding of the cell itself)
width: 100%, which will take it to the full width of the parent (which includes the padding).

The simplest way to fix this in your case would be to switch from padding-x (gutters are actually inside the cell, cell width includes the gutters) to margin-x (gutters are done by margin, so cell width excludes gutters).  This would change your grid to look like:

A codepen showing this: https://codepen.io/kball/pen/zEGoaR
Comment: It trades off a little complexity for power - definitely a little frustrating for simple cases, but far more powerful and easy to compose for complex cases.
Comment: You were spot on, it worked straight away.  Is it just me or is the new xy grid quite annoying with the extra markup required to make it do previously default behaviours like adding the margin and padding classes? I can understand why they have changed it to this way but can't help but feel its a lot of kerfuffle for very little reward


How does a contact and Legal Entity related in Person Account Salesforce?

Question: I have trouble understanding an aspect of Person Accounts in Salesforce. I have both Business and Person accounts (with different record types) in Salesforce. When I create a contact from the related list of a business Account I do see a person account & Contact created but it is NOT related to business Account in any way. Can someone explain if this is the expected behavior ?
Answer: Person Account is a contact and account at the same time. It should be used when an account is not an organization but an individual. For example your cable company will have you listed as a Person Account but create Account with related Contacts say for an Hospital.
More on this you can read in this pdf


Is it possible to disallow jsp execution on tomcat + apache

Question: I have an application tomcat + apache + mod_jk + spring mvc deployed on remote server. After making request to the controller I am having jsp source code in the response. It is not related with spring config cause locally it is working. After debugging mod_jk I see that tomcat returns jsp source.
I think the problem is related with remote tomcat or apache (cause it was configured by our it department). Is it possible to dissalow jsp execution on tomcat or apache (maybe httpd conf)? Plese suggest how can resolve this problem.
Comment: How are you deploying your application?
Comment: @ElliottFrisch we have some tool for deployment, but in general it just puts war file in the tomcat web folder
Comment: Are the JSPs inside Apache's HTDOCS folder rather than under Tomcat's webapps folder?
Comment: @developerwjk No they are in the tomcat webapps  folder. But is it important? How I understand Apache here is like a proxy..
Answer: Apache Web Server does not execute JSPs, so you're probably getting your JSP from there.
Normally, static files are deployed on Apache Web Server, and dynamic files (JSPs, Custom Tags, classes, etc.) are deployed on Apache Tomcat (where Apache Web server redirects the corresponding requests). Check if your app is deployed this way.
Try to send an HTTP request directly to the Apache Tomcat (without intervention of Apache Web Server, and see what happens)
Comment: i will try but i think it is not possible because tomcat is not visible from outside, only apache
Answer: The reason was that jsp compiler was disabled see org.apache.jasper.servlet.JspServlet, in the tomcat\conf\web.xml. It-team says that it is recommend option for production)


mysql between but not equal

Question: i have an query that returns values that are between 2 dates. The problem is that it returns the result even if the value is equal. Here is my query
$stmt=$dbh->prepare("Select * FROM tbl_rezervari tr

                where (:start BETWEEN tr.start AND tr.end or :end BETWEEN tr.start AND tr.end)");

                $stmt->bindParam(":start",$startDate);
                $stmt->bindParam(":end",$endDate);
                $stmt->execute();

Answer: BETWEEN is an inclusive range of values(https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#operator_between).
If you don't want the values to be included in the range you may have to do it long hand...
$stmt=$dbh->prepare("Select * FROM tbl_rezervari tr
         where ((:start > tr.start AND :start
 tr.start AND :end < tr.end))");

Comment: This answer works with date, datetime, and other kinds of numeric datatype. It is also more flexible because `>=` or/and `<=` could be used if needed.
Answer: Yeah. Between And means [a,b] including a and b.
So if you want to exclude either a or b just make it minus 1 day.
Answer: As mentioned already - the between operator is inclusive and thus includes the start and end dates in the range - you could however modify the query to adddate and subdate as below
$stmt=$dbh->prepare("select * from tbl_rezervari tr
    where (
    :start between adddate( tr.start, interval 1 day ) and subdate( tr.end, interval 1 day )
    or
    :end between adddate( tr.start, interval 1 day ) and subdate( tr.end, interval 1 day )
    )");

mysql between but not equal


dplyr mutate and purrr map: use data masking to select columns for map

Question: In a dplyr mutate context, I would like to select the column a function is applied to by purrr:map using the value of another column.
Let's take a test data frame
test <- data.frame(a = c(1,2), b = c(3,4), selector = c("a","b"))

I want to apply following function
calc <- function(col)
{res <- col ^ 2
return(res)
}

I am trying something like this:
test_2 <- test %>% mutate(quad = map(.data[[selector]], ~ calc(.x)))

My expected result would be:
  a b selector quad
1 1 3        a    1
2 2 4        b   16

but I get
Error in local_error_context(dots = dots, .index = i, mask = mask) :
  promise already under evaluation: recursive default argument reference or earlier problems?

I know .data[[var]] is supposed to be used only in special context of function programming, but also if I wrap this in functions or similar I cannot get it done. Trying to use tidy-selection gives the error that selecting helpers can only be used in special dplyr verbs, not functions like purrr:map.
how to use dynamic variable in purrr map within dplyr
hinted me to use get() and anonymous functions, but this also did not work in this context.
Answer: Here's one way:
test %>%
  mutate(quad = map(seq_along(selector), ~ calc(test[[selector[.x]]])[.x]))

#   a b selector quad
# 1 1 3        a    1
# 2 2 4        b   16

Instead of .data, you can also cur_data (which accounts for grouping):
test %>%
  mutate(quad = map(seq(selector), ~ calc(cur_data()[[selector[.x]]])[.x]))

Or, with diag:
test %>%
  mutate(quad = diag(as.matrix(calc(cur_data()[selector]))))

#  a b selector quad
#1 1 3        a    1
#2 2 4        b   16

Comment: I didn't know about seq_along - very interesting!
Comment: Thanks a lot, I didn't think about simply subsetting the selector in the function, the seq_along is great for this!
Answer: You can use rowwise() and get() the selector variable:
library(dplyr)

test %>%
  rowwise() %>%
  mutate(quad = calc(get(selector))) %>%
  ungroup()

# A tibble: 2 × 4
      a     b selector  quad
  <dbl> <dbl> <chr>    <dbl>
1     1     3 a            1
2     2     4 b           16

Or if the selector repeats, group_by() will be more efficient:
test <- data.frame(a = c(1,2,5), b = c(3,4,6), selector = c("a","b","a"))

test %>%
  group_by(selector) %>%
  mutate(quad = calc(get(selector[1]))) %>%
  ungroup()

# A tibble: 3 × 4
      a     b selector  quad
  <dbl> <dbl> <chr>    <dbl>
1     1     3 a            1
2     2     4 b           16
3     5     6 a           25

Answer: You could also change the function to return a single number and use purrr:
calc <- function(col, id) {test[[col]][[id]]^2}

test %>%
    mutate(
        quad = purrr::map2_dbl(selector, row_number(), calc)
    )
  a b selector quad
1 1 3        a    1
2 2 4        b   16

Answer: Using base R:
test$quad <- calc(test[,test$selector][cbind(seq_len(nrow(test)), test$selector)])

(R version 3.5.3 where strings are converted to factors in data.frame)
Answer: Not quite what you asked for but an alternative might be to restructure the data so that the calculation is easier:
test %>%
   pivot_longer(
       cols = c(a, b)
   ) %>%
   filter(name == selector) %>%
   mutate(quad = value**2)

# A tibble: 2 × 4
  selector name  value  quad
  <chr>    <chr> <dbl> <dbl>
1 a        a         1     1
2 b        b         4    16

You can join the results back onto the original data using an id column.


How to replace old ceiling fan-light with just a light fixture

Question: I would like to replace and old ugly ceiling fan-light in my dining room with a pendant type light. The original ceiling fan light was controlled by a dimmer switch on the wall and to operate the fan it was a pull chain. After taking down the fan and wiring the new light with what I thought were the correct wires, it still doesn't turn on. Does anyone know how to go about this?
I've attached pics of the wiring after I've pulled the fan down. Any help would be appreciated.
Comment: Have you now disconnected any wires?
Answer: I believe that you have a standard switch loop, coming off the black bundle as white and returning as black. That return black, which is connected to the red wire, is your switched hot.

So...

The white from your fixture goes to the white bundle (possibly without the jumper, which doesn't seem necessary).

The black from the fixture goes to the single black wire (to which the red is now connected).

The black from the fan that connects to the black bundle will simply be eliminated.

Make sure you have a good understanding of how to make safe connections with wire nuts, including the capacities of the different nut sizes.
Comment: I tried it and its still not working..... do you think its the dimmer switch? Should i replace it with a regular switch?
Comment: You shouldn't have accepted the answer if it didn't work. Sure... any device can fail. You can always nut the wires together to test.


An arctan series with a parameter $\sum_{n=1}^\infty \arctan \left(\frac{2a^2}{n^2}\right)$

Question: I'm trying to evaluate $$\sum_{n=1}^\infty \arctan \left(\frac{2a^2}{n^2}\right) \ , \ a >0. $$
The answer I get only seems to be correct for small values of $a$.
What accounts for this?
Using the principal branch of the logarithm, I get
$$
\begin{align}
&  \sum_{n=1}^\infty \arctan \left(\frac{2a^2}{n^2}\right) \\ & =  \text{Im} \sum_{n=1}^\infty \log \left( 1 + \frac{2ia^2}{n^2} \right) \\
& = \text{Im} \log \prod_{n=1}^\infty \left(1 + \frac{2ia^2}{n^2} \right) \\
& = \text{Im} \log \prod_{n=1}^\infty \left(1 - \frac{(\sqrt{-2i}a)^2}{n^2} \right) \\
& =\text{Im} \log \left(\frac{\sin (\pi \sqrt{-2i}a)}{\pi \sqrt{-2i}a} \right) \\
& = \text{Im} \log \left(\frac{\sin \left(\pi (1-i)a\right)}{\pi (1-i)a} \right) \\
& = \text{Im} \log \left(\frac{\sin (\pi a) \cos (i\pi a) - \cos (\pi a) \sin (i \pi a)}{\pi (1-i)a} \right) \\
& = \text{Im} \log \left(\frac{\sin (\pi a) \cosh (\pi a) - i\cos (\pi a) \sinh (\pi a)}{\pi (1-i)a} \right) \\
& = \text{Im} \log \left(\frac{\sin (\pi a) \cosh (\pi a) + \cos(\pi a) \sinh (\pi a) + i \left( \sin (\pi a) \cosh (\pi a) -  \cos (\pi a) \sinh ( \pi a) \right)}{2\pi a} \right) \\
& = \text{Arg} \  \Big(\sin (\pi a) \cosh (\pi a) + \cos(\pi a) \sinh (\pi a)+ i \left( \sin (\pi a) \cosh (\pi a) -   \cos (\pi a) \sinh ( \pi a) \right) \Big)
\end{align}
$$
Comment: $\sin(A+B)=\sin(A)\cos(B)+\cos(A)\sin(B)$. It seems like you have a minus sign that doesn't belong there, if I read this right. I don't know if that fixes the issue though.
Comment: What allows you to replace $\operatorname{Im}\,\log(X)$ with $\operatorname{Arg}(X)$ at the last step? This is only true if $\log(X)$ is imaginary.
Comment: I used the identity for $\sin (A-B)$.  And I don't quite understand your second point. $\log(z) = |z| + i \text{Arg}(z)$.
Comment: Then you should not have $-i\pi a$ as the argument in $\cos$ and $\sin$ on the next line. Rather you should have $i\pi a$.
Comment: I think the first line of my "solution" might me restrict me to only certain values of $a$.
Comment: For real numbers $z$, $\operatorname{Arg}(z)=0$. So the equation $\log(z)=|z|+i\operatorname{Arg}(z)$ would reduce to $\log(z)=|z|$ and is therefore false in general. A corrected version is $\log(z)=\log|z|+i\operatorname{Arg}(z)$
Comment: I concede your last step - my second comment is wrong. But you are still double counting a minus sign where that trig identity is used.
Comment: I edited my post.  But I still end up with the same answer. To me that first line only makes sense if I use the principal branch of the complex log. But then the final answer is off by increasingly more multiples of $\pi$ as $a$ gets larger.
Answer: I think I understand the issue now. In this setting, we cannot say that $\log(A)+\log(B)$ is equal to $\log(AB)$. This (generally) invalidates your exchange of an infinite sum for an infinite product. But keep reading to the end to see a fix.
Let's write $\log$ for the principle branched logarithm, and $\operatorname{lug}$ for a potentially different branched logarithm. For fixed $A$ and $B$, there is some $\operatorname{lug}$ for which $$\log(A)+\log(B)=\operatorname{lug}(AB)$$ but it might have a different branch.
Consider $A=B=\exp(i3\pi/4)$. Then
$$\begin{align}\log(A)+\log(B)&=i3\pi/4+i3\pi/4\\&=i3\pi/2\end{align}$$ But this addition has crossed over the negative real axis in an angular sense. So $\log(AB)$ is something different: $$\log(AB)=\log(\exp(i3\pi/2))=-i\pi/2$$
So it is not exactly that some values of $a$ cause a problem with your first line, but rather with your second line. If $a$ is small enough such that the infinite summation in the first line never surpasses $\pi i$, then the final result should be OK. For other $a$, you would want to find how many times that sum crossed the negative reals in an angular sense, and account for so many multiples of $2\pi i$.
$\operatorname{Arg}$ is discontinuous at $x+iy$ with negative $x$ and $y=0$. The discontinuities in $\operatorname{Arg}$ in your final line will correspond to values of $a$ where the original sum passes $\pi$, $3\pi$, etc. So let's solve for when the imaginary part of the input to $\operatorname{Arg}$ in your final line equals zero.
$$\begin{align}
\sin(\pi a)\cosh(\pi a)−\cos(\pi a)\sinh(\pi a) & = 0\\
\sin(\pi a)\cosh(\pi a)&=\cos(\pi a)\sinh(\pi a)\\
\tan(\pi a)&=\tanh(\pi a)
\end{align}
$$
The positive solutions to this equation can be solved numerically: $a\approx1.249\ldots,2.249\ldots,3.250\ldots,4.25\ldots$. Only every other solution actually corresponds to a discontinuity in $\operatorname{Arg}$, since we also require the real part of the input to $\operatorname{Arg}$ in your final line to be negative.
So rounding just a little, your result is valid as is for $|a|<a_0=1.25$. After that, we can count how many times the original sum has passed $\pi$, $3\pi$, $5\pi$, $\ldots$ with $\left\lceil\frac{a-a_0}{2}\right\rceil$. So to your result, let's add $2\pi\left\lceil\frac{a-a_0}{2}\right\rceil$. Of course, there has been some rounding here, so this won't always be right for values of $a$ very near to the critical $a$ values $\approx 1.25, 3.25, 5.25\ldots$.
Comment: Only $a$ where $\sum\log\left(1+\frac{2ia^2}{n^2}\right)$ has an imaginary part less than $\pi$. Roughly, $\log\left(1+\frac{2ia^2}{n^2}\right)\approx\frac{2ia^2}{n^2}$ when $a$ is small. So for small $a$, the sum is approximated by $2ia^2\frac{\pi^2}{6}$. Setting that equal to $i\pi$ and solving for $a$ yields $a=\sqrt{3/\pi}$. So, _roughly_ any positive $a$ below this will allow your formula to work. But then again that bound is close to $1$, and I'm not sure the approximation $\log\left(1+\frac{2ia^2}{n^2}\right)\approx\frac{2ia^2}{n^2}$ is still any good in that region.
Comment: That never crossed my mind, but is indeed true. But then what values of $a$ is my solution valid for?
Comment: So this is a bad approach to the problem since you don't really know when the value of $a$ is small enough.  And when it's too big, it's never exactly clear how many $2 \pi$'s you should add to the final answer.
Comment: Wolfram Alpha computes that if $a=1$, the original arctangent sum equals $3\pi/4$, shy of $\pi$. So if you can establish this independently of WA, then your result holds for $|a|\leq1$ (and also for larger $a$ but it's unclear where that boundary lies.)
Comment: No I think it's a great approach. I'm about to edit my answer to show how to determine the critical $a$ values.


Overloading template classes by template parameter number

Question: Is it possible to have multiple versions of the same class which differ only in the number of template arguments they take?
For instance:
template<typename T>
class Blah {
public:
    void operator()(T);
};

template<typename T, typename T2>
class Blah {
public:
    void operator()(T, T2);
};

I'm trying to model functor type things which can take a variable number of arguments (up to the number of different templates that were written out).
Comment: I'm wondering if you could do something with typelists.
Comment: @john that would be a good idea but I'm using MSVC++ 2010 which doesn't support them I don't believe.
Comment: Actually boost::tuple is probably a more accessible version of the same idea. Have a generic template with one type, then specialised version with tuples for two, three, four ... types.
Answer: The simplest answer would be to have just one template, with the maximum number you want to support and use void for a default type on all but the first type. Then you can use a partial specialization as needed:
template<typename T1, typename T2=void>
struct foo {
    void operator()(T1, T2);
};

template <typename T1>
struct foo<T1, void> {
     void operator()(T1);
};

int main() {
   foo<int> test1;
   foo<int,int> test2;
   test1(0);
   test2(1,1);
}

Comment: @ben - It doesn't work like that, hence the partial specialization which effectively gives the "overloading" on number of template arguments
Comment: I don't think the definition of `operator()(T, T2, T3, T4)` would work right if some of the types were `void`.
Comment: ok thanks, with the partial template specialization trick it works. Thanks very much, I'll mark this as the answer in 6 minutes.
Comment: @awoodland: This looks good.  Much better than your answer when I commented on it.
Comment: @Nikolai: The asker of the question states in a comment that he was using MSVC++ 2010, which [doesn't support them](http://msdn.microsoft.com/en-us/library/hh567368.aspx). That said, it could be a valid and useful answer if you want to add it.
Comment: Is this an example of SFINAE? Meaning: instantiating the base template definition would not compile because `T2` can't actually be `void`. Is this what's going on here?
Comment: No, it's just specialisation and default template arguments.
Answer: A template can have only one base definition. If you need a variable number of arguments and you don't want to use "null type" constructions as @awoodland suggests, and if you have a C++0x compiler, then you can use variadic templates:
template <typename ...Dummy> struct foo; // base case, never instantiated!

template <typename T> struct foo<T> { /*...*/ };  // partial spec. for one parameter
template <typename T, typename U> struct foo<T, U> { /*...*/ };  // ditto for two

Answer: This is untested code, I don't have a version of boost handy, but here goes anyway
#include "boost/tuple.h"

template <class T>
class Blah;

template <class T>
class Blah< boost::tuple<T> >
{
  void operator()(T arg);
};

template <class T, class U>
class Blah< boost::tuple<T, U> >
{
  void operator()(T arg1, U arg2);
};

etc. etc.