Extracting text from pdf using itextSharp changes digits

Question: I have a pdf file which I have a problem extracting text from it -  using an itextsharp api.
some of the numbers are replaced by other numbers or backslashes : "//"
The pdf file was originally came from MS Word and exported to pdf using "Save as pdf", and i have to work with the pdf file and not the Doc.
You can see the problem very clearly when you try to copy and paste some numbers from the file
For example - if you try to copy and paste a 6 digit number in the bottom you can see that it changes from 201333 to 333222.
You can also see the problem with the date string : 11/4/2016 turns into // // 11110
When I print the pdf file using adobe Pdf converter printer on my computer, it get fixed, but i need to fix it automaticlly, using C# for example
Thanks
The file is shared here :
https://www.dropbox.com/s/j6w9350oyit0od8/OnePageGili.pdf?dl=0
Comment: Please inspect you PDF and check whether it is an issue like the one [answered here](http://stackoverflow.com/a/22688775/1729265). If you cannot check yourself, please share your PDF for analysis.
Answer: In a nutshell
iTextSharp text extraction results exactly reflect what the PDF claims the characters in question mean. Thus, text extraction as recommended by the PDF specification (which relies on these information) always will return this.
The embedded fonts contain different information. Thus, text extraction methods disbelieving this information may return more satisfying results.
In more detail
First of all, you say

I have a pdf file which I have a problem extracting text from it - using an itextsharp api.

and so make it sound like an iTextSharp-specific issue. Later, though, you state

You can see the problem very clearly when you try to copy and paste some numbers from the file

If you can also see the issue with copy&paste, it is not an iTextSharp-specific issue but either an issue of multiple PDF processors including the viewer you copied&pasted with or it simply is an issue of the PDF you have.
As it turns out, it is the latter, you have a PDF that lies about its contents.
For example, let's look at the text you pointed out:

For example - if you try to copy and paste a 6 digit number in the bottom you can see that it changes from 201333 to 333222.

Inspecting the PDF page content stream, you'll find those six digits generated by these instructions:
/F3 11.04 Tf
...
[<00150013>-4<0014>8<00160016>-4<0016>] TJ

I.e. the font F3 is selected (which uses Identity-H encoding, so each glyph is represented by two bytes) and the glyphs drawn are from left to right:
0015
0013
0014
0016
0016
0016

The ToUnicode mapping of the font F3 in your PDF now claims:
1 beginbfrange
<0013> <0016> [<0033> <0033> <0033> <0032>]
endbfrange

I.e. it says

glyph 0013 represents Unicode codepoint 0033, the digit 3
glyph 0014 represents Unicode codepoint 0033, the digit 3
glyph 0015 represents Unicode codepoint 0033, the digit 3
glyph 0016 represents Unicode codepoint 0032, the digit 2

So the string of glyphs drawn using the instructions above represent 333222 according to the ToUnicode map.
The PDF specification presents the ToUnicode mapping as the highest priority method to map a character code to a Unicode value. Thus, a text extractor working according to the specification will return 333222 here.
Comment: Thank you very much for the detailed information . is there any ItextSharp solutiion ?
Comment: The solution to look for would be to fix the PDF. For a farily sure way to fix it, one can use iTextSharp as the PDF manipulation framework but one would use additional resources, in particular a font library and optimally the fonts from which the subset fonts in your document have created, and it may prove non-trivial, at least quite some work. To do this one should have some knowledge of font program and PDF internals.


CertainTeed DiamondBack- Waterproofing needed for tile?

Question: I picked up some DiamondBack CBU to tile a shower enclosure, as it seems like it would be a lot easier to work with than Hardibacker (I can't cut the stuff without making a huge dusty mess, so if you have hints, I'll take them) and also matches up to the 1/2" green board that abuts it. When I look at the installation instructions, they don't have a waterproof plastic sheet (say, 6 mil plastic) nor a waterproof coating (such as RedGard) on the surface.
Incredulous, I called their customer service line to verify. While friendly, their customer service rep seemed to have as much knowledge of the product's ability as I did. He said that the outer layer doesn't require it and that I need to butt the panels tightly against one another, seal changes of plane (corners, etc) with a flexible sealant and use an ANSI (i forget the number) rated thinset.
Has anyone used this product? Has anyone used this product without adding a waterproof layer? I am a bit nervous and, with the slicker coated surface on the DiamondBack am afraid that, if I defy the instructions and waterproof that I'd have issues with it and, ultimately, the tile's adhesion to the board.
Answer: According to the manufactures install specs, a separate vapor barrier is not required if you seal between panels with a waterproof sealant/caulk.  I found the complete install specs for you here:   http://www.certainteed.com/resources/CTG-2509_Diamondback_Install_Guide_Eng.pdf


Would the "Nest" thermostat work outside US?

Question: Looking at this Nest question reminded me that I'd really want one of these for my future house. The Nest website says that it's currently only available in the US but I'm wondering whether that is just a sales/marketing choice of if there might be technical reasons for the US limitation.
The Nest website has a widget where you can tick what cables you've got and it then tells you whether the Nest will work with that. I'm not sure that these cable markings/colors are international though. I would get a Vaillant gas heater very similar to this one.
At $250 it's just expensive enough that I hesitate to just order one and try if it works. Even if I did, I would also be afraid of damaging it by connecting the wires wrong.

Do the markings/colors on cables of gas heaters/thermostats follow an international standard?
Can I expect that a Nest would work in Europe, when connected to a European brand model?
Comment: I love the design of NEST, but I haven't been able to justify the cost. Given a programmable thermostat runs in the $50 range, and once set, you really don't touch it more than maybe once or twice a year, $250 seems excessive.
Comment: They announced yesterday that there is availability in other countries now.
Comment: Canada qualifies as _other countries_ but that's it, as far as I can tell. The website explicitly says Europe not yet, anyway.
Answer: Actually, you should be able to make them work in the UK. An electrically savvy friend of mine has one up for sale on ebay along with this note:
I would suggest that only the technology savvy avid DIYer, or keen professional electrician with enough research install this item.  Unfortunately because this thermostat is not intended for direct installation to common UK Central Heating systems, I will not accept returns.  It can be installed though!  It will work just fine when correctly installed, but there are the following caveats:

The Nest thermostat works on 24V AC North American HVAC wiring - in the UK most commonly we have zero volt contacts for Thermostats.  You can easily make this work with a 24V AC power supply and a relay after carefully studying the wiring.  The Nest draws a tiny current (12mA) through the coil to trickle charge its internal battery so I would suggest a good sized relay to avoid buzzing.
The WiFi in the Nest can only handle US FCC approved channels 1-11.  In the UK we allow channels 1-13, so just make sure your wireless access point is not set to channel 12 or 13.  No big deal.
You must skip the 'enter your zip code' stage of the setup process.  The Nest will not access weather data outside of the USA.  The smart algorithms still work fine without weather data - the sensors to check the temperature inside your house is what is most important anyway.
The Nest iPhone and Android apps to control your temperature from your phone are not available outside of the US.  If you have a rooted Android phone, you can install 'Market Enabler' to install the Nest app from the US Market and then it should work just fine.  I have no idea about whether such a thing is possible for the iOS App Store.

Once those four things are paid attention to, it should work well!  Would be a fantastic, high quality, high tech, rare addition to your home and definitely a cool talking point.
Comment: No worries. @ChrisF's answer is right for the vast majority of folks. I just popped this up here as a technically challenging alternative :-)
Comment: Thank you for more or less proving that it can be done!! _Oh boy_ I would love to do this, but I'm not so keen on hacking around with heating stuff in a new house. I've still accepted another answer because this one (although _technically_ enticing) would not be recommendable to the average person. Also, the Apple App Store requires a US credit card to access US apps; I'm not aware of any hack to circumvent that and it would be a pity to have the Nest without the app.
Comment: You can create US App Store account without a credit card. You just need an email address not currently tied to an Apple ID. Lots of instructions are available if you goggle it. You can use this account to download the free apps only available in the US.
Comment: As stated in latest software update (version 4.0) [release notes](http://support.nest.com/article/What-s-new-in-the-Nest-Thermostat-s-4-0-software-update), now you can input an European zip code! Nest will handle that correctly!
Answer: One big thing to remember about Nest is that it is a low voltage thermostat. Therefore, it can't be used on a typical heating system in the UK (say) as we tend to have 240V connections to thermostats and timers.
Check the voltage of your existing thermostat/timer. If it's a low voltage one then Nest should work.
Answer: Here are other personal experiences with using this device in The Nederlands.

Below a list of problems I encountered with the product due to the
  fact I'm not living in the US:

You can only set time by entering a US zipcode. No time support for    timezones outside the US. How difficult can it be to make a basic
  functionality like a clock work all around the globe? There is no
  option to set the time or timezone manually.
Weather is only    available for US cities. This is actually related to the point above.    The location for weather can only be
  set with the zipcode. It is not    possible to disable weather at all.
  How difficult would it be to make    weather work globally, or to make
  it possible to disable it? Most    weather databases work globally
  anyway.
No 24h clock support. Why    not? That's a simple switch? Setting the temperature to Celsius is    possible though, while Fahrenheit is
  the only system used in the US.    iPhone/iPad app is only available
  from the US appstore.This is just    checking a checkbox in Itunes
  Producer.
Auto away only works when    Nest thinks it's daytime. I managed to kinda work around the timezone    issue by setting it to Honolulu,
  which is exactly a 12 hour    difference with the Nerherlands. So
  during the night in my place the    Nest thinks it's day and vice
  versa. I saw that auto away only works    during daytime, so in my
  case nighttime. This caused my heater to    stop working until I
  activated it by entering the room again. So no    preheated room for
  me in the morning. I had to disable auto away.    This also seems a
  problem for people who work at night in the US.
No    OpenTherm support. OpenTherm is a widely used system for modulating    heaters. Ok, it's a non-US system, so I can accept that,
  since it's    indeed only sold in the US, but still I'm missing this
  feature.
Build    quality is dissapointing. One of the unique selling points used to    promote the product is that it is designed by a former
  Apple    designer. While this might be true it's not a very solid
  product. The    ring that you use to control it with doesn't run
  freely. It makes a    scraping sound when you turn it sometimes. It is
  very sensitive too,    so if you want to set a temperature in the
  schedule and press the    ring to confirm it, most times by pressing
  you also change your    setting slightly. Build quality is ok for a
  product like this, but    expectations are higher when the name
  "Apple" is mentioned.
Answer: I use a Nest Thermostat outside the US; I live in The Netherlands.
In The Netherlands, most systems use the same 24v system as in the US, so the Nest powered up nicely. It works fine, but I haven't connected it to the Internet - so I cannot control it remotely or use the apps to see savings and so on.
For me it was not possible to skip the zip-code question, it would not go further without the zip-code. So I entered 00000 as a zipcode. The main problem is that it uses the zipcode to determine the date and time - so it adjusts its time to a US timezone!!! Only when not connected to the Internet you can enter the time manually. When you connect again it will re-adjust its time.
If you are in the wrong timezone reading the shedule is really a hassle - even if you manage to find a zone that differs exactly 12hrs.
So besides technical challenges you will also have to live either with no connectivity or a wrong timezone.
Good luck.
Answer: I believe the reason that they say US only is because they provide services over the internet for which they only have US data.  I have a Filtrete Wi-Fi thermostat the has the same disclaimer, but it works just fine in Canada and their software even correctly displays Canadian weather.
As for the wires, there is not really a "standard" but instead a general pattern; but don't just assume this is followed.  Make sure to mark the cables based on how they are connected to your existing thermostat.  It's not uncommon for people to deviate.  You will also require a C (common) wire for this hookup - you may or may not already have this, but if you don't, you will need to run an additional conductor back to your furnace.
From http://wiki.xtronics.com/index.php/Thermostat_signals_and_wiring:

The usual terminals are:
G – Fan, usually a green wire
R – 24 VAC usually a red wire
C – 24 VAC Common
Y – Compressor, usually a yellow wire
W – Heat, usually a white wire


Get the number of affected rows in a MySQL update statement?

Question: I have stored procedure in MySQL, something like the below:
create procedure SP_Test (input1 varchar(20))
begin
update Table1 set Val1='Val' where country=input1;
//I want to see if this update changed how many rows and
//do some specific action based on this number
....
end

How can I determine how many rows were changed by this update?
Answer: Use ROW_COUNT():
SELECT ROW_COUNT();

Comment: How to use it? Where to use it? It didn't answer the question. I'm getting row count = 0, when I know at least one was affected.

UPDATE Users SET Users.password=3 WHERE userID=1; //1 affected
SELECT ROW_COUNT(); // returns 0
Comment: Note this doesn't _appear_ (like a lot of other things) to work in _MySQL Workbench_ for Mac, but it does work in the console (and in stored procedures of course).
Answer: one way, not very optimal is to simply do a select before you do the update.
select count(*) from table1 where country = 'country1'

Comment: This will not tell how many rows have been changed by the `UPDATE`.
Comment: @dolmen it will IF the where clause matches the updates AND none of the fields in the where were set AND nothing else has changed them between update and select so definitely not ideal but feasible
Comment: That is a _mighty_big_ "if"
Answer: Try the following code:
int mysql_affected_rows ([ resource $link_identifier = NULL ] )

Comment: The question is about stored procedures.


Would it be possible to change literals in the model below to reference values from an external file for localization or quick user changes?

Question: Given users who change their minds a thousand times.  How could I change the literals below to come from a config file or something similar?
namespace mvc3test.Models
{

    public class ChangePasswordModel
    {
        [Required]
        [DataType(DataType.Password)]
        [Display(Name = "Current password")]
        public string OldPassword { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "New password")]
        public string NewPassword { get; set; }

Comment: Also, doesn't this defeat part of the purpose of MVC? Which is to separate the logic from the presentation layer? Isn't the text to display on the screen very presentation specific?
Comment: do you want the validation error messages to be configurable or the types of validation attributes on a particular property?
Comment: @Eranga - I was more focused on the Display Attribute. really anywhere you see a literal in this example, so `Current Password`, `The {0} must be at least {2} characters long.`, and `New Password`,  Now imagine them all needing to be rewritten to be more customer friendly...
Answer: These attributes(eg DisplayAttribute) have ResourceType and Name properties. These can be used with a Resource file to externalize the literals and thereby localizing and/or changing literals. Have a look at this example.
Comment: Your solution appears that it might work for one single *.resx file.. The problem comes in with VSS2010 not being able to figure out how to generate the code for a file with the naming convention *.*.resx It will only generate an empty *.cs file.
Comment: @Doug Resource files are also class files that inherit from ResourceManager http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager.aspx class. So if you give a legal class name it should work
Comment: I'm suggesting there is a bug in the IDE, not that you are incorrect.  I do see there is a workaround. thanks for the link


Any recommendations to improve this function?

Question: I am very new to working with SQL queries. Any suggestions to improve this bit of code:
(by the way, I really don't care about sql security here; this is a bit of code that will be in a pyexe file connecting to a local sqlite file - so it doesnt make sense to worry about security of the query here).
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
    global heights, values
    D, heights, values, max, = [], {}, {}, 0.0001

    if reset: GHolder.remove()

    Q = "SELECT wbcode, Year, "+QA+" FROM DB WHERE commodity='"+QB+"' and "+QA+" IS NOT 'NULL'"

    for i in cursor.execute(Q):
        D.append((str(i[0]) + str(i[1]), float(i[2])))
        if float(i[2]) > max: max = float(i[2])

    for (i, n) in D: heights[i] = 5.0 / max * n; values[i] = n
    Gui["YRBox_Slider"].set(0.0)
    Gui["YRBox_Speed"].set(0.0)

after following the advices, this is what I got:
def InitBars(QA = "GDP1POP1_20091224_gdp", QB = "1 pork", reset = False):
    global heights, values; D, heights, values, max, = [], {}, {}, 0.0001
    if reset: GHolder.remove()

    Q = "SELECT wbcode||Year, %s FROM DB WHERE commodity='%s' and %s IS NOT 'NULL'" % (QA, QB, QA)
    for a, b in cursor.execute(Q):
        if float(b) > max: max = float(b)
        values[a] = float(b)

    for i in values: heights[i] = 5.0 / max * values[i]

    Gui["YRBox_Slider"].set(0.0); Gui["YRBox_Speed"].set(0.0)

Comment: Do not get used to bad habits. Always care about security.
Comment: given that sqlite3 is part of Python's standard library, you would have to make a better reason for not using its parameterized queries.
Comment: the advice was *not* to put multiple statements in the same line. this include the `if` and its branches.
Answer: If this is a one-off script where you totally trust all of the input data and you just need to get a job done, then fine.
If this is part of a system, and this is indicative of the kind of code in it, there are several problems:

Don't construct SQL queries by appending strings.  You said that you don't care about security, but this is such a big problem and so easily solved, then really -- you should do it right all of the time
This function seems to use and manipulate global state.  Again, if this is a small one-time use script, then go for it -- in systems that span just a few files, this becomes impossible to maintain.
Naming conventions --- not following any consistency in capitalization
Names of things are not helpful at all.  QA, D, QB, -- QA and QB don't even seem to be the same kind of thing -- one is a field, and the other is a value.
All kinds of questionable things are uncommented -- why is max .0001? What the heck is GHolder? What could that loop be doing at the end?  Really, the code should be clearer, but if not, throw the maintainer a bone.
Comment: +1, but I disagree with the first paragraph. There's no reason not to follow these rules in small scripts, and he shouldn't build bad habits. Also, he'll probably reuse the script in the future, even if he doesn't know it now.
Answer:
Use more descriptive variable names than QA and QB.
Comment the code.
Don't put multiple statements in the same line
Try not to use globals. Use member variables instead.
if QA and QB may come from user input, don't use them to build SQL queries
Answer: You should check for SQL injection. Make sure that there's no SQL statement in QA. Also you should probably add slashes if it applies.
Answer:
Use
Q = "SELECT wbcode, Year, %s FROM DB WHERE commodity='%s' and %s IS NOT 'NULL'" % (QA, QB, QA)

instead:
Q = "SELECT wbcode, Year, "+QA+" FROM DB WHERE commodity='"+QB+"' and "+QA+" IS NOT 'NULL'"

Care about security (sql injection).
Look at any ORM (SqlAlchemy, for example). It makes things easy :)
Comment: That does nothing to prevent SQL injection.  Set QB to something with a single quote and it's not escaped.  To prevent SQL injection, don't create strings from variables -- use the DB layer to pass in objects as parameters.


Cardinality of projection in the SPARQL 1.1 Recommendation

Question: The official SPARQL 1.1 defines projection as follows:
"Definition: Project
Let Ψ be a sequence of solution mappings and PV a set of variables.
For mapping μ, write Proj(μ, PV) to be the restriction of μ to variables in PV.
Project(Ψ, PV) = [ Proj(Ψ[μ], PV) | μ in Ψ ]
card[Project(Ψ, PV)](μ) = card[Ψ](μ)"

I cannot understand the definition of the cardinality of the resulting sequence Project(Ψ, PV). I interpret card[Project(Ψ, PV)](μ) = card[Ψ](μ) as follows: For each solution mapping μ in the result of the projection Project(Ψ, PV), the cardinality of μ in Project(Ψ, PV) is the cardinality of μ in Ψ, which I find odd since μ perhaps does not exist in Ψ when PVis only a part of the domain of the solution mappings occurring in Ψ.
What am I missing here?
Comment: So it should be something like  `card[Project(Ψ, PV)](μ) = sum card[Ψ](μ') for all μ' in Ψ such that μ = Proj(μ', PV)` ?
Comment: μ are the elements of Ψ. `... | μ in Ψ `
Comment: Then why write card[Project(Ψ, PV)](μ) ? This means the cardinality of μ in Project(Ψ, PV)]
Comment: (last line in the definition)
Comment: Cardinality has to be defined. The same pattern of definition is used. Here, the cardinality in the projection is the same as the cardinality in the sequence before projection.
Comment: But the sequence resulting from the projection and the sequence before projection are different! How could the cardinality of arbitrary solution mappings be the same in both sequences, if the solution mappings occurring in either sequence may be different from the ones occurring the other one?!
Comment: Yes, I think so!
Comment: Raised as an errata for SPARQL 1.2 to address. sparql-query/issues/80
Comment: Is it possible to provide a link?
Comment: Found the link https://github.com/w3c/sparql-query/issues/80
Comment: If you don't mind posting that with an answer so that we can close the question?
Answer: The card definition looks wrong.
It does not consider different solution mappings on the input projecting to the same solution mapping on the output.
A possible errata is:
card[Project(Ψ, PV)](μ) = sum card[Ψ](μ') for all μ' in Ψ such that μ = Proj(μ', PV)

and this has been passed to the working group for consideration.


Extend UILocalNotification

Question: I beginner in iOS. I try extend UILocalNotification. My class below.
@interface FSCustomNatification : UILocalNotification

typedef enum {
    FSCustomNatificationPay,
    FSCustomNatificationWrite,
    FSCustomNatificationSend
} NotificationTypeT;

@property (nonatomic, assign) NotificationTypeT typeNotificationT;

@end

#import "FSCustomNatification.h"

@implementation FSCustomNatification

@end

When I set typeNotificationT property I get -[UIConcreteLocalNotification setTypeNotificationT:]: unrecognized selector sent to instance 0x8144780. Why?
FSCustomNatification* localNotification = [[FSCustomNatification alloc] init];
localNotification.typeNotificationT = FSCustomNatificationWrite;

Comment: Have you tried overriding `init`? It looks like it thinks `localNotification` is a `UIConcreteLocalNotification` rather than a `FSCustomNatification `. Also, you have an a instead of an o in your class name.
Comment: Yes, I tried overrite init.
Answer: By the looks of your error message UILocalNotification is part of a class cluster. The docs don't say (that I can see quickly) but it seems unlikely that you should subclass UILocalNotification.
Instead, you should make use of the userInfo provided by UILocalNotification to add any extra information you want to be available when the notification fires.

Extend UILocalNotification


Installing a fridge inside a wall?

Question: I'm designing the kitchen (renovating a 100+ year old house) and I would really really like to make it a "G layout" kitchen (like a U shape but with breakfast bar peninsula) but in order to achieve this the fridge would need to be INSIDE the wall with the door flush with the wall! The back wall is already filled with cabinets and the sink so that is why I wouldn't want to put the fridge there. See my 3d model I made with ikea.com:

My question is:
What could go wrong? I'm basically just doing a sanity check and making sure this isn't a terrible idea. (I'm having a hard time googling this as this is not a common thing to do I guess)
Alright in order for you guys to answer the question you'll need much more info. Here's what I can tell you:

The room that the fridge will go into is the laundry room. There is nothing in the way! It's an ugly, utilitarian room and we don't care if the back of the fridge is facing the washing machine) though boxing in the fidge would be nice).
The laundry room in which the fridge will go into is a bump-out extension of the house.

When they added the extension, it's like they left the exterior of the house exactly as it was and made that the interior of the new laundry room. The old asbestos shingles are still there on the wall, the soffit from the old roof is right where it always has been, and there is a big window right where the fridge will go! In fact it is almost tall and wide enough to fit the fridge in it, but it's a few inches too far to the right.
the floors between laundry room and kitchen are not on the same level. And the corner of the floor (concrete) on the kitchen where the fridge will be nearest, there is an obvious rise in height making a concave shape in the floor. (I mean, its maybe an inch total, like you wouldn't notice it but it could screw with stuff).
the wall is a load bearing wall. However I don't think there'll be any problems installing a header or just moving the window header up a little bit.

the ceiling in the kitchen is low! 7 feet to be exact.
the electrical circuit breaker is in the laundry room. Thankfully its a couple inches to the right of the fridge so that won't be a problem however there may be wires running bellow the window frame but I suspect that there is not.
the door to the laundry room will be to the right of the fridge, as shown in the 3d model.
the whole kitchen is 11 feet wide and 21 feet long but we intent to use much of that space for a dining area. The other kitchen layout option we are considering is making it an L shaped kitchen by loosing the breakfast bar and puting the fridge there (to the right of the window) but we don't like that layout as much. Too open.

So, is this doable? How would YOU tackle this project? Are there any restrictions or code requirements? Would it be just like a cased opening? Thanks!
Comment: seems like a great idea!
Comment: According to National Electrical Code,  receptacles in laundry areas have to be GFCI protected. So if that code applies to you, you're going to be plugging the fridge into a GFCI protected receptacle.
Comment: It's common to put refrigerators in nooks, just make sure you obey the manufacturer's documentation for clearances
Answer: On the refrigerator, don't box it in so badly that you block airflow to the coils.  Remember how a refrigerator works.  It pumps the heat inside the refrigerator and dumps it outside through a set of cooling fins in the bottom back area.  If you box it in too much, it won't get enough fresh air to cool well, and it will run inefficiently, fail to cool well, or breakdown prematurely.  It's not a big deal if you provide space for that.
Bonus points if you can access the back of the fridge to clean the fins, as you should every few years.  Try to set it up so dryer lint isn't drawn into the cooling fins.
The fridge needs to be leveled.  The manufacturer has a spec for this.  Generally the fridge is slightly "tilted back" on purpose, so the doors will self-close by gravity freely and firmly.  When set up right, it's a thing of beauty.
On the electric service panel, remember you must have clear space around the panel as described in the link here.
Also don't forget that since this is a remodel, you must bring the remodeled area fully up to new electrical code.  Figure on dedicated circuits for each of dishwasher, garbage disposal, microwave if built in, at least 2 (I recommend more) circuits for kitchen counter receptacles (honestly in the age of USB you just can't possibly have enough kitchen receptacles). Might be worth thinking about fitting a 50A circuit for an electric range/oven, also consider providing outlets for in-cabinet or under-cabinet lighting since the LED options these days are marvelous and cheap.
I recommend a dedicated circuit with a SINGLE receptacle for the refrigerator.  Have that be non-GFCI if you can convince your inspector to allow that.
Comment: Yes I plan on updating all the electrical. I've already stipped out most of the old wiring (no ground wire) and have began replacing it. My understanding is that every section of countertop needs an outlet and if it's more than 2 ft then it needs multiple outlets. Which I have no problem with as we have plenty of little kitchen appliances. I've also began wiring the overhead lights - we're going with 8 can lights sense the height of the ceiling is a little low. Then I'll probably install a light above the breakfast bar and above the dining table
Comment: And thanks for the pointer about keeping space around the electric panel. The fridge and dryer will box in the panel into the corner a little bit, a large person would not be able to get to it. But there is some wiggle room with the dryer which can be scooted it it's right a few inches and I think that will help
Comment: One more thing: you're right about adding the 50A circuit for an electric oven. The oven we have now is gas but my girlfriend wants electric glass top so I'm going to install everything necessary to accommodate both gas and electric. I already have the 50 amp wire (#6-2), breaker, and outlet.
Comment: Why would you swap gas for electric range?  Keep the gas lines there and cap them off as surely the next owner will want the option.
Comment: The clear space around the panel is not a *suggestion*, an inspector could make you rip it out and redo it. . Don't let it happen to you, check with the inspector first, and don't sugarcoat it.
Answer: I don't foresee any issues with this one - I actually did something very similar in my first property.  I would advise boxing in the back of the fridge, mostly for aesthetic reasons, but also partially because it will help keep the back of the unit clean from any of the dust or lint that tends to accumulate in a laundry space.  I boxed mine in because it backed into the dining room and I didn't want it exposed.
You may have planned for this already, but you would need to consider how you want to power this thing.  You could locate an outlet inside the box you've constructed, but this would require a little bit of extra clearance at the back or on one side.
Your other options are to run the power cable through a little hole in the new wall into an outlet in the laundry room, or run the power cable out past the front of the appliance and into an outlet in the kitchen.  The first probably doesn't conform to code, and the second won't look that great.
--SOMETHING I JUST THOUGHT OF--
Consider the size of fridge that you might purchase in the future.  It's ill advised to make reasonably major changes to the structure of the wall without considering that at some point you're going to want to change that fridge out. Maybe have a quick look at some dimensions online to make sure you aren't limiting yourself
Answer: Restrictions or code requirements...show and explain your plan to the local building inspector. As doable...sure, why not? You could even close in the fridge, heat shouldn't be much of an issue as some fridges are put into pantry style cabinets. If it was something you worried about you could cut a vent in the back side of the wall. If your current window opening is the right height, you would have no need for a header replacement. If your opening is wide enough and could handle 2 extra jack studs, I would install those, other wise no need. Realize that the window there is not bearing the load, the wall around it is. If you need to make the opening larger, then you would need to do some new headers and jack studs. As far as leveling the floors, add what you might need to the floor under the fridge to bring it up to the kitchen height.
Now for the ugly part....asbestos. If you plan to remove any, you need to get an abatement team. I can't tell you the cost or time involved, but I doubt it will be cheap or quick. Best bet there is not to disturb it. You could have it tested to be sure it does contain asbestos.
Several things will have to be factored into which design you go with. The biggest is the asbestos issue.
Maybe a smaller fridge? Maybe moving the fridge into the door opening and making a new door opening where the window is. Again, if you have to remove the siding to make anything work....remember the word asbestos.
Comment: In some places, homeowners are allowed to remove asbestos from their own property.  So you'd have to check with your local government, to determine if an abatement company is required.
Comment: Yup, I imagine it will be just like installing a door or large window.
Answer: Your plan is certainly doable but I hope that your renovation includes stripping the walls down to the studs as new kitchen codes require a multitude of outlets at your counter as well as dedicated circuits for microwaves, ovens, etc. In fact, before you start, you should make sure that your box will accommodate a few new breakers. You're already pretty lucky to have the breaker box so close to the kitchen!
I've just done this work and by the time you've fished and drilled all of the holes through plaster and lath needed to get those circuits in place, you'll have realized that just tearing out the old and putting in the new sheetrock would have saved you many headaches and much time. You can pretty much bet that the insulation in your exterior walls is next to useless....assuming there's insulation in there at all.
edit: Asbestos is not weapons-grade plutonium. Many regulators waive notification and disposal requirements for homeowners performing small projects on non-friable asbestos materials like floor tiles and shingles. If you have doubts as to the friability of your asbestos shingles, you can simply paint them with some old latex paint and keep your pieces as whole as possible. Find your community regulations for homeowner handling of asbestos materials; below are a few details from a  Maryland Department of the Environment information leaflet, as an example:
Why doesn't the EPA regulate the removal of asbestos from individuals' homes?
Single family housing units are not subject to the regulations.
Who can remove asbestos containing material (ACM) from a single-family residence in Maryland?
Non-friable asbestos containing material can be removed from a single-family residence by a licensed asbestos contractor, a non-licensed contractor, or the homeowner.
Who can remove my asbestos roof?
If a contractor will be cutting, abrading, sanding or grinding 5,850 square feet or more of roofing material it needs to be done by a licensed asbestos contractor.
Where can I take asbestos containing material after it has been removed?
You can dispose of non-friable ACM at landfills that accept non-friable waste.
Comment: Agree with all of those. Some and most governmental entities will allow a home owner to remove asbestos themselves, however, dumping it won't be easy. Yes, you can hide it in your garbage, but safe, legal....no. When I definitely agree with a complete year out of walls being that old. And for the outlets, my inspector allowed the dishwasher and the garbage disposal to be on the same circuit. Since the garbage disposal is a momentary use. And most of the time both are not running at the same time.

Installing a fridge inside a wall?


Unable to tell if USB drive is correct

Question: I am attempting to install ubuntu desktop on a new PC with no other operating system on it.  I have followed the directions to place the install .iso on a USB drive, and the install menu comes up correctly.  However, when I select the Install option the computer just hangs with the install menu screen still up.  The same thing happens if I attempt to try out Ubuntu.  I found instructions for verifying the contents of the USB drive, but when I select that option, the computer hangs in the same way.  I found instructions for using F6 to change install options (like noapci, etc), but when I press F6, the screen flashes briefly to black (for less than a second) and then the install menu comes back up as if nothing happened.  The same thing happens if I try the Test Memory option.  I am able to use the very last menu option to get a boot: prompt to come up, but I'm not sure what to type there.  If I just press enter, the computer hangs also.  I was able to boot from this same USB drive to the network install (mini.iso) previously and got much further into the installation, but ran into DHCP problems I have not yet solved.
Comment: An update.  I tried using the [tab] key to edit the installation options and add nomodeset, noapci and apci=off to the line.  Those options appear to make no difference.  If I remove 'splash' from the line, however I can see that the screen is now absolutely full of periods (.) scrolling on and on forever.  I have left this go for ten minutes and nothing further happens.
Comment: You might want to check the downloaded ISO for errors https://help.ubuntu.com/community/HowToMD5SUM, also, some hardware specs would have been nice.
Comment: It appears that using the USB drive previously for the network install confused the program that tried to set it up for the full install.  I am now installing off a DVD made from the same .iso and I got a completely different-looking menu. (and it seems to be working as well.)
Answer: Try using a bootable USB with persistence enabled.

A Live USB is configured to run on almost all desktops and has a great
  compatibility with various hardware. If you want to test the Linux
  distro on various computers, using a Live USB with data persistency is
  the best way to do it.- https://www.maketecheasier.com/persistent-live-usb-vs-full-install-usb/
Comment: I did not get the impression that Gabriel wants "want to test the Linux distro on various computers". How is this answer relevant to the question???
Comment: I was pointing out that persistency would provide greater hardware support, if the ISO is error free
Comment: ...and what does one has to do with the other???
Comment: If it was a hardware problem that was causing the lockups, I could see that helping.  Turns out it was the program that created the bootable USB drive didn't work a second time on the same drive and produced a bad drive from a good image.  Perhaps if I had formatted the drive, but I had explorer windows I wanted to keep open, and that would have closed them.

Unable to tell if USB drive is correct


How to send TLS syslog message via logger command

Question: I am working on ubuntu 16.04.
Is there any way to send TLS syslog message by logger command?
Answer: No.
logger can only send cleartext data to either a UDP socket, a TCP socket, or a local UNIX Domain Socket (like /dev/log, which is the default if logger isn't instructed otherwise).
But.
I assume you have rsyslog setup on a remote server (say syslog-server.mydomain) to listen on TCP port 6514 because that is the default port when using Syslog over TLS. I further assume rsyslog on that remote server is configured similar to this:
# Certificate configuration for encrypted transmission:
global(
    defaultNetstreamDriver         = "gtls"
    defaultNetstreamDriverCAFile   = "/path/to/root-ca.crt"
    defaultNetstreamDriverCertFile = "/path/to/certificates/server-certificate.crt"
    defaultNetstreamDriverKeyFile  = "/path/to/keys/server-private.key"
)

# Load input module for encrypted TCP to receive messages from the clients:
module(
    load                  = "imtcp"
    StreamDriver.Name     = "gtls"
    StreamDriver.Mode     = "1"
    StreamDriver.AuthMode = "anon"
)

# Ruleset to write externally received messages to a certain file:
ruleset(name="from_remote") {
    action(type="omfile" File="/var/log/messages-from-remote.log")
}

# Bind above ruleset to the TCP listener on port 6514:
input(type="imtcp" port="6514" ruleset="from_remote")

Usually (if the remote server wasn't setup to use Syslog over TLS) you could issue
logger --tcp --server syslog-server.mydomain --port 6514 -p local1.info "Hello World, $RANDOM"

but due to logger's inability to handle TLS this does not work. Instead you must prepare a syslog message manually and send it via gnutls-cli. Copy the server's CA file to the local machine and then issue:
echo "<142>$HOSTNAME Hello World, $RANDOM" | \
    gnutls-cli syslog-server.mydomain --port=6514 --x509cafile=/path/to/root-ca.crt

The <142> is the encoded value for local1.info, $HOSTNAME is the source host and the text Hello World, $RANDOM is the actual logmessage. gnutls-cli reads this string from its stdin and sends it to the given server and port using the given CA.
The message should appear on the remote server in the file /var/log/messages-from-remote.log.
The tool gnutls-cli is part of the package gnutls-bin which can be installed via sudo apt install gnutls-bin.

Of course you can also configure your local rsyslog to forward certain messages via TLS to the remote server and then use logger as usual, that is: have logger send the messages to the local rsyslog daemon (which is the default anyway) and then let your local rsyslog forward the encrypted message.
Comment: Of course you can use openssl s_client instead of gnutls-cli. :)
Answer: is this still the case? I was able to test Logger for my syslog over TLS just using logger TEST The difference is I have a rule set as seen below. This forwards all logs. That being said, it will forward logger Tests via TLS since its rsyslog fwd it not logger.
action(type="omfwd"
queue.type="linkedlist"
queue.filename="example_fwd"
target="192.168.0.123"
port="6514"
protocol="tcp"
StreamDriver.Name="gtls"
StreamDriver.Mode= "1"
StreamDriver.AuthMode="x509/name"
StreamDriverPermittedPeers="rsyslog.lab"

Comment: Yes, this is still unfortunately the case. What you did is sending the log entry from `logger` to your Rsyslog server via probably unix socket and then `rsyslogd` (and not `logger`) forwarded it via TLS to some other TLS-using syslog server.


Why do I need to use separate accounts for installing and running a program?

Question: I bought some software from Atlassian (JIRA, Confluence etc.) and I am installing it. One of the programs recommend me to create a user with limited access for only that program, and it also wants me to install it in /usr/local. I am new to Linux so I don't understand why I need to create such a user nor do I know how. And this user would not be able to write in these folders does it? I don't understand the benefits to make several users? I am running Ubuntu server.
Answer: Writing a new user specifically for one application is a really good idea.
If someone was able to hack through the program somehow, will not have administrator privileges (they won't be "root"), only the privileges assigned to that specific user.
You can create a new user in debian/ubuntu consoles by executing this command:
sudo adduser mynewusername

(where you change mynewusername to your liking)
You may also want to assign the user into some groups: cat /etc/group
sudo adduser mynewusername newgroup

(where you change the newgroup and mynewusername. Changes when you logout/login that specific user.)
Also, they won't be able to see other users' files (if file permissions are assigned properly). You can change file permissions using the chmod command.
Comment: How would this user be able to create a folder for the application in /usr/local and such folders, and have the rights to execute/read/write programs in it?
Comment: You can create that folder using root privileges. As a note, folders need the executable bit (+x).
Comment: Okey, I see. So should these users have home folders?


Let $f(x)=x^2+17x+a$, $g(x)=x^2-17x-a$, $r$ a root of $f$ and $-r$ a root of $g$. Determine the roots of $f$.

Question: Let $f(x)=x^2+17x+a$ and $g(x)=x^2-17x-a$. Suppose $r$ is a root of $f$ and $-r$ is a root of $g$. Determine all roots of $f$.
From the descriptions, I can conclude that $f(x)-g(x)=2a$. But that doesn't help.
Answer: Since $r$ is a root of $f$ and $-r$ is a root of $g$,
$$\begin{aligned}
0 &= r^2 + 17r + a\\
0 &= (-r)^2 - 17(-r) - a = r^2 + 17r - a
\end{aligned}$$
Combining both equations,
$$\begin{aligned}
0 &= 2r^2 + 34r
\end{aligned}$$
So
$$\begin{aligned}
0 &= 2r(r + 17)
\end{aligned}$$
which shows that $r = 0$ and $r = -17$ are possible roots of $f$.
Answer: Hints:
$$\begin{cases}r^2+17r+a=0\\r^2+17r-a=0\end{cases}\implies \begin{cases}r=0\;,\;\;or\\{}\\r=-17\end{cases}$$
Take it from here...
Answer: $$
0=f(r)=r^2+17r+a=r^2+17r-a=g(-r)=0,
$$
and thus $a=0$.
This implies that the roots of $f$ are $0$ and $-17$, while the roots of $g$ are $0$ and $17$.
Answer: You can also see this from the quadratic formula.  For $ \ f(x) \ , $
$$ x_f \ = \ \frac{-17 \ \pm \sqrt{17^2 - 4a}}{2} \ , $$
while for $ \ g(x) \ , $
$$ x_g \ = \ \frac{17 \ \pm \sqrt{17^2 + 4a}}{2} \ . $$
In order to meet the stated condition, either both discriminants must be zero, which is not possible, or they must be equal, which requires $ \ a \ $ to be zero.  That situation produces the roots $ \ 0 \ \text{and} \ -17 \ $ for $ \ f(x) \ $ and $ \ 0 \ \text{and} \ +17 \ $ for $ \ g(x) \ . $


Add Permission to Lambda Function in Swagger Spec

Question: If I export my api gateway as Swagger and then use it in the body of a cloudformation template, I have to manually add permission to lambda function once the new api gateway is created from template.

Why doesn't export as Swagger handle this for me?  Is there anything I can add to the template to programmatically allow permission?
EDIT: So I finally got around to try the Serverless Application Model (SAM) as suggested below by Bob Kinney.  EXACT same problem.  Also when I go to do my manual fix (which is select edit lambda and then save without changing), this comes up:

Is SAM supposed to work this way?
Comment: Hit the same issue as you. If you solely just use SAM (let go Swagger integration) and define the lambdas with `RestApiId: Ref: yourAPIName`, it'll set up the permission of APIGateway->Lambda for you. Quite unfortunate that Swagger integration is lacking this permission creation (and nowhere mentioning this in the integration extension AWS doc). You'll have to create `"AWS::Lambda::Permission"` resource for each lambda or create a role, ... etc; don't think it's good developer experience.
Answer: This dialog makes a call to the AWS Lambda service. Currently the Swagger import feature will not execute that call for you. You may want to look into the serverless application model (SAM) as will encapsulate this permission, among other things.


making a database in mysql without duplicate values

Question: I have a tab separated text file in the format
id | field 1 | field 2 ...

I want to insert this into a mysql database with id as the primary key but the text file may contain duplicate id's .

How to make sure that there's just one entry corresponding to each id.
How to make a choice between two lines having the same id (Yes, they might not be consistent, but it's okay to choose one over other like the first or the last occurrence )
Answer: Read line by line from text file, parse that line and use INSERT ... ON DUPLICATE KEY UPDATE Syntax.
Answer: I would do a SELECT before INSERT and count the number of rows returned by the SELECT. Something like this:
SELECT * FROM yourTable WHERE yourTable.id = :id

If that returns any row, don't insert and go to next.  Otherwise insert it.
Edit: This would be a post strategy.  It would be good if you could add a Unique Constraint to guarantee uniqueness.  Something like:
ALTER TABLE yourTable ADD CONSTRAINT ukID UNIQUE (id)

Comment: Create a table that fits your needs (don't forget to add the UNIQUE CONSTRAINT for that id field).  Then you can do either what I suggested or what @AVD suggested in order to add your file rows into the database.  What AVD suggested is more efficient since you will need just one query to insert into the DB.
Comment: it's not in any table yet, it's in a text file. You mean I should first make a database and then another one out of it?
Answer: Presuming a Unix shell, I'd do this:
awk '!x[$1]++' inputfile.tsv > uniqfile.tsv

then do your import off of the uniqfile.
edit: to be clear, that script uniq's the input file based on the first field by only outputting rows that do not already have a non-zero value in a hash keyed off of the first field.


Sorting on 4th element and keep the same key value in php

Question: I have multiple array structure as below
array (
  'Mexico' =>
  array (
    'Regular_Club' =>
    array (
      '2015-02' =>
      array (
        'cost' => 41479.8,
        'signups' => 3891,
        'share' => 16241.46,
      ),
    ),
    'Sweepstakes' =>
    array (
      '2015-02' =>
      array (
        'cost' => 1186736.04,
        'signups' => 280850,
        'share' => 468069.14,
      ),
    ),
  ),
)

I want to sort this array descending order based on the field cost. I tried uasort, multisort but no luck. Result should be below.
Result:
array (
  'Mexico' =>
  array (
   'Sweepstakes' =>
    array (
      '2015-02' =>
      array (
        'cost' => 1186736.04,
        'signups' => 280850,
        'share' => 468069.14,
      ),
    ),
    'Regular_Club' =>
    array (
      '2015-02' =>
      array (
        'cost' => 41479.8,
        'signups' => 3891,
        'share' => 16241.46,
      ),
    ),

  ),
)

Thanks in advance.
Comment: 2015-02 is not fixed value it will change according to month so can't use that name and even the name regular_club or Sweepstakes they are not fixed name. It will change for other month, other countries.
Answer: Coolect costs before and use uksort:
foreach ($inputArray as $country => $array) {
  foreach( $array as $key => $value)
    foreach ($value as $val) $weight[$key] = (int) $val['cost'];
       uksort($array, function ($k1, $k2) use ($weight) { return $weight[$k2] - $weight[$k1]; });
  $resultArray = array($country => $array);
}

var_export($resultArray);

Comment: change witn $resultArray[$country] = $array;
Comment: In the result array Mexico also not fixed name. we will have different countries so I can not collect cost using fixed name. just take maxico as country key. It can be different country also.
Comment: Its not working. its not sorting on cost ... here in example I have written only 2 elements but originally i have many ... and its not sorting accordingly. its sorting only last two elements. Other objects were not sorted.
Comment: If you check https://eval.in/370435 . I am getting the same result. its not sorting descending.
Comment: @user1648204 my bad. try now
Comment: it works perfectly for last country array. Pleases check https://eval.in/371765 output array contains only India data. And other countries are missing.


Message: Invalid argument. Google maps

Question: Trying to debug this Google maps error.
Works in all tested browsers except IE. Sometimes markers show, sometimes they won't.
http://www.ecompanies.nl/pilot/warenhuis/breda.html
Webpage error details
Message: Invalid argument.
Line: 27
Char: 56
Code: 0
URI: http://maps.gstatic.com/intl/nl_nl/mapfiles/api-3/5/6a/main.js
Comment: Are you still having a problem or has this been fixed at the site?  What version of IE?
Comment: do u solve this problem? i have same problem.
Answer: I had this problem, and for me, it turned out to be a conflict with a jquery ajax call on document.ready(). notable details:

was including this gstatic file ref'd above
was including jquery 1.6.4, in noConflict() mode
was including jquery UI 1.8.14
was executing an ajax call to populate a div (a cart widget, how many items, how much etc.), on document.ready()

to solve, i ended up with something like this:
<code>// wrap ajax call in a function, then figure out if we execute it now, or delay.
var f = function(){
  $.getJSON('/ajax_handler/', function(data){/* do stuff */});
}
// check if google code is present (not sure how robust this is)
if(window['google']){ // We've got some Google, delay ajax call by 5s.
  setTimeout(f, 5000); // this was the lowest i could safely go, unfortunately.
} else { // No Google, do the ajax call immediately
  f();
}
</code>

Message: Invalid argument. Google maps


File contents not being read in nodejs program

Question: I have a file temp.js that contains text as below:
module.config = {
  key1 : 'value1',
  key2 : 'value2',
  key3 : ['abc','def']

}

I am reading the file as below:
fs.readFile('/temp.js', function(err,fileContents) {
   console.log(fileContents);
});

on the output I am getting values as below:
<Buffer 6d 6f .....
...>

What am i missing here ?
Comment: You're reading the hex contents of the file; it's being read as a binary rather than as a text string. Easy way to tell? In ASCII, all the lowercase letter range starts with 0x61, and the uppercase range starts with 0x41.
Comment: `6d 6f` are the letters `m` and `o`. I'm guessing you want to evaluate the file as Javascript, which... really isn't what you're doing, here.
Answer: From the documentation for fs.readFile:

If no encoding is specified, then the raw buffer is returned.

Therefore, if you want a string passed to your callback, specify the encoding of the file. Example:
fs.readFile('/temp.js', {encoding: 'utf8'}, function(err, fileContents) {
   console.log(fileContents);
});

Answer: The file is being read but as Buffer. To read it as string you've to tell fs the encoding.
Try this
require('fs').readFile('/temp.js','utf-8', function(err,fileContents) {
   console.log(fileContents);
});


How to set rate limit for user specific in springboot?

Question: I have some issue with rate limit concept, I have tried to create one POC where we are blocking the no of request based on time and its working fine.
But i need to imeplement rate limit based on user to user like, In my appication differnt user can search the product parallely if i am imeplenting rate limit then its blocking for all users not for single user.
Any one can help here..
I have craeted the POC for rate limit and i can see its applicable for all users.
Lets example as below:
1.Suppose for my application i keep 5 request per minute , For 6th request it will block and give error mesage .
2.But what about for the other user,He is not searched yet and when he will try to serach he will also get the same exception
Answer: First of all your implementation sounds to point as it is doing what is expected out of rate-limiting features.
The only part in which you are falling behind in is implementing this feature on a user basis which can be done basis on an identifier upon which we can separate out every user.
In a general use case, one can have a username+sessionid as a unique identifier to implement rate limiting on the user level which will solve your issue.
You can use a database or cache to understand or keep track of current hits being done to the server and then compare it with the rate-limiting logic you have in place.
Being said that this is a very requirement-specific implementation but I hope I gave you a starting point to work upon.
Comment: Hi Suchndra,
Thanks for the valuable suggestion, Could you plz send me the sample code to implement using username+sessionid.
Comment: Sure, this is nicely explained with all the code over here https://stackoverflow.com/questions/44042412/how-to-set-rate-limit-for-each-user-in-spring-boot

This beautifully works at the IP level which is one of the user identifiers.
Please accept the answer if this helped you in your current task.
Comment: Yes i have tried this code in my application, BUt whats the problem is Imy application for all user i am getting same Ipaddress so its very difficult to identify the user to whom i need to block it.Example: Ehen i am trying to acces to access commmon server it will always give the same ipaddress to all user.
Comment: So Nihar if you go through carefully. X-Forwarded-For is like an IP of the last hop of request. by any chance your application is running behind proxy?
Comment: Yes it running based on proxy address.
Comment: Thats why its not possible based on ip adress, Because it will always create the same ipaddress for all user.
Comment: Is there any alternate way instead of Ipadress? I have already tested with Ipaddress for my case Ipadress is not the proper way to handle my scenario.
Comment: Nihar so ip address is just one unique identifier. What does your request look like? do we have any client-related info which we send along with the request or more specifically any unique header in the request?
Comment: No,I have checked that also there is no unique identifier in the request.


Best way to allow editing of a datetime value in a jeditable environment?

Question: I use Jeditable to allow editing of a table on my page. It updates a MySQL table and it all works fine.
I would like to add the ability to edit a datetime value as well. So I tried using jquery.jeditable.datepicker.js to do the job. But it works only with date values not datetime values.
$('.editTimeIn').editable('save.php', {
    type        : 'datepicker',
        datepicker: {
            dateFormat: 'yy-mm-dd',
            numberOfMonths: 2
        }
});

I need to be able to give the user the ability to pick the date and time. What recommendations do you have for this functionality?
If possible please use examples.
Comment: Have a look at [this answer](https://stackoverflow.com/questions/642136/jeditable-with-jquery-ui-datepicker#1406886) + the second comment below it.
Answer: Directly from source file of jeditable. Look at the end of the fie
  if (settings.datepicker) {
    jQuery.extend(datepicker, settings.datepicker);
  }

  input.datepicker(datepicker);

What it's actually doing is applying jquery ui datepicker to your input element.
JQuery ui Datepicker doesn't have the ability to change datetime.
Alternatively you can find another library which support this. or you can request a feature from jeditable developers on github.
I recommend you to find any other library because I doubt that developers would help you because it's been six or seven years since they worked on it. and you shouldn't use depreciated libraries.
Answer: From jeditable documentation.

(String) type: Input type to use. Default input types are text,
  textarea or select. Additional input types are provided using custom
  input type API.

So if you take a closer look in jeditable additional input types you will see that you could use

timepicker type (dependency of timepicker)

or

a time input type (perhaps this is the best way in case you need
  something quick and without any other plugin dependancy).

A simple example of time input type can be found in this fiddle
EDIT
You could also try to extend additional input types by adding datetime-local input type such as below (just a simple demo)
$.editable.addInputType('datetime', {
/* Create input element. */
element : function(settings, original) {
    // pattern is fallback for browsers not supporting datetime-local
    var datetime_local = $('<input id="datetime_" type="datetime-local" pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}" required />');
    $(this).append(datetime_local);
var hidden = $('<input type="hidden">');
$(this).append(hidden);
return(hidden);
},
submit : function(settings, original) {
    var value = $('input:#datetime_').val();
    $("input", this).val(value);
}
});

Please check the updated fiddle also to view the changes
Comment: HI #Peter Darmis this is exactly what I'm looking for. However the fiddle withe the date isn't working. The end of the edit must have a value such as 2017-12-15 09:15:00  Can you show me how to do that in the fiddle?
Comment: @KeithDKaiser if you mean that when you submitted the form the date value was undefined then check the update.
Comment: Any way to use dropdown or other method to select the date and the time (similar to what you did in the first fiddle)?
Comment: @KeithDKaiser the UI of the `datetime-local` type depends strictly to the browser as seen here for the `time` type. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/time. The only way to use `select` for both date and time would be to write an additional type in `jeditable` similar to the `time` type that would also contain date.


How can a maven build process be retrofitted to an eclipse developed plugin?

Question: The eclipse plugin development environment is a pretty handy tool when creating from scratch a set of OSGi bundles that need to work together. Particularly this is true when trying to get all the package imports and exports and other manifest fluff right during development, or if there are third party jars that need to be embedded. But trying to retrofit a maven build process around this afterwards seems to be pretty tricky, mainly because most of the maven plugins for bundling/OSGi build the manifest themselves, whereas using the PDE, you are handcrafting the manifest.
What is the best way to retrofit a maven build process to a bunde/set of bundles, that dont respect the standard maven project layout, and already have handcrafted manifests?
Answer: Use Tycho. It lacks some documentation, but it does just that: builds the plugins using the PDE semantics (actually, it uses PDE compiler internally). So, all you need is to create almost empty pom.xml's for your modules.
Comment: tycho doesnt seem to work too well out of the box, and perhaps not at all with maven-2, seen some suggestions that its really only viable with maven-3. Not even the most basic inlcusion of tycho-maven-plugin seems to work on maven 2.2.1
Comment: Yes, it works only with Maven 3. Not a big problem, I think, since Maven 3 is mostly backward compatible.


apt changelog for to-be installed packages

Question: GUI update-manager is able to show the "changelog" of packages to-be installed (not downloaded yet).
I also found out how to provide the .changelog files in the right place for update-manager to show them, and now I'm happy since I'm able to tell my clients that they can see changelogs of my custom packages directly from their gui.
Unfortunately I'm not able to find any command line tool to do the same thing and that would be more useful on servers.
From what I saw it seems that this convention (putting .changelog files directly alongside the .deb files in the apt repo) is a ubuntu specific extension.
There are some debian resources (the reprepro man page for example) which point on a different way to store changelogs online, http://packages.debian.org/changelogs
Does anybody know if there already exists a tool like apt-cache to show the changelogs from packages which are not yet installed (nor downloaded) ?
Comment: Why is this question marked as a duplicate? The question linked in the duplicate notice was asked 3 years later , and specifically asks for a solution different to this question. That one links to this question in the first line and asks for a different problem.
Answer: There is also the apt changelog command.   It, and probably aptitude as well, pull from http://changelogs.ubuntu.com, which may not have all third party changelog files, if they didn't add them to it.
$ apt changelog  unity
Get:1 Changelog for unity (http://changelogs.ubuntu.com/changelogs/pool/main/u/\
unity/unity_7.0.0daily13.06.19~13.04-0ubuntu1/changelog) [251 kB]
Fetched 251 kB in 0s (350 kB/s)
unity (7.0.0daily13.06.19~13.04-0ubuntu1) raring; urgency=low

  [ William Hua ]
  * Revert 3196 to fix menu highlighting issues with LibreOffice.
    Revision 3196 prevents LibreOffices menu items from highangelog
hlighting.
    See Launchpad bug #1153350. (LP: #1153350)

  [ Chris Townsend ]
  * Fixes issue where minimizing a full screen window would not draw the
t of
:
    lp:unity revno. 3320. (LP: #1064155)

  [ Marco Trevisan (Treviño) ]
  * SwitcherController: use proper long long types for

Comment: Excellent! I never thought that it could be possible to see the changelog from any package in Debian-like OSes :).
Comment: on older ubuntu 14, `apt-get changelog ` worked for me whereas `apt changelog ` appeared to be unimplemented
Comment: It's weird, because `apt changelog ` is undocumented, but this works on a 20.04 system.
Comment: At least with Ubuntu 18.04 LTS the `apt-get changelog` is documented (see `man apt-get`) and `apt changelog` is not documented but forwards to `apt-get changelog` successfully.
Answer: Not sure if I understood what you really need, but
aptitude changelog package-name

will show the changelog for any package in the Ubuntu repos. It doesn't work in the PPAs though.
Comment: thank you, it's seems a good initial step. All I have to do now is to find out where does aptitude fetch these changelogs. I made my repo compliant with the ubuntu update-manager and I can see the changelogs from there (but I don't see them for the PPAs). Any idea?
Comment: `strace -f aptitude changelog bash 2>&1 | grep changelog` shows that it will just show changelog for the already installed package from files `/usr/share/doc/PACKAGENAME/changelog*`.
Comment: On the other hand `strace -f apt changelog bash 2>&1 | grep changelog` shows that it will in call to `https://changelogs.ubuntu.com` to query changelog.


Use in repairing wires

Question: Can these connectors be used for a splice inside of a wall in order to fix a damaged wire? If you have a damaged wire inside a wall - not a box - will these type connectors meet code as a permanent splice to fix the wire in the wall?
Comment: What type of connectors are you talking about, pray tell?  ;-)
Comment: Hi Terry. If you ever return to this post, please update it with the information asked for. Thanks!
Answer: You don't seem to have identified the type of connector you are asking about.
There are rated and approved splice kits suitable for splicing NM cable inside the wall without a junction box.
For example, look at this one: http://www.homedepot.com/p/Tyco-Electronics-Romex-Splice-Kit-2-Wire-1-Clam-CPGI-1116377-2/202204326.
Note the strain relief on both sides of the splice, and the enclosed nature of the connection. But the real point is that it is legally approved for this use.
Comment: Uprated for showing me something new... thanks!

Use in repairing wires


Execution log not working in Suitescript 2.0 Client script

Question: I have a suitelet and i have attached client script to suitelet this way
form.clientScriptModulePath = '../Client/cancel.js';
/**
 * @NApiVersion 2.0
 * @NScriptType ClientScript
 * @NModuleScope public
 */

define(['N/log'], function(myLog) {

 return({

 fieldChanged: function(context){

         myLog.debug({
         title: 'hello!',
         details: 'world'
         });

        alert(context.line);
 }
 });
});

This is a test script, here alert is giving me the line number but log in not working. Ideally it should log to the parent suitelet. What is the reason?
Answer: Form-level Client Scripts, which is what you've made by attaching your Client Script to the Suitelet Form, do not have an Execution Log as there is no associated Script or Script Deployment record.
I recommend using the browser console and console.log to print debugging messages from your Suitelet, then removing them once the script is ready.


MSVC do not generate lib via cmake

Question: CMakeLists:
if (MSVC)
    set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
endif()
add_library(${PROJECT_NAME} SHARED ${SOURCES})

CMake 2.8.12 + MSVC 2015
config outputs:
-- The C compiler identification is MSVC 19.0.24210.0
-- The CXX compiler identification is MSVC 19.0.24210.0
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe
-- Check for working CXX compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/cl.exe -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
CMAKE_C_FLAGS_DEBUG is /D_DEBUG /MDd /Zi /Ob0 /Od /RTC1
CMAKE_C_FLAGS_RELEASE is /MD /O2 /Ob2 /D NDEBUG
CMAKE_C_FLAGS_RELWITHDEBINFO is /MD /Zi /O2 /Ob1 /D NDEBUG
CMAKE_C_FLAGS_MINSIZEREL is /MD /O1 /Ob1 /D NDEBUG
-- Configuring done
-- Generating done

Referred https://cmake.org/pipermail/cmake/2009-March/027990.html.

You most likely have not setup your classes and/or function calls to be
  exported.  If you have no exported classes/functions Visual Studio will not
  generate an import library for you.

But adding CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON got the same result.
How to make MSVC generate lib & dll like mingw?
Answer: Update cmake 2.8 to 3.4 solves the problem.
https://cmake.org/cmake/help/v3.4/release/3.4.html?highlight=windows_export_all_symbols

MSVC do not generate lib via cmake


Oven 3 Wire in Subpanel

Question: I keep looking for a situation like mine on this website and other websites, but I was unable to find one.
A 3 wire oven (two insulated hots and 1 bare twisted wire) is connected in an old main panel where the neutral and ground bus bars were bonded.  A new main panel was setup elsewhere, thus, the old main panel with the oven was converted to a subpanel and the neutral and ground bus bars were separated.
FOR NOW, should the bare twisted wire be on the isolated neutral bus bar or on the grounded bus bar? The oven is plugged into a 3 prong outlet.
I understand that an updated oven now has 4 wires: 2 hot, 1 neutral, 1 ground.  I can add in an insulated neutral wire and change the outlet at a later date when the oven is updated.
Comment: You can retrofit a ground... You *can't* retrofit a neutral.  Allow the bare wire in the old cable to continue being your neutral as ThreePhaseEel recommends... and retrofit a ground wire also. (the reason is neutrals must be *in* the same cable... but as of NEC 2014, ground wires can follow any viable path back to the same sub-panel.  **You don't want to leave it NEMA 10; it's dangerous.**
Comment: Can you post a photo of the inside of the oven receptacle's box?
Answer: For now, your bare wire's a neutral
Your oven branch circuit appears to have been run using a type SE cable -- this was common practice in the 50's as heavy gauge NM was not available at that time.  As the NEMA 10 is an ungrounded outlet with 2 hots and 1 neutral, the bare wire in your type SE cable lands to the subpanel's neutral bar.

Oven 3 Wire in Subpanel


closing p:rowexpansion that contains a h:inputText result in "WARN There should always be a submitted value for an input if it is rendered..."

Question: I have a p:datatable within a p:rowexpansion that has a p:column containg a h:inputText form to change some value in the backing bean:

    ...

                <h:inputText value="#{invoiceSummationLine.amountAsDouble}" disabled="#{backerBean.savedOK}" size="10"/>

"savedOK" is only toggled after the entire form is submitted and validated some other place.
The problem is that when I close the rowExpansion, not only does the values in the h:inputText not get remembered upon re-opening, the log also throws JSF warnings of the kind:

There should always be a submitted value for an input if it is
  rendered, its form is submitted, and it was not originally rendered
  disabled or read-only.  You cannot submit a form after disabling an
  input element via javascript.  Consider setting read-only to true
  instead or resetting the disabled value back to false prior to form
  submission.

from what I understand this has to do with some mis-matching of the disabled states on input forms, but I cannot find other explanations for how to solve this issue on rowToggle, only for generic form submissions.
Anyone?
Comment: I'd like to experiment, but can you make it into a [mcve] then(a real one)? And does it make a difference if  you **don't** use a nested datatable in a datatable? And what PF version do you use? And what JSF impl and version?
Answer: It is a bug in Prime faces. The content of the closed rowExpansion gets removed from DOM so whatever is in it is set to null (therefore your error).
If you only need to use that for inputText, you are in luck. Add:
<f:ajax render="randomInputText" event="keyup" />

The field starts working as you would expect. If you need the same for a checkbox, you are out of luck. This fix (with "change" as the event) fixes reseting the value when opening and closing the expansion, however if the expansion is closed during submit, null is set no matter what was the user input.
Comment: What PF version did you use? Tried the latests to?
Comment: I have version 6.0.
Comment: After more intensive testing I realized my workaround does not work always. In my FF on Fedora 21 it worked, unfortunately from Mac it only helps in 70 % of attempts. That makes rowExpansion pretty useless for forms that are not read-only.
Comment: I'll try this in my application, where did you put the axax - listener? Outside the rowexpansion presumably?
Comment: I used this inside the failing component (textbox). Unfortunately it only helped in FF on Fedora.  When I switched to Mac, it has 50% success rate. Anything under 100% is not acceptable for any deployment so do not bother.


android - proguard error in android studio

Question: I want to use proguard for my application ,I enabled it but when I want to generate apk file ,it gives me this error:
<code>    Information:Gradle tasks [:app:assembleRelease]
:app:preBuild UP-TO-DATE
:app:preReleaseBuild UP-TO-DATE
:app:checkReleaseManifest
:app:preDebugBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72300Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72300Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2300Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72300Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42300Library UP-TO-DATE
:app:prepareJpWasabeefRecyclerviewAnimators122Library UP-TO-DATE
:app:prepareReleaseDependencies
:app:compileReleaseAidl UP-TO-DATE
:app:compileReleaseRenderscript UP-TO-DATE
:app:generateReleaseBuildConfig UP-TO-DATE
:app:generateReleaseAssets UP-TO-DATE
:app:mergeReleaseAssets UP-TO-DATE
:app:generateReleaseResValues UP-TO-DATE
:app:generateReleaseResources UP-TO-DATE
:app:mergeReleaseResources UP-TO-DATE
:app:processReleaseManifest UP-TO-DATE
:app:processReleaseResources UP-TO-DATE
:app:generateReleaseSources UP-TO-DATE
:app:processReleaseJavaRes UP-TO-DATE
:app:compileReleaseJava UP-TO-DATE
:app:compileReleaseNdk UP-TO-DATE
:app:compileReleaseSources UP-TO-DATE
:app:lintVitalRelease
:app:proguardRelease
Note: there were 7 duplicate class definitions.
      (http://proguard.sourceforge.net/manual/troubleshooting.html#duplicateclass)
Warning:library class org.apache.http.conn.scheme.LayeredSocketFactory extends or implements program class org.apache.http.conn.scheme.SocketFactory
Warning:org.acra.ErrorReporter: can't find referenced method 'void setLatestEventInfo(android.content.Context,java.lang.CharSequence,java.lang.CharSequence,android.app.PendingIntent)' in library class android.app.Notification
Warning:library class android.webkit.WebView depends on program class android.net.http.SslCertificate
Warning:library class org.apache.http.conn.ssl.SSLSocketFactory depends on program class org.apache.http.conn.scheme.HostNameResolver
Warning:library class org.apache.http.conn.ssl.SSLSocketFactory depends on program class org.apache.http.params.HttpParams
Warning:library class org.apache.http.params.HttpConnectionParams depends on program class org.apache.http.params.HttpParams
Warning:there were 17 instances of library classes depending on program classes.
         You must avoid such dependencies, since the program classes will
         be processed, while the library classes will remain unchanged.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#dependency)
Warning:there were 1 unresolved references to library class members.
         You probably need to update the library versions.
         (http://proguard.sourceforge.net/manual/troubleshooting.html#unresolvedlibraryclassmember)
:app:proguardRelease FAILED
Error:Execution failed for task ':app:proguardRelease'.
> java.io.IOException: Please correct the above warnings first.
</code>
I'm using the latest version of sdk 23 , this is my gradle file :
<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.0'

    defaultConfig {
        applicationId "com.x.x"
        minSdkVersion 11
        targetSdkVersion 23
    }

    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile 'com.android.support:recyclerview-v7:23.0.0'
    compile files('libs/acra-4.5.0.jar')
    compile files('libs/universal-image-loader-1.8.4-with-sources.jar')
    compile files('libs/org.apache.http.legacy.jar')
    compile 'com.android.support:cardview-v7:23.0.0'
    compile 'jp.wasabeef:recyclerview-animators:1.2.2'
    compile 'com.android.support:design:23.0.0'
}
</code>
What is wrong ? where I do wrong in this code?
thanks
Comment: I'm wondering about your dependency `    compile files('libs/org.apache.http.legacy.jar')`  ... if you're using the legacy apache lib, you don't need the jar, you just need to add `useLibrary 'org.apache.http.legacy'`to your `android {}` section.
Answer: Just add this on proguard:
<code>-keep class org.apache.http.** { *; }
-dontwarn org.apache.http.**
-dontwarn android.net.**
</code>
Comment: can you please explain how this work as i have started using proguard from today
Answer: As mentioned in your logcat check http://proguard.sourceforge.net/manual/troubleshooting.html#duplicateclass
You have duplicate class definitions in your application dependencies and this is just warnings.
Now If you want to fix it then please add below code in your proguard-android.txt:
<code># To enable ProGuard in your project, edit project.properties
# to define the proguard.config property as described in that file.
#
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in ${sdk.dir}/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the ProGuard
# include property in project.properties.
#
# For more details, see
#   http://developer.android.com/guide/developing/tools/proguard.html

# Add any project specific keep options here:

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
-dontwarn com.google.code.**
-dontwarn  org.apache.**
-dontwarn  jp.wasabeef.recyclerview.**
-dontwarn  com.nostra13.universalimageloader.**
-dontwarn  org.acra.**

#wasabeef recyclerview
-keep class jp.wasabeef.recyclerview.** { *; }
-keepattributes Signature
#HTTP Legacy
-keep class org.apache.** { *; }
-keepattributes Signature
#Universal Image Loader
-keep class com.nostra13.universalimageloader.** { *; }
-keepattributes Signature
#Acra
-keep class org.acra.**  { *; }
-keepattributes Signature
#Support libraries
-keep class com.android.** { *; }
-keepattributes Signature

# Keep the annotations
-keepattributes *Annotation*

-allowaccessmodification
-keepattributes *Annotation*
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
-repackageclasses ''

-dontnote com.android.vending.licensing.ILicensingService

# Explicitly preserve all serialization members. The Serializable interface
# is only a marker interface, so it wouldn't save them.
-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

# Preserve all native method names and the names of their classes.
-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembernames class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

# Preserve static fields of inner classes of R classes that might be accessed
# through introspection.
-keepclassmembers class **.R$* {
  public static <fields>;
}

# Preserve the special static methods that are required in all enumeration classes.
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep public class * {
    public protected *;
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}
</code>
Note : proguard-android.txt location -> android-sdk-path\tools\proguard
Thanks.!!
Comment: Wow, that's a giant proguard file..  which do you think are the important bits related to the question?


How delete all files in a folder except last 5 items with Python

Question: I am looking for a way how to clean a folder from files, except last newest five items with Python.
I am quite new to Python, so I was able to keep the last one only with max() function, but I am not able to find out how to keep 5 last files.
Does anyone have similar issue?
Thank you for any idea.
Answer: User os.listdir to get the name of the files. As this returns an iterator you can easily sort the way you want in python itself. then use list indexing to keep the last five ones.
then use os.remove to remove the files
import os
for filename in sorted(os.listdir("foldername"))[:-5]:
    filename_relPath = os.path.join("foldername",filename)
    os.remove(filename_relPath)

Comment: I want to sort filenames based on last modification time instead of filename sorting alphabetical. I think it sorts as per filename alphabetically and not recent one. Please suggest as per last modification time and keeping recent 5 in python 2.7
Answer: At Python standard library level, os.scandir retrieves both the file name and its attributes. It is then easy to sort the files according to their modification time:
filenames = [entry.name for entry in sorted(os.scandir(path),
                                            key=lambda x: x.stat().st_mtime, reverse=True)]

Will return a list of all filenames in path folder sorted from newest to oldest. You can then iterate on filenames[5:] to remove all the files except the 5 newest ones.
Comment: I want to delete further files with .log extension
Comment: What is entry. Name
Comment: how to delete files with a particular pattern, say *.log?
Answer: you can try with this if you are on linux:
import os

directory = /path/to/directory

os.system("cd " + directory + " ls -t1 | tail -n +5 | xargs rm -r")

you can try with this if you are on windows:
import os

directory = /path/to/directory

os.system('for /r "skip=5 delims=" %%a in ("dir ' + directory + ' ") do echo del /f "%%a"')

or just run this on cmd:
for /r "skip=5 delims=" %%a in ('dir /path/to/folder') do echo del /f "%%a"

Comment: I am unfortunately on Windows
Comment: how about `head -4` instead of `tail -n +5` ?


NULL check in WHEN statement is not working in SQL Server

Question: I expect 'No Conversion' should be printed for the below code but instead receiving the following error 'Error converting data type varchar to numeric.'
When the TRY_PARSE inside the WHEN statement returns null then the THEN block should execute?
DECLARE @VALUE varchar(20) = 'NA'

SELECT
    CASE
       WHEN TRY_PARSE(@VALUE AS DECIMAL) IS NULL
          THEN 'No Conversion'
          ELSE (CONVERT(DECIMAL(10, 3), @VALUE, 0))
    END

Comment: It's not the `NULL` check that's failing, it's that you're truly Ng to return either a `varchar` or `decimal` in the same expression. You can't do that, as an expression can only return one data type.
Answer: All branches of a CASE expression need to have the same type.  Given that the error message is text, you should also be including the cast decimal value as text, something like this:
SELECT CASE WHEN TRY_PARSE(@VALUE AS DECIMAL) IS NULL
            THEN 'No Conversion'
            ELSE CONVERT(varchar(max), CONVERT(decimal(10,3), @VALUE, 0)) END


Using $http callback inside AngularJS service

Question: I have a simple Angular service that uses $http to make a call to an API.
app.service("MyService", function($http){

  this.api = function(obj){

    return $http.post("/some-route", obj).success(function(data){

      //process data in various ways here

      var returnObj = {
        complete: true,
        data: data
      };

      return returnObj;

    });

  }

});

In the $http callback, I process the data before returning it. When I call this service in my controller, I want to get that processed data.
The following only gives me the unprocessed data:
MyService.api(someObj).success(function(data){
  console.log(data);
});

How do I get the processed data from the callback?
Comment: Have you passed this "obj" to the api
Comment: Can't chain multiple `success`. You can chain `then()`  or pass a callback as argument and call that within the success
Comment: @user sorry typo, yes I've passed the object.
Answer: I have tested up your code in a plunker, and guess what? Its working for me. Can you please confirm it, or send me more info, i'm glad if i could help.
Plunker
var app = angular.module('plunker', []);

app.service("MyService", function($http){

  this.api = function(obj){

    return $http.post("http://jsonplaceholder.typicode.com/posts", obj).success(function(data){

      //process data in various ways here
      console.log(data);
      var returnObj = {
        complete: true,
        data: data
      };

      return returnObj;

    });

  }

});

app.controller('MainCtrl', function($scope,MyService) {
  $scope.data = 'World';
  MyService.api({oi: true}).success(function(data){
    $scope.data = data
  });
});

Update:
I have misunderstood your question. You want to process the data in the callback to manipulate it in your action. Your code dont work because success() actually returns a promise, but it dont change it, it returns the original one. The one to go for is the then(), which is chainable and returns the modified version of the promise.
 I've made changes to the plunker to reflect my new vision of the scenario. Here is the new code.
Thanks for your time.
var app = angular.module('plunker', []);

app.service("MyService", function($http){

  this.api = function(obj){

    return $http.post("http://jsonplaceholder.typicode.com/posts", obj).then(function(data){

      //process data in various ways here
      console.log(data);
      var returnObj = {
        complete: true,
        data: data
      };

      return returnObj;

    });

  }

});

app.controller('MainCtrl', function($scope,MyService) {
  $scope.data = 'World';
  MyService.api({oi: true}).then(function(data){
    $scope.data = data
  });
});

New Plunker
Comment: Im am sorry to not understand your question right. I'm baking another answer right now and will update it soon.
Comment: I don't think this works at all. The `returnObj` should be the data going back to the controller. This doesn't happen in your example.
Comment: Thanks, this is correct now but unfortunately user3906922 got there before you.
Answer: The success function does not create a new promise, so your controller success callback is registered to the same promise as the service (the original one).
Instead you can use then, so it will create a new promise which will be resolved with your returnObj object:
// service
return $http.post("/some-route", obj).then(function(data){

// controller
myService.api().then(function(data) {

Comment: Works a treat! Thanks very much


How do you set your Default Bittorrent Application?

Question: Additional details are:
OS = 12.10
Present Default Torrent Application = qBittorrent
Preferred Default Torrent Application = Vuze
My main area in of which I'm looking for advise is magnet links. Plus the program in question isn't 'installed' per say I have downloaded the tarball file for Vuze and I run the executable file from there to run it.
Comment: possible duplicate of [How to set default program?](http://askubuntu.com/questions/90214/how-to-set-default-program)
Comment: Nope, that question is regarding things that are simple to set defaults for, this is for torrents, specifically magnet links.
Answer: I had the same problem and found a solution:
In escence you have to make sure your apps's .desktop file on:
/usr/share/applications

has this line:
MimeType=application/x-bittorrent;application/x-torrent;

and then add/edit this line on /usr/share/applications/defaults.list:
x-scheme-handler/magnet={$MYAPP}.desktop;

setting the correct app name of course.
Hope this can help.
Answer: Let me explain this again in my own words
Firstly we need to check that your program's ".desktop file" (in /usr/share/applications) has this line:
MimeType=application/x-bittorrent;application/x-torrent;

To check, open the text editor (called gedit) and hit "open" up to the left, then navigate to your program's .desktop file. As stated; you should find it in the folder /usr/share/applications. After you open it, search for "MimeType" (by pressing Ctrl+f and typing "MimeType" in the box that shows up).
...If you did find that it has this line then proceed. (if not then just paste the line wherever in between the lines. Or if you find the line incomplete then you can modify the existing line.) Close gedit.

Now that we've done the checking; open the file /usr/share/applications/defaults.list (the same way you opened the .desktop file). Search for "x-scheme-handler/magnet" (same way also). If you found it, make it look like this;
x-scheme-handler/magnet=YOURPROGRAM.desktop;

Replace YOURPROGRAM by the program you want to set default. The name must exactly match the name of your program's .desktop file.
example: x-scheme-handler/magnet=kde4-ktorrent.desktop;
And you're done!
Thanks to Adrian Matteo for the source.
Comment: that was awesome. thank you +1 :)
Comment: This has no effect for me. Using Linux Mint 17.1, based on Ubuntu 14.04. Perhaps one has to restart for it to take effect.

I was able to change the default by simply clicking the "select program" and choosing my program in `/usr/bin/`.
Comment: Thanks for an example.
Answer: Right click on the .torrent file > Properties > Open With (select Vuze), "set as default" and you're done.
You can always uninstall qbittorrent as well.
Comment: What about magnet files? I'd like to keep qBittorrent so I have a choice. Plus Vuze I don't have 'Installed' per say. I downloaded the tarball extracted the files and use the executable file to run the program.
Answer: Within Ubuntu 18.xx, if you want to set e.g. Transmission to open magnet links by default, you can go with this within terminal:
gio mime x-scheme-handler/magnet transmission-gtk.desktop

Next time you'll be opening magnet links in any browser, set the browser to remember the action for xdg-open and transmission will open automatically.
Answer: Add the following line to ~/.local/share/applications/mimeapps.list
x-scheme-handler/magnet=vuze.desktop

Or
If you are using Firefox go to Edit > Preferences > Applications change default application for magnet to vuze.


locationchangestart prevention in ngDialog

Question: I have used locationchangestart to prevent dialog close on clicking backspace key. It is working commonly for all dialogs. So it won't work for path change while closing the dialog. How can I restrict this? I need to change the $location.path when I close the dialog. Please suggest.
Answer: If your model is like
$scope.closeLoginModal = function () {
        $location.path("/myhome");
        });
          };


Generate asciidoctor doc with spring rest docs using maven (not gradle)

Question: With gradle to generate asciidoctor documentation you need to gradle asciidoctor in comand line and the documentation is generated by this task.
With maven I can generate the asciidoctor documentation with mvn package. But this packages all the project. Is there a way to use mvn just to generate the documentation without package all the project?
Answer: See Introduction to the Build Lifecycle. Usually in Maven the documentation generation/packaging is bound to the site lifecycle, that means it will be created when running mvn site.
Here is an example with Javadoc how to bind a plugin to the site phase:
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-javadoc-plugin</artifactId>
      <phase>site</phase>
      <goals>
        <goal>jar</goal>
      </goals>
      <configuration>
      ...
      </configuration>
    </plugin>
  </plugins>
</build>

You can also directly use the asciidoctor-maven-plugin:
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.4</version>
            <dependencies>
                <dependency>
                    <groupId>org.asciidoctor</groupId>
                    <artifactId>asciidoctor-maven-plugin</artifactId>
                    <version>{release-version}</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

(taken from the asciidoctor documentation)