Java app startup with computer and be able to see system.out.println?

Question: I wrote a simple Java app which I have placed in the start up folder of my programs which makes the program starts when the computer starts up. what is the easiest way to make it open a command line or something which I can see the System.out.println results instead of just running in the background?
Comment: Are you talking about logging the details ?
Comment: now that you mention it that can be another option too, initially I was thinking about seeing the output as its running.
Comment: I have given the answer for you question below. You can find there
Answer: You should familiarize yourself with logging frameworks such as logback and log4j. Instead of using System.out.println you use some special API and the logging library redirects all messages to preconfigured appenders like console or file.
In your case you can configure your application to log on console while developing and switch to file when configuring an application to run from startup.
This won't really open a new command line window on startup, but instead it will store all messages to some predefined file on disk - which is actually even better.
Answer: You can use Log4j API for logging the details with the predefined outputs. It is far better then using SOP. Because it is light waighted and also very simple to configure the logs in the other files with the output format whichever you want to make.
http://logging.apache.org/log4j/1.2/ Go to this url where you can find log4j api available.
Hope this work for you
Enjoy !!!


Remove HTML tag using jQuery

Question: I am new on jQuery. I want to remove HTML tag only, not its content. The following is my code
HTML

    Personal Loans

Secured Loans

Unsecured Loans

Bad Credit Loans

    Debt Management

Debt Consolidation Loans

Credit Card Debt Management

IVAs

    Payday Loans

Text Loans

Short Term Loans

Cash Loan

Same Day Loan

Instant Loans

Quick Loan

Cash Advances

Fast Loan

Car Loan

Mortgage

I want to remove the nested
 only, but not its children
. Is this possible in jQuery? Please help me.
Comment: It's not possible since `li` *must* be inside `ul` or other list tag. It will be possible if you replace `li` with, for example, `div`.
Comment: What end-result are you hoping for? An `li` is only a valid child of a `ul` or `ol`, so what you're asking becomes: 'how can I use JavaScript to create invalid HTML?' Which is, *at best*, unwise.
Comment: actually i want to use this same code on different places on website with different style so that i want to remove these nested '' on run time
Answer: You can't put an li inside another li. What you can do, though, is move the li elements from within the ul and put them just after the li that used to contain the ul. Something along these lines:
$("ul > li ul").each(function() {
    var $ul = $(this);
    $ul.children().insertAfter($ul.parent());
    $ul.remove();
});

Live Example | Source
Comment: @user1849368: Good deal, glad that helped.
Answer: You could call the unwrap() method on your list item.
This will remove the ul element and reparent the li element (and its siblings, if any) under the ul element.
Comment: *"This will remove the 'ul' element and reparent the 'li' element (and its siblings, if any) under the 'ul' element."* No, it will remove the `ul` and attempt to put its `li` elements *within* the `li` that used to contain the `ul`. The browser *may* then try its best to put up with the invalid DOM structure, but it's better not to create invalid DOM structures in the first place.

Remove HTML tag using jQuery


Sublime Text C plugin - code templates and autocomplete

Question: I'm looking for a plugin (or a way to create metadata for a plugin) that will allow me to do the following with Sublime Text 3 for the C programming language.

Generate C source file from a template
(Auto) generate C style function comments

For the plugin I am looking for something that handles autocompletion with argument hints (similar to the hover-box hints in VS indicating what the parameter is. I am aware that this may require some bit of coupling to the documentation of the function in a function block.
Answer: For the benefit of others, here's the workaround I ended up working with and the rationale

For C sourcefile generation, I ended up using eclipse CDT as it comes with the feature pretty much out of the box under templates.
For comment generation I also used eclipse CDT templates bound to hotkeys. It is somewhat limited (the auto-population of function name and parameters only gets picked up if the hotkey is triggered inside the scope of the function), but it works also pretty much out of the box.


MythTV works OK but other sounds do not with nVidia HDMI, what to do?

Question: I have a Home Theater Personal Computer.  It is connected via HDMI to a Samsung HDTV and then by optical cable to a 5.1 receiver.
Mythtv plays very well, the problem is other computer sounds.  These seem to overdrive the the speakers - causing loud spitting unless the volume is very low..

For instance, when playing audio using Firefox and mog.com when the ALSA plug-in [npviewer.bin] is set low enough to stop the spitting from overdriving in Sound Preferences/Application, the volume is too low to be useful and the volume level of the right speaker is much louder than other speakers.  The same thing happens when playing an audio CD and with system sounds.

The Alsa mixer shows only four check boxes for playback and , IEC958, IEC958 1, IEC958 2, and IEC958 3; with the first two checked.  Only IEC958 1 affects the audio.  For capture, it reports the device does not have any capture devices.
The specs are:

Ubuntu 10.10 (fully updated)
Linux 2.6.35-31-generic (x86_64)
Athlon(tm) X3 445 Processor (3x3.1GHz)
4055MB
Audio Adapter:HDA-Intel-HDA NVidia[nVidia Corporation High Definition Audio Controller/ (rev a1)]
GeForce GT 240/PCI/SSE2

Mythtv fixes/0.24 (v0.24.1-112-g40f3bae)
The motherboard has built in sound that is disabled in the BIOS.
alsa-info here.
The Loaded snd modules:
snd_hda_codec ⋯ HDA codec core
snd_hda_codec_nvhdmi ⋯ NVIDIA HDMI HD-audio codec
snd_hda_intel ⋯ Intel HDA driver
snd_hwdep ⋯ Hardware dependent layer
snd_page_alloc ⋯ Memory allocator for ALSA system.
snd_pcm ⋯ Midlevel PCM code for ALSA.
snd_rawmidi ⋯ Midlevel RawMidi code for ALSA.
snd_seq ⋯ Advanced Linux Sound Architecture sequencer.
snd_seq_device ⋯ ALSA sequencer device management
snd_seq_midi ⋯ Advanced Linux Sound Architecture sequencer MIDI synth.
snd_seq_midi_event ⋯ MIDI byte <-> sequencer event coder
snd_timer ⋯ ALSA timer interface

From lspci -vvnn for nvidia
01:00.0 VGA compatible controller [0300]: nVidia Corporation GT215 [GeForce GT 240] [10de:0ca3] (rev a2) (prog-if 00 [VGA controller])
    Subsystem: eVga.com. Corp. Device [3842:1242]
    Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Latency: 0
    Interrupt: pin A routed to IRQ 18
    Region 0: Memory at fc000000 (32-bit, non-prefetchable) [size=16M]
    Region 1: Memory at d0000000 (64-bit, prefetchable) [size=256M]
    Region 3: Memory at ce000000 (64-bit, prefetchable) [size=32M]
    Region 5: I/O ports at d800 [size=128]
    [virtual] Expansion ROM at fde80000 [disabled] [size=512K]
    Capabilities: [60] Power Management version 3
        Flags: PMEClk- DSI- D1- D2- AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot-,D3cold-)
        Status: D0 NoSoftRst+ PME-Enable- DSel=0 DScale=0 PME-
    Capabilities: [68] MSI: Enable- Count=1/1 Maskable- 64bit+
        Address: 0000000000000000  Data: 0000
    Capabilities: [78] Express (v2) Endpoint, MSI 00
        DevCap: MaxPayload 128 bytes, PhantFunc 0, Latency L0s unlimited, L1 <64us
            ExtTag+ AttnBtn- AttnInd- PwrInd- RBE+ FLReset-
        DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-
            RlxdOrd+ ExtTag+ PhantFunc- AuxPwr- NoSnoop+
            MaxPayload 128 bytes, MaxReadReq 512 bytes
        DevSta: CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr- TransPend-
        LnkCap: Port #0, Speed 2.5GT/s, Width x16, ASPM L0s L1, Latency L0 <512ns, L1 <4us
            ClockPM+ Surprise- LLActRep- BwNot-
        LnkCtl: ASPM Disabled; RCB 128 bytes Disabled- Retrain- CommClk+
            ExtSynch- ClockPM+ AutWidDis- BWInt- AutBWInt-
        LnkSta: Speed 2.5GT/s, Width x16, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt-
        DevCap2: Completion Timeout: Not Supported, TimeoutDis+
        DevCtl2: Completion Timeout: 50us to 50ms, TimeoutDis-
        LnkCtl2: Target Link Speed: 2.5GT/s, EnterCompliance- SpeedDis-, Selectable De-emphasis: -6dB
             Transmit Margin: Normal Operating Range, EnterModifiedCompliance- ComplianceSOS-
             Compliance De-emphasis: -6dB
        LnkSta2: Current De-emphasis Level: -6dB
    Capabilities: [b4] Vendor Specific Information: Len=14 <?>
    Capabilities: [100 v1] Virtual Channel
        Caps:   LPEVC=0 RefClk=100ns PATEntryBits=1
        Arb:    Fixed- WRR32- WRR64- WRR128-
        Ctrl:   ArbSelect=Fixed
        Status: InProgress-
        VC0:    Caps:   PATOffset=00 MaxTimeSlots=1 RejSnoopTrans-
            Arb:    Fixed- WRR32- WRR64- WRR128- TWRR128- WRR256-
            Ctrl:   Enable+ ID=0 ArbSelect=Fixed TC/VC=ff
            Status: NegoPending- InProgress-
    Capabilities: [128 v1] Power Budgeting <?>
    Capabilities: [600 v1] Vendor Specific Information: ID=0001 Rev=1 Len=024 <?>
    Kernel driver in use: nvidia
    Kernel modules: nvidia-current, nouveau, nvidiafb

01:00.1 Audio device [0403]: nVidia Corporation High Definition Audio Controller [10de:0be4] (rev a1)
    Subsystem: eVga.com. Corp. Device [3842:1242]
    Control: I/O- Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR+ FastB2B- DisINTx-
    Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
    Latency: 0, Cache Line Size: 64 bytes
    Interrupt: pin B routed to IRQ 19
    Region 0: Memory at fde7c000 (32-bit, non-prefetchable) [size=16K]
    Capabilities: [60] Power Management version 3
        Flags: PMEClk- DSI- D1- D2- AuxCurrent=0mA PME(D0-,D1-,D2-,D3hot-,D3cold-)
        Status: D0 NoSoftRst+ PME-Enable- DSel=0 DScale=0 PME-
    Capabilities: [68] MSI: Enable- Count=1/1 Maskable- 64bit+
        Address: 0000000000000000  Data: 0000
    Capabilities: [78] Express (v2) Endpoint, MSI 00
        DevCap: MaxPayload 128 bytes, PhantFunc 0, Latency L0s <4us, L1 <64us
            ExtTag+ AttnBtn- AttnInd- PwrInd- RBE+ FLReset-
        DevCtl: Report errors: Correctable- Non-Fatal- Fatal- Unsupported-
            RlxdOrd- ExtTag+ PhantFunc- AuxPwr- NoSnoop+
            MaxPayload 128 bytes, MaxReadReq 512 bytes
        DevSta: CorrErr- UncorrErr- FatalErr- UnsuppReq- AuxPwr- TransPend-
        LnkCap: Port #0, Speed 2.5GT/s, Width x16, ASPM L0s L1, Latency L0 <512ns, L1 <1us
            ClockPM+ Surprise- LLActRep- BwNot-
        LnkCtl: ASPM L0s L1 Enabled; RCB 128 bytes Disabled- Retrain- CommClk+
            ExtSynch- ClockPM+ AutWidDis- BWInt- AutBWInt-
        LnkSta: Speed 2.5GT/s, Width x16, TrErr- Train- SlotClk+ DLActive- BWMgmt- ABWMgmt-
        DevCap2: Completion Timeout: Not Supported, TimeoutDis+
        DevCtl2: Completion Timeout: 50us to 50ms, TimeoutDis-
        LnkCtl2: Target Link Speed: 2.5GT/s, EnterCompliance- SpeedDis-, Selectable De-emphasis: -6dB
             Transmit Margin: Normal Operating Range, EnterModifiedCompliance- ComplianceSOS-
             Compliance De-emphasis: -6dB
        LnkSta2: Current De-emphasis Level: -6dB
    Kernel driver in use: HDA Intel
    Kernel modules: snd-hda-intel

Answer: Out of hope, the last refuge of the desperate, I used Synaptic to re-install everything I could find for ALSA and Pulse Audio.
This fixed the problem.
Remember about hope, which is generally unreliable.
Answer: I think pulse audio is disabled on mythbuntu by default. Anyways you would need to ensure it is 48khz. Got to audio settings and enable advanced option. Select the force audio to 48khz option or it is something similar. This worked for me without reinstalling anything. It is digital out after all.
Comment: Occasionally the audio stops for all but mythtv, but switching to mythtv and playing something with audio, then switching back seems to fix that.  I'm suspecting npviewer.


I can't open Unity tweak tool

Question: I can't seem to open the [Unity][1] tweak tool, either from the launcher or dash or terminal. In the terminal, I got these errors:
    t***@t***-desktop:~$ unity-tweak-tool
Traceback (most recent call last):
<code> File "/usr/bin/unity-tweak-tool", line 72, in <module>

 UnityTweakTool.Application()
File "/usr/lib/python3/dist-packages/UnityTweakTool/__init__.py", line 79, in __init__
 executable_name=cmd_old.split('\x00')[1]
</code>
IndexError: list index out of range
How can I fix this problem?
Update
got another error from launching from terminal:
<code>WARNING **: Couldn't register with accessibility bus: Did not receive a reply. Possible causes include: the remote application did not send a reply, the message bus security policy blocked the reply, the reply timeout expired, or the network connection was broken.
Traceback (most recent call last):
File "/usr/bin/unity-tweak-tool", line 72, in <module>
UnityTweakTool.Application()
File "/usr/lib/python3/dist-packages/UnityTweakTool/__init__.py", line 79, in __init__
executable_name=cmd_old.split('\x00')[1]
IndexError: list index out of range
</code>
Comment: error like that, i usually do this: `sudo apt-get purge unity-tweak-tool && sudo apt-get autoremove` and then install it again: `sudo apt-get install unity-tweak-tool`
Comment: This was a [reported bug](https://bugs.launchpad.net/unity-tweak-tool/+bug/1258536). The fix has been released. Follow the method suggested by @blade19899
Comment: sorry, but that's not working, i've already tried it and tried once again now, i'm using 14.4 trusty, and do i need to add a seperate PPA to get the latest version?
Comment: What version of the unity tweak tool do you have installed?
Answer: Run bleachbit from terminal as SUDO and clear system cache.  I had the same problem and that resolved it.
Comment: Perhaps they need to install bleachbit first?
Comment: To improve this answer, you could add instructions of which commands are needed to install and then run bleachbit, perhaps also a screenshot of which option to select, etc.
Comment: no no no, i got bleachbit installed long before, what i did is that i reinstalled unity-tweak-tool and cleared system cache then restarted the system. sometime it works, sometime it wont works.
Comment: Clearly it worked....got the green check mark...THANK YOU! THANK YOU! THANK YOU!...WHO IS YOUR DADDY NOW BIIIOTCH?
Comment: Yes Seth, that is correct, he/she needed to install bleachbit first.  I was in such a rush to help out I omitted that.

I can't open Unity tweak tool


Priority Queue in R for OPTICS implementation

Question: I need to construct a priority queue in R where i will put the ordered seed objects (or the index of the objects) for the OPTICS clustering algorithm.

One possibility is to implement it with heap with the array representation, and pass the heap array in each insert and decrease key call, and return the changed array and reassign it in the calling function. In which case, the reassign operation will make the performance very poor and every time one insert or decrease operation is executed the entire array needs to be copied twice, once for calling, and another once for returning and reassigning.
Another possibility is to code the heap operations inside the function instead of calling it. This will result in code repetition and cumbersome code.
Is there any pointer like access as we do in C
Can i declare user defined functions in the S3 or S4 classes in R ? In the the case i think the call to these functions still requires the same reassignment after returning (not like C++/Java classes, operates on the object (am i right?) )
Is there any builtin way with which i can insert and extract an object in a queue in O(log(n)) time in R?
Is there any other way with which i can achieve the goal, that is maintain a priority based insertion and removal of the seeds depending on the reachability distance of an object in the OPTICS algorithm, except explicitly sorting after each insertion.
Comment: [R5 classes](https://github.com/hadley/devtools/wiki/R5) should allow you to avoid the copies when the object is modified.
Comment: Have you checked out this discussion: (http://firstname.lastname@example.com/msg108876.html)
Comment: nograpes: the queue implementation does not seems to be helpful for me. Vincent Zoonekynd: Looks like useful thing, much closer to C++/Java classes, need to have a detailed look.
Comment: @VincentZoonekynd: R5 classes are the thing i wanted. I can create objects and access its fields with the defined methods. Can you add it as an answer so that i can accept?
Answer: Note that you do not just need a priority queue.
It actually needs to support efficient updates, too. A simple heap is not sufficient, you need to synchronize a hashmap to find objects efficiently for updating their values. Then you need to repair the heap at the changed position.
Comment: This is exactly i found when i was designing the algorithm. Updating the keys in basic heap implementation are O(n + lg(n)) which defeats the purpose of using the heap for O(lg(n)) access. Can you shed any light on this for an R implementation by providing any document/resource?
Comment: Sorry, I don't use `R`. I only know the ELKI implementation of OPTICS, and it includes a pretty advanced heap, which is updatable in the way OPTICS needs it, and has some tricks for lazy heap building/repairing. For example, it seems to queue multiple "add" operations, then bulk-fixes the heap when actually needed. Your average heap will fix the heap on every add operation. Bulk loading a heap is O(n), fixing it incrementally is O(n log n). I don't know if this also holds for partial bulk operations.
Comment: At present i am just making the first iteration therefore i do not require lazy heap repair. In my case i am not inserting the objects in the heap, instead i am inserting the index of the object from the main array into the heap, therefore an auxiliary index array storing the location of the object index in the heap array is doing fine.
Answer: R5 classes
define mutable objects, and very similar to Java classes:
they should allow you to avoid the copies when the object is modified.


The 'correct' way to search for a string in a MySQL LongText field?

Question: I'm working on Nagios plugin to monitor our rsyslog server, which is back-ended into a MySQL database. The plugin operates by generating a unique string, sending it to syslog, and then querying the MySQL DB for the unique string, hence proving that the service is correctly receiving and storing messages.
The table is, unsurprisingly, big (~3.5 million rows, 2.1GB on disk), and in InnoDB format. The column holding the syslog messages is of type LONGTEXT.
I'm currently sending it queries of the form:
SELECT count(*) FROM allremote WHERE message LIKE '%check_rsyslogdb_1328869942%';

Where in this case check_rsyslogdb_1328869942 is the unique string logged by the plugin.
Is there a more efficient way for me to approach this query?
I looked into FULLTEXT indexes, but they are MyISAM only, and as a policy we avoid MyISAM because, it is, apparently, inferior.
Comment: http://stackoverflow.com/questions/1381186/fulltext-search-with-innodb
Comment: `select 1 from ...... limit 1` would help a bit. Instead of counting all matching rows we just find one match then return 1. If you get no result back it means no result found.
Comment: If you were to have a unique ID (auto_increment) then you can just check the rows since the last time you checked. So if you had ID 5000 last time you ran the check just put a condition to ensure the ID > 5000 before the string match condition.
Answer: It turns out that since I'm using MySQL 5.* I don't need to use a LONGTEXT, I can use a VARCHAR(2048) instead. This lets me create a normal index, and since I know the exact message, I can leave off the %s as long as I add in an extra trailing space at the end (not sure where that's coming from).


Calling a C function defined in another file

Question: I know this question has a lot of answers, but I am always getting an error on gcc c1.c
c1.c:(.text+0x5): undefined reference to `f'
collect2: error: ld returned 1 exit status

no matter what I try.
This is c1.c
#include <stdio.h>

#include "c.h"

int main()
{
    printf("F %d\n",f());
}

THis is c2.c
#include <stdio.h>

int f(void) {return 7;}

int main()
{
    printf("S %d\n",f());
}

This is c.h
int f(void);

How could I get it working? Actually, I was getting this error in a big program that is modelled like this. I guess this is the way to do it.
(And yes, main should return 0).
Answer: You're going to have problems, since you have two different main functions defined, but the general way to do this is a link-time issue:
gcc -c c1.c
gcc -c c2.c
gcc c1.o c2.o

All you need to do is figure out which main you want, and remove the unwanted one.
You could do something like:
gcc -Dmain=blah -c c1.c
gcc -c c2.c
gcc c1.o c2.o

Comment: c2.o: In function `main':
c2.c:(.text+0xb): multiple definition of `main'
c1.o:c1.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
Comment: Well, you really can't have two mains, can you?  If you want 'f' to be defined, put it in a file without a `main`.
Comment: Any way without putting it in a different file because the original program has a situation like this.
Comment: Use a preprocessor directive to redefine main.
Comment: BTW: *always* compile with `gcc -Wall -Wextra -g` (all warnings and debug info). Then learn how to use the debugger (`gdb`). At this point, you probably should learn how to use `make`. See [this](http://programmers.stackexchange.com/a/273582/40065)


A problem of Logarithm

Question: Find the minimum value of $$\frac{\log_bc}{\log a} + \frac{\log_ca}{\log b} + \frac{\log_ab}{\log c}$$
since I do not know how to write log base a index a so I gave it in that manner.
I tried out the problem and thought intuitively that the answer should be $1$ but cant find properly any reason.
Comment: upper log is like this $\log_b c$ and what is the base in denominator
Comment: Is anything else given? Like $\log a, \log b, \log c > 0$ or something?
Comment: @iostream007, why did you edit it this way? I am not sure what you wrote is correct. As for the the base is, it must be $e$ or $10$. But does it matter?
Comment: @soumyajit Am I edit it correctly?
Comment: @Soumajit, if you don't reply to any questions asked, obviously no one is gonna bother to answer your question.
Comment: @ParthThakkar In question he mentioned that he couldn't write base and index in log so he wrote in that way so I thought he wanted to write this.
Comment: Ok, then maybe I didn't understand him properly. But this is irritating, both of us are working at his problem and he isn't even interested.
Comment: @Soumajit, what are you intending to ask? please clarify, otherwise we can't answer.
Comment: I think, there must be some constraints on $a,b,c$ to get some interesting answer.
Comment: @iostream007 I suspect the intention was $\log_a (bc) + \log_b (ca) + \log_c (ab)$. That would lead to a classical minimisation problem.
Comment: @DanielFischer asker is not interested in replying so I'm not giving any effort
Comment: The OP may not have good Internet connection. Maybe has three kids and five cats and right now cannot reply. The good thing about this site is that your effort is not required for it to work.
Comment: the editing is wrong......
Comment: the thing is log in which base is a and index contains bc simmillarly the others....\
Comment: now i have found my solution......
Answer: The expression is the same as
$$\frac{\log(c)}{\log(a)\log(b)}+\frac{\log(a)}{\log(b)\log(c)}+\frac{\log(b)}{\log(a)\log(c)}$$
Fix $a$ and $b$, and make $c$ tend to $0$. What do you get?

A problem of Logarithm


Ruby on Rails route for wildcard subdomains to a controller/action

Question: I dynamically create URLs of the form username.users.example.com:
bob.users.example.com
tim.users.example.com
scott.users.example.com

All of *.users.example.com requests should go to a particular controller/action. How do I specify this in routes.rb?
All other requests to www.example.com go to the normal list of routes in my routes.rb file.
UPDATE: I watch the railscast about subdomains and it showed the following bit of code which would seem to be exactly what I need (changed the controller and subdomain):
match '', to: 'my_controller#show', constraints: {subdomain: /.+\.users/}

The problem is it only matches the root URL. I need this to match EVERY possible URL with a *.users subdomain. So obviously I would put it at the top of my routes.rb file. But how do I specify a catch-all route? Is it simply '*'? Or '/*'?
Comment: This railscast might help you : http://railscasts.com/episodes/221-subdomains-in-rails-3?autoplay=true
Comment: rails 3 rails 3.2 rails 4 hmhmmmm... which one exactly? just as a side-note, if you plan to have a lot of javascript, than keep in mind that ajax across subdomains is a PITA.
Comment: @phoet - I should've been more clear with the Rails versions. I'm using 3.2, but would upgrade to 4.0 if it meant this solution would be easier.
Comment: my recommendation would be: don't do it. but the railscast that @AmitThawait pointed you to is a perfect example. you can also have a look at a multitenacy example here: https://github.com/phoet/on_ruby/blob/master/config/routes.rb#L30
Comment: @phoet - what do you mean don't do it? Don't create my app that I want? Is there another solution?
Comment: @at. i would build an app that uses paths instead of subdomains whenever possible. there are so many constraints with cookies, javascript and ssl when it comes to domains...
Comment: @phoet - I need this because we sometimes need to change the DNS to point to a different system for individual users. The cookies/javascript/etc won't be an issue for my situation.
Comment: @AmitThawait - I watched a newer version of that Railscast, thanks. Updating my question based on it.
Comment: @at. if you look at the code i linked or the answer of @Amit you see that `constraints` is used to do exactly that.
Answer: I think, you just need to do the following :
create a class Subdomain in lib :
  class Subdomain
    def self.matches?(request)
      request.subdomain.present? && request.host.include?('.users')
    end
  end

and in your routes :
constraints Subdomain do
  match '', to: 'my_controller#show'
end

Answer: You can constraint route dynamically based on some specific criteria by creating a matches? method
Lets say we have to filter sub domain of URL
constraints Subdomain do
  get '*path', to: 'users#show'
end

class Subdomain
  def self.matches?(request)
    (request.subdomain.present? && request.subdomain.start_with?('.users')
  end
end

What we are doing here is checking for URL if it start with sub domain users then only hit users#show action. Your class must have mathes? method either class method or instance method. If you want to make it a instance method then do
constraints Subdomain.new do
  get '*path', to: 'proxy#index'
end

you can achieve same thing using lambda as well like below.
Instead of writing class we can also use lambdas
get '*path', to: 'users#show', constraints: lambda{|request|request.env['SERVER_NAME'].match('.users')}


uwsgi .ini param equivalents in nginx (500 errors on flask app)

Question: I have been attempting to move my flask code into uwsgi with nginx. It's gone through 502 (wrong socket filename) to 404 (default app 0 - not loading runable code in nginx config), to now a 500, and I have no info on why.

A) should uwsgi params be in nginx or uwsgi?
B) app name seems so picky all the time. is it just me?

Slowly but surely the modifications seem to be coming from problems in my uwsgi.ini or nginx.sites files, and I really just want someone to vet them and explain what's happening.
uwsgi.ini:
# can't these take over from nginx?
[uwsgi]
base = /home/aristatek/britishQueue
home = /home/aristatek/britishQueue
venv = /home/aristatek/britishQueue/clearable
socket = /home/aristatek/britishQueue/uwsgi.sock
chmod-socket = 666
wsgi-file = uwsgi.py
callable = application
daemonize=/home/aristatek/britishQueue/uwsgi.log
master = true
processes = 4
threads = 2

nginx config:
server {
    server_name intern.alpha.aristatek.com default_server;
    listen 80;
    location / {
        root /home/aristatek/britishQueue/srv/;
    }
    location /api/ { try_files $uri @britishQueue; }
    location @britishQueue {
        include uwsgi_params;
        uwsgi_param UWSGI_BASE /home/aristatek/britishQueue;
        uwsgi_param UWSGI_HOME /home/aristatek/britishQueue;
        uwsgi_param UWSGI_VENV /home/aristatek/britishQueue/clearable;
        uwsgi_param UWSGI_MODULE uwsgi;
        uwsgi_param UWSGI_CALLABLE application;
        uwsgi_pass unix:/home/aristatek/britishQueue/uwsgi.sock;
    }
}

uwsgi.py:
#!/usr/bin/env python
from britishQueue import webserve as application # why so picky all the time..

if __name__ == "__main__":
    application.run(host='0.0.0.0', port=6002, debug=True)

which one is supposed to properly help me start the server under uwsgi's control?
I've created a git branch with only the more relevant code if needed (and there's always the master branch): https://github.com/Thetoxicarcade/britishQueue/tree/flaskBug
edit (using production's log file):
*** Starting uWSGI 2.0.12 (64bit) on [Tue Jan 19 14:40:02 2016] ***
compiled with version: 4.8.4 on 13 January 2016 14:22:40
os: Linux-3.16.0-57-generic #77~14.04.1-Ubuntu SMP Thu Dec 17 23:20:00 UTC 2015
nodename: intern.alpha.aristatek.com
machine: x86_64
clock source: unix
pcre jit disabled
detected number of CPU cores: 8
current working directory: /home/aristatek/britishQueue/flask
detected binary path: /usr/local/bin/uwsgi
your processes number limit is 31835
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uwsgi socket 0 bound to UNIX address /home/aristatek/britishQueue/flask/uwsgi.sock fd 3
Python version: 2.7.6 (default, Jun 22 2015, 18:01:27)  [GCC 4.8.2]
Set PythonHome to /home/aristatek/britishQueue/clearable
Python main interpreter initialized at 0x1ab2c80
python threads support enabled
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 415360 bytes (405 KB) for 8 cores
*** Operational MODE: preforking+threaded ***
WSGI app 0 (mountpoint='') ready in 1 seconds on interpreter 0x1ab2c80 pid: 1148 (default app)
spawned uWSGI master process (pid: 1148)
spawned uWSGI worker 1 (pid: 1280, cores: 2)
spawned uWSGI worker 2 (pid: 1281, cores: 2)
spawned uWSGI worker 3 (pid: 1283, cores: 2)
spawned uWSGI worker 4 (pid: 1286, cores: 2)
[pid: 1286|app: 0|req: 1/1] 192.168.2.60 () {54 vars in 1147 bytes} [Tue Jan 19 14:40:14 2016] GET /api/v1.0/status/ => generated 291 bytes in 30 msecs (HTTP/1.1 500) 2 headers in 84 bytes (1 switches on core 0)
[pid: 1286|app: 0|req: 2/2] 192.168.2.60 () {54 vars in 1147 bytes} [Tue Jan 19 14:40:15 2016] GET /api/v1.0/status/ => generated 291 bytes in 1 msecs (HTTP/1.1 500) 2 headers in 84 bytes (1 switches on core 1)
[pid: 1286|app: 0|req: 3/3] 192.168.2.60 () {54 vars in 1147 bytes} [Tue Jan 19 14:40:15 2016] GET /api/v1.0/status/ => generated 291 bytes in 1 msecs (HTTP/1.1 500) 2 headers in 84 bytes (1 switches on core 0)

Comment: If you haven't already, I would suggest running uwsgi by itself and verifying that it can correctly serve your application before trying to integrate with nginx
Answer: Let's divide it to steps.
Built-in HTTP server
First, your application seems to have some built-in http server, let's run it. Just call python wsgi.py and on address 127.0.0.1:6002 will be your application (if you're doing it on remote server, replace 127.0.0.1 with his IP address).
This will help you narrow errors in application.
If this works fine, stop that application server (probably ctrl+c or ctrl+d).
uWSGI server
Now, when you're sure that app is working, let's try to put it behind uWSGI. Here is configuration that works for me every time:
chdir                   = /home/aristatek/britishQueue # put here directory, where you're storing your app code
uid                     = aristatek # username and groupname on which your app will be running (if you're running uWSGI as root, you really should do this, for security reasons)
gid                     = aristatek
auto-procname           = 1 # this 2 options will set user-readable name for your uWSGI processes, in this example each processname will be prefixed by your username and app name
procname-prefix-spaced  = [aristatek_britishQueue]

#chmod-socket            = 660 # this 2 options will ensure that your socket will be readable by user that is running app and uWSGI, no one else.
#chown-socket            = aristatek:www-data
#socket                  = /home/aristatek/britishQueue/uwsgi.sock
http                    = :8000
pidfile2                = /home/aristatek/britishQueue/uwsgi.pid

virtualenv              = /home/aristatek/britishQueue/clearable
workers                 = 4
threads                 = 2
master                  = true
module                  = wsgi # python path to your wsgi file, relative to main project dir
enable-threads          = 1

logger                  = file:/home/aristatek/britishQueue/uWSGI.log

After running that uWSGI server, go to 127.0.0.1:8000 in your browser. That should give your same results as running application built-in server. If not, check uWSGI logs (located in your project dir by default) for clue why it isn't working.
If uWSGI is working fine, uncomment in it's config lines with socket and comment http one (or remove).
nginx server
Here is my config for nginx to communicate with uWSGI app:
server {

    listen 80;
    server_name intern.alpha.aristatek.com default_server;

    client_max_body_size 4G;

    root /home/aristatek/britishQueue/srv/;

    location @britishQueue {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        include /etc/nginx/uwsgi_params;

        uwsgi_pass unix:/home/aristatek/britishQueue/uwsgi.sock;
        break;
    }

    location /api/ {
        try_files $uri @default;
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
        try_files /500.html /error.html /error500.html;
    }
}

And that's it, your app should be accessible on address intern.alpha.aristatek.com. If it's not, check nginx errors and if nginx is running on www-data user and group and if not, change groupname for uwsgi socket in your uWSGI config file.
Comment: Just got back. `python uwsgi.py` works fine, but running the uwsgi -i uwsgi process is slow and can only run using `module = britishQueue; callable = webserve`, and further beyond that nginx wasn't loading it, so I tried to use daemonize which doesn't work any more ('connect(): Permission denied [core/loggin.c line 276]'... But your advice is incredibly helpful and I thank you for that.
Comment: That means there is something wrong with wsgi part of your application. On what libraries is based on?
Comment: uwsgi --version gives 2.0.12, pip show uwsgi gives: Metadata-Version: 1.0
Name: uWSGI
Version: 2.0.12
Summary: The uWSGI server
Home-page: UNKNOWN
Author: Unbit
Author-email: email@example.com
License: GPL2
Location: /usr/local/lib/python2.7/dist-packages
Requires:
/usr/local/lib/python2.7/dist-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: (long error message)
Comment: I'm not asking about uWSGI but about your application that you're trying to run on top of uWSGI.
Comment: it seems to be that I goofed on the http port the application was running on, possibly, and that I can't call celery's .delay() method within uwsgi. Thank You for all your help :)
Answer: Uwsgi needs to be directly told to use an async-like method. In my case, that's:
[uwsgi]
plugins                 = python
virtualenv              = /home/aristatek/britishQueue/clearable
chdir                   = /home/aristatek/britishQueue/flask
module                  = britishQueue
callable                = webserve

uid                     = aristatek
gid                     = aristatek

#http                    = :6002
socket                  = /home/aristatek/britishQueue/flask/uwsgi.sock
chown-socket            = www-data:www-data
chmod-socket            = 666
pidfile2                = /home/aristatek/britishQueue/flask/uwsgi.pid
stats                   = /home/aristatek/britishQueue/flask/uwsgi.stats

#master                  = true
ugreen                  = true
async                   = 4
#workers                 = 4
#enable-threads          = 1
#threads                 = 4
#auto-procname           = 1
#procname-prefix-spaced  = [aristatek_britishQueue]

Which works fantastically and lets the threads that fail, fail on their own :)


A Recurrence Equation From a Game

Question: $a_n=a_{n-1}(a_{n}-a_{n-2}+1)$
The above equation is defined in $[0,m]$ st. $a_{0}=0$ and $a_m=1$. It turned up as I was trying to analyze a simple richman game.
I have managed to solve the equation as a system for small m's, however it becomes harder as m grows, even though the values seem to follow a nice distribution. I would quite like to know if there was a way to solve it, or perhaps approximate it using differential equations or similar.
Edit: This is a plot given $m=10$:

It is symmetric such that $a_{m-n}=1-a_{n}$
Comment: You are right. I was referring to the smooth shape of the plot above + the symmetry property. At least it doesn't seem like a sequence likely to do anything 'crazy'.
Comment: What do you mean by *nice distribution*? Sharing your thoughts here might help.
Answer: Write it as $a_n - a_{n-1} =a_n a_{n-1}-a_{n-1}a_{n-2}$.  Now you can telescope.
$$a_n - a_{n-1} =a_n a_{n-1}-a_{n-1}a_{n-2}$$
$$a_{n-1} - a_{n-2} =a_{n-1}a_{n-2}-a_{n-2}a_{n-3}$$
$$...$$
$$a_2 - a_1 =a_2 a_1-a_1 a_0$$
Summing all of that and simplifying you have $a_n  = \dfrac{a_1}{1-a_{n-1}}$ or $a_{n-1} = 1 - \dfrac{a_1}{a_n}$.  Thus $a_2 = \dfrac{a_1}{1-a_1}$ and $a_3 = \dfrac{1-a_1^2}{1-2a_1}$
Similarly, given $a_m = 1$, you have $a_{m-1} = 1-a_1$ and $a_{m-2} = 1 - \dfrac{a_1}{1-a_1} = \dfrac{1-2a_1}{1-a_1}$
Thus we can express every term in terms of $a_1$, in two ways depending on which path we take. To find $a_1$, we need to have the forward and backward paths meet at some point, equate the terms and solve the resulting equation.  However this doesn't look easy given the expressions coming up, unless we can use some symmetry in early terms itself.  Perhaps someone else can help more.
Comment: Your formula yields $a_{\frac{m}{2}+1}=2a_1$ for even $m$. As $a_{\frac{m}{2}+1}$ seems to be tending towards $\frac{1}{2}$ for large $m$s, it looks like $a_1$ tends towards $\frac{1}{4}$. Solving your $a_n=\frac{c}{1-a_{n-1}}$ in mathematica and letting c go towards $\frac{1}{4}$ gives the simple formula $\frac{n}{2+2n}$. This might be a good approximation for large $m$s if we combine it with the symmetry property.
Answer: @Thomas ahle: Did you solve it yet? Please show me your methods because I also met a similar problem above.
$\left\{\begin{matrix}
S_{n}=S_{n-1}+T_{n-1}\\
T_{n-1}=C_{n-3}+D_{n-4}\\
C_{n-3}=E_{n-4}+F_{n-4}\\
E_{n-4}=K_{n-5}+T_{n-5}\\
F_{n-4}=E_{n-7}+D_{n-7}\\
D_{n-7}=H_{n-8}+F_{n-8}\\
H_{n-8}=S_{n-11}+C_{n-11}\\
K_{n-5}=S_{n-7}+C_{n-8}
\end{matrix}\right.$
Now, I'm trying to solve it by matrix form but it is so hard. Particularly, find generating matrix and characteristic polynomial.

A Recurrence Equation From a Game


About condition of homomorphism between $\mathbb{Z}[G]$-modules (free as $\mathbb{Z}$-module) factors through free $\mathbb{Z}[G]$-module

Question: I came across an exercise in Alexander Beilinson's note refered by Tom here.
The exercise is:
Let $G$ be a finite group, M and N be $\mathbb{Z}[G]$-module that is free as $\mathbb{Z}$-module.
Show following are equivalent for $\mathbb{Z}[G]$-homomorphism $f:M\to N$.
(a) There is a $\mathbb{Z}$-homomorphism $h:M\to N$ and $f(x)=\sum_{g \in G}ghg^{-1}(x)$.
(b) There is a free $\mathbb{Z}[G]$-module $R$ and $f$ can factored by two  $\mathbb{Z}[G]$-homomorphism $f_1:M \to R$ and $f_2:R \to N$.

I observed an example $G=\{g,g^2,g^3,g^4,g^5,g^6=1\}, M=N=\mathbb{Z}^2, g(a,b)=(a,-b)$, so $g^2m=m, h(a,b)=(a,b), f(a,b)=3(a,b)+3(a,-b)$ to construct below.
My solution:
Let $m_1,m_2,..$ be the generators of $M$ as $\mathbb{Z}$-module.
Let $ H_k =  \{ g|\ g(m_k)=m_k \}$.
Assume (a).
Take $r_1$ as the first generator of $R$ and define $f_1(m_1) = \sum_{g \in H_1} g(r_1)$, and $f_2(r_1)= |G/H_1| \cdot h(m_1)$. This satisfy (b) for $m_1$, and thus for any $m \in M$ generated by $m_1$, by compatibility of $\mathbb{Z}[G]$-module.
If there remains any generator $m_k$ not generated by $m_1$, repeat this as:
Take $r_k$ as a new generator of $R$ and define $f_1(m_k) = \sum_{g \in H_k} g(r_k)$, and $f_2(r_k) = |G/H_k| \cdot h(m_k)$.
Assume (b).
For $g \in H_1$, $f_1(m_1) = f_1(g(m_1)) = g(f_1(m_1))$. So $f_1(m_1)$ can be write as $\sum_{g \in H_1} g(r_1)$ by some $r_1 \in R$. Then take a representative coset $G/H_k$ and define $h(g(m_1))=f_2(g(r_1))$ if $g \in G/H_k$ and $h(g(m_1))=0$ otherwise. This satisfies (a).
If there remains any generator $m_k$ not generated by $m_1$, repeat this.
Question:
(1) I have a concern in my argument. For example if I take $m_1=(1,1),m_2=(0,1)$, the first step defines $f_1(m)$ for every $m = s(1,1)+t(1,-1)$ where $s,t \in \mathbb{Z}$. The second step is to define $f_1(m_2)$ but $f_2(2m_2)=f_2(0,2)$ have already defined in the first step, so it is not trivial whether I can make them compatible in such situation. Is there some way to fix this problem?
(2) I think I essentially decomposed $M$ into some irreducible modules. But I am not sure I can generally decompose $M = M_1 \oplus M_2 \oplus...$ such that each $M_k$ is free as $\mathbb{Z}$ module, especially of the form $M_k = \mathbb{Z}^{|G/H_k|}$ where $ H_k =  \{ g|\ g(m_k)=m_k \}$.
Is there some counterexamples?
[Edit] How about injecting $M$ into $M'=M\otimes \mathbb{Q}$ and decompose $M' = M'_1 \oplus M'_2 \oplus...$ such that $M'_k$ is irreducible and free as $\mathbb{Q}$ module and then take $M_k = M'_k \cap M$? (I don't have much experience with module over group)
(3) I appreciate any related information.

EDIT (observation after the answer)
I made some observation based on the answer. They gave good experience for me.
The condition (a) can be described as $M \to N$ can be factored into
$M \to \mathbb{Z}[G] \otimes M \to \mathbb{Z}[G] \otimes N \to N$,
$m \to \sum g \otimes g^{-1}(m)$, $1 \otimes m \to 1 \otimes h(m)$, $g \otimes n \to g(n) $.
Then (a)⇒(b) is obvious.
For the inverse implication, I noticed free $\mathbb{Z}[G]$-module $R$ is injective module and $M \to \mathbb{Z}[G] \otimes M$ is injective, so $M \to R$ factors through $\mathbb{Z}[G]\otimes M$. Similarly, $R$ is projective module and $\mathbb{Z}[G] \otimes N \to N$ is surjective so $R \to N$ factors through $\mathbb{Z}[G]\otimes N$.
It remains to show that I can factor them so that the $\mathbb{Z}[G] \otimes M \to \mathbb{Z}[G] \otimes N$ sends $1 \otimes m \to 1 \otimes h(m)$ for some $h$. I could comfirm this directly, and I also noticed this describes the bijection
$ {\mathrm{Hom}}_{\mathbb{Z}[G]} (\mathbb{Z}[G] \otimes M, N) \cong {\mathrm{Hom}}_{\mathbb{Z}} (M,N)$ obtained from forgetful and free adjoint functors between $\mathbb{Z}$-mod category and $\mathbb{Z}[G]$-mod category.
Comment: Are you assuming you can divide when you write $f_1(m_1)=\sum_{g\in H_1} gr_1$?
Comment: @aerile - $(2)$: Over a field of characteristic zero any finite group $G$ is "linearly reductive" in the sense that for any inclusion of $G$-modules $V \subseteq W$ there is a complementary module  $(*) V\oplus V' \cong W$. This does not hold for modules over $\mathbb{Z}[G]$. You use the Reynolds operator to construct the complementary module $V'$, and this exists over a field, not over $\mathbb{Z}$.
Answer: Here is a simple solution.
(a)$\implies$(b):
Regard $\mathbb{Z}[G]\otimes_\mathbb{Z}N$ as a free $\mathbb{Z}[G]$-module by
$$
g(x\otimes n)=(gx)\otimes n.
$$
Define a $\mathbb{Z}[G]$-module homomorphism $f_1\colon M\to \mathbb{Z}[G]\otimes_{\mathbb{Z}}N$ by
$$
f_1(m)=\sum_{g\in G}g\otimes h(g^{-1}m),
$$
and $f_2\colon \mathbb{Z}[G]\otimes_{\mathbb{Z}}N \to N$ by
$$
f_2\biggl(\sum_{g\in G}g\otimes n_g\biggr) = \sum_{g\in G}gn_g.
$$
Then we have $f_2\circ f_1 = f$, so (b) holds.
(b)$\implies$(a):
We can write $R\simeq \mathbb{Z}[G]\otimes_\mathbb{Z}L$ where $L$ is a free $\mathbb{Z}$-module.
Define $\mathbb{Z}$-module homomorphisms $h_g\colon M\to L\;(g\in G)$ by
$$
f_1(m)=\sum_{g\in G}g\otimes h_{g^{-1}}(m).
$$
Since $f_1$ is a $\mathbb{Z}[G]$-module homomorphism, we have $h_g(m)=h_e(gm)$.
Therefore we can write
$$
f(m)=\sum_{g\in G}gf_2(h_e(g^{-1}m)),
$$
so (a) is satisfied for $h=f_2\circ h_e$.


Ripped off paint on bathtub

Question: The paint on my bathtub has been ripped off so much like this:

What should I do to fix this?
Comment: The paint was already a fix. You'll need to strip it completely or replace the tub.
Comment: @isherwood Replacing the tub will probably cost too much. If I strip it off, what should do next?
Comment: Maybe just get a big inside-tub bath mat.
Comment: ... or wear a blindfold whenever you're taking a shower.
Answer: Assuming this is a cast-iron tub in decent condition below the surface, it can be refinished to look like new. Here's an article from This Old House that explains one process. There are likely vendors who will come to your house to refinish the tub, as well as DIY products. For any repair approach, it's vital to properly prepare the surface by removing the prior paint attempt, patching any deep scratches, and sanding thoroughly to ensure good bonding of the new enamel.
Comment: @JimmyFix-it, thanks - I didn't mean to suggest the homeowner needs to do the prep, just that proper prep is vital and you can't just paint on a new layer. I've edited the answer so it doesn't suggest anything about whose responsibility the prep is.
Comment: Most contractors providing tub refinishing prepare the surface themselves as part of the job. In fact, if OP prepares it he will probably be charged the same as if he did not.
Answer: Companies do recoat tubs much cheaper than replacement.
The problem is the tub is porcelain, Paint usually won't last long.
Here is one product that states it works on porcelain.
There are other products this is just 1.

Ripped off paint on bathtub


inside security door

Question: EDIT:   Sorry, I didn't realize I couldn't ask this question.  It is in a commercial type setting (it is a non-profit and seperates a living area from another area).
I need to know what kind of door handle to look for.  We have a door access program that uses keyfobs to open the doors.  We also need to be able to use a key from both sides of the door (double keyed) in case the power goes out.  I need the door to open only, not unlock. Any idea what kind of hardware I need to look for?
Comment: Is this in a home or somewhere else? Requiring a key (electronic or otherwise) to exit is unusual, and dangerous.
Comment: I'm voting to close this question because this sounds like a commercial installation (without any evidence from the OP that it isn't), and commercial work is off-topic.
Comment: Could you provide a picture of the door you're asking about?  Commonly we call a door with a handle that doesn't operate the latch a *passage* door, but a picture would help immensely.
Comment: Please revise your post title to ask a clear, _specific_ question. Take the [tour] for tips. I'd make an effort to do it myself but I'm not sure I understand your question.
Comment: If the door needs to remain locked from the inside, you need to seriously consider a "crash bar" type for the inside to allow occupants to exit in a panic (like when there's a fire) so they don't have to fumble with a key.
Answer: You already know you can't just push a locked door open, because a thing in the door (the latch) is blocking a thing in the wall (the strike).  And of course you know normally, you open the door by having the latch retract.  Well, there's a way to have the strike retract instead!   So now, either way can open the door.
That is called an electric strike.
You have your badge system operate the strike electrically... and your key system operate the latch mechanically.
This is a very common way badge entry systems are set up.  If the electric strike is stone dead, the latch can still be retracted the old-fashioned way.
Comment: Snark free interpretation: Any old keyed door knob/latch will do the trick, since all the key is doing is retracting the latch and it has nothing to do with the electronic operation. (snark not totally inappropriate in this situation). +1

inside security door


Is it safe to test electrical bonding of natural gas pipes with a multimeter resistance test?

Question: I would assume the currents and voltages produced by a consumer grade multimeter (testing electrical resistance) would not be large enough to produce any danger of natural gas combustion. But I was curious if CSST piping in my home was electrically bonded across its fittings to the manifold (and from the manifold to the black iron gas pipes). As there is conflicting information on the internet about where it is necessary to bond yellow CSST piping (one clamp on the manifold vs one clamp on the fitting for each run of CSST piping).
However, I could not find information online about the safety of using a multimeter in this way, and as I don't fully understand the exact mechanics of how a multimeter measures electrical resistance, I figured I shouldn't just try it, even though I'd assume it's likely fine, and that things are in the millivolt and milliamp range. I've also seen situations where multimeters behaved in unexpected ways and arc flashed, but I think that mostly involves cheap meters and mains voltages.
Comment: A relevant previous question on the site:  https://diy.stackexchange.com/questions/221839/bonding-gas-piping-flexible-csst-in-conjuction-with-iron-pipe
Comment: The incidents you saw likely involved setting the multimeter to current mode and then connecting it to mains voltage.
Comment: From the 2021 Oregon specialty plumbing code: "The bonding jumper shall connect to a metallic pipe, pipe fitting, or CSST fitting. [NFPA 54:188.8.131.52]"
Answer: you can't set the gas inside the pipes on fire, and unless there's a leak there shouldn't be any gas outside the pipes.
The test is safe, most multimetes test resistance at very low power. but a multimeter resistance test is probably not sufficient to be sure that the ground bonding is good, but it will in many instances detect deficient ground bonding.
Comment: Understandable! Could you expound on what additional tests would be sufficient to confirm proper bonding?
Comment: you use a ground bonding tester,  a device costing several thousand dollars.
Comment: Just splitting hairs for fun (I do not wish to buy or rent a ground bonding tester). But a ground bonding tester in this situation would probably be unsafe to use, at the very least until the gas lines were evacuated, as its improved stringency comes from (and I may be wrong) the larger amount of current that would likely melt and possibly arc across points of weak continuity? In addition, the stringency also comes from testing the capacitance and induction of the system?
Answer: Yes, this is safe. A multimeter on resistance mode doesn't put out enough voltage to cause a spark even under the most extreme circumstances.
Answer: As @percynthion wrote, doing a resistance check cannot put out enough voltage to cause a spark.
However, first check for AC voltage. If you have a bad ground and no bond, there could already be AC voltage there. Such voltage could damage your multimeter when checking resistance.
Comment: @doxylover, only cheap brands. quality brands can withstand hundreds of unexpected volts during a resistance test.
Comment: Having 120 Volt on the gas line would be EOL
Comment: @Ruskes Not necessary full 120 volts. A poor ground giving 20 volts AC would be plenty to fry a multimeter set to measure resistance.
Comment: Only if gas lines are used as grounding rod
Comment: i 2nd jasen on that, i've accidently measured the resistance of live mains, which for the curious read "OL"...


iOS UIView drawRect resize animation

Question: I tried to override the drawRect method in a simple UIView extension to draw a rectangle with rounded edges and fill it with black color, and also animate the view to resize on touch.
The thing is, resizing completely deforms the drawing, as if the context remains the same for the whole time. drawRect is never called during the animation.. However, if I tell the view to draw itself after the animation it gets drawn correctly.
How can I animate the resizing without the drawing becoming deformed?
- (void)drawRect:(CGRect)rect {
  CGContextRef context = UIGraphicsGetCurrentContext();
  CGFloat radius = rect.size.height * 0.5f;

  CGMutablePathRef path = CGPathCreateMutable();

  CGPathMoveToPoint(path, NULL, CGRectGetMidX(rect), CGRectGetMinY(rect));
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect),
                  CGRectGetMaxX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMaxY(rect),
                  CGRectGetMinX(rect), CGRectGetMaxY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect),
                  CGRectGetMinX(rect), CGRectGetMinY(rect), radius);
  CGPathAddArcToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect),
                  CGRectGetMaxX(rect), CGRectGetMinY(rect), radius);
  CGPathCloseSubpath(path);

  CGContextSaveGState(context);
  CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
  CGContextAddPath(context, path);
  CGContextFillPath(context);
  CGContextRestoreGState(context);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, -100.f);
  }];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
  [UIView animateWithDuration:1.f animations:^{
    self.frame = CGRectInset(self.frame, 0.f, +100.f);
  }];
}

Comment: I wild guess here http://www.nomadplanet.fr/2010/11/animate-calayer-custom-properties-with-coreanimation/
Answer: If you want rounded edge for a UIView you don't need to explicitly redefine the drawRect. There is a simpler way which consist to change the layer property of your UIView. Your view and its border will correctly be drawn during your animation.
// Make your view background color black
myView.backgroundColor = [UIColor blackColor];

// The following will allow you to change the color/border width/ corner radius of your UIView
myView.layer.borderColor  = [UIColor whiteColor].CGColor;
myView.layer.borderWidth  = kDefaultBorderWidth;
myView.layer.cornerRadius = kDefaultBorderRadius;

make sure you have include the #import <QuartzCore/QuartzCore.h> in your .m file and you have imported the QuartzCore.framework
Comment: Agreed - and make sure you set `myView.clipsToBounds = YES;`.
Comment: Yes, but what if I want to draw some custom effects on that rounded rectangle?
Comment: What kind of other effect you would like to achieve - my answer was related to your question...
Comment: http://stackoverflow.com/questions/9000376/animate-a-uiviews-coregraphics-drawrect-content according to this post drawrect only work for one point in time so there is no way it will work with animation

iOS UIView drawRect resize animation


PHP Prepared Statement SQL with where value

Question: I am trying to run this query on an existing row in sql table:
if($stmt = $mysqli->prepare("INSERT INTO 4rounds (player2_name, player2_army1_name, player2_army2_name, player2_army3_name, player2_army4_name, player2_identifier, player2_stage, player2_army1_position, player2_army2_position, player2_army3_position, player2_army4_position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) WHERE pairing_id = ?")) {

but it returns the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE pairing_id = ?' at line 1

The query works without the WHERE clause. I think there is a problem with binding the parameter in this matter and I should use VALUE as well to bind it later but I can't seem to find anything online about binding a param in this manner.
These are the binds I am trying with:
$stmt->bind_param("ssssssssssss", $player2_name, $player2_army1_name, $player2_army2_name, $player2_army3_name, $player2_army4_name, $player2_identifier, $player2_stage, $player2_army1_position, $player2_army2_position, $player2_army3_position, $player2_army4_position, $pairing_id);

Comment: INSERT statements don't have WHERE clauses - you may want to look at UPDATE instead.
Answer: INSERT statements don't have WHERE clauses, and I'm not sure why you would want such a thing... Those only exist in SELECT and UPDATE queries, typically.


Proof that $\lim_{n\to\infty}\|x_n-x\|=0$ with weak convergence

Question: I want to prove that in a normed linear space $H$, that if $x_n$ is weak convergent to $x$, and $\lim_{n\to\infty} \|x_n\| = \|x\|$ then:
$$\lim_{n\to\infty}\|x_n-x\|=0$$

Can I please have a hint? Also does $\langle x,x\rangle^{\frac12}=\|x\|$ or something?

The impression I have is, essentially $\lim_{n\to\infty}\|x_n\|-\|x\|=\lim_{n\to\infty}\|x_n - x\|$ due to the weak convergence, otherwise in the general case:
$$\|x\|-\|y\|=\|x - y\|$$ could be true, but only if they are in opposite directions.

My definition of weak convergence is $\lim_{n\to\infty} \langle x_n,y\rangle =\langle x,y\rangle$, so I suspect that this is a hilbert space.
Comment: Really important: is this a Hilbert space?
Comment: There is generally no relationship between $\langle x,y \rangle^{1/2}$ and $\|y-x\|$
Comment: Hmmm I suspect so based on weak convergence, but it isn't specified
Comment: @Omnomnomnom See edit, sorry
Comment: Weak convergence makes perfect sense in Banach spaces. But if you are in a Hilbert space, we can prove the claim quite easily.
Comment: @bartgol I edited in my definition of weak convergence at the end. Since it is an inner product, I suspect it is an inner-product space, but without completeness I don't know
Comment: @Bartgol: Does weak convergence together with $\left\|x_{n}\right\|\rightarrow\left\|x\right\|$ imply strong convergence in any arbitrary Banach space $X$? If $X$ is reflexive, then it would seem true by simple modification of the Hilbert space proof.
Comment: @MattRosenzweig Consider $u_n(x)=1+\sin(nx)$ for $x\in(0,2\pi)$. Then $u_n\to u\equiv 1$ weakly in $L^1(0,2\pi)$ and $\|u_n\|=\|u\|$ for all $n$, but $u_n$ does not converge to $u$ in $L^1$ norm.
Comment: @ByronSchmuland: Thanks. I believe I may have mispoke too about the radon-riesz property holding in a reflexive Banach space.
Comment: @MattRosenzweig I think it would for the reflexive case, using the canonical isometric isomorphism from $X$ to $X^{**}$ and some corollary of the Hanh-Banach theorem... For the general Banach space case, I have the feeling it would fail, but I haven't thought deeply about it...
Comment: @Bartgol: See the comments to Hamza's answer below.
Answer: This property is called "(H)" property and the space is called a "Radon Riesz" space.
As example of this space we can say every Hilbert space as the proof given by @bartgol and $L^p$ for $1<p<\infty$, and schur space (in particular $\ell^1$).
Comment: Thank you for this nice paper. Just for reference: The counterexample is the following: Take $X = (\mathbb{R^2}, \|\cdot\|_{\ell^1})$. Then, $L^2(0,1;X)$ is a counterexample.
Comment: Does look extremely relevant, thanks!
Comment: Is there a simple counterexample of a reflexive Banach space that does not have the Radon-Riesz property?
Comment: This link? https://en.wikipedia.org/wiki/Radon%E2%80%93Riesz_property
Comment: @Hamza Thanks for this. I knew there was a name for this, but I'd forgotten it!
Comment: such example can be found in SMITH and TURETT paper : "ROTUNDITY IN LEBESGUE-BOCHNER FUNCTION SPACES" page 113.
http://www.ams.org/journals/tran/1980-257-01/S0002-9947-1980-0549157-4/S0002-9947-1980-0549157-4.pdf
Comment: I was not aware of Radon-Riesz spaces. Thanks for the link! Do you think/know if it is possible to say that every reflexive space is a Radon-Riesz space (I'm thinking exploiting some corrollary of the Hanh-Banach theorem)?
Comment: @bartgol, the above counter-example is reflexive. However, it seems that uniformly convex spaces should fall into this class.
Answer: Ok, assuming you are in a Hilbert space (otherwise I think we must use Hanh-Banach), you can simply consider the functional
$$
F(x_n) = \langle x_n,x \rangle
$$
and see what happens when $n\to\infty$.
Then what happens to $\|x-x_n\|^2=\langle x-x_n,x-x_n\rangle$?
Edit: yes, in any Hilbert space, by definition, $\|x\|^2 = \langle x,x \rangle$.
Comment: Thanks, I'll see what I can do.(I'll upvote after I get sufficient rep)


Finding the angle between vectors

Question: What is the difference between
$\cos(\theta) = \frac{(v \cdot u) }{( \|v\| \|u\| )}$
and
$\cos(\theta) = \frac{|(v\cdot u)|}{( \|v\| \|u\| )}$
I noticed that my textbook uses simply the value of the dot product of vectors $v$ and $u$ for vectors with only $x$ and $y$ components but the absolute value of the dot product for vectors with $x, y$, and $z$ components. I would like to know why this is.
Comment: The sign tells you the orientation of $v$ with respect to $u$.
Comment: *I noticed that my textbook uses* -- Which textbook is this?
Answer: Note that both $u$ and $v$ are vectors. Since the absolute value is the non-negative form of that value, the absence and addition of the modulus is related to direction of the vectors. For example, take $-u$ and $v$ (or $u$ and $-v$). From the diagram below, the vectors $v$ and $w$ are in different directions in the first quadrant. Changing the sign of $v$ would move it into the second quadrant.
Answer: $\vec v = a \hat i + b \hat j$
$\vec u = c \hat i + d \hat j$
Angle of $\vec v = \theta = \arctan \frac{b}{a}$
Angle of $\vec u = \phi = \arctan \frac{d}{c}$
Adjusting for quadrants as required ...
The angle between $\vec v$ and $\vec u$ = $\theta - \phi$
Answer: Given vectors $v$ and $u$,

$\theta=\cos^{-1}\frac{v \cdot u }{ \|v\| \|u\| }$ is the angle between $v$ and $u$; while
$\mu=\cos^{-1}\frac{|v \cdot u |}{ \|v\| \|u\| }$ is the non-obtuse angle between $v$ and $u$.

We always have $\theta\in[0,\pi]$ and $\mu\in[0,\pi/2]$.
If $\theta\in[0,\pi/2]$, then $\mu=\theta$.
If $\theta\in(\pi/2,\pi]$, then $\mu=\pi-\theta$.

Example 1: $\beta=\cos^{-1}\frac{\mathbf c \cdot \mathbf d }{ \|\mathbf c\| \|\mathbf d\| }$ is the angle between $\mathbf c$ and $\mathbf d$, while $\alpha=\cos^{-1}\frac{|\mathbf c \cdot \mathbf d |}{ \|\mathbf c\| \|\mathbf d\| }$ is the non-obtuse angle between $\mathbf c$ and $\mathbf d$.

Example 2: $\gamma=\cos^{-1}\frac{\mathbf e \cdot \mathbf f }{ \|\mathbf e\| \|\mathbf f\| }=\cos^{-1}\frac{|\mathbf e \cdot \mathbf f |}{ \|\mathbf e\| \|\mathbf f\| }$ is both the angle and the non-obtuse angle between $\mathbf e$ and $\mathbf f$.

I noticed that my textbook uses simply the value of the dot product of vectors $v$ and $u$ for vectors with only $x$ and $y$ components but the absolute value of the dot product for vectors with $x, y$, and $z$ components. I would like to know why this is.

This is strange and I'm not sure why this would be. But not knowing which textbook this is and what you're referring to, I can't answer this.

Finding the angle between vectors


Firmware/Bios update and no sound on ubuntu 20.04

Question: My laptop is a Dell Vostro 5490
After a firmware update that was made from Ubuntu Software Center I have no sound from speakers, although when I use a usb headphones/microphone I get sound.
arecord -l
arecord: device_list:276: no soundcards found...

lspci
00:00.0 Host bridge: Intel Corporation Device 9b61 (rev 0c)
00:02.0 VGA compatible controller: Intel Corporation UHD Graphics (rev 02)
00:04.0 Signal processing controller: Intel Corporation Xeon E3-1200 v5/E3-1500 v5/6th Gen Core Processor Thermal Subsystem (rev 0c)
00:08.0 System peripheral: Intel Corporation Xeon E3-1200 v5/v6 / E3-1500 v5 / 6th/7th/8th Gen Core Processor Gaussian Mixture Model
00:12.0 Signal processing controller: Intel Corporation Comet Lake Thermal Subsytem
00:13.0 Serial controller: Intel Corporation Comet Lake Integrated Sensor Solution
00:14.0 USB controller: Intel Corporation Device 02ed
00:14.2 RAM memory: Intel Corporation Device 02ef
00:14.3 Network controller: Intel Corporation Wireless-AC 9462
00:15.0 Serial bus controller [0c80]: Intel Corporation Serial IO I2C Host Controller
00:16.0 Communication controller: Intel Corporation Comet Lake Management Engine Interface
00:17.0 SATA controller: Intel Corporation Comet Lake SATA AHCI Controller
00:1c.0 PCI bridge: Intel Corporation Device 02bc (rev f0)
00:1d.0 PCI bridge: Intel Corporation Device 02b0 (rev f0)
00:1d.4 PCI bridge: Intel Corporation Device 02b4 (rev f0)
00:1f.0 ISA bridge: Intel Corporation Device 0284
00:1f.3 Multimedia audio controller: Intel Corporation Device 02c8
00:1f.4 SMBus: Intel Corporation Device 02a3
00:1f.5 Serial bus controller [0c80]: Intel Corporation Comet Lake SPI (flash) Controller
01:00.0 3D controller: NVIDIA Corporation GP108M [GeForce MX250] (rev a1)
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 15)
03:00.0 Non-Volatile memory controller: SK hynix Device 1339

I have tried also to reinstall alsa and pulseaudio but that did not work.
I have tried updating over and over again via Ubuntu software Center but it keeps coming back each time

For fwupdmgr
# fwupdmgr get-devices
Vostro 5490
│
├─BC511 NVMe SK hynix 512GB:
│     Device ID:          3743975ad7f64f8d6575a9ae49fb3a8856fe186f
│     Summary:            NVM Express solid state drive
│     Current version:    11004101
│     Vendor:             SK hynix (NVME:0x1C5C)
│     Serial Number:      SN9AN91721090B50M
│     GUIDs:              71575487-e6fa-52be-a95f-62cd22ec72fc ← STORAGE-DELL-108787
│                         8811e962-e1d5-e811-9f8b-f2801f1b9fd1
│     Device Flags:       • Internal device
│                         • Updatable
│                         • System requires external power source
│                         • Supported on remote server
│                         • Needs a reboot after installation
│                         • Device is usable for the duration of the update
│                         • Signed Payload
│
├─System Firmware:
│ │   Device ID:          a45df35ac0e948ee180fe216a5f703f32dda163f
│ │   Summary:            UEFI ESRT device
│ │   Current version:    1.3.0
│ │   Minimum Version:    1.3.0
│ │   Vendor:             Dell (DMI:Dell Inc.)
│ │   Update State:       Failed
│ │   Update Error:       failed to update to 0: invalid firmware format
│ │   GUIDs:              f90be13c-2383-47bc-936f-4b7ba031ec69
│ │                       230c8b18-8d9b-53ec-838b-6cfc0383493a ← main-system-firmware
│ │   Device Flags:       • Internal device
│ │                       • Updatable
│ │                       • System requires external power source
│ │                       • Supported on remote server
│ │                       • Needs a reboot after installation
│ │                       • Cryptographic hash verification is available
│ │                       • Device is usable for the duration of the update
│ │
│ └─UEFI dbx:
│       Device ID:        362301da643102b9f38477387e2193e57abaa590
│       Summary:          UEFI revocation database
│       Current version:  238
│       Minimum Version:  238
│       Vendor:           UEFI:Linux Foundation
│       Install Duration: 1 second
│       GUIDs:            00fe3755-a4d8-5ef7-ba5f-47979fbb3423 ← UEFI\CRT_E28D59CA489BD2AD580F2EA5D62D6A29BB9C02AE5A818434A37DA7FC11DFF9E9
│                         4a6cd2cb-8741-5257-9d1f-89a275dacca7 ← UEFI\CRT_E28D59CA489BD2AD580F2EA5D62D6A29BB9C02AE5A818434A37DA7FC11DFF9E9&ARCH_X64
│                         c6682ade-b5ec-57c4-b687-676351208742 ← UEFI\CRT_A1117F516A32CEFCBA3F2D1ACE10A87972FD6BBE8FE0D0B996E09E65D802A503
│                         f8ba2887-9411-5c36-9cee-88995bb39731 ← UEFI\CRT_A1117F516A32CEFCBA3F2D1ACE10A87972FD6BBE8FE0D0B996E09E65D802A503&ARCH_X64
│       Device Flags:     • Internal device
│                         • Updatable
│                         • Needs a reboot after installation
│                         • Only version upgrades are allowed
│                         • Signed Payload
│
└─TPM 2.0:
      Device ID:          a3487e128cf1413519bce8e9a1ab3f5981e61458
      Summary:            UEFI ESRT device
      Current version:    188.8.131.52
      Vendor:             Dell Inc. (PCI:0x1028)
      Update State:       Success
      Update Error:       Updating disabled due to TPM ownership
      GUIDs:              894074d4-d977-5b30-9d19-b2031c86103b ← 0959-2.0
                          ff71992e-52f7-5eea-94ef-883e56e034c6 ← system-tpm
                          7d65b10b-bb24-552d-ade5-590b3b278188 ← DELL-TPM-2.0-NTC-NPCT
                          6f5ddd3a-8339-5b2a-b9a6-cf3b92f6c86d ← DELL-TPM-2.0-NTC-NPCT75x
                          fe462d4a-e48f-5069-9172-47330fc5e838 ← DELL-TPM-2.0-NTC-NPCT75xrls
      Device Flags:       • Internal device
                          • System requires external power source

________________________________________________

Devices that were not updated correctly:

 • System Firmware (1.3.0 → 1.23.0)

Devices that have been updated successfully:

 • BC511 NVMe SK hynix 512GB (11001101 → 11004101)

If I reboot then I see that BIOS version is on version 1.23.0
I ve booted with live usb either ubuntu 22.04 or 23.04 and I still have Dummy Output and no soundcard.
Any ideas?
Answer: I was able to fix the problem with the solution provided here
https://askubuntu.com/a/1295435/1072868
Added /etc/default/grub to be:
GRUB_CMDLINE_LINUX="snd-intel-dspcfg.dsp_driver=1"

And then executed
sudo update-grub


Data entity insert : An item with the same key has already been added

Question: I know this question has been asked many times and after going through posts, I believe it has something to do with entity name, but I am completely new to data entity model and while trying to do a simple insert of a blog entry with blog details, I encountered this problem.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: An item with the same key has already been added.

Source Error:

Line 365:    public void AddToblogs(blog blog)
Line 366:    {
Line 367:        base.AddObject("myblogs", blog);
Line 368:    }
Line 369:

Source File: C:\Inetpub\int422_113b16\webcontent\App_Code\blogModel.cs    Line: 367

Stack Trace:

[ArgumentException: An item with the same key has already been added.]
   System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) +52
   System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) +9382923
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadRelationshipTypes() +661
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.LoadTypesFromAssembly() +17
   System.Data.Metadata.Edm.ObjectItemAssemblyLoader.Load() +25
   System.Data.Metadata.Edm.ObjectItemAttributeAssemblyLoader.Load() +4
   System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, ObjectItemLoadingSessionData loadingData) +160
   System.Data.Metadata.Edm.AssemblyCache.LoadAssembly(Assembly assembly, Boolean loadReferencedAssemblies, KnownAssembliesSet knownAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage, Object& loaderCookie, Dictionary`2& typesInLoading, List`1& errors) +166
   System.Data.Metadata.Edm.ObjectItemCollection.LoadAssemblyFromCache(ObjectItemCollection objectItemCollection, Assembly assembly, Boolean loadReferencedAssemblies, EdmItemCollection edmItemCollection, Action`1 logLoadMessage) +316
   System.Data.Metadata.Edm.ObjectItemCollection.ImplicitLoadAssemblyForType(Type type, EdmItemCollection edmItemCollection) +84
   System.Data.Metadata.Edm.MetadataWorkspace.ImplicitLoadAssemblyForType(Type type, Assembly callingAssembly) +151
   System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity) +211
   blogEntities.AddToblogs(blog blog) in C:\Inetpub\int422_113b16\webcontent\App_Code\blogModel.cs:367
   BlogManager.BlogAdd(String title, String content, String userName) in C:\Inetpub\int422_113b16\webcontent\App_Code\BlogManager.cs:27
   Project_Admin_create_post.post_Click(Object sender, EventArgs e) in C:\Inetpub\int422_113b16\webcontent\Project\Admin\create-post.aspx.cs:25
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

BlogManager.cs
public class BlogManager
{
    private blogEntities _dbEnt = new blogEntities();

    public BlogManager()
    {
    }

    public void BlogAdd(int numId, string title, string content,string userName)
    {

        blog newPost = new blog();
        newPost.blog_id = 1;
        newPost.blog_title = title;
        newPost.blog_content = content;
        newPost.date_created = null;
        newPost.user_name = userName;

        _dbEnt.AddTotheblog(newPost);
        _dbEnt.SaveChanges();
    }

    public class NameNotUniqueException : Exception
    {
        public NameNotUniqueException(string msg = "INT422 ERROR: matching data already exists")
            : base(msg)
        { }
    }
}

create-post.cs
public partial class Project_Admin_create_post : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            blogStatus.Text = "Your post is published";
            title.Enabled = false;
            content.Enabled = false;
        }
    }

    protected void post_Click(object sender, EventArgs e)
    {
        string _userName = User.Identity.Name;

        BlogManager blogMgr = new BlogManager();
        blogMgr.BlogAdd(title.Text, content.Text, _userName);
    }
}

Answer: I think the error message is telling you the truth here.  You've previously, either in a child object in your blog post, or the blog post itself—added another entity of this type with the same entity key.
Is it possible that in one of your tables you've forgotten to set the identity key for your PK?  If so you might have a row with a key of 0, and subsequent inserts are conflicting with it.
Comment: Code is updated with the files I am using for insert. Let me know if you are seeking any other particular file
Comment: Everything is still same.. I have the PK, identity key & i added the number manually.. problem is still there
Comment: Are you using POCO?  when you say: `new blog()` - does the constructor create any child objects that might be screwing things up?
Comment: POCO? dont know.. just starting with data entity so ..
but if I dont create new object, I wont be able to pass the values.. is there any other way?
Comment: Did these classes get auto-created when you dragged your tables onto the designer, or did you write the classes by hand?
Comment: The blog class itself.  The class that's saved to the database.  Is that created by you by hand, or did the designer create it for you?
Comment: it was auto created with the entity cs file
Comment: @BhrugeshPatel - sorry I'm fresh out of ideas then.
Comment: its okay...I will find some way
Thanks for all your help... I was able to realize lots of things that I ignored the first time :D
Comment: a question..recreating data entity
will there be a problem my data entity model name and model namespace are same?
both "BlogModel"?
Comment: Dropped the entity model & recreated it
& its working now O.O
Sorry for troubling you so much.
Answer: if(blog.EntityState==EntityState.Detached)
    base.AddObject("myblogs", blog);

Comment: What is blog PK? Are you forgot assign value to it?
Comment: its blog_id .. instead of auto assign..did it manually...
check the updated code of method BlogAdd(..)
Comment: Debug to sure BlogAdd method not called twice, Are you sure in context before add to context, not exist a blog with blog_id=1?
Comment: I wish I could.. School server doesnt allow it
but I just downloaded the whole site.. I am gonna debug on my local server


Brewing stand not accepting water bottles

Question: I've built the automatic brewing station from this tutorial. I've been through it three times to make sure I have everything as per the video, but things aren't quite working.
The full water bottles make it to the hopper than is pointing towards the brewing stand but for some reason they won't load into the brewing stand. I have a feeling it's something 'locking' the brewing stand (like you can lock hoppers), but that's just a guess. Here's a screen cap of the offending hopper;

The hopper is meant to be locked while the stand empties of the previous batch, but for some reason it never refills.
If it matters I'm on 1.11.2 and I'm playing on a server.
Comment: Does [MC-111753](https://bugs.mojang.com/browse/MC-111753) describe your issue?
Answer: I do believe that the water bottle should be inserted from the top, as I do think that only the blaze powder can be added from the side (that was added before 1.11) hopefully this helps...
Answer: There maybe multiple issues here:

Sometimes servers have specific glitch "fixes" that hinder you to be able to do certain things. For example, there is a glitch in Minecraft that uses redstone. When used, it acts as a X-ray machine allowing the player to see underground. Many servers prevent this from occurring and the result is some redstone contraptions don't work properly.
A redstone pulse or current will stop hoppers from pulling things into them and from going out of them. Make sure no other redstone current is interfering with your hoppers. You may have to space things better.
Make sure the tutorial you watched corresponds with the version of Minecraft you are running. For example, I use Minecraft commands all the time and it seems every time Minecraft updates, the way commands are written get changed and no longer apply. Make sure the video still applies.
Some servers allow multiple versions of Minecraft players all at once. This can influence your game play. For example, If you play with 1.8 players, and your contraption is for a fairly new version (1.10 or 1.11) than it also may not work because the server has to compromise features so all players (of different versions) can still play without the server crashing.


Time is never stored when using %time% in batch file

Question: I'm currently writing a batch files that records the ping of an ip and records the time.
Unfortunately when i try to use the %time% command and store it, it always returns nothing.
when i run the command alone it works, just not with my other code
Set packet=0
Set Down=0
Set Up=0
Set time=0
SET /P IP=enter ip.
set counter=0
:ping
Rem ping -n 1 -w 2500 %IP%>>ping.txt
ping -n 1 -w 2500 %IP% > nul 2>&1 && set Test=Pass || set Test=Fail
FOR /F "tokens=1-9 delims==< " %%a IN ('PING -n 1 -w 2500 %IP%') DO IF "%%h"=="TTL" SET RESPONSE=%%g
mode 100
Set time= %TIME:~0,5%
echo %time%
pause

Comment: Don't use the name of a system variable to store a local variable.
Comment: Type `set` to see all set variables and `set /?` (at the end) for the names of the volatile variables (that change like `%time%` does).
Comment: Read answer on [Defining a variable in a batch file not working](https://stackoverflow.com/a/47930012/3074564) containing the relevant part of help of command __SET__ output on running `set /?` in a command prompt window about __dynamic environment variables__. It is clearly described in help that a line like `Set time=0` overwrites dynamic variable `TIME` making it not further useful as you would like. See also [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/a/26388460/3074564)
Answer: Let me reiterate what @SomethingDark already said.
And that is precisely what is causing your problem, along with the fact that you have a space after the = sign in:
Set time= %TIME:~0,5%
This prefixes a space before the current time, and the value is saved as ' 17:3' (5 characters), for example. Next time you run the same command, the value stored in the time variable will be '  17:' (with 2 spaces) and so on. Eventually, you will end up with 5 spaces being saved in the time variable.
Comment: so how would i make the variable local? I removed the space and im still having the same issue
Comment: The links in @Mofi's comment above may have helped you with this issue, already.

If not, would you mind posting a latest version of your script?

I have a simple script that look like this and works fine, each time I run it:

    `SET MY_TIME=%TIME:~0,5%`
    `echo %MY_TIME%`
Comment: I removed the space and added the extra "%" on each side but now it just returns %TIME:~0,6%

 Set time=%%TIME:~0,6%%
echo %time%
pause
Comment: Is there a reason why you added those extra **%**s? Also, as suggested earlier, please stop using `set time`. Just give that variable a different name, as in, `CURR_TIME` or something like that.

Any particular reason for changing to `0,6`? That will give you an extra colon at the end.

Please follow the code that I had shown previously and let me know if it still does not work for you.

Here is some additional explanation:

`echo %TIME%` displays the current time. It displays 11:48:08.58, for example.
You needed a sub-string of that, just HH:MM, which is what  `%TIME:~0,5%` returns.
Comment: In one of the links above stated it need 2 "%" on each side cause it was in a batch file, i put the 6 in cause i was trying to get this thing to work, I changed the variable name to potato and it still returns 0 but for some reason %date% works with no issues.                                                   Set potato=%TIME:~0,5%
echo %potato%
pause
set date=%date%
echo %date%
echo %time%
pause
Set /?
Comment: Ok i fixed the issue, looks like i had a variable at the top that was also named time that was set to 0 so i guess it was pulling that. thanks for all the help guys.


How to determine if a Water Pressure Reducing Valve (PRV) is working properly

Question: I've been trying to track down water pressure/flow issues throughout the plumbing in my entire house, but haven't found anything which made any significant difference. For example, I discovered that the main valve and a few others were not fully open. I am able to access all other valves and they are fully open. All lines are copper. My house is a single level with a basement (where the main is located). My neighbors do not have any problems.
Here's my configuration:
City Water -> 3/4" lines -> main -> gauge (reading is maxed out over 100 psi) -> PRV -> gauge reading static 60 psi -> valve -> continue 3/4" lines feeding 1/2" lines for all fixtures.
I have a thermal expansion tank with the hot water heater which is also set to 60 psi.
As soon as any water fixture is turned on (sink, shower, toilet flush, washing machine, etc.), the pressure on gauge immediately following my PRV drops significantly (falls to 20psi or less). As a result, trying to use a second fixture is difficult and a third is near impossible. Additionally, I attempted to turn all water fixtures through the house on. During this test, the water fixtures on the main level did not put out any water.
I'm inclined to believe there is an issue with the PRV. Is that the right place to be looking? Should a PRV have such a large drop in pressure when one fixture is open?
Comment: My guess is that either the city's shutoff valve is not fully open, or there is an obstruction in the 3/4" line from the shutoff valve to your PRV. I'd think the former would be more likely, as the latter would mean something caused the obstruction (roots, collapse), which, one would think, would also cause a leak. The pressure should drop whenever any plumbing fixture is turned on (per Bernoulli), but going down to 20 PSI from 60 seems a bit excessive to me.
Comment: If the pressure before the PRV is 100 psi, and the pressure after is 60 psi, then the valve seems to be working.  When you open a valve so that water starts flowing, the pressure in the system will drop.  Without seeing how your plumbing is set up, it's difficult to help you locate the problem.  It sounds like you have a problem with the volume of water, not the pressure.
Comment: You said you live in a one story with a basement, and then said the fixtures on the "main" level did not put out water.  How many fixtures are in the not main (basement?) level, and what type of fixtures?
Comment: Do the 1/2" lines feed more than one fixture per line?
Comment: @Tester101 Thanks for getting back to me. On the basement level, there is: a half bath with a sink and toilet (I opened the sink hot and cold a little) and flushed the toilet, a laundry tub (I opened the hot and cold a little) and the washing machine (I started a load of laundry).
Comment: I also noticed something interesting. I took the heads of all the faucets that were easily accessible. They were all filled pretty good with white-ish debris. I cleared it out and let them run. It did not fix the problem, but the sinks are running better. I let them run and flipped the shutoff valves off and on and went back and checked and there is more of the white-ish debris. I wonder if the issue is related to the lines being clogged?
Comment: Yes, it looks like all fixtures are feeding (as 1/2" lines) off of the 3/4" main lines.
Comment: Is it all copper plumbing?
Comment: Yes. The only thing I'm not sure about is the pipe that goes from the meter to the main shutoff, as it's all in the wall.
Answer: I replaced the PRV with an exact match and it fixed the issue. It was a fairly straight forward replacement since the PRV had one union and my backflow preventer (about 10" down the line) had another.
Comment: Can you open up the old PRV, and inspect the strainer? You might be able to see the deposits, if you look in the inlet side of the valve. I suspect that it may be blocked up with the same white-ish debris that was blocking up the faucets.


Sum of all even Fibonacci numbers

Question: I'm trying to get the sum of all the even Fibonacci numbers. I can print the numbers out but I can't get the sum of them. This is in java.
class driver {
    public static void main(String [] args) {
        int a;
        int b = 0;
        int c = 1;

        for (int i = 0; i < 10; i++) { // Finds fibonacci sequence
            a = b;
            b = c;
            c = a + b;

            if ( c % 2 == 0) { // Check if it's even
                int sum = 0;
                sum = sum + c;
                System.out.println(sum);
            }
            else {

            }
        }
    }
}

Comment: Take the print statement outside the loop.
Comment: you keep setting the sum to `0` inside your loop every time you find an even, so effectively the code is simply `sum = c`. e.g. move the `int sum = 0` outside of the loop.
Comment: Look at where you're initializing ```sum```; step through the code yourself and see why that is a problem.
Comment: Even terms will just keep on coming, so the sum of all even fibonacci terms is infinity.
Answer: You should not reinitialize the sum every time inside the loop, because that will cause it to lose the value it has. It should have its scope outside the if so that the same variable can be incremented each time.
class driver {
    public static void main(String [] args) {
        int a;
        int b = 0;
        int c = 1;
        int sum = 0;

        for (int i = 0; i < 10; i++) { // Finds fibonacci sequence
            a = b;
            b = c;
            c = a + b;

            if (c % 2 == 0)  // Check if it's even
                sum += c;
        }
        System.out.println(sum);
    }
}

Comment: It gives a negative number when you use 4 million
Answer: public static void main(String [] args) {
    int a;
    int b = 0;
    int c = 1;
    int sum = 0;

    for (int i = 0; i < 10; i++) { // Finds fibonacci sequence
        a = b;
        b = c;
        c = a + b;

        if ( c % 2 == 0) { // Check if it's even
            sum += c;
        }
    }
    System.out.println(sum);
}

You originally set sum = 0 every single time 'c' was an even number. This code should work as sum = 0 only before the process begins. This is actually a common mistake, but you will quickly learn that it is a bad idea.
Just so you know, I put the System.out.println(sum) statement outside of the loop so you don't have 10 different numbers as output.
Comment: When you use 4 million as the value for the fibonacci sequence, it gives you a negative number. This cannot be the right answer.
Answer: Declare the integer variable sum, outside the for loop. That should do it.
Answer: public final class eu_p002_sol {

    public static void main(String[] args) {
        System.out.println(new eu_p002_sol().run());
    }
public String run() {
        int sum = 0;
        for (int x = 0; ; x++) {
            int fib = fibonacci(x);
            if (fib > 4000000)
                break;
            if (fib % 2 == 0)
                sum += fib;
        }
        return Integer.toString(sum);
    }

    private static int fibonacci(int n) {
        if (n < 0 || n > 46)
            throw new IllegalArgumentException();
        int a = 0;
        int b = 1;
        for (int i = 0; i < n; i++) {
            int c = a + b;
            a = b;
            b = c;
        }
        return a;
    }
}

Try this
Answer: maybe someone is still searching for a right answer:
static int sum = 0, seq = 0;

public static void main(String[] args) {

    fib(1,2);

}

static void fib(int i, int j) {

    seq = j;
    if (seq <= 4000000) {
        if (j % 2 == 0) {
            sum += j;
        }
        fib(j, i + j);
    } else {
        System.out.println(sum);
    }
}

Sum of all even Fibonacci numbers


Date subtracting quandary Excel 2007

Question: Answer is being returned as a date, even if i put =int( in front of this.  Any obvious reasons why?
=YEAR(TODAY()-YEAR(J2))

where J2 is 4/10/1939 and the answer given is 06/28/05.  Why is this not simply outputting the person's age?
Answer: Don't you have the parentheses in the wrong place? I suspect you want this formula
=YEAR(TODAY())-YEAR(J2)
To make sure you see the result as a number format the result cell as general
....but that doesn't give "age" as most people would understand it because it increments always on Jan 1st rather than on the birthday. To get accurate age in years try DATEDIF function
=DATEDIF(J2,TODAY(),"y")
For your example that will give 72 today but change to 73 on the birthday, 4/10/2012
Note: DATEDIF is not well documented in Excel and probably doesn't appear in your "function list"....but you can use it by simply typing it in a cell
Answer: try =INT((TODAY()-J2)/365.25) as your formula to return the age in years
Using =year(today()-J2) would return the age plus the century (1900) so you could just append -1900 from it, but the above solution works more simply
Answer: This should work:
=INT(YEARFRAC(A1,TODAY()))

If you're trying this in the same cell as before, you will have to reformat the cell as 'General'. That's just one of the pains of Excel autoformatting.
Answer: Your formula should be =YEAR(TODAY())-YEAR(J2).  The cell the formula is in must be formatted General or Number for it to display the correct value.  Note that this will not give the proper age if the person has not had a birthday in the current year.
This gives a more accurate age =INT((TODAY()-(B1))/365)

Date subtracting quandary Excel 2007


Find the equation of the parabola

Question: We have a point $A(6,0)$ and a line $k:y=2$. Show that the equation of the parabola with a locus $A$ and a directrix $k$ has the formula: $\dfrac{1}{4}x^2-3x+8$.
I had a test on analytic geometry today and this was one of the questions. I was 100% sure that the question was wrong, however, all my classmates told me that they had solved it correctly (apart from the fact that it should have been $-\dfrac{1}{4}$ instead of $\dfrac{1}{4}$, something which I noticed too, disregard this when answering my question). So my question is what I did incorrectly:
We use the formula of a parabola, $y-b=\dfrac{1}{4c}(x-a)^2$. The distance between the directrix and the locus is 2, so $c=1$. We get $y-b=\dfrac{1}{4}(x-a)^2$. We see that the top of the parabola is $T(6,1)$, so we get $y-1=\dfrac{1}{4c}(x-6)^2$. This can also be written as: $y=\dfrac{1}{4}x^2 -12x + 37$. And here we go, a totally different answer. Can anyone point out my mistakes?
Comment: I suppose you meant "focus" instead "locus"...didn't you?
Comment: Indeed I did (at least I thought it was named focus).
Comment: @DavidMitra Well, that doesn't help me, sir.
Answer: If the directrix is the line $y=2$:
Your value of $c$ should be negative, since the focus lies below the directrix. So, your initial equation should be $$\tag{1} y-1={-1\over 4}(x-6)^2.$$
 Apart from $c=-1$, and not $c=1$, what you had there is correct.
But, it seems you  made some algebraic errors when writing your initial equation in standard form.
To write equation $(1)$ in standard form, you could first multiply both sides by $-4$  to obtain
$$
-4y+4=(x-6)^2.
$$
Now expand the right hand side:
$$
-4y+4=x^2-12x+36.
$$
So, subtracting $4$ from both sides, we obtain $$-4y=x^2-12 x +32.$$
Finally, divide through by $-4$
$$
y={-1\over4} x^2+3x-8.
$$
But then, the proposed solution is incorrect; the right hand side should be multiplied by $-1$. (But the given answer would be correct if the directrix were the line $y=-2$.)
Answer: I think the sign of c depend of the position of the focus compared to the directrix (question of orientation) because if you set it at -1 you will get the answer I compute (-1/4 for 1/4).
By the way, you forgot to divide by four the affine term.
Please excuse the deplorable english of a french (thought I hope it remains understandable).

Find the equation of the parabola