text:
Q: "show full processlist" shows no time-hogging processes, yet my script takes too long I have a script residing on my webserver's cron that should run every night. It has stopped running recently due to exceeding the time limits set by the webserver on cron jobs. It used to run fine. Anytime I manually ran it, it was very quick (well under 5 minutes). All of the sudden, it takes over half an hour.
The script basically updates a MySQL database. The DB is around 60mb according to them. I can't seem to find this information, but it seems reasonable (though the file that I transfer to the server every night is only around 2mb).
I have undertaken their steps suggested to optimize my DB, but nothing really came of that. It still takes ages for the script to run. All the script does is delete everything out of the DB and fill it in again with our updated inventory.
So now I am running "show full processlist" on one Putty window, while running the script in another. "show full processlist" shows only a couple of items, both of which show 0 for the time.
mysql> show full processlist;
+-----------+--------------+--------------------+-------------------------+---------+------+-------+-----------------------+
| Id        | User         | Host               | db                      | Command | Time | State | Info                  |
+-----------+--------------+--------------------+-------------------------+---------+------+-------+-----------------------+
| 142841868 | purposely omitted | purposely omitted | purposely omitted_net_-_main | Sleep   |    0 |       | NULL                  |
| 142857238 | purposely omitted | purposely omitted | NULL                    | Query   |    0 | NULL  | show full processlist |
+-----------+--------------+--------------------+-------------------------+---------+------+-------+-----------------------+
2 rows in set (0.05 sec)

If I keep using the show full processlist command really quickly, occasionally I can catch other things being listed in this table but then they disappear the next time I run it. This indicates to me that they are being processed very quickly!
So does anyone have any ideas what is going wrong? I am fairly new to this :(
Thanks!!
PS here is my code
#!/usr/bin/perl
use strict;
use DBI;
     my $host = 'PURPOSLEY OMITTED';
     my $db = 'PURPOSLEY OMITTED';
     my $db_user = 'PURPOSLEY OMITTED';
     my $db_password = "PURPOSLEY OMITTED";

my $dbh = DBI->connect("dbi:mysql:$db:$host", "$db_user", "$db_password");
$dbh->do("DELETE FROM main");
$dbh->do("DELETE FROM keywords");

open FH, "PURPOSLEY OMITTED" or die;

while (my $line = <FH>) {

my @rec = split(/\|/, $line);

print $rec[1].' : '.$rec[2].' : '.$rec[3].' : '.$rec[4].' : '.$rec[5].' : '.$rec[6].' : '.$rec[7];

$rec[16] =~ s/"//g;
$rec[17] =~ s/"//g;
$rec[13] =~ chomp($rec[13]);

my $myquery = "INSERT INTO main (medium, title, artist, label, genre, price, qty, catno,barcode,created,received,tickler,blurb,stockid) values (\"$rec[0]\",\"$rec[1]\",\"$rec[2]\",\"$rec[3]\",\"$rec[4]\",\"$rec[5]\",\"$rec[6]\",\"$rec[7]\",\"$rec[8]\",\"$rec[9]\",\"$rec[10]\",\"$rec[11]\",\"$rec[12]\",\"$rec[13]\")";

$dbh->do($myquery);

$dbh->do("INSERT IGNORE INTO keywords VALUES (0, '$rec[2]','$rec[13]')");
$dbh->do("INSERT LOW_PRIORITY IGNORE INTO keywords VALUES (0, \"$rec[1]\", \"$rec[13]\")");

print "\n";
}
close FH;

$dbh->disconnect();

A: I have two suggestions:

*

*(less impact) use TRUNCATE instead of DELETE, it is significantly faster, and is particularly easy to use when yo don't need to worry about an auto-incrementing value.

*Restructure slightly to work in batches for the inserts. Usually I do this by keeping a stack variable of a given size (start with something like 20 rows), and for the first 20 rows, it just fills the stack; but on the 20th row it also actually performs the insert and resets the stack. It might boggle your mind how much this can improve performance :-)

Pseudo-code:
const buffer_size = 20
while(row) {
  stack.addvalues(row.values)
  if(stack.size >= buffer_size) {
    // INSERT INTO mytable (fields) VALUES stack.all_values()
    stack.empty()
  }

then play with the "buffer" size. I have seen scripts where tweaking the buffer to upwards of 100-200 rows at a time sped up massive imports by almost as many times (i.e. a drastically disproportionate amount of work was involved in the "overhead" of executing the individual INSERTs (network, etc)


text:
Q: Reputation 200 reached, account wasn't yet registered in combined reputation graph yet It seems a different, although related problem as my another long-standing one, although maybe it were more efficient if they were fixed in the same sprint. Please don't sign this question as duplicate, they aren't.
There is also a very similar bug from 2011. I also don't think they were related, during this 3 years probably not too many part of the SE engine left unchanged.
So, my problem is that although I've recently stepped over the reputation 200 on electronics SE, but my combined reputation graph of meta doesn't show my reputation there.
Maybe it is related to the significant number of my 200+ SE accounts, but I must also mention, there is at least one SE user having more as twice as me.
I suspect here a bug.
P.s. I suggest a better fix as last time (somebody quickly upvoted me somewhere...)
P.s.2. Finally it appeared, but it took around 2 days.

A: I'm going to blame some sort of caching here because I see Electrical Engineering in your rep list when I check it now:

redpajama_set_name: RedPajamaStackExchange


text:
Q: Parsing JSON into R Data Frame I have a JSON file which has a slightly different format:
{"review/profileName": "Carleen M. Amadio \"Lady Dragonfly\"", "product/price": "unknown", "review/time": "1314057600", "product/productId": "B000GKXY4S", "review/helpfulness": "2/2", "review/summary": "Fun for adults too!", "review/userId": "A1QA985ULVCQOB", "product/title": "Crazy Shape Scissor Set", "review/score": "5.0", "review/text": "I really enjoy these scissors for my inspiration books that I am making (like collage, but in books) and using these different textures these give is just wonderful, makes a great statement with the pictures and sayings. Want more, perfect for any need you have even for gifts as well. Pretty cool!"}{"review/profileName": "Barbara", "product/price": "unknown", "review/time": "1328659200", "product/productId": "B000GKXY4S", "review/helpfulness": "0/0", "review/summary": "Making the cut!", "review/userId": "ALCX2ELNHLQA7", "product/title": "Crazy Shape Scissor Set", "review/score": "5.0", "review/text": "Looked all over in art supply and other stores for \"crazy cutting\" scissors for my 4-year old grandson. These are exactly what I was looking for - fun, very well made, metal rather than plastic blades (so they actually do a good job of cutting paper), safe (\"blunt\") ends, etc. (These really are for age 4 and up, not younger.) Very high quality. Very pleased with the product."}{"review/profileName": "L. Heminway", "product/price": "unknown", "review/time": "1156636800", "product/productId": "B000140KIW", "review/helpfulness": "1/1", "review/summary": "Fiskars Softouch Multi-Purpose Scissors, 10\"", "review/userId": "A2M2M4R1KG5WOL", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "These are the BEST scissors I have ever owned. I am left-handed and take note that either a left or right-handed person can use these equally well.If you have arthritis, as I do, these scissors are amazing as well. Well worth the price. I now own three pairs of these and have convinced many other people in my quilting group that they NEED a pair as well!They cut through muli layers and difficult to cut items really well.Do buy them, you won't regret it!"}{"review/profileName": "R. GARCIA", "product/price": "unknown", "review/time": "1214784000", "product/productId": "B000140KIW", "review/helpfulness": "0/0", "review/summary": "Best scissors ever", "review/userId": "ARQAQ6ZYMFPCA", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "This Fiskars Scissors are the best i've bougth in time. It are excellent for delicated fabrics and silck ribbon embroidery, also work perfectly with paper."}{"review/profileName": "Dea Carey \"deacarey\"", "product/price": "unknown", "review/time": "1173484800", "product/productId": "B000140KIW", "review/helpfulness": "0/0", "review/summary": "A great tool to make your work easier", "review/userId": "A3FPG4LAJ1HOHZ", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "I finally gave in and bought these after years of wanting them. I'm so glad I did!I'm a book artist and crafter, and I usually do my creative work in marathon stretches. (You know, nothing for three weeks and then an all-day session...) These scissors make it so much easier. They cut easily and cleanly, with no hand fatigue. They also saved me when I did all my Christmas gift wrapping.I should have just bought these in the first place!"}

I'd like to get this into Data Frames which has ProfileName, Price, ReviewText etc. as column names. Is there a simple way to do this in R?

A: In your string there are multiple JSON objects. I guess you should split them before and then parse them. For your example string (call it x), you can try this:
 require(RJSONIO)
 do.call(rbind,lapply(strsplit(x,"(?<=\\})",perl=TRUE)[[1]],fromJSON))

You obtain a character matrix which can be easily converted to a data.frame if you need it.

A: I played a little with your data and it seems like the last 3 datasets are a bit messy and I couldn't figure out why.
But for the first two, after adding , and [] to the string and removing single quotes, it is working as in the link I suggested.
t <- '[{"review/profileName": "Carleen M. Amadio \"Lady Dragonfly\"", "product/price": "unknown", "review/time": "1314057600", "product/productId": "B000GKXY4S", "review/helpfulness": "2/2", "review/summary": "Fun for adults too!", "review/userId": "A1QA985ULVCQOB", "product/title": "Crazy Shape Scissor Set", "review/score": "5.0", "review/text": "I really enjoy these scissors for my inspiration books that I am making (like collage, but in books) and using these different textures these give is just wonderful, makes a great statement with the pictures and sayings. Want more, perfect for any need you have even for gifts as well. Pretty cool!"},
{"review/profileName": "Barbara", "product/price": "unknown", "review/time": "1328659200", "product/productId": "B000GKXY4S", "review/helpfulness": "0/0", "review/summary": "Making the cut!", "review/userId": "ALCX2ELNHLQA7", "product/title": "Crazy Shape Scissor Set", "review/score": "5.0", "review/text": "Looked all over in art supply and other stores for \"crazy cutting\" scissors for my 4-year old grandson. These are exactly what I was looking for - fun, very well made, metal rather than plastic blades (so they actually do a good job of cutting paper), safe (\"blunt\") ends, etc. (These really are for age 4 and up, not younger.) Very high quality. Very pleased with the product."}]'
# {"review/profileName": "L. Heminway", "product/price": "unknown", "review/time": "1156636800", "product/productId": "B000140KIW", "review/helpfulness": "1/1", "review/summary": "Fiskars Softouch Multi-Purpose Scissors, 10\"", "review/userId": "A2M2M4R1KG5WOL", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "These are the BEST scissors I have ever owned. I am left-handed and take note that either a left or right-handed person can use these equally well.If you have arthritis, as I do, these scissors are amazing as well. Well worth the price. I now own three pairs of these and have convinced many other people in my quilting group that they NEED a pair as well!They cut through muli layers and difficult to cut items really well.Do buy them, you wont regret it!"},
# {"review/profileName": "R. GARCIA", "product/price": "unknown", "review/time": "1214784000", "product/productId": "B000140KIW", "review/helpfulness": "0/0", "review/summary": "Best scissors ever", "review/userId": "ARQAQ6ZYMFPCA", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "This Fiskars Scissors are the best ive bougth in time. It are excellent for delicated fabrics and silck ribbon embroidery, also work perfectly with paper."},
# {"review/profileName": "Dea Carey \"deacarey\"", "product/price": "unknown", "review/time": "1173484800", "product/productId": "B000140KIW", "review/helpfulness": "0/0", "review/summary": "A great tool to make your work easier", "review/userId": "A3FPG4LAJ1HOHZ", "product/title": "Fiskars Softouch Multi-Purpose Scissors 10\"", "review/score": "5.0", "review/text": "I finally gave in and bought these after years of wanting them. Im so glad I did!Im a book artist and crafter, and I usually do my creative work in marathon stretches. (You know, nothing for three weeks and then an all-day session...) These scissors make it so much easier. They cut easily and cleanly, with no hand fatigue. They also saved me when I did all my Christmas gift wrapping.I should have just bought these in the first place!"}]'
require(RJSONIO)
json_file <- fromJSON(t)
json_file <- lapply(json_file, function(x) {
  x[sapply(x, is.null)] <- NA
  unlist(x)
})
do.call("rbind", json_file)


text:
Q: MSVC++ handling unsigned long long int I'm having an issue with the way MSVC handles unsigned long long integers. Here's code to reproduce:
// test.cpp (note extension)
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
    unsigned long long int address = 0x0A0B0C0D0E0F;
    printf("Address=%llu\n", address);

    printf("%02X:%02X:%02X:%02X:%02X:%02X\n",
            ((address >> (5 * 8)) & 0xff),
            ((address >> (4 * 8)) & 0xff),
            ((address >> (3 * 8)) & 0xff),
            ((address >> (2 * 8)) & 0xff),
            ((address >> (1 * 8)) & 0xff),
            (address & 0xff));

    printf("%02X:", ((address >> (5 * 8)) & 0xff));
    printf("%02X:", ((address >> (4 * 8)) & 0xff));
    printf("%02X:", ((address >> (3 * 8)) & 0xff));
    printf("%02X:", ((address >> (2 * 8)) & 0xff));
    printf("%02X:", ((address >> (1 * 8)) & 0xff));
    printf("%02X\n", (address & 0xff));

    exit(0);
}

When I compile this on linux, I get (as expected):
Address=11042563100175
0A:0B:0C:0D:0E:0F
0A:0B:0C:0D:0E:0F

However, when I compile this on MSVC++ 2008 Express I get:
Address=11042563100175
0A:00:0B:00:0C:00
0A:0B:0C:0D:0E:0F

Have I formatted my printf statement incorrectly? Or does MSVC leave an extra byte on the stack after the shift/and operations? Or is the issue with something else?
Note: when compiling with MSVC you need to use the '.cpp' file extension to force C++ mode. I believe this is because MSVC in straight C mode does not include (all of) C99 which includes the '%llu' flag for printf.
Simon.

A: The %X format specifier expects a 32-bit argument.  You are passing 64-bits, throwing off the stack.  You can use %llX.  The CRT is the same for C and C++ code.


text:
Q: PHP/Browser Performance: Generating thumbnails by the browser A user uploads a large resolution image to the server. A thumbnail needs to be created for this image. I thought about instead of having a GD intensive operation to create the thumbnail in PHP, can this process actually be off-loaded to the client/browser? Modern browers these days have support for scaling down images rapidly, but I'm sure there are many cons and pros of doing such a task, so my questions are...

*

*This would be a more efficient way of doing it, but how much more efficient rather than GD operation on server side?

*Is there any Javascript libraries out there that can save an image in JPG format quickly so it can be sent to the server via Ajax?

*As a general note, the conversion will be done using Web Workers, so not to affect users browser.

*Obviously the user can potetionally exploit and send a thumbnail that's completely unrelated to the full size image. Is there any good way around this, i.e. calculating quickly how alike the thumbnail and full size image is and if they are i.e. 98% alike, then allow the image?

I understand there are probably better ways of doing it, such as offloading to another server entirely, or doing a batch job at 3am for example, but for academic/informatic purposes, with the advent of modern browser and their improved Javascript engines, can work like this be put on clients browser?

A: The similarity calculation will likely be no faster then simply creating a quick downscale, although I don't have code to prove this right offhand.
Bandwidth comes to mind as a possible issue, sending the file back and forth.
One possible idea is using a Flash/Java applet to handle the upload, automatically generating the thumbnail and sending it along.

A: What I've been doing is grabbing the EXIF thumbnail on those images that have it and only creating real thumbnails for those that don't contain EXIF data.
Doesn't entirely answer your question, but it's my 2 cents :-)
Edit : I still queue all images for later full processing via a CRON job as they are resized to multiple sizes -> it's just getting that immediate thumbail that I'm concerned about initially.

A: Are you going to be hammered with so many uploads per second that you have to distribute the load back out to the browsers?
ImageMagick can handle resizing easily, and that could be threaded or offloaded to a separate machine if even that much is really necessary.
You should load test this before attempting to optimize something that is probably lost in the network transfer overhead anyway.

A: I think your messing up the client / server sides. Javascript can't generate a thumbnail. if you want to delegate the browser to scaling just set the width/height of the image

A: Thanks for all your comments however I've found a good solution to this:
HTML5: Saving Canvas Image Data Using PHP And Ajax

I'll do some further testing to work out it's feasability.
Obviously the main points/concern here are:

*

*a. I'm under no delusion that everyone is using the same browser, and with the same canvas/html5 capabilities, so a fallback system should be in place.

*b. Users have different performing browsers/machines. So this is something to keep in mind when working with large images to scale down to thumbnail size.

*c. Should any garbage data/exploit be sent from the browser/clients then I'll work around that when it comes to it (the fact is, people could upload garbage data for the full size image, anyway, and if that users intention is to screw up the site in the first place, they'll always find a way)
I'll do some testing to see performance improvements and report back here.


text:
Q: Why is the current version of Eclipse called Galileo? It's silly, but I've been wondering about this for some time.  Eclipse 3.2 was Callisto, 3.3 was Europa, and 3.4 was Ganymede, so why wasn't 3.5 Io instead of Galileo? Was it the risk of being confused with I/O?
On a related note, it looks like 3.6 will be called Helios.  How did we wind up there instead of moving to, say, moons of Saturn?
I just wondered if anybody knew the answer.  Thanks!

A: Suggestions were taken and voted on, "Galileo" was the winner.  You can see the discussion in bug 235189.
Similarly, for this year's Helios.


text:
Q: Column fill in css in a sequential order
My CSS:
    #columns {
    -webkit-column-count: 3;
    -webkit-column-gap: 10px;
    -webkit-column-fill: auto;
    -moz-column-count: 3;
    -moz-column-gap: 10px;
    -moz-column-fill: auto;
    column-count: 3;
    column-gap: 10px;
    column-fill: auto;
}

My column count is 3 however the fill happens as seen in the picture how do i show 3 images at a time.
Below is my jsfiddle
https://jsfiddle.net/swh36mLm/
Sorry it contains my complete css file.

A: If you want to have 3 columns for your content cards column-count isn't the right option. You can use column-count to divide a long text into multiple columns. In your example you try to divide cards into multiple coulmns. It's possible if you set a height for the wrapper div, but I guess you might not receive the results you expected:

...

If you want to have a multi column layout, please check out this question.

A: Can you use a CSS flexbox instead? If you change your #columns to be a flex container, then set the immediate children divs to a width of 33% (less, actually to accommodate for gaps, borders, etc. -- you can figure out the appropriate figure), you wind up with a three-column layout that you can continuously add to.
Since your CSS is almost 25,000 lines long, here is what I changed:

*

*Removed the @media rules from lines 23,142 thru 23,156

*Rewrote the #columns rule to be a flexbox (see code below)

*Added a #columns > div rule to set the widths of the children divs to 30% (again, the 30% is something you'll have to play with to get the biggest "one-third" column you can get)

#columns {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-items: flex-start;
}

#columns > div {
  width: 30%;
}

I edited your JSFiddle with these changes and got the result seen below:

I hope it helps. If you want more info on CSS Flexboxes, check out this URL (it's helped me a lot in the past): Visual Guide to CSS3 Flexbox Properties

A: "column-count" not divide on points you want,
for example in this code

...

...

...

not consider every single div with "c" class as single item.

"column-count" divide on points that wants,
for example
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard

in this text make three partly equal part and show them in three columns.

for solution you most get every item
width: 33.33333333%;

and float them.
if you want complete code just comment for me.


text:
Q: Working with datetime in Python I have a file that has the following format:
20150426010203 name1
20150426010303 name2
20150426010307 name3
20150426010409 name1
20150426010503 name4
20150426010510 name1

I am interested in finding time differences between appearances of name1 in the list and then calculating the frequency of such appearances (for example, delta time = 1s appeared 20 time, delta time = 30s appeared 1 time etc). The second problem is how to find number of events per minute/hour/day.
I found all time differences by using
pd.to_datetime(pd.Series([time]))

to convert each string to datetime format and placed all values in list named 'times'. Then I iterated through the list:
new=[x - times[i - 1] for i, x in enumerate(times)][1:]

and the resulting list was something like this:
dtype: timedelta64[ns], 0   00:00:50
dtype: timedelta64[ns], 0   00:00:10
dtype: timedelta64[ns], 0   00:00:51
dtype: timedelta64[ns], 0   00:00:09
dtype: timedelta64[ns], 0   00:00:50
dtype: timedelta64[ns], 0   00:00:11

Any further attempt to calculate frequency results in 'TypeError: 'Series' objects are mutable, thus they cannot be hashed' error. And I am not sure where to find how to calculate number of events per minute or any other time unit.
Obviously, I don't have a lot of experience with datetime in Python, so any pointers would be appreciated.

A: Use resample and sum to get the number of events per time period - examples below
I gather you want the intervals for individuals (name1: 1st to 2nd event interval; and then his/her 2nd to 3rd event interval). You will need to group by name and then difference the times for each group. In your dataset, only name1 has more than one event, and two events are necessary for a person-centric interval.
Quick and dirty ...
# --- get your data into a DataFrame so I can play with it ...
#     first, put the data in a multi-line string (I would read it from a file
#     if I had it in a file - but for my purposes a string will do).
data = """
time name
20150426010203 name1
20150426010303 name2
20150426010307 name3
20150426010409 name1
20150426010503 name4
20150426010510 name1"""
#    second I will use StringIO and pandas.read_csv to pretend I am
#    reading it from a file.
from StringIO import StringIO # import from io in Python 3
df = pd.read_csv(StringIO(data), header=0, index_col=0, sep='\s+')
#    third, because pandas did not recognise the date-time format
#    of the column I made the index, I will force the string to be
#    converted to a pandas Timestamp come DatetimeIndex.
df.index = pd.to_datetime(df.index, format='%Y%m%d%H%M%S')

# number of events per minute
df['event'] = 1 # we will sum this to get events per time-period
dfepm = df.resample('1min', how=sum)

# number of events per hour
dfeph = df.resample('1h', how=sum)

# time differences by name
del df['event'] # we don't need this anymore
df['time'] = df.index
df['time_diff_by_name'] = df.groupby('name')['time'].diff()


text:
Q: I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format I have an oracle table which has date in dd-mm-yyyy and dd/mm/yyyy format in same field. Now i have to convert into one common format.
Please suggest how to approach this?
I did tried but it is failing as it is failing due to invalid month.
Is there a way i can first identify what format the date is and then based on case statement i might convert.
or something easy way? Please

A: I trust you've learnt your lesson and you're now going to store these dates in the date data type.
Your two different date formats actually aren't important, Oracle already is a little over accepting when it comes to separating characters.
e.g
to_date('01/01/1900','dd-mm-yyyy')

Does not error

I did tried but it is failing as it is failing due to invalid month.

Your error is coming because you've allowed a value that doesn't match either of those formats into your string column.
If you are on version 12.2 at least (which you should be in 2020) then you can use the validate_conversion function to identify rows that don't convert to a date with your format (https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/VALIDATE_CONVERSION.html#GUID-DC485EEB-CB6D-42EF-97AA-4487884CB2CD)
select string_column
from  my_table
where  validate_conversion(string_column AS DATE,'dd/mm/yyyy') = 0

The other additional helper we got in 12.2 was the on conversion error clause of to_date. So you can do.
alter table my_table add my_date date;
update my_table set my_date = to_date(my_string default null on conversion error,'dd/mm/yyyy');

A: If you are confident that there is no other format than those two, a simple approach is replace():
update mytable set mystring = replace(mystring, '/', '-');

This turns all dates to format dd-mm-yyyy.
I would suggest taking a step forward and convert these strings to a date column.
alter table mytable add mydate date;
update mytable set mydate = to_date(replace(mystring, '/', '-'), 'dd-mm-yyyy');

This will fail if invalid date strings are met. I tend to consider that a good thing, since it clearly signals that this a problem with the data. If you want to avoid that, you can use on conversion error, available starting Oracle 12:
to_date(
    replace(mystring, '/', '-') default null on conversion error,
    'dd-mm-yyyy'
)

Then you can remove the string column, which is no longer needed.


text:
Q: Закрыть popup по клику вне окна react Верстка popup готова, как функционал сделать не знаю. По клику на .b-popup наверное нужно закрыть  сам попап

*{
    font-family: Areal;
}
.b-container{
    width:200px;
    height:150px;
    background-color: #ccc;
    margin:0px auto;
    padding:10px;
    font-size:30px;
    color: #fff;
}
.b-popup{
    width:100%;
    height: 2000px;
    background-color: rgba(0,0,0,0.5);
    overflow:hidden;
    position:fixed;
    top:0px;
}
.b-popup .b-popup-content{
    margin:40px auto 0px auto;
    width:100px;
    height: 40px;
    padding:10px;
    background-color: #c5c5c5;
    border-radius:5px;
    box-shadow: 0px 0px 10px #000;
}

        Text in Popup

A: import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class OutsideAlerter extends React.Component {
  constructor(props) {
    super(props);
    this.setWrapperRef = this.setWrapperRef.bind(this);
    this.handleClickOutside = this.handleClickOutside.bind(this);
  }

  componentDidMount() {
    document.addEventListener('mousedown', this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener('mousedown', this.handleClickOutside);
  }

  setWrapperRef(node) {
    this.wrapperRef = node;
  }

  handleClickOutside(event) {
    if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
      this.props.onOutside();
    }
  }

  render() {
    return
{this.props.children}
;
  }
}

OutsideAlerter.propTypes = {
  children: PropTypes.element.isRequired,
};

Пример использования:
export class MyPopup extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        visible: true
    }

 render() {
    if(!this.state.visible)
        return "";
    return(

       <OutsideAlerter onOutside={() => this.setState({visible: false})}>

                Text in Popup

       </OutsideAlerter>

)
 }
}

В компоненте MyPopup лучше не возвращать пустоту, а не рендерить его вообще в том компоненте, где он будет отображаться, я сделал на скорую руку.
P.S. Авторство OutsideAlerter за @Ben Bud, я не стал сильно менять его код
UPD: Пример без обертки
export class MyPopup extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        visible: true
    }

 render() {
    if(!this.state.visible)
        return "";
    return(
 this.setState(visible: false)}>

                Text in Popup

)
 }
}

A: В самом попапе вам нужно добавить кнопку для его закрытия. По клику на сам попап, кроме кнопки которая его должна закрывать, никто закрытие не делает. Зачастую попап закрывают либо по кнопке либо по области за попапом (это и показано в примере). Но все же рекомендую еще кнопку добавить

$(document).click(function(e){
  if ($(e.target).closest(".b-popup-content").length) return;
  $('.b-popup').hide();
  e.stopPropagation();
  });
*{
    font-family: Areal;
}
.b-container{
    width:200px;
    height:150px;
    background-color: #ccc;
    margin:0px auto;
    padding:10px;
    font-size:30px;
    color: #fff;
}
.b-popup{
    width:100%;
    height: 100vh;
    background-color: rgba(0,0,0,0.5);
    overflow:hidden;
    position:fixed;
    top:0px;
}
.b-popup .b-popup-content{
    margin:40px auto 0px auto;
    width:100px;
    height: 40px;
    padding:10px;
    background-color: #c5c5c5;
    border-radius:5px;
    box-shadow: 0px 0px 10px #000;
}

        Text in Popup


text:
Q: Access Write Violation When Accessing the Value of a Register in assembly x86 compare PROTO, p1:DWORD, p2:DWORD
.code
compare proc p1:DWORD, p2:DWORD
    mov eax, p1
    mov edx, p2
    mov eax, [eax] ;Getting an access violation here
    mov edx, [edx] ; Would probably get one here too, why?
    sub eax, edx
    ret
compare endp
main PROC
     LOCAL thesize:DWORD
    mov thesize, 3
    mov fill, 5
    INVOKE compare, thesize, thesize

    ret
main ENDP

Hey guys, just curious as to why this code isn't working? What's an alternative way to make it work, I'm just playing around with registers and was trying some similar code when filling an array, but I got stuck at this point.
Thanks in advance!

A: Not sure what you are doing, but since it looks like you want dereference a mem address, you must use addr for local vars to get/pass that address.
main PROC
     LOCAL thesize:DWORD
    mov thesize, 3

;    INVOKE compare, thesize, thesize
;    same as:
;    push    3
;    push    3
;    call    compare

    ; this is what you want:
    invoke compare, addr thesize, addr thesize
;    same as:
;    lea     eax, thesize
;    push    eax
;    push    eax
;    call    compare
    ret
main ENDP


text:
Q: Images can be dragged and drop in textbox in jqgrid In my rails application ,iam using jqgrid to enter data in rows.there is a description box which allows certain no of characters.The problem here is i can drag and drop images and urls which the description box accepts.How can i prevent it.
here is the short code i have taken out from the main after some edit..

  $(document).ready(function() {

     colNamesData = [ 'Description', 'Hours']
     colModelHash = [
     {name:'description',index:'description', width:130,sorttype:"text", editable:true, edittype:"textarea", editoptions: {rows:"5",cols:"25",maxlength:"255"}, stype:'text'},
     {name:'hours',index:'hours', width:130, align:'center',editable:true, edittype:"select",editoptions:{value:"<%= hours_options %>"}, search:true, stype:'text'}
                      },
          ]
   $("#data_table").jqGrid({
      datatype: "local",
      height: "auto",
      autowidth: true,
      ignoreCase: true,
      colNames: colNamesData,
      colModel: colModelHash,
      pager: '#pager',
      rowNum:10,
      rowList:[10,25,50,100],
      sortname: 'hours',
      sortorder: 'desc',
      viewrecords: true,
      editurl:"/data_call.json",
      caption: 'My info',

     },
      data:<%= raw @data_jqgrid_date.to_json %>
   });

   jQuery("#data_table").jqGrid('navGrid','#pager',{del:false,add:true,edit:false},{}, {}, {});
   var details =  <%= raw @details.to_json %>

A: You can bind 'drop' event handler to the 'description' column having edittype:"textarea". To do this you can include dataEvents which look like
editoptions: {
   dataEvents: [
       {
            type: 'drop',
            fn: function(e) {
                console.log('drop');
                if (e.originalEvent !== undefined &&
                    e.originalEvent.dataTransfer !== undefined &&
                    e.originalEvent.dataTransfer.getData) {

                    console.log("URL: "+e.originalEvent.dataTransfer.getData('URL'));
                    console.log("Text: "+e.originalEvent.dataTransfer.getData('Text'));
                    e.preventDefault();
                }
            }
       }
   ]
}

in the code the URL and the Text dropped in the control will be displayed on the console and the dropping will be prevented. You can prevent the dropping depend on the data returned by dataTransfer.getData('URL') and dataTransfer.getData('Text').

A: In my view you can have a JavaScript method.
Just bind the change method of that text box with the method.
Check the value, if it contains any invalid character then reset it to balnk('') and return false.


text:
Q: VueJs not working on first click or first event I was able to create this dynamic elements.
My purpose in this is to create dynamic divs that will be based on "count", and inside that div, I can add multiple textboxes.
Here's what I came up with
You'll notice that the first click, it will not be the expected result. But when you click it the 2nd time, it will work.
I should be missing something. But I don't know what it is as I'm new to vue.
Here's the code as well:

    <button @click="populate">Populate</button>

          Id

            <input type="text" v-model="i.name">

          <button v-show="act > 0" @click=input_add(act)>Add</button>

    {{inputs}}

const app = new Vue({

  el: '#app',

  data: {
    inputs: [],
    counter: 0,
    count: 3
  },

  methods: {
    populate(){
      var x = 1
      while(x <= this.count){
        this.inputs.push(
          {
            id: this.counter + 1,
            items: []
          }
        )
        this.input_add(x)
        this.counter++
        x++
      }
    },
    input_add(x){
      this.inputs[x].items.push(
        {
         name: null
        }
      )
    }
  }

})

A: Try setting  var x = 1 to var x = 0 - that way it should have the functionality you get on the second click on initial.


text:
Q: Help understanding the difference between "to have+verb" and "to+verb" I'm always confused about using 'to have'. I know it is a perfect infinitive but the meaning of it must have a different usage than 'to+verb'!

If you go there you need to have registered a room.

Why it is not just "to" before register?

It would've been possible to have met him if you'd been there.
To appreciate the success, you need to have had the failure.

Why not just "to have" instead of "to have had"?

A: Let's say you go to a very popular restaurant where it is difficult to get a seat, and you must make a reservation weeks in advance.

To eat there, you have to make a reservation.

Now, let's say a tourist is visiting the city, and does not know that the restaurant is always full. He enters, expecting to be seated.  The greeter can say:

Sorry, you have to make a reservation beforehand.

or

Sorry, you have to have made a reservation.

The first version, "have to make", describes the general state of affairs. People who wish to eat there must reserve a place in advance. This is probably what the greeter would say, or even "You need a reservation". Present tense, to describe what is customary.
The second version describes the very specific situation in respect to time. The person is standing now in the restaurant. The person should have made a reservation already, in the past: When you come here, expecting to be seated, you must have made a reservation.
The tense have made contains the idea "beforehand", that is, "before now". The reservation should exist already.


text:
Q: What datatype should I use for class properties when reading API data in XML from VBA I am trying to read a Web API call from a test program we have in Excel. Basically, I have VBA classes where all properties are currently of the Variant type. I'm trying to assign values to those properties from an API in XML format. I can get the XML data and pass it to my function that reads it. When the program hits the first line that assigns a value to a property, the code skips to the bottom of my function and exits without giving an error.
I had classes with actual data types, the code would read the XML data until it tried to assign a null value to a Double property type.
I'm assigning values like so:
with Object1
    .Property1 = XMLData.SelectSingleNode("//Parent/Child/Property1").text
End With


text:
Q: Redirecting alias domains to primary domain in IIS? My hosting setup is Windows 2003 Server with IIS 6.0
I have 3 domains

*

*ex.com

*ex.org

*ex.net

I want when user open http://www.ex.com then they will be redirected to http://ex.com and when they open http://ex.org or http://ex.net then redirect them to http://ex.com.
How is it possible in IIS server.
Please help, Thanks!

A: In the home directory tab of iis web site there is the option "redirect to a url" enter there "http://ex.com" and choose:"a permanent redirection for this resource".
You will have to create a web site for each web site you want to redirect to ex.com . Do it with different IP or host headers.
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/fbcccfce-6695-4f92-bd55-869d85ff49fb.mspx?mfr=true

A: Do you really need a redirection? Because you can use Host Headers, it's like Apache ServerAlias.
You only have to create one web site, use ex.com as your primary host header, and then add other host headers.
Click right button under your website name and choose "Properties", go to Web Site -> Advanced Button, on "Multiple identities for this web site" press Add, then type the domain name
Example: (All Unassigned, TCP Port 80, ex.net)


text:
Q: Invalid website id requested - Customers can't log into other sites I deleted an old website id that we have not used for the past year.
However in doing so the customers that registered with this site can no longer login to the other websites associated with the account.
When we try to access the customer via the admin panel we get the following error:
a:5:{i:0;s:29:"Invalid website id requested.";i:1;s:2920:"#0 /home/socia641/public_html/app/code/core/Mage/Core/Model/App.php(969): Mage::exception('Mage_Core', 'Invalid website...')
#1 /home/socia641/public_html/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php(128): Mage_Core_Model_App->getWebsite('2')
#2 /home/socia641/public_html/app/code/core/Mage/Adminhtml/Block/Customer/Edit/Tabs.php(58): Mage_Adminhtml_Block_Customer_Edit_Tab_Account->initForm()
#3 /home/socia641/public_html/app/code/core/Mage/Core/Block/Abstract.php(918): Mage_Adminhtml_Block_Customer_Edit_Tabs->_beforeToHtml()
#4 /home/socia641/public_html/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract->toHtml()
#5 /home/socia641/public_html/app/code/core/Mage/Core/Block/Abstract.php(919): Mage_Core_Block_Text_List->_toHtml()
#6 /home/socia641/public_html/app/code/core/Mage/Core/Block/Abstract.php(637): Mage_Core_Block_Abstract->toHtml()
#7 /home/socia641/public_html/app/code/core/Mage/Core/Block/Abstract.php(581): Mage_Core_Block_Abstract->_getChildHtml('left', true)
#8 /home/socia641/public_html/app/design/adminhtml/default/default/template/page.phtml(58): Mage_Core_Block_Abstract->getChildHtml('left')
#9 /home/socia641/public_html/app/code/core/Mage/Core/Block/Template.php(241): include('/home/socia641/...')
#10 /home/socia641/public_html/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template->fetchView('adminhtml/defau...')
#11 /home/socia641/public_html/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template->renderView()
#12 /home/socia641/public_html/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template->_toHtml()
#13 /home/socia641/public_html/app/code/core/Mage/Core/Block/Abstract.php(919): Mage_Adminhtml_Block_Template->_toHtml()
#14 /home/socia641/public_html/app/code/core/Mage/Core/Model/Layout.php(555): Mage_Core_Block_Abstract->toHtml()
#15 /home/socia641/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(390): Mage_Core_Model_Layout->getOutput()
#16 /home/socia641/public_html/app/code/core/Mage/Adminhtml/controllers/CustomerController.php(151): Mage_Core_Controller_Varien_Action->renderLayout()
#17 /home/socia641/public_html/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Adminhtml_CustomerController->editAction()
#18 /home/socia641/public_html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('edit')
#19 /home/socia641/public_html/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#20 /home/socia641/public_html/app/code/core/Mage/Core/Model/App.php(365): Mage_Core_Controller_Varien_Front->dispatch()
#21 /home/socia641/public_html/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#22 /home/socia641/public_html/index.php(83): Mage::run('', 'store')
#23 {main}";s:3:"url";s:40:"/index.php/admin/customer/edit/id/14397/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";}

We are still able to search the customer email in manage customers we just cant access the account and they cant log into the site. In the website column it is blank compared to other customers. All other details seem normal. How do we fix this issue?

A: Export customer list, and change _website field to correct one for particular customer. And then import the list again
Make sure to take backup


text:
Q: Consecutive Combine Publishers. Isolating business logic in a Simple Sign In flow example I'm quite new to Combine and, instead of running all my tasks into the viewModel, I'm trying to better isolate the code that has to do with business logic.
Let's take a SignIn service as example. The service receives username and password and return token and userID.
The exposed call of the service is signIn that internally calls a private func networkCall. I'd like to implement the two functions to return a Publisher.
The role of networkCall should be calling the API and storing the received token, while the role of signIn is only to return a success or a failure.
This is my code, where I'm also highlighting where I'm getting stuck.
In general I don't know where is the right place to work with the information received from the API (and store the token). At the moment I'm doing it inside a .map call but it sounds wrong to me. Could you share some advice to improve this logic and especially explain which is the right place to run the business logic... I'm supposing that .map is not the right place! and .sink will just stop the chain.
struct SignInResponse:Codable{
    var token:String
    var userID:String
}

class SignInService {

    // Perform the API call
    private func networkCall(with request:SignInRequest)->AnyPublisher<SignInResponse, ServiceError>{
        return URLSession.DataTaskPublisher(request: request, session: .shared)
        .decode(type: SignInResponse.self, decoder: JSONDecoder())
        .mapError{error in return ServiceError.error}
        .eraseToAnyPublisher()
    }

    func signIn(username:String, password:String)->AnyPublisher<Result<String, ServiceError>, Never>{
        let request = SignInRequest(with username:username, password:password)

        return networkCall(with: request)
            .map{ (response) -> Result<String, ServiceError> in

                if response.token != ""{
                    // THIS SOUNDS EXTREMELLY WRONG. I SHOULD NOT USE MAP TO HANDLE THE TOKEN -------
                    self.storage.save(key: "token", value: response.token)
                    return Result.success(response.userID)
                }else{
                    return Result.failure(ServiceError.unknown)
                }
            }
            .replaceError(with: Result.failure(ServiceError.unknown))
            .eraseToAnyPublisher()
    }
    ......
}

From the model I call SignIn in this way:
func requestsSignIn(){

    if let username = username, let password = password{
        cancellable = service.signIn(username: username, password: password)
            .sink(receiveValue: { (result) in
                switch result{
                case .failure(let error):
                    self.errorMessage = error.localizedDescription
                case .success(let userID):
                    // the sigin succeeded do something here

                }
            })
    }
}

A: As an alternative setup have signIn return a publisher with just Output String and Failure type Service.Error directly (the Result type becomes redundant with a Publisher).
Then, for an error like an empty token string in the response, use tryMap instead of map to transform the Result type from network function and have it throw an ServiceEror.emptyToken or something like that. That will cause the publisher to publish that as the Failure right away.

A: Basically I agree with the existing answer. Your misconception here seems to be what a Combine pipeline is for. The idea is that either a useful value — here, your  user ID — or an error (if appropriate; otherwise, nothing) should pop out the end of the pipeline. The subscriber at the end of the pipeline stands ready to receive either of those.
Thus it generally makes no sense to pass a Result object out the end of the pipeline, which must be further analyzed into a success or failure value. The goal of a Result object is merely to allow you to pass asynchronicity around, i.e. by handing someone else a completion handler to be called with a Result at some future time, just so as not to have to call with one of two values, i.e. either a real value or an error, using two Optional parameters.
Once a Combine publisher has published, though, asynchronicity has already happened, and you're getting the signal of this fact; that's what publishing means. The only thing you now need to preserve is whatever part or mutation of the signal is meaningful and useful to you.
Here is a fairly typical pipeline that does the sort of thing you want to do; I have not divided this into two separate pieces as you do, but of course you can divide it up however you like:
    URLSession.DataTaskPublisher(request: request, session: .shared)
        .map {$0.data}
        .decode(type: SignInResponse.self, decoder: JSONDecoder())
        .tryMap { response -> String in
            if response.token == "" {
                throw ServiceError.unknown
            }
            return response.userID
        }
        .receive(on:DispatchQueue.main)
        .sink(receiveCompletion: {err in /* do something with error */ },
              receiveValue: {userID in /* do something with userID */})
        .store(in:&storage)

First, the result of a data task is a tuple, but all we need is the data part, so we map to that. Then we decode. Then we check for an empty token, and throw if we get one; otherwise, we map down to the user ID because that is the only useful result. Finally we switch to the main thread and capture the output using a sink, and store the sink in the usual Set<AnyCancellable> so that it persists long enough for something to happen.
Observe that if at any stage along the way we suffer a failure error, that error is immediately propagated all the way out the end of the pipeline. If the data task fails, it will be a URLError. If the decoding fails, it will be an Error reporting the issue, as usual with a decoder. If the token isn't there, it will be a ServiceError. At any point along the way, of course, you can catch and block or transform the error as it comes down the line if you wish.


text:
Q: Visual Studio C++ Standard Regex get tag till whitespace I have this string:
LOWS 111150Z 38005KT 320V050

I need the KT Tag 38005KT. The KT Tag can be in the following formats:

*

*18010KT

*35012G20KT

*00000KT

*VRB16G28KT

I tried it with the following regex:
regex wind("[^\\\s].*KT");

But I get the following string:
LOWS 111150Z 38005KT

What I'm doing wrong?

A: regex wind( "[0-9a-zA-Z]*KT" );

will give you the desired string.
It means unlimited times 0-9 and a-z and A-Z before the KT.
So whitespaces and everything else is not included.


text:
Q: path url is reformatted when opening clicking on a tag I have some image path whose url outputs this way (using php smarty escaping)

but when I click, on this doc the browser opens a âge wholes is
`www.mysite.com/documents/Capture+d'écran+2014-07-08+à+19.33.51.png`

It seems that it is formatted in incorrect format. How can I deal with that

A: You can use url_encode() and url_decode() function for remove this type of error.


text:
Q: calculate item length in outer of map I have a json like this
var person = [{
    "name": "john",
    "age": 20
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}]

My desire output is
age 10 (2)
- Samuel
- Jin

age 20 (1)
- John

I have problem counting the total. I would do
ages.map(doList) //where ages is [10,20]

doList(age) {
    persons.filter(p => p.age === age)
    .map(p => {
       p.name
    })
}

but how do print out the length of the age group?

A: You might change your data structure for easier output like.
var person = [{
    "name": "john",
    "age": 10
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}];

let newArray = [];
person.forEach((p) => {
  let findPreviousIndex = newArray.findIndex((itm) =>{
    return itm.age == p.age;
  });

  if(findPreviousIndex > -1){
    // previous found, push the name
    newArray[findPreviousIndex].names.push(p.name);
  }else{
    // not found. create a new object and push it
    newArray.push({
      "age" : p.age,
      "names" : [].concat(p.name)
    })
  }
});

console.log(newArray);

Now, its easy to print your grouped data and easy to find length.

A: Here's one way to produce the desired output, first using .reduce() to set up a result object with a property for each age that is an array of names for that age, then mapping over the properties of result to create a formatted string that gives the specific format in the question:

var person = [{
    "name": "john",
    "age": 20
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}]

var result = person.reduce((a, c) => {
  (a[c.age]||(a[c.age]=[])).push(c.name)
  return a
}, {})
console.log(result)

var formatted = Object.keys(result)
  .map(k=>`age ${k} (${result[k].length})\n${result[k].map(n => `- ${n}`).join('\n')}`)
  .join('\n\n')
console.log(formatted)

A: var person = [{
    "name": "john",
    "age": 20
}, {
    "name": "Samuel",
    "age": 10
}, {
    "name": "Jin",
    "age": 10
}];

// create a map where the key is the person's age and the value is a list of names
var ageMap = person.reduce(function(result, p) {
    var key = p.age;
    var name = p.name;
    if (result[key]) {
        result[key].push(name);
    } else {
        result[key] = [name];
    }
    return result;
}, {});

// traverse the map and print the names of people grouped by age
Object.keys(ageMap).forEach(function(key) {
    var value = ageMap[key];
    console.log("age " + key + " (" + value.length + ")");
    value.forEach(function(name) {
        console.log("- " + name);
    });
    console.log("");
});

JSFiddle: https://jsfiddle.net/njcms8rj/


text:
Q: Mysql: using two foreign keys to the same table I'm using MySQL workbench to design a database. Server is mysql 5.5.6
I've defined a few foreign keys linking the "candidates" table to the "countries" table. I get this error:
Executing SQL script in server
ERROR: Error 1005: Can't create table 'customer.candidats' (errno: 150)

The thing is: i'm referencing twice the countries table: once for the "nationality" column, once for the user address's country of origin. Is that allowed? Is this the right way to do it?
Here is the generated code that seems to trigger the issue.
CREATE TABLE IF NOT EXISTS `customer`.`candidats` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nom` VARCHAR(40) NULL,
  `prenom` VARCHAR(40) NULL,
  `qualite` ENUM('0001','0002') NULL COMMENT '0001 = Madame\n0002 = Monsieur',
  `sexe` SET('1','2') NULL COMMENT '1 = Femme\n2 = Homme',
  `date_de_naissance` DATE NULL,
  `Nationalite` INT NOT NULL,
  `selor_bilinguisme` TINYINT(1) NULL,
  `rue` VARCHAR(60) NULL,
  `numero` VARCHAR(10) NULL,
  `pays` INT NOT NULL,
  `region` INT NOT NULL,
  `localité` VARCHAR(40) NULL,
  `code_postal` VARCHAR(10) NULL,
  `email` VARCHAR(241) NULL,
  `tel_domicile` VARCHAR(30) NULL,
  `tel_bureau` VARCHAR(30) NULL,
  `tel_mobile` VARCHAR(30) NULL,
  `tel_prefere` ENUM('01','02','03') NULL DEFAULT '03',
  PRIMARY KEY (`id`),
  INDEX `fk_candidats_pays_idx` (`Nationalite` ASC, `pays` ASC),
  INDEX `fk_candidats_régions1_idx` (`region` ASC),
  CONSTRAINT `fk_candidats_pays`
    FOREIGN KEY (`Nationalite` , `pays`)
    REFERENCES `customer`.`pays` (`id` , `id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_candidats_régions1`
    FOREIGN KEY (`region`)
    REFERENCES `customer`.`régions` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB

The "pays" table ("countries" in French)
CREATE TABLE IF NOT EXISTS `customer`.`pays` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `nom_fr` VARCHAR(45) NULL,
  `nom_nl` VARCHAR(45) NULL,
  `nationalite_fr` VARCHAR(45) NULL,
  `nationalite_nl` VARCHAR(45) NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `id_UNIQUE` (`id` ASC))
ENGINE = InnoDB

A: Your schema generator doesn't work correctly.
It should generate:
CONSTRAINT `fk_candidats_pays`
    FOREIGN KEY (`pays`)
    REFERENCES `customer`.`pays` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
CONSTRAINT `fk_candidats_Nationalite`
    FOREIGN KEY (`Nationalite`)
    REFERENCES `customer`.`pays` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,

To your other question: This type of referencing seems strange when you see it the first time, but it's quite normal and I think there is no other way of constructing this type of relationship.


text:
Q: Xcode 6 GM Seed - iPhone 6 simulator does not show the home button I am creating a game in Xcode-6-GM-Seed and am having an issue that the home button is not showing up in the simulator.
I need to be able to press the home button to be able to quickly delete the app from the phone but am not seeing the home button.
How do I get around this? Is there some sort of command to use or do I need to do it programmatically until they add the home button? Is there another way to delete the app and it's content?

A: Use Command + Shift + H for pressing Home button.
You can also choose "Reset Content and Settings" to erase the App.

A: As mentioned above, shift+command+h is how you should trigger the home button to get to SpringBoard.
If you need to uninstall an app, you can also do that from the command line via simctl:
xcrun simctl uninstall booted com.mycompany.myapp


text:
Q: Can this problem be solved using nested loops? Would it be possible to produce this layout with nested loops? I'm still new to nested to Java/loops and cannot solve this issue.
*****====+
*****===++
*****==+++
*****=++++
*****+++++
====++++++
===+++++++
==++++++++
=+++++++++

I'm having trouble looping through five times with the "*" character without allowing the "+" to increment.
Here is my code:
class Main {

  public static void main(String[] args) {
    for (int k = 4; k > 0; k--) {
      System.out.print("*****");
      for (int l = 0; l < k; l++) {
        System.out.print("=");
      }
      for (int m = 0; m < 1; m++) {
        for (int n = 0; n < m; n++) {
          System.out.print("+");
        }
      }
      System.out.println();
    }
    System.out.print("*****+++++");
  }

}

A: there are could be multiple approaches to this problem, here is how I would think about it:

*

*you need to display 9 lines of "something", so lets have top level loop:

for (int i=0; i<9; i++) {...}

*now, each iteration of this loop you need to display X stars, Y equal signs, Z plus signs:

for (int i=0; i<9; i++) {
    for (int j=0; j< #X# ; j++) System.out.print("*");
    for (int j=0; j< #Y# ; j++) System.out.print("=");
    for (int j=0; j< #Z# ; j++) System.out.print("+");
    System.out.println();
}

*now you need to determine rules how X,Y,Z are changed, here is the logic I came up with:

if (stars > 0 && equals == 0) {
    stars = 0;
    equals = 5;
}
equals--;
pluses++;

so, final code will look like:
public static void main(String[] args) throws InterruptedException {
    int stars = 5; // initial state
    int equals = 4;
    int pluses = 1;
    for (int i=0; i<9; i++) {
        for (int j=0; j<stars; j++) System.out.print("*");
        for (int j=0; j<equals; j++) System.out.print("=");
        for (int j=0; j<pluses; j++) System.out.print("+");
        System.out.println();

        if (stars > 0 && equals == 0) {
            stars = 0;
            equals = 5;
        }
        equals--;
        pluses++;
    }
}

A: If you notice there is a pattern.
It prints a * starting from left to right.
It prints a + for each increasing number starting from right to  left.
It prints a = instead of * if you are past mid point (first the mid point of left to right, then the mid point of top to bottom).
The logic can be applied as following,
class Main {
    public static void main(String[] args) {
        int max = 10;
        int switchPoint = max - 1;

        for(int i = 1; i <= max -1; i++) {
            for(int j = 1; j <= max; j++) {
                if(j > switchPoint)
                    System.out.print("+");
                else if( i > max/2 || j > max / 2)
                    System.out.print("=");
                else
                    System.out.print("*");

            }
            switchPoint--;

            System.out.println();

        }
    }
}

/* Output:
*****====+
*****===++
*****==+++
*****=++++
*****+++++
====++++++
===+++++++
==++++++++
=+++++++++
*/

A: public class A {

    public static void main(String[] args) {
        for (int k = 4; k > 0; k--) {
            System.out.print("*****");
            for (int l = 0; l < k; l++) {
                System.out.print("=");
            }
            for (int m = 0; m < 5 - k; m++) {
                System.out.print("+");
            }
            System.out.println();
        }
        System.out.print("*****+++++");
        System.out.println();
        for (int s = 4; s > 0; s--) {

            for (int k = 0; k < s; k++) {
                System.out.print("=");
            }

            for (int l = 0; l < 5; l++) {
                System.out.print("+");
            }
            for (int m = 0; m < 5 - s; m++) {
                System.out.print("+");
            }

            System.out.println();
        }

    }

}

A: As you may notice the behavior of the "*" and "=" is different in the first five lines than in the next five lines, so you may either divide the loop in two loops or make a single one and check wether you are printing the first five lines or the last ones, that check may be done either by an if statement or in the loops conditions.
So the code will look like:
class Main {

  public static void main(String[] args) {
    for (int i = 1; i < 10; i++){
        for (int j = 1; i <= 5 && j <= 5; j++){
            System.out.print("*");
        }
        for (int k = 5; (i <= 5 && k > i) || (i > 5 && k > i-5); k--){
            System.out.print("=");
        }
        for (int l = 1; l <= i; l++){
            System.out.print("+");
        }
        System.out.println();
    }
  }
}


text:
Q: iPhone - Replacing a block of pixels in an image with another block of pixls I would like to know if anyone can point me in the right direction regarding what frameworks/methods
to use when replacing a block of pixels in an image with another block of pixels.
For example lets say I have a simple image colored fully red and I consider my pixel block size as 5x5
pixels. Now every 3 blocks I want to replace the 3rd block with a blue colored block (5x5 pixels) so
that it would result in a red image with blue blocks appearing every 3 red blocks.
I've found information regarding pixel replacement but am trying to figure out how to determine and process pixel blocks. Any advice would be appreciated.. and any code would be a wet dream.

A: Although it may sound like a simple question, it's not quite easy to do something like that. You need a lot of background information to get everything going. It also depends on where the image comes from, and what you want to do with it.
I will not provide you with a working example, but here's some pointers:
Reading in an image:
UIImage *img = [UIImage imageNamed:@"myimage.png"];
// make sure you added myimage.png to your project

Creating your own "graphics context" to draw on:
UIGraphicsBeginImageContext(CGSizeMake(480.0f, 320.0f)); // the size (width,height)
CGContextRef ctx = UIGraphicsGetCurrentContext();

Painting your image onto your (current) context:
[img drawAtPoint:CGPointMake(0.0f, -480.0f)]; // (draws on current context)

Doing some other painting:
CGContextBeginPath(ctx); // start a path
CGContextSetRGBStrokeColor(ctx,1,0,0,1); // red,green,blue,alpha with range 0-1
CGContextMoveToPoint(ctx,50,0); // move to beginning of path at point (50,0)
CGContextAddLineToPoint(ctx,100,100); // add a line to point (100,100)
CGContextStrokePath(ctx); // do the drawing

Transforming the bitmap context to an image again:
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

And then, either:
Show the image to the audience, from within a view controller:
[self.view addSubview:[[[UIImageView alloc] initWithImage:resultImage] autorelease]];

Or write the image as jpeg:
NSData *imagedata = UIImageJPEGRepresentation(img,0.8); // 0.8 = quality
[imagedata writeToFile:filename atomically:NO];

Or as PNG:
NSData *imagedata = UIImagePNGRepresentation(img);
[imagedata writeToFile:filename atomically:NO];

For those last ones you would need to have a filename, which is not so trivial either (given the phone environment you live in). That's another topic on which you'll find a lot, search for things like:
NSArray *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filename = [[path elementAtIndex:0] stringByAppendingPathComponent:@"myimage.png"];

This is the general outline, I might have made some errors but this should get you going at least.


text:
Q: Finding the direction between two bluetooth devices (localization) I have an app that scans for a specific UUID that another phone is broadcasting and measures the signal strength between them and tells you whether you're getting closer or further away from them. I want to add an arrow for direction. I know you can use triangulation if you have 3 points but I want to get something somewhat accurate with 2 points.
Any algorithm or suggestion that would help?
My current idea (since for this app's use case one node will be relatively still) is to have some algorithm learning as you walk. Like if you get further away the arrow knows to disregard this direction and keep refining itself as you walk different directions.
I found a bunch of research papers on the topic but I'm not an electrical engineer so it's easy to get lost. Also I read this post and understand the many pitfalls How to measure distance between two iphone devices using bluetooth?
Thanks!

A: Such a solution is extremely convoluted.
Getting the direction of the signal requires far more data than normal app usage can provide. The user would have to slowly rotate the phone while taking many samples of all directions.
Getting the relative distance, as you said like "getting closer" or "going farther away" is kinda possible within a 12 meter range using the formula posted below. Above 12 meters it gets very buggy. But it's quite complex and requires you to use a moving average solution with a length that you consider adequate.
You can calculate the relation between RSSI and distance using the following formula:
RSSI = -(10*n*log10(d) + A)

In this case,
n = path loss exponent, since you don't want an exact distance, just a way to check if it's closer or further, you can use 2 as a value, I found this the most realistic one in most cases.
A = the measured RSSI value at 1 meter distance, you need to measure this in advance to do your calculations, but since this varies a lot, just use a value like -60dB. Also this one is about average in most situations.
So getting a crudely guessed distance in meters can be achieved by the formula:
distance = 10 ^ ((-RSSI - 60) / (10 * 2));

This isn't very exact but will be sufficient to tell you if it is closer/farther within a limited range.


text:
Q: ZIpArchive not found Fatal error: Class 'ZipArchive' not found in /home/coaster/public_html/system/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php on line 234.
I am using the version of extension 2.31 in opencart.
How to solve this?

A: The ZipArchive class is available in the ZIP extension. You want to install the zip extension first. You can do that with handy app called pecl which installs PHP extensions: pecl install zip.
If you don't have the pecl app installed, you can do that with your favorite package manager, for instance: apt-get install pecl.
To check if the extension was installed successfuly, you can check via command line
php -r "echo extension_loaded('zip') ? 'Installed' : 'Not installed';"

or
php -m | grep zip

A: In the console run:
sudo apt-get install php7.0-zip

and be sure to restart apache after that.

A: This can be done self as well if you have cPanel access:
STEP 1:
Go to Cpanel - PHP Pear Packages - Find PHP Extension - Search for zip.
Install the zip extension found.
STEP 2:
Go to Cpanel - Select PHP Version - Tick the zip Option - Save.
Now try to upload the .ocmod.zip file. Should work now.
Worked for me.


text:
Q: Save a select from another table in a CRUD application I have a Categories table and a Gender table. In the Categories form you can choose your gender, which comes from the Gender table.
The problem is that the option you choose doesn't show when you want to edit something. after you made the Category. However it does show in the database in the Categories cte_gender_id as an integer. (1, 2 or 3)
This is my CategoryController:
$category = Category::find($id);
$array_category_gender_id = array();
$gender_id = $category->cte_gender_id;

$genders = Geslacht::where("gen_id", $gender_id)->get();

foreach($genders as $gender){
$array_category_gender_id[] = $gender->gen_name;
}

And the html:
<label>Gender</label>
<select name="gender_id" class="form-control" id="gender_id">
    <option disabled selected value>Select a gender...</option>
    @foreach($genders as $gender)
        <option value="{{ $gender->gen_id }}" {{ ($category ? (in_array($gender->gen_id, $array_category_gender_id) ? 'selected' : '') : '') }}>{{ $gender->gen_name }}</option>
    @endforeach
</select>

Thanks in advance!

A: Try this
$category = Category::find($id);

$category_gen = $category->cte_gender_id;

$genders = Geslacht::where("gen_id", $gender_id)->get();
return view('your_view',compact('category_gen','gender'));

@foreach($genders as $gender)
@if($category_gen==$gender->gen_id)
        <option value="{{ $gender->gen_id }}" selected>{{ $gender->gen_name }}</option>
@else
option value="{{ $gender->gen_id }}">{{ $gender->gen_name }}</option>
@endif
@endforeach


text:
Q: MouseEvents don't fire on body when inner div has position fixed in firefox Look at this example
Here is the code:
CSS:
div {
   position:fixed;
   top:100px;
   left: 320px;
   border: solid 1px blue;
}

Javascript:
 var i = 1;
 $(document.body).mousemove(function () {
     $("#text").html(i++);
 });

HTML:

      Test Text:

This code just updates the span while mouse is moved over the body. It works fine in Google chrome but in Firefox the span is only updated when mouse moves over the div, To debug I looked into firebug and found that the height of the body is 0, so the mouse is actually not moving over the body, but in Google chrome body covers whole document.
So My question is:

*

*Which is the right behavior?(chrome's or firefox's)?

*Is the right behavior documented somewhere?
Also surprisingly when I added this code in jsfiddle, chrome started behaving like firefox, can someone explain me this unusual behavior also?
EDIT: I know I can make the code work in both browser by adding height:100% to body, I want to know why this different behavior in browsers and the right one.

A: You can see what's going on if you add this css:
body { border: 1px solid red; }

I'm not entirely sure of the reasoning, but Chrome decides that the 'body' element should be the full height of the window, whereas Firefox collapses the body element to a single line.  I believe the body collapsing is the correct behavior, because a 'block' element (such as  or
) should only be as tall as necessary to contain its contents (and since you made the inner div absolutely positioned, it won't take this into account in calculating its height).
The correct fix depends on your intended outcome, but you could use document or window instead of document.body because they represent the entire viewable window instead of just the actual  element.
You could also set your body to a specific height like 100%.  Alternatively, once you add more content to the body (stuff that isn't absolutely positioned), it will "fill out" and cause the mousemove event to fire properly anyway, so you won't need any of these fixes.

A: Additional to Alex's answer I was still interested in the different behaviour. I found the solution: in jsfiddle you are not supposed to add the 'body' element in the html. If you remove that then you get the same behaviour as with the stand-alone page.
UPDATE:
That wasn't the case. The real reason is that the stand-alone page missed the
<!DOCTYPE html>

declaration which caused a HTML version difference.

A: I don't know why but this works
Replaced document.body with document in
$(document.body).mousemove(function () {
This also works on Firefox.


text:
Q: How do I get rid of - Warning: Each child in a list should have a unique "key" prop How can I get rid of this warning. I hate seeing it in the console. I feel I'm doing everything right but I keep getting this warning. This is what I'm doing:
      {reviews.map((review, i) => {
    return (
      <>
        <sl-details summary={`${review.name}`} key={i} open>

{review.review}

        </sl-details>

      </>
    );
  })}

I don't know if the stack is of any relevance but I'm using Nextjs and shoelace.

A: You didn't position your key on the first node within your map's callback.

Fragments declared with the explicit <React.Fragment> syntax may have
keys. A use case for this is mapping a collection to an array of
fragments

Checkout the very last section of that page.
So your code should become:
{reviews.map((review, i) => {
    return (
      <React.Fragment key={i}>
        <sl-details summary={`${review.name}`} open>

{review.review}

        </sl-details>

      </React.Fragment>
    );
  })}

A: The key={i} should be put on the outer <></> elements, and for that to be possible, you need to convert them to full <Fragment> elements.
Updated code:
{reviews.map((review, i) =>
    <Fragment key={i}>
      <sl-details summary={`${review.name}`} open>

{review.review}

      </sl-details>

    </Fragment>
)}

PS I also shortened it to not use the unneeded return.


text:
Q: How to include system dependencies in war built using maven I've searched on internet for quite some time and I'm unable to figure out how to configure the maven-war plugin or something alike so that the system dependencies are included in the built-war (WEB-INF/lib folder)
I use the maven dependency plugin in case of a jar-build as :
<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <phase>install</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

but I'm unable to understand what is to be done in case of a war build. I've tried using the maven-war plugin, but it's not including system-dependencies in the build.
[UPDATE]
I'm having depedencies of type :
<dependency>
    <groupId>LoginRadius</groupId>
    <artifactId>LoginRadius</artifactId>
    <scope>system</scope>
    <version>1.0</version>
    <systemPath>${basedir}\lib\LoginRadius-1.0.jar</systemPath>
</dependency>

in my POM and these dependencies are not included in WEB-INF/lib when the war is build.

A: You can configure the war plugin to have all or some jar included or excluded as per your need as mentioned below. Simple & works
           <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <webResources>
                        <resource>
                            <directory>${project.basedir}\lib</directory>
                            <targetPath>WEB-INF/lib</targetPath>
                            <filtering>false</filtering>
                            <includes>
                                <include>**/*.jar</include>
                            </includes>
                            <excludes>
                                <include>**/javax.servlet-api-3.1.0.jar</include>
                            </excludes>
                        </resource>
                    </webResources>
                </configuration>
            </plugin>

A: If you meant as jar dependencies, then below is a sample pom.xml which takes are needed files and generates a war file:
 <build>
        <defaultGoal>install</defaultGoal>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <outputDirectory>${project.basedir}/target/classes</outputDirectory>
        <testOutputDirectory>${project.basedir}/target/test-classes</testOutputDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.0.2</version>
                    <configuration>
                        <source>1.5</source>
                        <target>1.5</target>
                        <debug>true</debug>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.4</version>
                    <configuration>
                        <includeEmptyDirs>true</includeEmptyDirs>
                        <webResources>
                            <resource>
                                <directory>ui</directory>
                                <targetPath></targetPath>
                                <includes>
                                    <include>**</include>
                                </includes>
                            </resource>
                            <resource>
                                <directory>lib</directory>
                                <targetPath>WEB-INF</targetPath>
                                <includes>
                                    <include>**/*.xml</include>
                                    <include>**/log4j.properties</include>
                                </includes>
                            </resource>
//edited below
                            <resource>
                               <directory>lib</directory>
                               <targetPath>WEB_INF/lib</targetPath>
                               <includes>
                                    <include>**/*.jar</include>
                               </includes>
                            </resource>
                        </webResources>
                        <webXml>${project.basedir}/WEB-INF/web.xml</webXml>
                    </configuration>
                </plugin>

                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>attach-sources</id>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>

            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

A: Based on your initial POM, I would suggest to send them directly to the WEB-INF/lib directory
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${project.build.directory}/${project.artifactId}-${project.version}/WEB-INF/lib</outputDirectory>
                    </configuration>

A: Let me try to summarise the options I tried :
<packagingIncludes>${java.home}/lib/jfxrt.jar</packagingIncludes>

This doesn't work! Also, only having the jar name, excludes everything else, so if you are willing to try then try
<packagingIncludes>${java.home}/lib/jfxrt.jar,**/*</packagingIncludes>

Jatin's answer seemed a bit complex and I tried going through the POM again & again to figure out where exactly were the system jars mentioned to be included in WEB-INF POM.
Anyways, I ended up using this solution, which wasn't working at first but after some time and some corrections worked :
I installed the jar in my local repository using the below command :
mvn install:install-file -Dfile="C:\Users\hp\Documents\NetBeansProjects\TwitterAndLoginRadiusMaven\lib\LoginRadius-1.0.jar" -DgroupId=LoginRadius -DartifactId=LoginRadius -Dversion=1.0 -Dpackaging=jar`

After running the above command, I changed the dependency in POM to
<dependency>
   <groupId>LoginRadius</groupId>
   <artifactId>LoginRadius</artifactId>
   <!--<scope>system</scope>-->
   <version>1.0</version>
   <!--<systemPath>${basedir}\lib\LoginRadius-1.0.jar</systemPath>-->
</dependency>

NOTE - See I've commented the system scope & systemPath.
Building the war now, includes this LoginRadius-1.0.jar in WEB-INF/lib

A: If by chance you can't install the third party library to your local repository, due to some silly naming/packaging checks by the third party, you can still add your system scoped dependencies to your final package at build time (at least if you are building a webapp) using the maven-war-plugin where you would need to create a configuration like this.
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.0</version>
    <configuration>
        <failOnMissingWebXml>true</failOnMissingWebXml>
        <webResources>
            <resource>
               <directory>path/to/lib/in/project</directory>
               <targetPath>WEB-INF/lib</targetPath>
            </resource>
        </webResources>
    </configuration>
</plugin>

Not sure but I believe that the library must be somewhere local to the project's base directory. I tend to create a directory under src/main/ called lib to hold these sorts of 3rd party libs. During build process they are placed in the correct directory and added to the war file.

A: mvn org.apache.maven.plugins:maven-install-plugin:2.5.1:install-file \
  -Dfile=~/Desktop/medici-1.0.1.jar \
  -DgroupId=com.hp \
  -DartifactId=medici \
  -Dversion=1.0.1 \
  -Dpackaging=jar \
  -DlocalRepositoryPath=lib

If all went well, you can find your artifact published inside of lib.
project$ find lib
lib
lib/com
lib/com/hp
lib/com/hp/medici
lib/com/hp/medici/1.0.1
lib/com/hp/medici/1.0.1/medici-1.0.1.jar
lib/com/hp/medici/1.0.1/medici-1.0.1.pom
lib/com/hp/medici/maven-metadata-local.xml
Note the structure here mimics what you'd find in ~/.m2.

Now, in your pom.xml, declare it in your project a Maven repository.
<repositories>
    <repository>
        <id>local-repo</id>
        <url>file://${basedir}/lib</url>
    </repository>
</repositories>

And lastly, in your pom.xml declare a dependency on the local .jar like you would for any dependency.
<dependencies>
    <dependency>
        <groupId>com.hp.medici</groupId>
        <artifactId>medici</artifactId>
        <version>1.0.1</version>
    </dependency>
</dependencies>

A: It may be problem of the scope where the dependencies are defined:

*

*compile: Dependencies in "compile" scope will automatically be copied to the target's WEB-INF/lib as part of the Maven build.

*provided: Dependencies in "provided" scope will not be copied (you would use this for server-supplied jars such as the JSP-api.jar).

To generate a WAR in Maven, 2 goals have to be run: "compile" and "war:war". Running the war goal alone won't compile the Java source . If you prefer, run one of the master goals, such as "package".
If using eclipse:
select the POM in the project explorer and select the "Run" context menu option. This will build and execute Maven run profile (or use an existing one). Maven run profiles behave just like regular run/debug profiles except that their profile edit dialogs support Maven-specific features.
source: https://coderanch.com/t/594897/ide/include-maven-dependencies-war-file


text:
Q: How to call server method to list items in a table? I have a simple ASP.Net Core 3.0 webapp with SignalR which is used to list and view posts. I added the following js script:
"use strict";

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/PostsHub")
    .withAutomaticReconnect()
    .build();

if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {
                var r = o[b];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

connection.start().then(function () {
    $postsTable = $('#postsTable'),
    $postsTableBody = $postsTable.find('tbody'),
    rowTemplate = '
{Date}	{User}	<button onclick="btn_click({Id})" id="viewPost{Id}">View</button>
';

    connection.invoke("getAllPosts").done(function (posts) {
        $postsTableBody.empty();
        $.each(posts, function () {
            $postsTableBody.append(rowTemplate.supplant(this));
        });
    });
}).catch(function (err) {
    return console.error(err.toString());
});

But with the above code, the posts are not being listed. I can't see where the error is. Could it be the supplant function?

A: If you'd like to invoke a hub method that would return all posts, and dynamically populate table with returned data, you can refer to following sample.
PostsHub Class
public class PostsHub : Hub
{

    public List<Post> GetAllPosts()
    {
        var posts = new List<Post>() {
        new Post(){Id=1,User="feihan",Date="11/25/2019" },
        new Post(){Id=2,User="test1",Date="11/23/2019" },
        new Post(){Id=3,User="test2",Date="11/25/2019" }
        };

        return posts;
    }
}

Post Class
public class Post
{
    public int Id { get; set; }
    public string User { get; set; }
    public string Date { get; set; }
}

On JavaScript client
if (!String.prototype.supplant) {
    String.prototype.supplant = function (o) {
        return this.replace(/{([^{}]*)}/g,
            function (a, b) {

                //convert to  lowercase letters
                var r = o[b.toLowerCase()];
                return typeof r === 'string' || typeof r === 'number' ? r : a;
            }
        );
    };
}

connection.start().then(function () {
        $postsTable = $('#postsTable'),
        $postsTableBody = $postsTable.find('tbody'),
        rowTemplate = '
{Date}	{User}	<button onclick="btn_click({Id})" id="viewPost{Id}">View</button>
';

    //use connection.invoke(...).then

    connection.invoke("getAllPosts").then(function (posts) {
        $('#postsTable').find('tbody').empty();

        $.each(posts, function () {
            $postsTableBody.append(rowTemplate.supplant(this));
        });
    });
}).catch(function (err) {
    return console.error(err.toString());
});

Test Result


text:
Q: Installation Error --  Class 'DateTime' not found I got this error when I was installing the SugarCRM  on the server:

Fatal error: Class 'DateTime' not found in /home/fuyinshidai/CRM/include/SugarDateTime.php on line 43
Fatal error: Class 'DateTime' not found in /home/fuyinshidai/CRM/include/TimeDate.php on line 1353

But it didn't happen during local installation.

A: Which version and flavor of Sugar is this for? And which version of PHP are you using?
Sugar only supports 5.2.1 and later.


text:
Q: How to disable the database on Rails 3 for a webservice-based application I am making an application that does not, as of now, require a database. So I want to disable it!
I am making this with Rails 3beta4 with Postgres 8.4.x.
In order to serve up a view, Rails 3 seems to need the database specified in database.yml to exist--why? I never checked this with Rails 2.3, but it seems silly that it should need to connect to the database if I don't pull any data from it. Which means I never want to connect to the database at all for this application.

A: If you are creating a new application, you can use 'skip-active-record' to skip database configuration:
rails new my_app --skip-active-record

A: Go to config and make the following changes in the database.yml file
under the database development,
comment out your database. This way controller will stop looking for the database.
Once you're ready to use your database, just uncomment the above.