How to Launch an Android AppWidget's configuration Activity from another activity?

Question: Well this is driving me crazy. I have developed an App-widget. Everything is working fine.
I have a configuration activity which launches every time a widget is added on the home screen and works beautiful. I save the user settings per widget id etc.
The widget has some buttons, one of them launches an activity with about information, the "About Activity".
The "About Activity" has a button which I want to use to launch the configuration activity for the widget id that launched the "About Activity". The reason I want to do that is because I want the user to be able to configure the contents of any instance of my widget without having it removed and added again (in order to launch the configuration activity).
The configuration activity needs the AppWidgetManager.EXTRA_APPWIDGET_ID in order to make the job (save the user settings for this specific widgetid) so I must somehow pass this extra when I 'm calling it from another activity. The obvious think to do is this:
startActivity(new Intent(context,act_configure.class).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, ??? ));

Now my question is where is the widgetid? I found a million ways to get the widgetids (the array) but not a single clue on how to get the specific widgetid which launched the "About Activity"
Any help about this will make the hours I spent to find a solution, worth something. Thank you in advance.
p.s. Please forgive my English as they are not my native language...
Comment: Well I deserve somekind of badge. It seems I asked the most difficult android appwidgets question...
Comment: Why don't you put the widget id into the intent to start your about activity? So about knows the id and can use it to start configure
Comment: This is exactly what I am trying to achieve but I could not find the widget ID. It is only in one place, in the  onUpdate method of the widget provider. So based on this fact and on Cory Chaltron's answer I finally managed to do the job. See comments in the accepted answer and in my answer too. Thank you very much.
Answer: Thanks to Cory Chaltron here is the solution to my problem.
In the widget provider onUpdate method I should create a "unique" intent to pass to the pending intent which handles the launch of the about activity. Because of the way Android compares Intents, passing the WidgetID in the extras IS NOT ENOUGH, you should also pass it as data to the intent in order to be unique. So here is the code:
Intent aboutIntent = new Intent(cx, act_about.class);
aboutIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetIds[i]);
// Make this unique for this appWidgetId
aboutIntent.setData(Uri.withAppendedPath(Uri.parse("customuri://widget/id/"), String.valueOf(widgetID)));
PendingIntent aboutPendingIntent = PendingIntent.getActivity(cx, 0, aboutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK), PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.cmdabout, aboutPendingIntent)

Although I answer my own question I am not accepting it because it is based on Cory's answer. Thank you all for the help...
Comment: alternatively, `aboutIntent.setData(aboutIntent.toUri(Intent.URI_INTENT_SCHEME));` will also work (it encodes the extras as well).
Comment: You would need to parse that into a Uri like this `aboutIntent.setData(Uri.parse(aboutIntent.toUri(Intent.URI_INTENT_SCHEME)));`
Answer: How are you setting your widget views? I have an app where I iterate over the active widgets and configure set the RemoteView there. You could set your widget id in the onClick you are attaching to the "About" button.
final AppWidgetManager widgetManager = AppWidgetManager.getInstance(this);
final ComponentName widgetName = new ComponentName(this, WidgetProvider.class);

final int[] widgetIds = widgetManager.getAppWidgetIds(widgetName);

for (int widgetId : widgetIds) {
    final RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.widget);

    // This is the important part :-D
    remoteViews.findViewById(R.id.your_about_button).setOnClickListener(... a listener to start your about activity that puts the widget id in the extra like you suggest in your question ...);

    widgetManager.updateAppWidget(widgetId, remoteViews);
}

Comment: I am accepting your answer as it opens my eyes and pointed me to the right direction. However there is a "catch" you have to make the Intent unique in order for this to work if the user has more than one widget instance running. This is why I am posting my answer also just in case someone wants the full solution in hand. Thank you.
Comment: RemoteViews has no findViewById method, and clicks are managed via setOnClickPendingIntent


RSpec testing for non-integers

Question: I recently created an account model.  In this account model i have an id which i want to be strictly numeric.  I am trying to create an RSpec test to make sure that I can not enter in any letters, but am having difficulty.
Question: how do I test my id to make sure that it can not contain any letters?
Answer: Use kind_of like so:
object.should be_a_kind_of(Numeric)

From the documentation:
3.should be_a_kind_of(Fixnum) => 3.kind_of?(Numeric) #passes
3.should be_a_kind_of(Numeric) => 3.kind_of?(Numeric) #passes
3.should be_an_instance_of(Fixnum) => 3.instance_of?(Fixnum) #passes
3.should_not be_instance_of(Numeric) => 3.instance_of?(Numeric) #fails

Answer: Even better, you can kill two bird with one stone with a expectation like this
subject.should be_eql 3

since it will have right type and right value. Using eql? guarantees you that id1.hash == id2.hash
Although, you can always split your case into two expectations: value and type. For type matching you can use kind_of matcher or check inheritance with < operator on classes.
subject.should be_kind_of(Numeric)

or
subject.class.should < Numeric

Answer: By default, in Rails you cannot save any other data type in the primary_key attribute.

RSpec testing for non-integers


An invalid form control with name='' is not focusable. WITHOUT ANY REQUIRED OR HIDDEN INPUTS

Question: I'm facing the well known Chrome's "not-focusable-input" error but my situation is different from the explained in the other post I could find there.
I have this error message duplicated first on a well pointed input, this input has no required attribute:
The code:
<fieldset>
    Total (montaje incl.)
    <input type="number" id="priceFinal" name="priceFinal"> €
</fieldset>

The error:
An invalid form control with name='priceFinal' is not focusable.
While the user is filling the form this field gets its value by a js script with jquery. The user type a size in another input, the script do its maths with the size value and then put the outcome in the 'priceFinal' input with the jquery function: .val()
In the browser we can see that the input is correctly filled and no errors are displayed at that time. And with the 'novalidate' solution everything goes fine, so it couldn't be responsible for the nofocusable error, I think.
Then I got the same error with an input with no name which I didn't write and doesn't exist in my DOM:
An invalid form control with name='' is not focusable.
This is weird because the only input without name in my form is the type:submit one
<input type="submit" class="btn btn-default" value="Ver presupuesto" />

I have a few required fields but I've always checked that their are all filled when I send the form. I paste it just in case it could help:
<fieldset>
    <input type="text" id="clientName" name="clientName" placeholder="Nombre y apellidos"  class="cInput" required >
    <input type="text" id="client_ID" name="client_ID" required placeholder="CIF / NIF / DNI" class="cInput">
</fieldset>
<fieldset>
    <input type="text" id="client_add" name="client_add" placeholder="Dirección de facturación" class="addInput" required >
</fieldset>

<fieldset>
    <input type="text" id="client_ph" name="client_ph" placeholder="Teléfono" class="cInput" required>
    <input type="email" id="client_mail" name="client_mail" placeholder="Email" class="cInput" required>
</fieldset>

The novalidate solution clears the error but it doesn't fix it, I mean there must be a way to solve it with no hacks.
Any one have any idea of what's might going on?
Thanks
Comment: Do you have a button control that is being clicked at some point while using the form? - If yes, does the button have its type attribute correctly set? - If a button does not cause form submission, you must explicitly set its type attribute with the value _button_: ``.
Answer: I had the same problem, and everyone was blaming to the poor hidden inputs been required, but seems like a bug having your required field inside a fieldset.
Chrome tries to focus (for some unknown reason) your fieldset instead of your required input.
This bug is present only in chrome I tested in version 43.0.2357.124 m.
Doesn't happen in firefox.
Example (very simple).

<form>
  <fieldset name="mybug">
    <select required="required" name="hola">
      <option value=''>option 1</option>
     </select>
    <input type="submit" name="submit" value="send" />
  </fieldset>
</form>

An invalid form control with name='mybug' is not focusable.
The bug is hard to spot because usually fieldsets don't have a name so name='' is a WTF! but slice piece by piece the form until I found the culprid.
If you get your required input from the fieldset the error is gone.

<form>
    <select required="required" name="hola">
      <option value=''>option 1</option>
     </select>

  <fieldset name="mybug">
    <input type="submit" name="submit" value="send" />
  </fieldset>
</form>

I would report it but I don't know where is the chrome community for bugs.
Comment: We had the exact same thing.  Chrome tries to focus the fieldset. I just changed to  instead and it works.
Comment: Thanks, this led me down the path of just removing the fieldset. After I did that all my problems went away.

Information about reporting Chrome bugs: https://support.google.com/chrome/answer/95315?hl=en

Or report them against Chromium at https://code.google.com/p/chromium/issues/list
Comment: Same thing here, but I'll juste wait for chrome to solve this issue.
Answer: Thanks to this post, I saw that my problem also rested with Chrome trying to focus on my fieldsets, instead of the input field.
To get a better response from the console:

Assign every DOM element a new name
Set every input & select style.display to 'block'
Changed the type of input[type="hidden"] elements to 'text'
function cleanInputs(){
    var inputs  = document.getElementsByTagName( 'input' ),
        selects = document.getElementsByTagName( 'select' ),
        all     = document.getElementsByTagName( '*' );
    for( var i=0, x=all.length; i<x; i++ ){
        all[i].setAttribute( 'name', i + '_test' );
    }
    for( var i=0, x=selects.length; i<x; i++ ){
        selects[i].style.display = 'block';
    }
    for( var i=0, x=inputs.length; i<x; i++ ){
        if( inputs[i].getAttribute( 'type' ) === 'hidden' ){
            inputs[i].setAttribute( 'type', 'text' );
        }
        inputs[i].style.display = 'block';
    }
    return true;
}

In the console, I ran cleanInputs() and then submitted the form.
The result, from the console, was:

An invalid form control with name='28_test' is not focusable.
An invalid form control with name='103_test' is not focusable.

Then, switching over to the Web Developer "Elements" view, I was able to find "28_test" and "103_test" (both fieldsets) -- confirming that my problem was a required input field, nested inside a fieldset.
Comment: This was insanely helpful and a good brute force way of identifying it.
Comment: This was so helpful, I could not find where this error was coming from for the life of me!
Answer: While I was writting the question I realized one thing: the value the script was putting into the 'priceFinal' field sometimes was a decimal number.
In this case the solution was to write the step attribute for this input:
... step="any" ...

Step on w3s
So this 'nofocusable' bug is not only a required and hidden fields issue, it's also generated by format conflicts.
Answer: Nach gave me the best pointer... (y) I also had a input type="number" with step="0.1" and the console shows me this error while validating: An invalid form control with name='' is not focusable.
remove the step="0.1" on the element and now the form can be validated
Answer: I had the same issue so I removed required="required" from the troublesome fields.
Answer: If you get the error when jQuery function is executed, try to put "return false" on your function, or function(e) { e.preventDefault(); ... }
Answer: i had this issue once. to fix it, add
novalidate

as an attribute to the form. e.g
<form action="" novalidate>
....
</form>

Comment: This isn't a "fix" if you need client-side form validation for UX. Sure, you should be validating server-side anyway. But it really helps if the client knows exactly what's missing before the form will submit.
Comment: This isn't a fix
Answer: In my case, the input element did not have a required attribute but it was hidden. and the problem was while it was hidden, it had a value in it. I guess if an input field is hidden it shouldn't have a value too, aside required attribute.
When I remove the value through my javascript code, everything works fine.
Element is hidden, No required Attribute, No value. Worked
Answer: Here is the solution....
<form>
  <input type="text" ng-show="displayCondition" ng-required="displayCondition"/>
</form>

Many people do not realize that passing false into ng-required disables the directive.


Concatenate Videos with node.js in AWS Lambda

Question: Im wondering if it's possible to merge (concatenate) two video clips into one with an AWS Lambda function using Node.js?
The dependency that I was going to use is ffmpeg (or fluent-ffmpeg), but from what I can tell, all the APIs use the actual file path, not the file variables. I download the actual video files from an S3 bucket so I can't use the path's... can I?
I haven't found a single example that uses file variables. If there's a better way to do this that Im not thinking of, feel free to share! Thanks for the help as always.
Answer: I found a way around it! All I needed to do was save the object body from the item I get from S3 to a file on the local Lambda file system. Not sure why I didn't think of this in the first place. I ended up doing
<code>fs.writeFile("out.mp4", item.Body, (err) => {
        if(err) console.log(err);
        console.log("Body saved!")
});
</code>
Hopefully this answer helps someone that comes across a similar mental block in the future.
Comment: Hi, can you post the full solution?


Writing ARM machine instructions and executing them from C (On the Raspberry pi)

Question: I'm trying to write some self modifying code in C and ARM. I previously asked a similar question about MIPS and am now trying to port over the project to ARM.
My system := Raspbian on raspberry pi, ARMv6, GCC
There are a few things I am unsure of:

Does ARM require a D-cache write-back/I-cache invalidate (cache flush)? If so, how can we do this?

Also I tried an example
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int inc(int x){ //increments x
    uint16_t *ret = malloc(2 * sizeof(uint16_t));

    *(ret + 0) = 0x3001; //add r0 1 := r0 += 1
    *(ret + 1) = 0x4770; //bx lr    := jump back to inc()

    int(*f)(int) = (int (*)(int)) ret;
    return (*f)(x);
}

int main(){
    printf("%d",inc(6)); //expect '7' to be printed
exit(0);}

but I keep getting a segmentation fault. I'm using the aapcs calling convention, which I've been given to understand is the default for all ARM
I'd be much obliged if someone pointed me in the right direction
Bonus question (meaning, it doesn't really have to be answered, but would be cool to know) - I "come from a MIPS background", how the heck do ARM programmers do without a 0 register? (as in, a register hardcoded to the value 0)
Comment: this is not an arm or mips question it is a linux and protection question.  Use mmap to allocate the memory space and enable it for execution, etc, then modify that then you can branch to it without a protection fault.  There are many SO questions that already answer the "self modifying code on linux" question, the question has the same answer for mips, arm, x86, ppc, etc.
Comment: @C.E.Sally For the bonus bonus that would be `MOV Rd,#1` and that will work for any 8-bit value. The nice part is that if you need to set additional bits, you can OR them in while rotating the original 8 bits to an arbitrary location in the register. With `MVN` you can set 8 zero bits.
Comment: As to your bonus question: the ARM has the most extended ways to enter constants into the datapath of the processor, of all the processors I know (around 10), so why bother with just 0. So my counter question would be: why the heck does the MIPS wast instruction encoding space of one register to just get a 0 into the datapath? A rhetorical question of course.
Comment: You need at least, `int tmp = 0; /* Drain WB */ __asm volatile(" mcr p15, 0, %0, c7, c10, 4\n" : "=r" (tmp));` to ensure that the writes are committed to RAM before jumping.
Comment: Also, you'll want to allocate executable memory. Memory allocated through malloc might not be guaranteed to executable since it's supposed to be data and not code. Try allocating memory using mmap and setting the executable flag. Here's an answer I wrote for x86 (but should work under ARM too) http://stackoverflow.com/a/14826557/268025 Edit: Beaten - just saw dwelch's comment.
Comment: There is a zero register in arm, wzr. http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0024a/ch05s01s03.html
Comment: @dwelch: Sorry, you're not very convincing. See the link I added (similar question); The answer wasn't the same for MIPS.
But getting back to the question, are you saying that you know for ARM the only way to go is with mmap?
Comment: @BryanOlivier: I guess I have to clock more hours coding in assembly then =) As a bonus bonus I don't suppose you'd show the "standard" way to set a register to 1? (ie, the ARM equivalent of the MIPS addi $t0, $0, 1)
Comment: @artlessnoise: Yes, Thumb-2 the documentation tells me. Did I encode my instructions wrong? I'm using the ARMv6-M Architecture Reference Manual.

I did come across something strange. The manual seemed to be saying that
    `bx lr`
has unpredictable behaviour. I didn't know what to make of that and so ignored it.
Comment: @C.E.Sally  Your thumb instructions look good.  I just wonder if you started in `thumb` mode.  Ie, if you are initially in ARM mode and jump to a `thumb` routine without switching modes, you will crash.
Comment: @artlessnoise: Ah... I'm not to sure about that(the mode switching I mean). The impression I got is that the Pi would basically always be in Thumb mode (I got this impression from the ARMv6-M manual. Is that correct?)
Could you add a little colour on the mcr instruction? When I did a quick google, it seemed to come up a bit, but when I looked through the technical documentation I couldn't find it.

I also don't quite understand your code, could you elaborate or perhaps point me in the direction of documentation? Also, if you made it an answer I could accept.
Comment: @artlessnoise: I'm still getting a segmentation fault even with that. Also, if ARMv6-M only supports thumb2, do we need to change it to `mcrr`?
Comment: You cannot execute a page which doesnt have the permission. You should use mmap with right flags not malloc.
Answer: Read Caches and Self-Modifying Code on blogs.arm.com. Article includes an example as well which does what you are describing.
To answer your question from article

... the ARM architecture is often considered to be a Modified Harvard Architecture. ...
The typical drawback of a pure Harvard architecture is that instruction memory is not directly accessible from the same address space as data memory, though this restriction does not apply to ARM. On ARM, you can write instructions into memory, but because the D-cache and I-cache are not coherent, the newly-written instructions might be masked by the existing contents of the I-cache, causing the processor to execute old (or possibly invalid) instructions.

See __clear_cache for how to invalidate cache(s).
I hope you are also aware of ARM/Thumb instruction sets, if you are planning to push your instructions into memory.
Comment: I'm aware that there are ARM and thumb but now I'm having a hard time trying to understand if the set up I have can run in arm. The documentation seems to be saying for ARMv6-M, only thumb is available
Answer: Ok, so this works on my raspberry Pi.
#include <stdio.h>
#include <sys/mman.h>
#include <stdint.h>
#include <stdlib.h>

int inc(int x){ //increments x

    uint32_t *ret = mmap(NULL,
            2 * sizeof(uint32_t),  // Space for 16 instructions. (More than enough.)
            PROT_READ | PROT_WRITE | PROT_EXEC,
            MAP_PRIVATE | MAP_ANONYMOUS,
            -1,0);
    if (ret == MAP_FAILED) {
        printf("Could not mmap a memory buffer with the proper permissions.\n");
        return -1;
    }

    *(ret + 0) = 0xE2800001; //add r0 r0 #1 := r0 += 1
    *(ret + 1) = 0xE12FFF1E; //bx lr        := jump back to inc()

    __clear_cache((char*) ret, (char*) (ret+2));

    int(*f)(int) = (int (*)(int)) ret;
    return (*f)(x);
}

int main(){
    printf("%d\n",inc(6)); //expect '7' to be printed
exit(0);}

Comment: Thank you so much for this sample code. It was very helpful.
Answer: There are a couple of problems.

You don't flush your D-Cache and I-Cache, so most times the I-Cache will fetch stale data from L2. Under linux there is a libc/sys-call which does that for you. Either use __clear_cache(begin, end) or _builtin_clear_cache(begin, end).
You output Thumb-Code, but you don't take care of how your code gets called. The easiest way to fix that would be to use some asm-code to do the actual blx call and OR the address with 1, as this bit sets the mode the processor runs in. As you're malloc address will always be aligned to a word boundary, making you call thumb-code in arm-mode.
Comment: The impression I'm getting from the documentation is that thumb instructions are halfword aligned, so if my block of memory is word aligned I'll be good?

I also don't yet understand what you mean about setting the thumb mode. Again from the documentation, the impression I'm getting, is that I'll always be in thumb mode for ARMv6-M
Comment: As for the cache coherrence, I've tried both but unfortunately am still seg faulting, so I think I have another problem elsewhere


JS Regex: (a|b) Matches the a or the b part of the subexpression. Different behaviour when a and b switched

Question: I am trying to replace 2% with ''(empty) using regexp concept. If input string is either % or 2%, it should be replaced with ''(empty):

const str = "2%";

console.log(`2%`.replace(/^\d%$|\d(?=%)/, ''));
console.log(`2%`.replace(/\d(?=%)|^\d%$/, ''));

(a|b) Matches the a or the b part of the subexpression.
"2%".replace(/^\d%$|\d(?=%)/, ''). This works well.
But, "2%".replace(/\d(?=%)|^\d%$/, '') does not.
Comment: So what is your question and problem? You appear to have working source code....
Comment: The left side of the `|` matches, so that's what's replaced. What exactly is it that's surprising here?
Comment: @Pointy, Does it work like short-circuit operator?
Comment: Yes, the first alternative that matches "wins".
Answer: The difference is in what the regex tries to match first. The left expression takes precedence. The right is only tried when the left one fails to match.


Does this variation on "return last numeric value in column" formula have any known fail conditions that anyone can see?

Question: The parameters are:

The column may contain either negative or positive numbers (including the decimals forms of proper fractions), blank cells, text or errors (like #DIV/0!), and will have data added to it over time.
It uses LOOKUP in its vector form.

The formula (with Column A as the column in question) is:
=LOOKUP(1,-1/A:A^2,A:A)
The thinking is

First make sure any negative numbers are positive by squaring them using A:A^2
Make all the numbers negative by using -1/<resulting number from 1.>.
Then, when LOOKUP goes looking for the value 1, it will exploit the behaviour of LOOKUP to return the last number in column for a value that it can't find that is greater than any of the numbers in the resulting array.

I think it works in all circumstances, but can anyone see something that breaks it?
Thanks in advance.
Answer: It won't work if the last number is zero, that will generate a #DIV/0! error which LOOKUP will ignore
Why not
=LOOKUP(9.99999999999999E+307,A:A)
Comment: No, I got that wrong, apologies Endlessloop......but what if the last number is zero, that will convert to an error so the LOOKUP will ignore it, do you want to show zeroes?
Comment: I imagine it will be less efficient than using 9.9999999999....but how about `=LOOKUP(2,1/ISNUMBER(A:A),A:A)`?
Comment: No, there are no large numbers - 1/ISNUMBER(A:A) generates an array entirely consisting of 1s (when the value is a number) or #DIV/0! errors (when the value is not a number)
Comment: It makes 0.5 into -4, though. That's the point of `-1/.`
Comment: BINGO! D'oh + facepalm. You found an obvious fail condition. I wanted to avoid the 9.99999999999999E+307 trick, but I might not be able to. Thanks.
Comment: Yes, I just realised -- I think you've cracked it -- thanks again! Do you want to modify your answer to include that solution?


Include C++ File to another C++ File

Question: I'm havin a problem in including my files. I got 3 C++ files and all of them got int main(void).
THe problem is whenever i include 1 of them it says that:
function 'int main(void)' already has a body
but if i will remove the int main(void) to other two C++ file this errors will prompt now.
'one or more multiply defined symbols found'

"class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl convertInt(int)" (?convertInt@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) already defined in FormatPosDataXml().obj

"class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl convertInt(int)" (?convertInt@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) already defined in FormatPosDataXml().obj

and so forth
this is the codes that i've got:
FormatPosDataXml().cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

using namespace std;

#define nextline '\n'

inline bool TextContains(char *text, char ch) {
  while ( *text ) {
    if ( *text++ == ch )
      return true;
  }

  return false;
}

void Split(char *text, char *delims, vector<string> &words) {
  int beg;
  for (int i = 0; text[i]; ++i) {

    while ( text[i] && TextContains(delims, text[i]) )
      ++i;

    beg = i;

    while ( text[i] && !TextContains(delims, text[i]) )
      ++i;
        words.push_back( string(&text[beg], &text[i]) );
  }
}

string convertInt(int number)
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}

string dateFormatChecker(const char *date){
    string strdate=date;
    char getdate[50];
    strcpy_s(getdate, strdate.c_str());

    vector<string> checkdate;
    Split( getdate, "-", checkdate );
    int year, month, day;
    year=atoi(checkdate[0].c_str());
    month=atoi(checkdate[1].c_str());
    day=atoi(checkdate[2].c_str());

    string checkyear, checkmonth, checkday, checkhour, checkminute, checksecond;

            checkyear = convertInt(year);
            if(month<10){
            checkmonth = "0" + convertInt(month);
            }
            else{
            checkmonth = convertInt(month);
            }
            if(day<10){
            checkday = "0" + convertInt(day);
            }
            else{
            checkday = convertInt(day);
            }

            /*
            cout << checkdate[0] << ' ' << checkyear << '\n'
                 << checkdate[1] << ' ' << checkmonth << '\n'
                 << checkdate[2] << ' ' << checkday << '\n';
            */
            if (checkyear.size() != checkdate[0].size()||
                checkmonth.size() != checkdate[1].size()||
                checkday.size() != checkdate[2].size()){
                return "";
            }
    return date;
}

string dateandtimeFormatChecker(const char *dateandtime){
        string strdate=dateandtime;
        char getdateandtime[50];
        strcpy_s(getdateandtime, strdate.c_str());

        vector<string> checkdateandtime;
            Split( getdateandtime, "-: ", checkdateandtime );
        int year, month, day, hour, minute, second;
            year=atoi(checkdateandtime[0].c_str());
            month=atoi(checkdateandtime[1].c_str());
            day=atoi(checkdateandtime[2].c_str());
            hour=atoi(checkdateandtime[3].c_str());
            minute=atoi(checkdateandtime[4].c_str());
            second=atoi(checkdateandtime[5].c_str());

            string checkyear, checkmonth, checkday, checkhour, checkminute, checksecond;

            checkyear = convertInt(year);
            if(month<10){
            checkmonth = "0" + convertInt(month);
            }
            else{
            checkmonth = convertInt(month);
            }
            if(day<10){
            checkday = "0" + convertInt(day);
            }
            else{
            checkday = convertInt(day);
            }
            if(hour<10){
            checkhour = "0" + convertInt(hour);
            }
            else{
            checkhour = convertInt(hour);
            }
            if(minute<10){
            checkminute = "0" + convertInt(minute);
            }
            else{
            checkminute = convertInt(minute);
            }
            if(second<10){
            checksecond = "0" + convertInt(second);
            }
            else{
            checksecond = convertInt(second);
            }

            if (checkyear.size() != checkdateandtime[0].size()||
                checkmonth.size() != checkdateandtime[1].size()||
                checkday.size() != checkdateandtime[2].size()||
                checkhour.size() != checkdateandtime[3].size()||
                checkminute.size() != checkdateandtime[4].size()||
                checksecond.size() != checkdateandtime[5].size()){
                return "";
            }

        //cout << year<< '/' << month << '/' << day << ' ' << hour << ':' << minute << ':' << second << '\n';

        return dateandtime;
}

string transaction (const char * SequenceNumber, const char * RetailStoreID, const char * WorkStationID, const char * BusinessDayDate, const char * BeginDateTime, const char * StartTransTime, const char * EndTransTime, const char * EndDateTime, const char * RawData){

    string output;

    string bdd, bdt, stt, ett, edt;

    bdd = dateFormatChecker(BusinessDayDate);
    bdt = dateandtimeFormatChecker(BeginDateTime);
    stt = dateandtimeFormatChecker(StartTransTime);
    ett = dateandtimeFormatChecker(EndTransTime);
    edt = dateandtimeFormatChecker(EndDateTime);

    cout << "<Transaction>" << "\n\t<RetailStoreID>"
         << RetailStoreID   << "</RetailStoreID>\n\t<WorkStationID>"
         << WorkStationID   << "</WorkStationID>\n\t<SequenceNumber>"
         << SequenceNumber  << "</SequenceNumber>\n\t<BusinessDayDate>"
         << bdd             << "</BusinessDayDate>\n\t<BeginDateTime>"
         << bdt             << "</BeginDateTime>\n\t<StartTransTime>"
         << stt             << "</StartTransTime>\n\t<EndTransTime>"
         << ett             << "</EndTransTime>\n\t<EndDateTime>"
         << edt             << "</EndDateTime>\n\t<RawData>"
         << RawData         << "</RawData>\n</Transaction>";

    output = _getch();
    return output;
}

int main(void) {
  vector<string> words;
  char * data = "1,1,SAMPLE,2010-01-31,2011-01-31 14:09:10,2011-01-31 14:42:10,2011-01-31 14:42:10,2011-01-31 14:42:10,JELLY-O RUBBERB\n\r               13.25V.¶üÁËO";

  Split( data, ",", words );

  char SN[11], RSI[200], WSI[200], BDD[100], BDT[100], STT[100], ETT[100], EDT[100], RD[100];

  strcpy_s(SN, words[0].c_str());
  strcpy_s(RSI, words[1].c_str());
  strcpy_s(WSI, words[2].c_str());
  strcpy_s(BDD, words[3].c_str());
  strcpy_s(BDT, words[4].c_str());
  strcpy_s(STT, words[5].c_str());
  strcpy_s(ETT, words[6].c_str());
  strcpy_s(EDT, words[7].c_str());
  strcpy_s(RD, words[8].c_str());

  string PosData;
  PosData = transaction(SN,RSI,WSI,BDD,BDT,STT,ETT,EDT,RD);

/* Checker
  for (int i = 0; i != words.size(); i++){
      cout << words[i] << nextline;
  }
    cout << SN << nextline << RSI << nextline << WSI << nextline << BDD << nextline << BDT << nextline << STT << nextline << ETT << nextline << EDT << nextline << RD;
*/
return 0;
}

FSNPC.cpp
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <cstring>
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include "FormatPosDataXml().cpp"

using namespace std;

string getstring(string holder){
    if (holder == "" || holder.size()>100){
        exit(1);
    }

    int i=0,ch=0;
    int size;
    char charInput[100];

        strcpy_s(charInput, holder.c_str());
        size = strlen(charInput);

        #define DATA_LENGTH 100
        #define BUFFER_LENGTH (DATA_LENGTH)

        char Buffer[BUFFER_LENGTH];

            while (i < DATA_LENGTH) {
                Buffer[i++] = charInput[i];
                Buffer[i] = '\0';
                if(size == i){
                        break;
                    }
            }
            holder = Buffer;

            strcpy_s(charInput, holder.c_str());
            size = strlen(charInput);

            i = 0;
            for(int j = 0;j<size;j++)
            {
                if (charInput[j] < 2)
                {
                    if (charInput[j+i] > 2 && charInput[j+i] != 17){
                        charInput[j] = charInput[j+i];
                        charInput[j+i]='\0';
                        i=0;
                        }
                    else{
                        i++;
                        j--;
                    }
                }else if (charInput[j] == 17)
                {
                    if (charInput[j+i] > 2 && charInput[j+i] != 17){
                        charInput[j] = charInput[j+i];
                        charInput[j+i]='\0';
                        i=0;
                        }
                    else{
                        i++;
                        j--;
                    }
                }
            }
            size = strlen(charInput);
            for(int remove = 0; remove<size ;remove++)
            {
                if (charInput[remove] < 2 || charInput[remove] == 17)
                {
                    charInput[remove]='\0';
                }
            }

             string handler;
             handler = charInput;

             handler = handler.substr(0, handler.length() - 1);
             return (handler);
    }

/*
int main(void){

    string final;

    string input = "JELLY-O RUBBERB\n\r               13.25V.¶üÁË0";
    string input2 = "STIÁËCK-O CHOCO\n\r               10.52C.ÁË0¶ü";
    string input3 = "STICÁËK-O VANILLA\n\r               10.52C.ÁË0¶ü";

      final = getstring(input)+ "\n" +getstring(input2)+ "\n"
+getstring(input3);
        cout<<final;
        _getch();

    return 0;

}*/

keypress.cpp
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <string>
#include "FormatPosDataXml().cpp"

    using namespace std;

int c;
char temp[256];

    char getkeypress(char c){

        if (c==0x1b){
            exit(1);
         }

         else if (c==0||c==224)
          {
                    c = _getch();

                    if (c==0x3b){
                        cout << "You typed: F1\n";
                    }
                    else if(c==0x3c){

                        cout << "You typed: F2\n";
                    }
                    else if(c==0x3d){
                        cout << "You typed: F3\n";
                    }
                    else if(c==0x3e){
                        cout << "You typed: F4\n";
                    }
                    else if(c==0x3f){
                        cout << "You typed: F5\n";
                    }
                    else if(c==0x40){
                        cout << "You typed: F6\n";
                    }
                    else if(c==0x41){
                        cout << "You typed: F7\n";
                    }
                    else if(c==0x42){
                        cout << "You typed: F8\n";
                    }
                    else if(c==0x43){
                        cout << "You typed: F9\n";
                    }
                    else if(c==0x44){
                        cout << "You typed: F10\n";
                    }
                    else if(c==133){
                        cout << "You typed: F11\n";
                    }
                    else if(c==134){
                        cout << "You typed: F12\n";
                    }
          }

          else
          {
                while((cin.getline(temp, sizeof(temp), '\n'))&&(temp!="")){
                    cout << "You typed:" << temp << '\n';
                    break;
                }
          }

    }
/*
int main(void){

    while (c^=0x1b){
            cout<<"Press any key:\n";
            c = getkeypress(_getch());
    }
      _getch();
      return 0;
}
*/

how could I link all of these files. I want them to be a library. How could i do it then?
Comment: This code is way too hard to read. Perhaps you or someone else can format it better. Also you should not post complete code examples in a question. Try stripping it down to the bare minimum code required to generate the error.
Comment: Why do you want to include a cpp file into another one? What are you trying to accomplish (in abstract terms - don't think of code for now)?
Comment: @Andro, please accept my edit. Your code will be quite a bit more readable.
Comment: @mgiuca: You *should* post complete code examples in a question!  You should also narrow down a test case to a manageable size before posting.  (I've "voted" on your "edit suggestion", and it won't let me edit until that's either approved (needs more votes) or rejected; I'm unfamiliar with this system.)
Comment: @Fred Nurk Sorry, I meant ... well ... don't post three hundred lines of code when your question is about a linker error. Thanks for voting. I'm not sure how it works either, except I know the original asker can immediately approve the edit.
Comment: @Fred Nurk: I guess my vote to approve "put it over the top", so to speak. Unfortunately, while the code is much more nicely formatted now (thanks @mgiuca), it's still just a big bunch of code, with nothing to tell us what he really wants...
Comment: @JerryCoffin: I completely agree; I just don't want people like Andro to post two lines of code without any context by following "you should not post complete code examples".
Answer: In general, it is bad practice to include another .cpp file inside of a .cpp file. The right way is to break out declarations into .h files and put the definitions in .cpp files. Make sure to put a bogus define at the top of each of your .h files to prevent accidental re-inclusion, as in:
#ifndef MYFILE_H_
#define MYFILE_H_

// your code goes here

#endif

When you compile your program, you need to compile all the .cpp files into .o files (or .obj on Windows), and then link them together. For example (Linux/Mac):
g++ -c foo.cpp
g++ -c bar.cpp
g++ foo.o bar.o -o theMainExecutable

Comment: \_MYFILE\_H\_ is a reserved name; don't use it.
Comment: Good point - changed. See http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier for why.
Answer: You can't include .cpp files, you need to use .h files, which are definitions for functions. Define the stuff in the header files, then implement them (Write the code for them) in the .cpp files.
int main() can only go in one .cpp file, you need to put your code in a function, define it in a header, then include into your main file, then execute it in int main().
Comment: @Øystein Sure it is, but a) it is against all conventions and established practice of the past 30 years, and b) it is quite illegal to import a file which contains any function definition in multiple modules of a project.
Comment: @mgiuca inline functions (including templates) are extremely common in headers. In other words, "function body" is not the thing that distinguishes what should be in a .cpp vs .h, it's more about where the resulting code should be generated - inline or linked.
Comment: SO i need to put the codes of the other C++ files to the .h files?
Comment: @Andro See my answer. You should always have one .h file for every .cpp file. Functions should **only** go in .cpp files, never in .h files. Each public function in the .cpp file should have a declaration (the same heading, but with a semicolon instead of a body) in the corresponding .h file. You should always #include .h files from other modules, never .cpp files.
Comment: Technically it is perfectly legal to #include whatever kind of file you want.
Comment: I'd guess he's coming from a language such as Lua or Blitz where include means copy and paste the contents of that file into the file you are in now.
Comment: @mgiuca: Disagree with a) too, I use it, it's common for large aggregate-initialization lists.
Comment: @tenfour I am ignoring inline functions since this is a fairly basic mistake and it isn't helpful to go into all the exceptions -- better just to lay some initial ground rules. But yes, if you want to be technically correct, inline functions are an exception.
Comment: CPP uses a header system though, in good practice your 'final' file with everything included in it would have forward declarations, in Blitz at least (not completely sure about Lua) ALL of the code is imported into the 'final' file.
Comment: @Chris C/C++ #include *does* just copy and paste the contents of that file into the file you are in now. It's just different due to the linker. In Lua, for example, you do want to paste the entire contents of the file because the top-level module is not linked with the other ones later. In C/C++, you can't because you are going to separately link all the definition files later.
Comment: @mgiuca That was kind of what I was getting at, you would have the declarations in your 'final' file and then link the implementation later.
Comment: @Øystein: "A #include directive shall identify a header or source file that can be processed by the implementation." [§16.2p1]  You cannot just name any file.
Comment: @Fred: Huh? *goes to get standard*
Comment: @Fred: You are right, it does say that. So the file must be processable by the implementation, I stand corrected. Then again, it does not make much sense to include a file that can not be processed.
Comment: @Øystein: I was also looking for a requirement that spelled out that a file must also not end with a partial line (missing a terminating newline), but I don't see it in the C++ standard; perhaps it's specified in C's.
Comment: @Fred: It's in C++ too, see 220.127.116.11 - no newline => UB. What I really meant with my comment was of course that you could #include anything as long as the file contained valid C++ code.
Comment: @Øystein: And I was nitpicking it, of course, because it's just bad advice.  Don't include .cpp files.
Comment: @Fred: No problem with that, my whole role in this question so far has been nitpicking.
Answer: I haven't read all the code, but I would guess you are defining the same function in two modules. Firstly, you should not have a main in all three files. Only one of them. If you are planning to make a library, none of the files should have a main -- that should be in the program which imports your library.
As for convertInt, I suspect it is defined in multiple files. If it isn't, then perhaps it is defined in a header file. You should only put declarations in a header file, such as this:
string convertInt(int number);

(note the semicolon)
The definition should always appear in the corresponding CPP file, like this:
string convertInt(int number) { ... // Body of the function }

If the definition appears in the header file, you have a problem, because every CPP file which #includes that header will contain a duplicate definition.
Comment: Ah, having read Chris's answer, I see the problem: You are #including a CPP file, effectively causing it to be used as a header file.
Comment: Definitions may appear in headers as well, most commonly as inline.
Comment: @Øystein Well, only as inline (it's the only way to avoid an error). I was trying to lay some initial ground rules for beginning C++, not explain all the quirks of the language.
Comment: By "most commonly" I think you mean "always".
Comment: @tenfour and mgiuca: No, I mean "most commonly". You write your whole program in a header and just include it in a .cpp file (or just compile the header, unless your compiler freaks out) if you wish.
Comment: @Øystein I think you are massively confusing the issue. First, it doesn't help to bring up all the possible special cases which you might use as an advanced user when the OP clearly has not gotten the fundamental concept of header files. Second, why would you ever write a program in a header file and include it in a .cpp file? It would break if you ever included it in multiple .cpp files and linked them. (Yes, inline is an exception, but it's the only exception.) Just because you *can* do something doesn't mean you should bring it up here, especially if it has no use ever.
Comment: @mgiuca: Knowledge does not hurt. Even though the OP won't have a use for it, you and tenfour should be happy at least :) And this does have its use, as I mentioned in a comment to another answer.
Comment: @Øystein Knowledge certainly can hurt. As someone who has taught this concept at university for the past five years, I know better than to offer students random advice, even if technically correct. If something *can* be done but shouldn't be with a handful of advanced exceptions, it is better to simply tell students *not* to do it, rather than say "sure you can do it" and then start a lengthy discussion about when and why. Students are then less likely to think it's okay. Even though, you *can*, I don't want to encourage people to go #including .cpp files or placing definitions in headers.
Comment: @mgiuca: I never offered any advice to the OP. As a programmer I naturally react to inaccuracies, and prefer not to see false facts. I think part of what makes this community good is the pedantry going on here, and the attention that is payed to being succinct and accurate. It has taught me a lot.
Answer: Without weeding through your huge jumble of code, it seems that you are trying to merge different source files into the same project resulting in conflicting names.
I think you will just need to find a way to structure your code so that you don't get conflicting symbols. You obviously cannot have three different entry-points in your application. Which one do you want to be called? If you want the user to choose, for example, then you have to write the code for this, and name your functions accordingly.
For example with convertInt, if you need to include different variations of this function in your application, then you will need to name it properly to distinguish it.
Possible solutions for convertInt include:

Wrap convertInt (and possibly other functions) in a namespace, and call them like Variation1::convertInt(x)
Just give things unique names. convertInt1, convertInt2, etc.
Take the time to merge related functions. I doubt that two functions named convertInt, in the same project, with the same signature, actually do different things. Merge them so there is only 1 function to think about.

Apologies if my answer has nothing to do with your problem.
Comment: He's not trying to define different versions of `convertInt`. Rather, there is only one version, but it is being #included into all three files.
Answer: The Technique I use as to import classes and variables from other files is : (as I know of)

Importing the Raw C++ File(s). [Tho not the most preferred method.]

Let's say I've two C++ Files :
file_1.cpp
#include<iostream>
using namespace std;

int x = 8;            // A Random Variable

class Math{           // A Random Class

    public:

        static int multiplyBy5(int x){
            return x * 5;
};

file_2.cpp [The Driver File let's Say]
#include<iostream>
#include "file_2.cpp"                // This can be the Relative/Absolute Path.
using namespace std;

int main()
{
    // Importing External Variable present in the imported File. [Tho we don't need to define `extern` as we're importing the whole file itself.]
    extern int x;
    cout<<x<<endl;
    cout<<Math::multiplyBy5(5)<<endl;
    return 0;
}

Note :

The main() method should exist only in the Driver Program. Defining main() method in other files will break your driver code.
You can replace the .cpp extensions of the files being imported by .h [Interface] which is considered a better practice then importing directly the raw .cpp.
Doing so, you don't need to compile the other files you're importing. So, basically you can access and run all the files all together by simply running the driver code i.e. -

g++ file_2.cpp -o file_2
./file_2

Include C++ File to another C++ File


cannot specify name of the download file using Javascript

Question: I am using Javascript to create a CSV file for user to download.
Until May 22nd, Chrome still downloaded the file with the name I specified. However, today I found that the files downloaded are named "download" and do not have the extension .csv.
This problem does not exist in Firefox!
Here is a fiddle with sample Javascript:
var A = [['n','sqrt(n)']];  // initialize array of rows with header row as 1st item
for(var j=1;j<10;++j){ A.push([j, Math.sqrt(j)]) }
var csvRows = [];
for(var i=0,l=A.length; i<l; ++i){
    csvRows.push(A[i].join(','));   // unquoted CSV row
}
var csvString = csvRows.join("\n");

var a = document.createElement('a');
a.href     = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvString);
a.target   = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();

Comment: That's weird... Last time I tried this it worked just fine in Chrome too. I'll have a look at why this is happening.
Answer: Nice work! This is a regression.
I just created another fiddle, and filed a Chrome bug.
If you're interested, star it in the bug tracker.
Click here

EDIT: It look like it depends on the URL. Absolute URLs work, as well as objects URLs (according to https://code.google.com/p/chromium/issues/detail?id=376197).
Comment: The error report is not completely correct though. [only data-URIs don't work anymore](http://jsfiddle.net/Cf48L/).
Comment: I'm sorry, I take that back (also removed Google forums post). I'm sure I must have been looking at the wrong thing or something, but I thought it worked. I have no idea if I was just derping there (probably) or if it was something else, but you're right.
Comment: so...this is a bug in one of the chromium update right?
Comment: fwiw @PaulDraper jsfiddle working ok at chromium 31. _at_ Joeytje50 Both links at jsfiddle work ok at chromium 31. jsfiddle at original post work ok, too. Is issue with chrome/chromium 35+ ? Thanks
Comment: @guest271314, yes hence "This is a regression".
Comment: @PaulDraper Interesting. retrieved chromium 34 and chrome 37. The file name appears to be related to `href` attribute? Have a simple web page that had to check following this Question and Answer. Similar scenario, a `.pdf` file for download or print. That web page had both `download` and `href` attribute with same name, i.e.g., `foo.pdf`. Worked ok at both chromium 34 and chrome 37. Went back to your jsfiddle and changed the `href` to same as `download`, works ok  http://jsfiddle.net/n6QTS/. Have not tried further adjustments; appears file name is listed when `download` and `href` is same ?
Comment: @PaulDraper yes, createObjectURL does work. Thank you!


R - Access an object own's name in apply functions

Question: This is a problem I often encounters: I try to access an object's own name when using a function from apply family and spend hours figuring out how to do it... For instance (this is not the core of my question), today I was willing to inspect an attached package trying to figure out if it contained some non function objects. After a lot of tries and fails, I finally came up with (for the rrapply package - I know looking at the documentation is also easy but this one illustrates well the problem):
library(rrapply)

eapply(rlang::pkg_env('rrapply'), function(x) {if(!is.function(x)) x}) %>%
`[`(sapply(., function(x) !is.null(x))) %>%
names()

## [1] "renewable_energy_by_country" "pokedex"

I feel that is really too complicated for a simple test !
So my question: is there an easy way to loop through an object in base R (or maybe tidyverse) and return only the names of those elements that correspond to a certain condition ? rrapply seems to be able to achieve that but:

it is fairly complicated
and it seems to work on lists only and to loop through all sub-elements as well which is not desired

Thanks !
Comment: You may also find that `purrr::imap` is your friend
Comment: `grep(names(x), value = TRUE)` may be your friend. Or just `names(x)[names(x) %in% whatever]` or similar. You might also check out https://github.com/hughjonesd/rumpel for functions which return not the names but the named elements.
Comment: I think the question needs some clarification. Is it just about finding names of vector elements? Or is it about finding names of objects in an environment? The former is pretty trivial.
Comment: Actually you may give us an example of what you are after?
Comment: imap does easily returns the names : `imap_chr(ls('package:rrapply'),~ .x)` gives `[1] "pokedex"                     "renewable_energy_by_country" "rrapply"  `. That is OK, but then why on earth can't I just operate on them ?? `imap_chr(ls('package:rrapply'),~ is.function(.x))` unexpectedly gives `[1] "FALSE" "FALSE" "FALSE"` and  `imap_chr(ls('package:rrapply'),~ as.name(.x))` gives an error
Comment: with a call to get, we obtain better results : ```imap_chr(ls('package:rrapply'),~ is.function(get(.x)))  ====>
[1] "FALSE" "FALSE" "TRUE" ``` but still not easy to use as ```imap_chr(ls('package:rrapply'),~ if (is.function(get(.x))) .x)```throws an error :(
Answer: Identify the environment of interest, e, and then use eapply with the indicated function taking the names of the extracted elements at the end.  This isn't conceptually different from the code in the question but does seem somewhat less complex when done in base R in the following way:
e <- as.environment("package:rrapply")
names(Filter(`!`, eapply(e, is.function)))

or the same code written as a pipeline:
library(magrittr)

"package:rrapply" %>%
   as.environment %>%
   eapply(is.function) %>%
   Filter(`!`, .) %>%
   names

Comment: Clean and neat in base R, Thanks !


Spring Boot - Error creating bean with name 'requestMappingHandlerAdapter', NoSuchFieldError: defaultReader

Question: I am working on a Spring Boot REST application. However, whenever I attempt to start it I receive the following error:
Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]: Factory method 'requestMappingHandlerAdapter' threw exception; nested exception is java.lang.NoSuchFieldError: defaultReader

Now, from this question (and the stack), I gather it is an issue with JsonSmart and/or JsonPath as used by Jackson for conversion.
Caused by: java.lang.NoSuchFieldError: defaultReader
at com.jayway.jsonpath.spi.json.JsonSmartJsonProvider.<init>(JsonSmartJsonProvider.java:39) ~[json-path-2.2.0.jar:2.2.0]
at com.jayway.jsonpath.internal.DefaultsImpl.jsonProvider(DefaultsImpl.java:21) ~[json-path-2.2.0.jar:2.2.0]
at com.jayway.jsonpath.Configuration$ConfigurationBuilder.build(Configuration.java:231) ~[json-path-2.2.0.jar:2.2.0]
at org.springframework.data.web.JsonProjectingMethodInterceptorFactory.<init>(JsonProjectingMethodInterceptorFactory.java:72) ~[spring-data-commons-1.13.9.RELEASE.jar:na]
at org.springframework.data.web.ProjectingJackson2HttpMessageConverter.initProjectionFactory(ProjectingJackson2HttpMessageConverter.java:85) ~[spring-data-commons-1.13.9.RELEASE.jar:na]
at org.springframework.data.web.ProjectingJackson2HttpMessageConverter.<init>(ProjectingJackson2HttpMessageConverter.java:70) ~[spring-data-commons-1.13.9.RELEASE.jar:na]
at org.springframework.data.web.config.SpringDataWebConfiguration.extendMessageConverters(SpringDataWebConfiguration.java:129) ~[spring-data-commons-1.13.9.RELEASE.jar:na]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurerComposite.extendMessageConverters(WebMvcConfigurerComposite.java:143) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration.extendMessageConverters(DelegatingWebMvcConfiguration.java:122) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.getMessageConverters(WebMvcConfigurationSupport.java:722) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.requestMappingHandlerAdapter(WebMvcConfigurationSupport.java:529) ~[spring-webmvc-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration.requestMappingHandlerAdapter(WebMvcAutoConfiguration.java:384) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$f44b477f.CGLIB$requestMappingHandlerAdapter$7(<generated>) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$f44b477f$$FastClassBySpringCGLIB$$d3f16523.invoke(<generated>) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358) ~[spring-context-4.3.13.RELEASE.jar:4.3.13.RELEASE]
at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$f44b477f.requestMappingHandlerAdapter(<generated>) ~[spring-boot-autoconfigure-1.5.9.RELEASE.jar:1.5.9.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_40]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_40]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_40]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_40]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
... 19 common frames omitted

I presume it may be some sort of dependency issue; however, I have made  attempts at switching versions and manually bringing in dependencies (such as Spring Data) to override the starter defaults. No success. Here is my gradle file:
  buildscript {
    ext {
        springBootVersion = '1.5.9.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

group = 'com.midamcorp'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
testCompile('junit:junit:4.11')
    testCompile('org.springframework.boot:spring-boot-starter-test')
    compile('org.springframework.boot:spring-boot-starter-data-jpa')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-data-rest')
    compile('org.springframework.boot:spring-boot-starter-security')
    compile('org.springframework.security.oauth:spring-security-oauth2:2.2.1.RELEASE')
        compile('org.springframework.security:spring-security-jwt:1.0.9.RELEASE')
compile('org.modelmapper:modelmapper:0.7.5')
    compile('org.hibernate:hibernate-java8:5.0.0.Final')
compile('com.microsoft.sqlserver:mssql-jdbc:6.1.0.jre8')

}

Any advice is appreciated.
Thanks.
Comment: Have you checked [this](https://stackoverflow.com/questions/40954331/json-parser-java-lang-nosuchfielderror-defaultreader) question?
Comment: Just in case it helps anyone else, I found the issue. The conflict arose because of the version of mssql-jdbc driver I was using (it apparently depended on an old version of JsonSmart). Switching to a newer version resolved the conflict. Thanks.
Comment: @amdg yes, thanks, but unfortunately, while it provided some guidance, it did not help resolve my particular case. I am using Spring Boot Starters and Gradle to load in the dependencies. I assume there no issues with the Spring Starters independently (as I am sure this would have been reported), but I am curious if anyone might be able to, based upon their knowledge of the Spring framework, point me to where the fault might be or there are some compatibility concerns (for example, loading spring-boot-starter-data-rest and spring-security-oauth2). Thanks.
Comment: I have an identical stack trace, yet no mssql-jdbc driver :-/
Answer: Managed to fix it by going to Open Module Settings -> Dependencies and delete the Test dependency com.jayway.jsonpath:json-path


Boolean Function in ada 'procedure or entry name expected' 'invalid use of subtype mark in expression or call'

Question: I am stuck on my ada program which is supposed to for loop through an array and return true for the number of 100 in the list. I am having trouble getting my code to compile without errors, i am brand new to ada and also ada boolean functions. If someone could help point me in the right direction I would seriously appreciate it
with Gnat.Io; use Gnat.Io;
procedure Arr is

type ArrayType is array (Integer range<>) of Integer;

    Array1 : ArrayType := (45, 100, 75, 32, 99, 66, 82);
    Array2 : ArrayType := (67, 78, 89, 97, 45);
    Array3 : ArrayType := (1,2);

function HasPerfectScore (theArray : ArrayType) return Boolean is
begin
    for I in Array1'Range loop
       if I = 100 then
            Put("Perfect score = (I)");
       else
            Array1(I=I+1);
       end if;

    end loop;
return Boolean;
end HasPerfectScore;
begin
    null;
end Arr;

Comment: You cannot say 'return Boolean' as a statement. Boolean is a type and not a value. True and False are Boolean values
Comment: I am sorry to say that you lack of basic understanding of function in Ada. Even we help you with the code, you may not understand it unless you understand the basic. First, it is function parameter.  Second, it is the function return (True or False). Third, it is about actual parameter passing.
Comment: There are several problems with this program. Please provide exact list of compiler errors with your question
Answer: I suspect you do not understand the comments you received. Here is a program that does what you want to do.
-------------------------------------------------------------
-- Indicate whether or not an array of integers contains
-- the value 100
-------------------------------------------------------------

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   type Nums is array (Positive range <>) of Integer;

   function contains_100 (Arr : Nums) return Boolean is
      Result : Boolean := False;
   begin
      for I in Arr'Range loop
         if Arr(I) = 100 then
            Result := True;
         end if;
      end loop;
      return Result;
   end contains_100;

   Num_Elements : Positive;
begin
   Put ("Enter the number of elements in the array: ");
   Get (Num_Elements);

   declare
      Sample : Nums (1 .. Num_Elements);
   begin
      Put_Line ("Enter the" & Num_Elements'Image & " values:");
      for I in Sample'Range loop
         Get (Sample(I));
      end loop;

      if contains_100 (Sample) then
         Put_Line ("The array contains the value 100.");
      else
         Put_Line ("The array does not contain the value 100.");
      end if;
   end;

end Main;

The function named contains_100 takes a parameter of the type Nums, which is an unconstrained array type. This means that the array passed to the function contains_100 can be any size, but it will have a definite size as we will see further on in the program.
The function contains_100 returns a Boolean value, which must be either True or False. The function declares a local variable named Result. Result is a Boolean initialized to False because at this point in the function we have not found the value 100 in the array.
The for loop iterates through all the values in the parameter Arr, comparing each value in turn to the number 100. If the value equals 100 the local variable Result is assigned the value True. After the loop completes the local variable Result will either be False because we never encountered the value 100 or it will be True because the array contains at least one element with the value 100. The value of Result is returned.
This program gets the values for the array from user input. We must know how many values the user wants to input so that we can make an array of the correct size. The local variable Num_Elements will hold the number of elements the user wants to enter.
The user is prompted to enter the number of elements in the array. The Get procedure from Ada.Integer_Text_IO inputs the user's response and places the value in the variable Num_Elements.
The program now needs to create an array containing Num_Elements, but we are now in the executable portion of the procedure Main where we cannot declare variables. The simple answer is to create a new code block within main beginning with the reserved word "declare". The reserved word "declare" creates a new declarative region allowing the creation of an array named Sample with exactly Num_Elements elements.
A new executable portion of the internal code block begins and the user is prompted to enter the Num_Elements values into the array.
The for loop then calls Get to input a value in each element of the array Sample.
Finally, an "if" condition is executed, calling contains_100 and passing in the local variable Sample. If contains_100 returns True then the program outputs a message stating that the array does contain the value 100. If contains_100 returns False the program outputs a message stating that the array does not contain the value 100.
Following are some examples of executing the program:
Enter the number of elements in the array: 3
Enter the 3 values:
-100 0 9
The array does not contain the value 100.

Enter the number of elements in the array: 8
Enter the 8 values:
1 2 3 4 5 100 6 7
The array contains the value 100.

Edit: In response to the discussion concerning the use of a quantified expression the program above can be simplified to the following.
-------------------------------------------------------------
-- Indicate whether or not an array of integers contains
-- the value 100
-------------------------------------------------------------

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   type Nums is array (Positive range <>) of Integer;

   Num_Elements : Positive;
begin
   Put ("Enter the number of elements in the array: ");
   Get (Num_Elements);

   declare
      Sample : Nums (1 .. Num_Elements);
   begin
      Put_Line ("Enter the" & Num_Elements'Image & " values:");
      for I in Sample'Range loop
         Get (Sample (I));
      end loop;

      if (for some I of sample => I = 100) then
         Put_Line ("The array contains the value 100.");
      else
         Put_Line ("The array does not contain the value 100.");
      end if;
   end;

end Main;

Comment: Nowadays, the entire body of `contains_100` could be `is (for some E of Arr => E = 100);`
Comment: Simon Wright
I realize that, but the original author is very new to programming and is still thinking in terms of explicit looping. In fact the entire function can be deleted and the quantified expression can replace the function call.


gcloud rebuilds complete container but Dockerfile is the same, only the script has changed

Question: I am building Docker containers using gcloud:
gcloud builds submit --timeout 1000 --tag eu.gcr.io/$PROJECT_ID/dockername Dockerfiles/folder_with_dockerfile

The last 2 steps of the Dockerfile contain this:
COPY script.sh .
CMD bash script.sh

Many of the changes I want to test are in the script. So the Dockerfile stays intact. Building those Docker files on Linux with Docker-compose results in a very quick build because it detects nothing has changed. However, doing this on gcloud, I notice the complete Docker being re-generated whereas only a minor change in the script.sh has been created.
Any way to prevent this behavior?
Answer: Actually, gcloud has a lot to do:
The gcloud builds submit command:

compresses your application code, Dockerfile, and any other assets in the current directory as indicated by .;
uploads the files to a storage bucket;
initiates a build using the uploaded files as input;
tags the image using the provided name;
pushes the built image to Container Registry.

Therefore the compete build process could be time consuming.
There are recommended practices for speeding up builds such as:

building leaner containers;
using caching features;
using a custom high-CPU VM;
excluding unnecessary files from upload.

Those could optimize the overall build process.
Comment: This is kind of a trade-off between: 1) universal, documented, supported, with provided computing capacity, perhaps not fitted to the particular needs so not the fastest solution; and 2) customized, not documented, supported by a local team, consuming local on-premise resources but fitted ideally to the particular needs one. It is up to you to choose.
Comment: might it be wiser to build the Docker files locally and thereby employ Docker-compose that does it much quicker? And then upload the locally generated container?
Answer: Your local build is fast because you already have all remote resouces cached locally.
Looks like using kaniko-cache would speed a lot your build. (see https://cloud.google.com/cloud-build/docs/kaniko-cache#kaniko-build).
To enable the cache on your project run
gcloud config set builds/use_kaniko True

The first time you build the container it will feed the cache (for 6h by default) and the rest will be faster since dependencies will be cached.
If you need to further speed up your build, I would use two containers and have both in my local GCP container registry:

The fist one as a cache with all remote dependencies (OS / language / framework / etc).
The second one is the one you need with just the COPY and CMD using the cache container as base.


In what year did venting bathroom exhaust out of the house become a code requirement?

Question: what was the year for code for vented bathroom exhaust fan?
What is the code for vented bathroom exhaust fan?
Comment: I think I see where you're going with this. Your's is not and you think it should be? It's been a requirement (to go outside, not necessarily through the roof) for quite a while in many jurisdictions, but it is a commonly overlooked requirement resulting in many installations being out of compliance. Despite this, the world continues to turn.
Comment: you need to state your city/province/country
Comment: @bcworkz, it's generally worth fixing if the room has a shower or bathtub though, because otherwise you're either overstressing (and paying a lot) for your HVAC system to remove all the moisture, or you're going to have mold problems eventually.
Answer: This completely depends on your location, and what codes you follow.  The first mention of exhausting to the outdoors I could find in International Residential Code (IRC), was in the 2003 version.

International Residential Code (IRC) 2003
Chapter 15 - Exhaust Systems
SECTION M1506 MECHANICAL VENTILATION
M1506.2 Recirculation of air. Exhaust air from bathrooms and toilet rooms shall not be recirculated within a residence or to another dwelling unit.

In 2006 the code was moved and updated a bit.

International Residential Code (IRC) 2006
Chapter 15 - Exhaust Systems
SECTION M1501 GENERAL
M1501.1 Outdoor discharge. The air removed by every mechanical exhaust system shall be discharged to the outdoors. Air shall not be exhausted into an attic, soffit, ridge vent or crawl space.
Exception: Whole-house ventilation-type attic fans that discharge into the attic space of dwelling units having private attics shall be permitted.

In 2012 they added a reference to another code section.

International Residential Code (IRC) 2012
Chapter 15 - Exhaust Systems
SECTION M1501 GENERAL
M1501.1 Outdoor discharge. The air removed by every mechanical exhaust system shall be discharged to the outdoors in accordance with Section M1506.2. Air shall not be exhausted into an attic, soffit, ridge vent or crawl space.
Exception: Whole-house ventilation-type attic fans that discharge into the attic space of dwelling units having private attics shall be permitted.
SECTION M1506 EXHAUST DUCTS AND EXHAUST OPENINGS
M1506.2 Exhaust openings. Air exhaust openings shall terminate not less than 3 feet (914 mm) from property lines; 3 feet (914 mm) from operable and nonoperable openings into the building and 10 feet (3048 mm) from mechanical air intakes except where the opening is located 3 feet (914 mm) above the air intake. Openings shall comply with Sections R303.5.2 and R303.6.
Chapter 3 - Building Planning
SECTION R303 LIGHT, VENTILATION AND HEATING
R303.5.2 Exhaust openings. Exhaust air shall not be directed onto walkways.
R303.6 Outside opening protection. Air exhaust and intake openings that terminate outdoors shall be protected with corrosion-resistant screens, louvers or grilles having a minimum opening size of 1/4 inch (6 mm) and a maximum opening size of 1/2 inch (13 mm), in any dimension. Openings shall be protected against local weather conditions. Outdoor air exhaust and intake openings shall meet the provisions for exterior wall opening protectives in accordance with this code.

NOTE: It's possible that this requirement existed prior to the 2003 code version, but I was not able to find it. Also note that this is only one building code, and that others do exist.

Thanks to @HerrBag for making me take a second look at 303.3, it appears there is mention of exhausting to the outside in the 2000 version of IRC.

International Residential Code (IRC) 2000
Chapter 3 - Building Planning
SECTION R303 LIGHT, VENTILATION AND HEATING
R303.3 Bathrooms. Bathrooms, water closet compartments and other similar rooms shall be provided with aggregate glazing area in windows of not less than 3 square feet (0.279 m²), one–half of which must be openable.
Exception: The glazed areas shall not be required where artificial light and a mechanical ventilation system are provided. The minimum ventilation rates shall be 50 cfm (23.6 L/s) for intermittent ventilation or 20 cfm (9.4 L/s) for continuous ventilation. Ventilation air from the space shall be exhausted directly to the outside.

Since this is as far back as I've been able to access the IRC (so far), I can only come to the conclusion that it has always been a requirement. At least ever since mechanical ventilation has been an approved bathroom ventilation method.
Answer: While it is highly recommended, having a bath exhaust fan, per se, is NOT required as of the  2009 IRC code (which is current for my location).  Language including the option for mechanical exhaust appears to be 2003.
Summarizing IRC R 303.3
What is required is either:

A window that will open to a minimum of 1.5 sq-ft (with a total
glazing of 3 SF) or
Artificial light and mechanical ventilation.  Minimum of 50 CFM
intermittent or 20 CFM continuous.


Determine if a JSON file has been downloaded correctly?

Question: A very simple question, how to I determine if a JSON file has been downloaded correctly? I am connecting and getting the file from the API using ajax.
Thanks.
Let me show the code:
$.ajax({
    url: url,
    type: "GET",
    data: {},
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    timeout: 10000,
    success: function(uri){
        writeFile(name, JSON.stringify(uri), "Inmark/InmarkDictionary");
        ISAPP.spinner.hide();
    },
    error: function(xhr, status, error){
       if(status == "timeout") {
           ErrorAlert(label.requestTimeoutLabel);
       } else {
           ErrorAlert('URL : ' + error.message + ' | status: ' + status);
       }
    }
});

Comment: If you are receiving a 200 response code (the done handler on ajax) and you can parse the data coming back as JSON then you can be satisfied the json is correct.
Comment: Not sure, but you can try to parse it and verify successful parsing happened or not. `JSON.parse()`
Comment: Mostly this is not a problem. If you think you're likely to have trouble then you could create a checksum with SHA256, MD5, whatever, and send that along with the file and check it after the transfer is complete.
Answer: You can use done() or success() to know if transfer is complete:
$.ajax({
  url: "example.php"
}).done(function() {
  alert( "success" );
});

and then check with JSON parse:
$.ajax({
  url: "example.php"
}).success(function() {
  try {
    parsedData = JSON.parse(response);
  } catch (e) {
    // is not a valid JSON string
  }
});

Comment: @Nothing Since you have improved your answer I have now removed my comment. Your comment, however, I have flagged as not constructive
Answer: If i understand your question correctly, if its a simple JSON file or any other format your application wont know its downloaded correctly or not unless the downloaded file/script runs and/or communicate to it or you make your application look for it (something like File.exist).
However in order to make JSON download available, you may find this helpful:
http://jsfiddle.net/cowboy/hHZa9/
var obj = {a: 123, b: "4 5 6"};
var data = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

$('download JSON').appendTo('#container');

Answer:
If the status code of the ajax request is 200, it means the download job is done as expected.
If you want to make sure the content of the JSON Object is 100% correct, you can sign the content (To be simple, MD5/SHA is good enough; if you want to be more secure, you can use RSA or EC). For example, the remote server calculate the signature, and put it in JSON :
json : {
content : {
     //put your origional JSON here
},
signature : "13241234123412342134"
}
After browser gets the JSON object, re-check the signature to validate the content.
Or you can use HTTPS. The browser will do validation for you.
Comment: How do I sign it if I don't have access to the API? the app only fetches the JSON file.
Comment: I am afraid you must be able to access the server code (To do signature, both server and client/browser code needs to be changed).
Comment: If you cannot, I think using HTTPS is the simplest way. HTTPS protocol makes sure the security, integrity of data between server and browser.
Comment: when i made it HTTPS i started having problem connecting to the API.
Comment: Please make sure the remote API supports HTTPS protocol.


fetching json data from local file

Question: TypeError: this.state.data.map is not a function
Trying to access local json data.
    import React, { Component } from 'react';
    import './index.css'
   class App extends Component {
     constructor(){
        super()
        this.state = {
         data: []
         }

       }
     componentDidMount()
      {
        fetch("./employeeData.json")
       .then(res => res.json())
       .then(daabta => {
        this.setState({data: daabta })
        } )
       }
     render() {
       return (

{this.state.data.map((item, index) =>

              {item.userId}
              {item.firstName}
              {item.lastName}
              {item.region}

            )
           })}

        )
       }
      }
     export default App;

Comment: Please describe your problem and what you try to achieve. So far you only gave us there error and the code (good start).
Answer: You can just import your json file directly at the top of your component like
import * as employeeData from "./employeeData.json";

but be careful your json data would be inside and object named default so when you want to access the data you should use employeeData.default

fetching json data from local file


How to secure these wooden porch posts to the concrete slab?

Question: The front of my house has an overhang extension of the roof, held up by three posts. The posts are loose on bottom and I'm wondering how best to affix them to the concrete.

While they are stable most of the time, if I pull up on a post, it can move side to side a bit. If someone leaned with all their weight on one of these posts, I wouldn't be surprised if it would slip out and get loose of the soffits/roof overhang.
As you can see in this next picture, there are indents in the concrete, presumably for these posts. The bottom of the posts don't fit snugly in those holes, though, or not enough to stay put when the posts or horizontal plank between them gets pushed on. To show these indents, I lifted up the post a little by the horizontal planks attached to it, then it can sway side to side a few inches. The roof extension and its vinyl soffits seem unaffected by any of this.

What's the simplest way to affix these to the slab? I'm not opposed to holding them in place with bricks, I'm just not sure that's enough if someone were to put their weight on it (I'm trying to make it safe in case someone were to lean against it, or stumble and push on it).
Comment: Looks like the (ceramic?) bottom pads are doing a good job of keeping the post away from water on the ground. The concrete looks like it's not very thick at all and so probably isn't suitable for embedding an anchor.
Comment: @Armand related post about painting: https://diy.stackexchange.com/questions/272897/safe-to-keep-these-outdoor-posts-in-use-by-painting-and-how-to-handle-old-paint
Comment: @Armand does seem like ceramic. Shoving a ruler underground, the slab is at least 4" thick and maybe 6". On one side of that front "porch", the far end in the first picture, the slab is 10"+ thick as grade goes downhill. That said, anchoring into concrete is far less simple for me than your suggestion with rebar in soil - thanks!
Comment: Are those little holes (in the last pic) the original location for the standoff at the bottom of the post?
Comment: @Huesmann to the best of my knowledge yes, they've been this loose/unsecured since I got here
Answer: There are many kinds of post bases available which are designed for exactly this purpose. You want something attached to the concrete. You'd do that with concrete screws and a hammer drill.
"Holding them in place with bricks" isn't viable. A brick (or even a small pile of bricks) provides very little lateral support. The solution doesn't come close to being effective or safe, structurally speaking. It would also increase moisture retention, accelerating rot.
Something stuck in the ground won't work well either unless it's deep and rigid, such as a pipe or treated 4x4 down at least 36" or embedded in concrete. A bit of rebar will flop around and be practically useless. It'll also look like poop.
I would want to know whether these posts are intended to bear load, or if they're just decorative. If the former, you may need to jack the roof back into position before you install bases or new posts. You could have some sag that shows on the roof plane and strains framing.
Comment: From the top photo it is not clear that they should be several inches back from the edge - perhaps the OP can clarify. That giant crack also isn't giving me a warm fuzzy that trying to solidly attach a post base isn't just going to shatter more concrete. Just something for them to contemplate if they want to try that. As indicated, I know that post bases can work just fine, there are some issues for them to consider here though.
Comment: 4x4 posts can carry massive weight, and we have no idea what sort of beams could be in the roof.
Comment: Those would work, but I like [these](https://www.strongtie.com/retrofitpostbases_postbases/aba_base/p/aba) better. They're less conspicuous and the concrete fasteners are hidden. They also keep the wood off the concrete.
Comment: Have a look at the bottom photo. They're apparently out of position now and need to be brought back in a fair bit.
Comment: @isherwood Let's not exagerate, they can stand their load, but not massive ones over the years, the OP moved one easily to show the indents, which is a good clue
Comment: Are you implying that the posts dented the concrete? That's certainly not the case. Decks and porches much larger than this are carried without issue on 4x4 posts. If the concrete settled that's a problem with the concrete, not the posts. I'm not exaggerating. I'm experienced.
Comment: @isherwood I assume the indents had something fastening the posts to the pad that rusted away.
Comment: Being right on the edge of the concrete could be a problem for the outermost bolts. I did something similar some 20 years ago on our porch, but the post bases are about 8cm from the concrete pad edge, so they could drive the explosive concrete anchors in with no worries. No shifting since that time.
Comment: Yes from the spacing between posts and how thin they are, I doubt they carry much weight
Comment: If you say so, I think "massive weight" doesn't have the same meaning for an architect that worked on public buildings with all the safety regulation. I reckon the US building style is much more "temporary" designed than here in europe, we often have 20cm posts, they last centuries. The indents are mentioned in the question, they were probably a poor man's solution to lock the post's supports in place
Comment: Post bases are all 2.5" or more from the edge of concrete on all sides.
Comment: It appears all that's held up is this roof extension. In the attic the extension is visible as rafters and joists appended on to the main roof rafters and joists. So, these posts are not holding up the rest of the roof, but they are the only vertical members supporting the roof extension.
Comment: It looks like https://www.strongtie.com/retrofitpostbases_postbases/rpbz_base/p/rpbz would work easily to screw into the posts and the concrete, paint it, then it's good to go. If I need to replace the posts, I can unscrew those from this metal bracket, put a jack up to secure the roof temporarily, then swap out new posts. Does that sound reasonable?
Comment: The porch roof may be cantilevered and self-supporting. Many modern roofs are, or they have obvious beams across the posts. I can't tell what situation you have, but there doesn't seem to be enough height in the roof for beams.
Comment: @isherwood thanks for the suggestion, that part you linked to makes sense to me. The reason I didn't go with that first is it seems I'd need to pick the post up further, and/or knock the ceramic bottoms off the posts. Since the posts move a bit already, does it seem reasonable to slightly push one at a time off its center, drill and screw this metal base to the concrete slab, then lift the post up 1" or so to get it on the base and screwed in?
Comment: @isherwood when you refer to not enough height in the roof for beams - are you saying that if a beam spanned horizontally across the top of the three posts, that would indicate these posts provide meaningful support? And if there is no beam between the posts, then the roof extension is probably held up more by cantilevering from rafter and joist extensions?
Comment: That's the general assumption, yes. You'd need height for the beam as well as the rafters resting on it.
Comment: You would not retain ceramic supports with the part I linked. That would be redundant and less stable.
Comment: @isherwood digging into this, I'd appreciate your guidance on what to use as an anchor. If I get https://www.homedepot.com/p/Simpson-Strong-Tie-ABA-ZMAX-Galvanized-Adjustable-Standoff-Post-Base-for-4x4-Nominal-Lumber-ABA44Z/100374999#overlay what's the safest way to secure that base? The porch appears to be a monolithic concrete slab, with a crack near one post's base as comments noted. From an exposed side of the slab on one end, it is 10" deep.
Comment: Would a 5/8" carbide drill bit followed by a 1/2" https://www.strongtie.com/mechanicalanchors_mechanicalanchoringproducts/thd_anchor/p/titen-hd or something similar, 5" deep, do the trick? I've only hammer-drilled into block walls for tapcon screws before so this is new to me.
Comment: If you're drilling holes that large, use expanding sleeve anchors. There's absolutely no reason for a bolt that thick or to rely solely on _threads_.
Answer: Why not drive a 3 or 4 foot length of 1/2" rebar into the ground right at the dirt edge behind each post? Leave 1 foot above the surface and use U-shaped pipe/conduit "two hole straps" to secure each bar to the back of a post. The rebar will rust, so first paint the above ground end with "galvanizing" or similar paint.
Comment: That would look hideous and provide only modest support. The rebar would move around a lot in soft soil. It's very flexible, and most of the load will be right near the surface.
Comment: I agree with isherwood on this, a rebar straight in soil will offer very little resistance to lateral forces, particularly when the soil is wet, the rebar will just move in the soil, and the more loose it will get, the less it will resist, as the space around the rebar will fill with water when it rains. Drilling a hole in concrete is simpler and quicker than stick a rebar 4 feet in the soil
Comment: @cr0 1/2" rebar is pretty strong, and with 2 or especially 3 feet underground will be well-anchored.  Just use 3 or 4 straps on each above-ground section with strong 3" long screws to secure them into the wood.
Comment: Also, after noticing the original post position, you'd need a standoff to reach the edge of the slab.
Comment: This is the kind of simple and easy fix I was hoping for! I wonder if it would be strong enough to hold the posts in place? It helps that the most likely direction people would push on the posts would be directly against the rebar.
Answer: What isherwood said is correct. You need to know how structural these posts are. Based solely on your photos, they seem to be holding up on the overhang part of your roof.
What I would do is remove the soffits and see what you have underneath. How are these 4x4s doing their jobs? Are they bolted? Lag bolted? Screwed? Nailed? Can they be easily removed?
The good news for you is it may be simple to not only fix this better than it is now, but you would gain a little porch space in the process. It looks like the roof overhangs a bed in front of your house. With the soffits removed, I would dig out three new footings in line with the existing posts. Pour concrete in and add a column base to each one. Be sure these are in-line with your roof trusses and square with both the ground and roof.
Once cured, add new 4x4s in. Bolt them to the trusses and the column base. You can now remove the existing posts (they appear to merely sit on the concrete, which is why they can move). Done properly, your roof shouldn't move at all. This gives you the full use of your porch pad and should be more structurally sound. The only catch here will be the soffits, which might need replacing.
Comment: I will try to confirm how these 4x4s are doing their jobs. I might be able to see from the attic, I had looked before but not in this much detail. It sounds like removing the soffits is likely a destructive process, they'd need to be cut and replaced? I'll poke around, thanks!


Zend Framework Doctrine create entity with ManyToMany

Question: I'm using Zend Framework 2 with Doctrine.
I have two entities with ManyToMany relations, Portfolio and Tag.
When I'm editing Portfolio, I use select2 and I have possibility to not only select existing Tags, but also create new Tag from text input.
Can someone give me advice how to implement creation of new Tag? Seems like this case (zf2, doctrine, select2) is typical. Is there built-in methods to create new entities?
Answer: Logically Many to Many relationships should be resolved into One to Many with a new table.
if you can post your table schema I will create you the complete model/entity.


Looking for slider plugin can use image from url

Question: I need a very simple slider plugin for WordPress that can use images from URL for slider!!
My host space is very low and I couldn't use upload image for my slider , just can use URL for that but couldn't find a plugin that support image from URL !!
I use many images for sliders in my works and I could not upload all of them on my website host!!
thanks
Answer: I would probably try making the slider myself using one of the various jquery sliders available (for example jQuery cycle).
Then us Advanced Custom Fields to create fields with Wordpress where you can paste in the urls of the images you want to use.