Categories
askquestion

range for integer values of chars in c++

range for integer values of chars in c++

Ask Question

Asked
11 years, 3 months ago

Active
7 years, 7 months ago

Viewed
5k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

13

1

I’m reading The C++ Programming Language and in it Stroustrup states that the int value of a char can range from 0 to 255 or -127 to 127, depending on implementation. Is this correct? It seems like it should be from -128 to 127. If not, why are their only 255 possible values in the second implementation possibility, not 256.

c++ language-implementation language-details

share|improve this question

asked Nov 4 ’08 at 20:47

108108

1,50333 gold badges1818 silver badges2525 bronze badges

do you have any idea as to why the range of integer is from -128 to 127 and not -127 to 128??

– user1437027
Jul 7 ’12 at 13:37

add a comment
 | 

5 Answers
5

active

oldest

votes

16

You’re stuck in two’s complement thinking – The C++ standard does not define the representation used for negative numbers!

If your computer (god forbid) uses ones’s complement to represent negative numbers, you have a range of -127 to + 127 in an 8-bit byte. On the upside, you have two different possible representations for zero…

However, in the real world, you’re unlikely to meet a one’s complement computer.

share|improve this answer

edited May 23 ’17 at 12:00

Community♦

111 silver badge

answered Nov 4 ’08 at 20:52

RoddyRoddy

60.2k3535 gold badges151151 silver badges255255 bronze badges

add a comment
 | 

4

It’s wrong to think that an unsigned char ranges from 0 to 255. that’s only its minimal range. a char must have at least 8 bits, and signed char, unsigned char and char itself can have indeed more that just 8 bits. so then that means that unsigned char could go beyond 255. though admittedly, i haven’t got an implementation where it had more than 8 bits, it theoretically is possible. that’s specified in the c89 standard (on which c++03 bases), documenting file limits.h (CHAR_BIT, UCHAR_MAX, CHAR_MAX).

share|improve this answer

answered Nov 5 ’08 at 0:38

Johannes Schaub – litbJohannes Schaub – litb

439k107107 gold badges811811 silver badges11281128 bronze badges

This is true. I’ve worked with embedded DSP processors where char, short, int, and long are all 32 bits.

– ChrisN
Nov 5 ’08 at 10:01

add a comment
 | 

1

Character types in C and C++

From reading that it seems it can be any of those, depending on implementation.

share|improve this answer

answered Nov 4 ’08 at 21:06

Esteban BrenesEsteban Brenes

1,13311 gold badge1414 silver badges1919 bronze badges

add a comment
 | 

1

Because the standard doesn’t say anything about the char type, “char” can be:

“unsigned char” (0-255) on some compilers (example: TexasInstruments compiler for their ARM processors – OMAP series)
“signed char” (-128-127) on most compilers (gcc, MSVC …)

To make sure you always have a well defined range you should use “signed char” or “unsigned char”.

share|improve this answer

answered Nov 5 ’08 at 19:57

INSINS

9,23044 gold badges4949 silver badges8484 bronze badges

add a comment
 | 

0

Thanks Roddy and Esteban Brenes for the helpful replies.

This is my current understanding:

There are three possibilities. If the values are represented as unsigned, a char will range from 0 to 255. If the values are represented as signed in two’s complement, a char will range from -128 to 127. Finally, if the values are represented as signed in one’s complement, a char will range from -127 to 127. This final possibility suggests that there would only be 255 possible values in contrast to the 256 possible values for the first two implementations, but this fails to take into account the negative zero in one’s complement representations.

share|improve this answer

edited Nov 4 ’08 at 22:55

answered Nov 4 ’08 at 22:49

108108

1,50333 gold badges1818 silver badges2525 bronze badges

Almost: unsigned goes from 0 to 255 not 256. I’ve never worked on a 1’s complement machine so exactly how +0 and -0 work is a guess. I’d expect from a C perspective you could never tell the difference

– Roddy
Nov 4 ’08 at 22:52

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged c++ language-implementation language-details or ask your own question.

Blog

How Shapeways’ software enables 3D printing at scale

The Overflow #10: The 500-mile email

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Linked

6

Why is the range of signed char -127 to 127 in C++11?

1

What is the range of a char variable ? -127 to 127 or 0 to 255?

28

Is one’s complement a real-world issue, or just a historical one?

Related

3176What are the differences between a pointer variable and a reference variable in C++?31Why is a char and a bool the same size in c++?1766How can I profile C++ code running on Linux?4245The Definitive C++ Book Guide and List1554What is the effect of extern “C” in C++?8711What is the “–>” operator in C++?853Why should C++ programmers minimize use of ‘new’?1612Image Processing: Algorithm Improvement for ‘Coca-Cola Can’ Recognition1394Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Hot Network Questions

Print this maximally long URL

Are there any planets or moons denser than Earth?

How can I make the detail of this map stand out better?

Two year old son sometimes using female verb endings – grammar issue?

Different behavior inside self-contained macro

What will happen if someone/a group can’t be confirmed that they commited a crime?

Dealing with unwanted “Joking” physical contact

Why is it so difficult to collect Iowa caucus results as opposed to election results?

How did the Sega CD decompress video?

Is there an online list of Perakim of Mishnayos arranged alphabetically?

Why does US still require the President a fairly high age (35) in order to be able to serve?

What are the requirements for receiving the Presidential Medal of Freedom?

Did Sauron have the military power to control all Middle-earth?

Proper use of a coma in a criminal sentence

what is the best ingredient to add to a normal french toast recipe to make it taste pumpkin flavored

How to show a “Yes” for a negative occurrence and “No” for a positive occurrence

Select all the last vertices of every branch

Why is aluminium body considered better than magnesium?

Does gravity increase the closer to the core you get?

We can ignore the wire resistance if the current delivered by the wire is low?

Grand-canonical Gibbs measure for continuous systems

Why did the Amstrad CPC use a nonlinear screen memory layout?

What is a “standard orbit” in Star Trek?

Why is 2019-nCoV prioritized over other infectious diseases?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cpp

Categories
askquestion

Java.util.Calendar – milliseconds since Jan 1, 1970

Java.util.Calendar – milliseconds since Jan 1, 1970

Ask Question

Asked
11 years, 3 months ago

Active
4 months ago

Viewed
38k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

8

2

Program followed by output. Someone please explain to me why 10,000,000 milliseconds from Jan 1, 1970 is November 31, 1969. Well, someone please explain what’s wrong with my assumption that the first test should produce a time 10,000,000 milliseconds from Jan 1, 1970. Numbers smaller than 10,000,000 produce the same result.

public static void main(String[] args) {

String x = “10000000”;
long l = new Long(x).longValue();
System.out.println(“Long value: ” + l);

Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println(“Calendar time in Millis: ” + c.getTimeInMillis());

String origDate = c.get(Calendar.YEAR) + “-” + c.get(Calendar.MONTH) + “-” + c.get(Calendar.DAY_OF_MONTH);
System.out.println(“Date in YYYY-MM-DD format: ” + origDate);

x = “1000000000000”;
l = new Long(x).longValue();
System.out.println(“nLong value: ” + l);

c.setTimeInMillis(l);
System.out.println(“Calendar time in Millis: ” + c.getTimeInMillis());

origDate = c.get(Calendar.YEAR) + “-” + c.get(Calendar.MONTH) + “-” + c.get(Calendar.DAY_OF_MONTH);
System.out.println(“Date in YYYY-MM-DD format: ” + origDate);
}

Long value: 10000000

Calendar time in Millis: 10000000

Date in YYYY-MM-DD format: 1969-11-31

Long value: 1000000000000

Calendar time in Millis: 1000000000000

Date in YYYY-MM-DD format: 2001-8-8

java calendar

share|improve this question

edited Nov 4 ’08 at 20:58

Chris Jester-Young

194k4141 gold badges356356 silver badges406406 bronze badges

asked Nov 4 ’08 at 20:48

Nathan SpearsNathan Spears

1,64577 gold badges2323 silver badges3030 bronze badges

add a comment
 | 

6 Answers
6

active

oldest

votes

12

The dates you print from Calendar are local to your timezone, whereas the epoch is defined to be midnight of 1970-01-01 in UTC. So if you live in a timezone west of UTC, then your date will show up as 1969-12-31, even though (in UTC) it’s still 1970-01-01.

share|improve this answer

answered Nov 4 ’08 at 21:03

Chris Jester-YoungChris Jester-Young

194k4141 gold badges356356 silver badges406406 bronze badges

add a comment
 | 

6

First, c.get(Calendar.MONTH) returns 0 for Jan, 1 for Feb, etc.

Second, use DateFormat to output dates.

Third, your problems are a great example of how awkward Java’s Date API is. Use Joda Time API if you can. It will make your life somewhat easier.

Here’s a better example of your code, which indicates the timezone:

public static void main(String[] args) {

final DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);

long l = 10000000L;
System.out.println(“Long value: ” + l);
Calendar c = new GregorianCalendar();
c.setTimeInMillis(l);
System.out.println(“Date: ” + dateFormat.format(c.getTime()));

l = 1000000000000L;
System.out.println(“nLong value: ” + l);
c.setTimeInMillis(l);
System.out.println(“Date: ” + dateFormat.format(c.getTime()));
}

share|improve this answer

edited Sep 12 ’19 at 14:45

deHaar

6,24099 gold badges2727 silver badges3131 bronze badges

answered Nov 4 ’08 at 21:05

Steve McLeodSteve McLeod

46.4k4040 gold badges116116 silver badges168168 bronze badges

Very helpful; you answered my question a bit indirectly. The time zone thing was causing me the most confusion. The improved code is greatly appreciated.

– Nathan Spears
Nov 5 ’08 at 0:42

add a comment
 | 

5

Calendar#setTimeInMillis() sets the calendar’s time to the number of milliseconds after Jan 1, 1970 GMT.

Calendar#get() returns the requested field adjusted for the calendar’s timezone which, by default, is your machine’s local timezone.

This should work as you expect if you specify “GMT” timezone when you construct the calendar:

Calendar c = new GregorianCalendar(TimeZone.getTimeZone(“GMT”));

share|improve this answer

answered Nov 4 ’08 at 21:18

MikeMike

1,4391010 silver badges1111 bronze badges

add a comment
 | 

3

Sadly, java.util.Date and java.util.Calendar were poorly designed leading to this sort of confusion.

share|improve this answer

answered Nov 5 ’08 at 0:25

Julien ChastangJulien Chastang

16.1k1111 gold badges5757 silver badges8888 bronze badges

add a comment
 | 

1

Your timezone is most likely lagging behind GMT (e.g., GMT-5), therefore 10,000,000ms from epoch is December 31 1969 in your timezone, but since months are zero-based in java.util.Calendar your Calendar-to-text conversion is flawed and you get 1969-11-31 instead of the expected 1969-12-31.

share|improve this answer

edited Sep 12 ’19 at 14:45

deHaar

6,24099 gold badges2727 silver badges3131 bronze badges

answered Nov 5 ’08 at 0:16

AlexanderAlexander

7,94622 gold badges2020 silver badges2121 bronze badges

add a comment
 | 

0

You can figure out yourself if you change your first c.setTimeInMillis(l); in c.clear();

share|improve this answer

answered Nov 4 ’08 at 21:02

DavideDavide

14.5k1010 gold badges4040 silver badges6262 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged java calendar or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

An account of my meeting with the Stack Overflow management team

Did Stack Exchange cut the number of negative comments nearly in half between…

Linked

14

Java time since the epoch

0

Android inconsistency when dates are stored as longs and the time zone is changed

Related

1About GregorianCalendar : the same input but different output in java67Convert Date/Time for given Timezone – java1Millisecond time difference from Calendar too big212I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?2Is it safe to rely on milliseconds when calculating dates?0trying to fix a dereferencing error in java15How to check if a certain date is passed1How to set Calendar object to current date but time from SimpleDateFormat that contains HH:mm:ss0Getting milliseconds from JSpinner in Java Swing

Hot Network Questions

Why do baud rates need to be same in asynchronous communication?

While abroad 2 bank cards suddenly has stopped working. They worked yesterday, in the same country

What does a strength check of 24 actually mean?

OLS as approximation for non-linear function

Why were the Space Shuttle’s main engines placed on the orbiter?

Is there an online list of Perakim of Mishnayos arranged alphabetically?

Did Hitler ever tell a joke?

How to avoid comments about one line of code for cleanliness

Is PCA always recommended?

What happens if I lose a match due to time in a single-elimination game, but I have a Platinum Angel on the battlefield?

How to deal with a promotion if you are not sure you want it?

Cue Ball Moving on a Train Problem

Why is 2019-nCoV prioritized over other infectious diseases?

Perform a Caesar Cipher Shift on a given string

If police come to my house with a warrant for my arrest, can they break in?

We can ignore the wire resistance if the current delivered by the wire is low?

Why does Haku send Chihiro to Kamaji the boilerman to ask for a job instead of Yubaba?

Why is aluminium body considered better than magnesium?

Does gravity increase the closer to the core you get?

How to show a “Yes” for a negative occurrence and “No” for a positive occurrence

Does a non-creature God entering the battlefield trigger Pelt Collector?

What is this large engine doing on a B52?

Mountain range numbers

Can open-source software be peer-reviewed and published?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-java

Categories
askquestion

Showing too much ‘skin’ detection in software

Showing too much ‘skin’ detection in software

Ask Question

Asked
11 years, 3 months ago

Active
1 year, 3 months ago

Viewed
5k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

31

17

I am building an ASP.NET web site where the users may upload photos of themselves. There could be thousands of photos uploaded every day. One thing my boss has asked a few time is if there is any way we could detect if any of the photos are showing too much ‘skin’ and automatically move flag these as ‘Adults Only’ before the editors make the final decision.

asp.net image-processing

share|improve this question

edited Feb 17 ’09 at 18:44

George Stocker

52.5k2929 gold badges160160 silver badges225225 bronze badges

asked Nov 4 ’08 at 20:48

CraigCraig

33.1k3232 gold badges104104 silver badges187187 bronze badges

9

I can’t really answer, but I just want to point out that those automatic detectors are really good at identifying bald people as nude.

– Michael Stum♦
Nov 4 ’08 at 20:54

2

lol, there has to be a use for that somewhere!

– Andrew Bullock
Nov 4 ’08 at 21:59

add a comment
 | 

14 Answers
14

active

oldest

votes

37

Your best bet is to deal with the image in the HSV colour space (see here for rgb – hsv conversion). The colour of skin is pretty much the same between all races, its just the saturation that changes. By dealing with the image in HSV you can simply search for the colour of skin.

You might do this by simply counting the number of pixel within a colour range, or you could perform region growing around pixel to calculate the size of the areas the colour.

Edit: for dealing with grainy images, you might want to perform a median filter on the image first, and then reduce the number of colours to segment the image first, you will have to play around with the settings on a large set of pre-classifed (adult or not) images and see how the values behave to get a satisfactory level of detection.

EDIT: Heres some code that should do a simple count (not tested it, its a quick mashup of some code from here and rgb to hsl here)

Bitmap b = new Bitmap(_image);
BitmapData bData = b.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, b.PixelFormat);
byte bitsPerPixel = GetBitsPerPixel(bData.PixelFormat);
byte* scan0 = (byte*)bData.Scan0.ToPointer();

int count;

for (int i = 0; i < bData.Height; ++i)
{
for (int j = 0; j < bData.Width; ++j)
{
byte* data = scan0 + i * bData.Stride + j * bitsPerPixel / 8;

byte r = data[2];
byte g = data[1];
byte b = data[0];

byte max = (byte)Math.Max(r, Math.Max(g, b));
byte min = (byte)Math.Min(r, Math.Min(g, b));

int h;

if(max == min)
h = 0;
else if(r > g && r > b)
h = (60 * ((g – b) / (max – min))) % 360;
else if (g > r && g > b)
h = 60 * ((b – r)/max – min) + 120;
else if (b > r && b > g)
h = 60 * ((r – g) / max – min) + 240;

if(h > _lowerThresh && h < _upperThresh)
count++;
}
}
b.UnlockBits(bData);

share|improve this answer

edited Nov 7 ’08 at 9:52

answered Nov 4 ’08 at 21:22

Andrew BullockAndrew Bullock

32.2k3232 gold badges139139 silver badges211211 bronze badges

2

Very important, of course, would be to make sure the editors are quick to review suspect images, because you’re probably going to get lots of false positives.

– Kip
Nov 6 ’08 at 14:18

add a comment
 | 

34

Of course, this will fail for the first user who posts a close-up of someone’s face (or hand, or foot, or whatnot). Ultimately, all these forms of automated censorship will fail until there’s a real paradigm-shift in the way computers do object recognition.

I’m not saying that you shouldn’t attempt it nontheless; but I want to point to these problems. Do not expect a perfect (or even good) solution. It doesn’t exist.

share|improve this answer

answered Nov 4 ’08 at 21:46

Konrad RudolphKonrad Rudolph

438k109109 gold badges838838 silver badges10791079 bronze badges

Most probably a good compromise is to implement a high-sensitivity people detector, so that only absolutely-not-porn is accepted by the computer, and everything else (hopefully a much smaller fraction of the total) should be reviewed by a human classifier.

– heltonbiker
Dec 13 ’12 at 16:08

@heltonbiker And then you get PR disasters like Facebook who recently blocked images of people that looked naked even though they weren’t (mind you, Facebook uses human moderators rather than a software solution). And besides bad PR, this simply smacks of censorship. Each their own but if I were required to implement a similar solution that favours false positives rather than false negatives this might be grounds for resignation.

– Konrad Rudolph
Dec 13 ’12 at 16:38

add a comment
 | 

21

I doubt that there exists any off-the-shelf software that can determine if the user uploads a naughty picture. Your best bet is to let users flag images as ‘Adults Only’ with a button next to the picture. (Clarification: I mean users other than the one who uploaded the picture–similar to how posts can be marked offensive here on StackOverflow.)

Also, consider this review of an attempt to do the same thing in a dedicated product: http://www.dansdata.com/pornsweeper.htm.

Link stolen from today’s StackOverflow podcast, of course :).

share|improve this answer

edited Nov 6 ’08 at 17:29

answered Nov 4 ’08 at 20:53

JSBձոգչJSBձոգչ

37.1k1313 gold badges9393 silver badges149149 bronze badges

1

Do you really trust users of a site to check the ‘evil bit’ when they up load an image that is questionable?

– Peter M
Nov 4 ’08 at 20:58

I think he means that other users will flag it as offensive / adult only. (And a copy will be sent to me =D)

– StingyJack
Nov 4 ’08 at 20:59

@StingyJack or implement a list of users to send it all =)

– Seiti
Nov 4 ’08 at 22:03

1

There is an off the shelf free software for that, here github.com/EugenCepoi/nsfw_api 🙂

– eugen
Oct 14 ’18 at 6:34

@eugen This answer is almost 10 years old, and i suspect that the explosion of ML in the meantime means that this is now a much more feasible proposition!

– JSBձոգչ
Oct 16 ’18 at 7:58

add a comment
 | 

15

We can’t even write filters that detect dirty words accurately in blog posts, and your boss is asking for a porno detector? CLBUTTIC!

share|improve this answer

answered Nov 4 ’08 at 20:54

Tim HowlandTim Howland

7,45833 gold badges2424 silver badges4545 bronze badges

I know it’s not easy but I am sure large dating sites such as match.com use some kind of detection. And there will be a second level human editors to check for false positives.

– Craig
Nov 4 ’08 at 21:01

It’s all good until they try automatically drawing clothes on the pics; which is what screws most people up.

– NotMe
Nov 4 ’08 at 21:33

I think you are buttuming that the same algorithm is used for pictures and words. People like you should be buttbuttinated (which strangely sounds worse than the the original word, reminds me of the death by bongo-bongo joke:-)).

– Tim Ring
Nov 10 ’08 at 9:32

add a comment
 | 

11

I would say your answer lies in crowdsourcing the task. This almost always works and tends to scale very well.

It doesn’t have to involve making some users into “admins” and coming up with different permissions – it can be as simple as to enable an “inappropriate” link near each image and keeping a count.

share|improve this answer

edited Nov 8 ’08 at 21:08

answered Nov 4 ’08 at 21:32

connyconny

8,64166 gold badges3434 silver badges4141 bronze badges

We will go down that route as well I think.

– Craig
Nov 4 ’08 at 21:40

Or outsource it to Mechanical Turk

– John Sheehan
Nov 6 ’08 at 5:36

There’s a userfriendly cartoon on this: ars.userfriendly.org/cartoons/?id=20081210

– ConcernedOfTunbridgeWells
Dec 24 ’08 at 17:19

add a comment
 | 

6

See the seminal paper “Finding Naked People” by Fleck/Forsyth published in ECCV. (Advanced).

http://www.cs.hmc.edu/~fleck/naked.html

share|improve this answer

answered Feb 17 ’09 at 18:34

gravecagraveca

66477 silver badges66 bronze badges

add a comment
 | 

5

Interesting question from a theoretical / algorithmic standppoint. One approach to the problem would be to flag images that contain large skin-colored regions (as explained by Trull).

However, the amount of skin shown is not a determinant of an offesive image, it’s rather the location of the skin shown. Perhaps you can use face detection (search for algorithms) to refine the results — determine how large the skin regions are relative to the face, and if they belong to the face (perhaps how far below it they are).

share|improve this answer

answered Nov 4 ’08 at 21:36

dbkkdbkk

11.4k1212 gold badges4949 silver badges5757 bronze badges

Very good suggestion. It’s easy enough to actually implement and would probably work pretty good.

– Hannes Ovrén
Nov 15 ’08 at 13:42

add a comment
 | 

3

I know either Flickr or Picasa has implemented this. I believe the routine was called FleshFinder.

A tip on the architecture of doing this:

Run this as a windows service separate from the ASP.NET Pipeline, instead of analyzing images in real time, create a queue of new images that are uploaded for the service to work through.

You can use the normal System.Drawing stuff if you want, but if you really need to process a lot of images, it would be better to use native code and a high performance graphics library and P/invoke the routine from your service.

As resources are available, process images in the background and flag ones that are suspicious for editors review, this should prune down the number of images to review significantly, while not annoying people who upload pictures of skin colored houses.

share|improve this answer

answered Nov 4 ’08 at 21:42

FlySwatFlySwat

148k6565 gold badges236236 silver badges304304 bronze badges

add a comment
 | 

3

I would approach the problem from a statistical standpoint. Get a bunch of pictures that you consider safe, and a bunch that you don’t (that will make for a fun day of research), and see what they have in common. Analyze them all for color range and saturation to see if you can pick out characteristics that all of the naughty photos, and few of the safe ones have.

share|improve this answer

answered Nov 4 ’08 at 21:46

Bill the LizardBill the Lizard

345k164164 gold badges521521 silver badges812812 bronze badges

This is an interesting point. I have heard people from Google say before that given enough data anything can be solved using statistics. Algorithms are not alway required. For example the spell check on Google.com is statistics driven not a spell check algorithm.

– Craig
Nov 4 ’08 at 21:54

This is kind of what i was getting at, just from the other approach. This is probably the starting point for what i suggested. Do a load of analysis first to give you some starting off points for the suggested thresholds in your detector.

– Andrew Bullock
Nov 4 ’08 at 22:27

Im actually quite interested in this, if you can send me a farly decent sized set of test images, I’d have a play for you – you can happily have the code, i might sourceforge it as a library if its any good

– Andrew Bullock
Nov 4 ’08 at 22:28

1

@Trull: You could probably sift through SO gravatars for images that are in the safe category. The internet is full of test image in the “naughty” category. 🙂

– Bill the Lizard
Nov 5 ’08 at 14:59

add a comment
 | 

1

Perhaps the Porn Breath Test would be helpful – as reported on Slashdot.

share|improve this answer

answered Nov 4 ’08 at 21:28

BIBDBIBD

13.6k2222 gold badges7373 silver badges119119 bronze badges

add a comment
 | 

1

Rigan Ap-apid presented a paper at WorldComp ’08 on just this problem space. The paper is allegedly here, but the server was timing out for me. I attended the presentation of the paper and he covered comparable systems and their effectiveness as well as his own approach. You might contact him directly.

share|improve this answer

answered Nov 5 ’08 at 13:56

plinthplinth

43.1k88 gold badges7373 silver badges113113 bronze badges

Ah, that might actually be another paper by Rigan, but it might be helpful anyway.

– Rasmus Faber
Nov 5 ’08 at 14:28

add a comment
 | 

0

I’m afraid I can’t help point you in the right direction, but I do remember reading about this being done before. It was in the context of people complaining about baby pictures being caught and flagged mistakenly. If nothing else, I can give you the hope that you don’t have to invent the wheel all by yourself… Someone else has been down this road!

share|improve this answer

answered Nov 4 ’08 at 21:15

Brian KnoblauchBrian Knoblauch

16.9k1212 gold badges4848 silver badges7979 bronze badges

IIRC, the solution there was to disallow baby pictures completely.

– Joel Coehoorn
Nov 4 ’08 at 21:20

add a comment
 | 

0

CrowdSifter by Dolores Labs might do the trick for you. I read their blog all the time as they seem to love statistics and crowdsourcing and like to talk about it. They use amazon’s mechanical turk for a lot of their processing and know how to process the results to get the right answers out of things. Check out their blog at the very least to see some cool statistical experiments.

share|improve this answer

answered Nov 6 ’08 at 21:21

reconbotreconbot

4,65855 gold badges3838 silver badges5757 bronze badges

add a comment
 | 

0

As mentioned above by Bill (and Craig’s google quote) statistical methods can be highly effective.

Two approaches you might want to look into are:

Neural Networks
Multi Variate Analysis (MVA)

The MVA approach would be to get a “representative sample” of acceptable pictures and of unacceptable pictures. The X data would be an array of bytes from each picture, the Y would be assigned by you as a 1 for unacceptable and a 0 for acceptable. Create a PLS model using this data. Run new data against the model and see how well it predicts the Y.

Rather than this binary approach you could have multiple Y’s (e.g. 0=acceptable, 1=swimsuit/underwear, 2=pornographic)

To build the model you can look at open source software or there are a number of commercial packages available (although they are typically not cheap)

Because even the best statistical approaches are not perfect the idea of also including user feedback would probably be a good idea.

Good luck (and worst case you get to spend time collecting naughty pictures as an approved and paid activity!)

share|improve this answer

answered Jul 7 ’12 at 16:40

PTRMarkPTRMark

2722 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged asp.net image-processing or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Linked

8

PHP – Blocking of uploaded adult images

Related

1451A potentially dangerous Request.Form value was detected from the client349Can I automatically increment the file build version when using Visual Studio?0ASP.NET DLL publish method of deployment deletes entire published app73Visual Studio 2010: How to enforce build order of projects in a solution?852Peak detection in a 2D array2Are there web editing tools that can work with ASP.NET that a layman can use?1612Image Processing: Algorithm Improvement for ‘Coca-Cola Can’ Recognition0Push facebook images to ASP.net website?25Detecting truck wheels

Hot Network Questions

Print this maximally long URL

Does a non-creature God entering the battlefield trigger Pelt Collector?

How to avoid comments about one line of code for cleanliness

Single Minded Riley

Who first understood the importance of poles?

What is the use of this socket/port seen on an airplane passenger’s seat?

Give me Triangles

OLS as approximation for non-linear function

Does the race of half-orcs on Khorvaire in Eberron have its own name?

What kind of effect would low gravity have on geography?

Fifth year of my PhD and I hate my project. What should I do?

The ideal pinhole camera has an infinite depth of field

Is it bad to use special characters in passwords?

What does a strength check of 24 actually mean?

What will happen if someone/a group can’t be confirmed that they commited a crime?

Living next door to Alice

My prefix is a memory; my infix, you may hate

What are the ramifications of changing Armor Class to be Constitution-based instead of Dexterity-based?

We can ignore the wire resistance if the current delivered by the wire is low?

New UK passport dual citizenship observation

Why were the Space Shuttle’s main engines placed on the orbiter?

what is the best ingredient to add to a normal french toast recipe to make it taste pumpkin flavored

Can open-source software be peer-reviewed and published?

Windows 10 Search not loading, showing blank window

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

default

Categories
askquestion

Is MonoRail ready for productive usage?

Is MonoRail ready for productive usage?

Ask Question

Asked
11 years, 3 months ago

Active
9 years, 4 months ago

Viewed
347 times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

4

2

Right now I’m not sure…

model-view-controller castle-monorail

share|improve this question

edited Sep 16 ’10 at 10:04

Tim

5,71022 gold badges3636 silver badges7474 bronze badges

asked Nov 4 ’08 at 20:49

Stefan KoelleStefan Koelle

10577 bronze badges

add a comment
 | 

5 Answers
5

active

oldest

votes

5

I’d say yes. I’m using it. I know for a fact that Universal are using it on some of their (thousands of) sites. I will add some caveats, however:

There are serious problems with setting it up, especially if you want to debug into the libraries.
The helper functions favour prototype, as opposed to the more modern jQuery. This is changing rapidly, however.
The documentation is a bit chaotic, again the Castle Team are working on that.

I’m not guaranteeing every last “out-there” feature works, but the point of the system is actually to keep it simple.

Compared to vanilla ASP.NET, it’s an absolute joy. I assure you that you won’t miss viewstate.

share|improve this answer

answered Nov 5 ’08 at 23:36

Julian BirchJulian Birch

2,0701414 silver badges2626 bronze badges

2

What are the serious problems in setting up?… are your just referring the issues some people have with building it from trunk… or something else?

– Bittercoder
Nov 6 ’08 at 9:50

Thanks for this answer. I’m for sure I never miss viewstate, because the whole idea of ASP.NET WebForms was a bit strange after years of classic ASP. MVC gives me a much cleaner solution and right now I think we’ve choosen the right way.

– Stefan Koelle
Nov 13 ’08 at 22:24

It’s in use by Universal, as in, Universal Studios? How do you know? Can you provide links or contacts to ask about their experiences, maybe? Do their developers have blogs? I’d be really interested to hear about it!

– Peter Mounce
Dec 11 ’08 at 22:01

Bittercoder: Getting even a simple example working involves building it from trunk, which was a nightmare at the time of writing (it’s much better now) and then actually getting anything done at first is a maze of blog posts most of which are no longer valid. It’s much easier if you’ve got an experienced Monorail developer, but the initial curve is /steep/. Peter: I know because a friend of mine worked on some. I’m afraid I don’t have much more information than that. It was definitely taken seriously as a delivery platform, however.

– Julian Birch
Sep 2 ’09 at 16:04

1

Since MR 2.0 was released a couple of months ago, do you still think that setting up a project is a problem? btw, even if it was a problem (say taking an extra day), this is a one-time-cost per project. Since you’d want a project to be long lived, a day is perhaps an ok price to pay for the gains. And it certainly is not a day, not even an hour.

– Ken Egozi
Mar 26 ’10 at 19:46

 | 
show 2 more comments

1

We have been building a fairly large application with it for the past year and a half. Its been nice not to have to deal with the old ASP/Page based model and use the better Model/View/Controller design pattern.

To get the new stuff you really need to work off the trunk of development because they don’t do releases very often. We have a lot of tests that get the framework involved so when an update in the framework breaks something we depend on we know about it immediately.

If you have to work in .NET this beats the heck out of the alternatives.

share|improve this answer

answered Jan 16 ’09 at 17:03

Gareth FarringtonGareth Farrington

1,55411 gold badge1717 silver badges2222 bronze badges

add a comment
 | 

1

There is an overview on the monorail forum: http://forum.castleproject.org/viewforum.php?f=6

I’m using it for an application and haven’t had any big issues with it.
The biggest problem is indeed find good documentation and examples.

share|improve this answer

answered Apr 9 ’09 at 15:23

user62843user62843

1111 bronze badge

add a comment
 | 

1

I’ve had no problems setting it up. Julian, I don’t think it is constructive to say things like “serious problems” without any further clarification or example.

Debugging into the libraries is trivial. Because it’s open source, you can debug into the whole thing.

share|improve this answer

answered Apr 21 ’09 at 3:42

nocachenocache

18411 silver badge77 bronze badges

add a comment
 | 

1

I’ve been using MonoRail for production for ages on many projects, as an employee, as an indie contractor, and for non-work related sites.

I know I’m biased on that, however I can whole heartedly promise that my positive usage experience is what lured me into contributing to the project, not the other way around.

share|improve this answer

answered Jun 17 ’09 at 8:21

Ken EgoziKen Egozi

1,8051111 silver badges1313 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged model-view-controller castle-monorail or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

An account of my meeting with the Stack Overflow management team

Did Stack Exchange cut the number of negative comments nearly in half between…

Visit chat

Related

1Log in function in monorail c#0Mapping Castle MonoRail default requests to a controller action3Entire monorail action invocation in tests0MonoRail – “Unexpected item on the stack” Error0Upgrading MonoRail – $HtmlHelper.InputFile & $HtmlHelper.DateTime missing?0MonoRail CheckboxList?0MonoRail – Get All Controllers0MonoRail Select Using Enum0MonoRail: how to remove prototype validation?1358Passing Data between View Controllers

Hot Network Questions

Does gravity increase the closer to the core you get?

Why wouldn’t dragon-hide make me fire-resistant?

Did Sauron have the military power to control all Middle-earth?

Which mathematical property allows us to combine proportional relationships?

New UK passport dual citizenship observation

Why is aluminium body considered better than magnesium?

Where can I get a fork that will fit a 7 speed gear and a disc brake? Or how could I make one for said specification?

Does the tailplane have a positive/negative camber?

Are screened transistors an endangered species?

Third degree equation

Mountain range numbers

What will happen if someone/a group can’t be confirmed that they commited a crime?

Aliens, masquerading as foreign humans, have conquered the Earth; fly using pressor beams

Fifth year of my PhD and I hate my project. What should I do?

Why would 2 aircraft fitted with the P&W PT6 Engine have different top speed?

How to quickly and inexpensively deposit cash?

How did the Sega CD decompress video?

The Magical Piper

Primitive underwater melee combat

What does 「いねえのかよ」mean?

My prefix is a memory; my infix, you may hate

Windows 10 Search not loading, showing blank window

What made Jesus question at Mt 21:25 a good example for Christians or was it a bad question because the Jews could not answer?

Why is 2019-nCoV prioritized over other infectious diseases?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Categories
askquestion

Transitioning from WinForms to AJAX, what do I need to know?

Transitioning from WinForms to AJAX, what do I need to know?

Ask Question

Asked
11 years, 4 months ago

Active
4 years, 1 month ago

Viewed
195 times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

1

1

I currently have a functioning in-house Windows Forms application which extensively uses the DataGridView control for data entry. There are some support issues which are expected when we roll this out to more locations, so one of our consultants has recommended putting together an AJAX application with substantially the same functionality.

I have used ASP.NET a bit in the past with the old model where basically everything goes to the server, but I’ve heard AJAX applications can be made more UI responsive than that.

So my question is, what’s the best way to get started with AJAX, for someone who has worked mostly in WinForms C#?

c# .net ajax user-interface asp.net-ajax

share|improve this question

edited Dec 25 ’15 at 5:11

Mi-Creativity

8,5341010 gold badges3030 silver badges4444 bronze badges

asked Oct 9 ’08 at 11:13

Tony PetersonTony Peterson

16.5k1414 gold badges4343 silver badges6464 bronze badges

add a comment
 | 

2 Answers
2

active

oldest

votes

2

The easiest way, but not neccessarly the best way is to get familiar with the UpdatePanel, which is part of the ASP.net AJAX controls.
You can use an ASP.net GridView control (which shares much of the Winforms equiv. functionality), wrap an UpdatePanel around it and you’re away.

Further on from that you will want to get involved with web/wcf services to make calls from javascript to the server and update your UI based on the responce. That of course involved more time, effort and knowledge!

There are many gridview controls you can buy that will help e.g. One from essential objects is nice, not perfect, but very cheap compared to Telerik and other big names.

ASP.net is still a server based technology, but with the inclusion of ASP.net AJAX calls to the server are easy and with jQuery updating the UI is getting easier!!

Hope this helps

share|improve this answer

answered Oct 9 ’08 at 11:21

SteveClSteveCl

4,40566 gold badges2323 silver badges3737 bronze badges

add a comment
 | 

0

What you’re wanting to do isn’t very hard especially with Telerik’s or Infragistic’s controls, but as the previous commenter stated, they aren’t cheap. They are probably worth the price if you don’t want to spend the time rolling your own responsive and editable grid.

share|improve this answer

answered Oct 16 ’08 at 21:12

Jeremy BadeJeremy Bade

52155 silver badges1111 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged c# .net ajax user-interface asp.net-ajax or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Related

9Does This ASP.NET Consultant Know What He’s Doing?1Is it Asp.Net or Ajax or can both technologies be used together when developing web sites?0Json, Timer, Ajax, What is faster (for shared Chronometer)?0Statistical analysis in winforms319What is the purpose of a stack? Why do we need it?376Handle file download from ajax post2How to tell if SQL Server automated upgrade is successful from C# WinForms app2Need a very customized large Winforms grid1Access winform variable from browsercontrol

Hot Network Questions

Doubt on how move as black after pawn in e5

What is the use of this socket/port seen on an airplane passenger’s seat?

What will happen if someone/a group can’t be confirmed that they commited a crime?

How much better was DEC Alpha than contemporary x86?

Half my power out, but firing up an appliance turns it back on

I accidentally unset $PATH. Why did `echo` still work?

I was playing a tournament and some kids were talking about the game in a foreign language

Primitive underwater melee combat

Concentric rings on a snub square tiling

Are there any planets or moons denser than Earth?

Lines crossing with different widths in a declared shaped

Story about a boy who could wish to be someone else and would gain their skills

Acyclic group and finite CW-complex

94 Toyota Pickup hard to put into gear after clutch in too long

OLS as approximation for non-linear function

Give me Triangles

How to quickly and inexpensively deposit cash?

Why is 2019-nCoV prioritized over other infectious diseases?

Does the tailplane have a positive/negative camber?

Is Earth’s moon the only one where a total eclipse of the sun covers the entire sun?

What is this large engine doing on a B52?

How do I explain the long life spans of Elves?

How often should I clean my water bladder/reservoir while on a thru-hike, extended backpacking trip, or survival scenario?

LongEst in anothEr way?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cs

Categories
askquestion

Best security practices in Linux

Best security practices in Linux

Ask Question

Asked
11 years, 4 months ago

Active
4 months ago

Viewed
1k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

1

5

What security best-practices would you strongly recommend in maintaining a Linux server? (i.e. bring up a firewall, disable unnecessary services, beware of suid executables, and so on.)

Also: is there a definitive reference on Selinux?

EDIT: Yes, I’m planning to put the machine on the Internet, with at least openvpn, ssh and apache (at the moment, without dynamic content), and to provide shell access to some people.

linux security selinux

share|improve this question

edited Apr 17 ’15 at 10:32

Stefan Steiger

59.3k5858 gold badges298298 silver badges381381 bronze badges

asked Oct 9 ’08 at 11:15

Federico A. RamponiFederico A. Ramponi

41k2424 gold badges9999 silver badges129129 bronze badges

add a comment
 | 

8 Answers
8

active

oldest

votes

5

For SELinux I’ve found SELinux By Example to be really useful. It goes quite in-depth into keeping a sever as secure as possible and is pretty well written for such a wide topic.

In general though:

Disable anything you don’t need. The wider the attack domain, the more likely you’ll have a breach.
Use an intrusion detection system (IDS) layer in front of any meaningful servers.
Keep servers in a different security zone from your internal network.
Deploy updates as fast as possible.
Keep up to date on 0-day attacks for your remotely-accessible apps.

share|improve this answer

answered Oct 9 ’08 at 11:31

OliOli

200k5454 gold badges192192 silver badges270270 bronze badges

add a comment
 | 

4

The short answer is, it depends. It depends on what you’re using it for, which in turn influences how much effort you should put into securing the thing.

There are some handy hints in the answers to this question:
Securing a linux webserver for public access

If you’re not throwing the box up onto the internet, some of those answers won’t be relevant. if you’re throwing it up onto the internet and hosting something even vaguely interesting on it, those answers are far too laissez-faire for you.

share|improve this answer

edited May 23 ’17 at 10:32

Community♦

111 silver badge

answered Oct 9 ’08 at 11:27

Angry AlbatrossAngry Albatross

add a comment
 | 

4

There’s an NSA document “NSA Security Guide for RHEL5” available at:

http://www.nsa.gov/ia/_files/os/redhat/rhel5-guide-i731.pdf

which is pretty helpful and at least systematic.

share|improve this answer

edited Feb 2 ’14 at 6:41

AMB

2,85266 gold badges4646 silver badges9696 bronze badges

answered Oct 9 ’08 at 12:11

tonystonys

3,5692727 silver badges3636 bronze badges

add a comment
 | 

2

Limit the software to the only ones you really use
Limit the rights of the users, through sudo, ACLs, kernel capabilities and SELinux/AppArmor/PaX policies
Enforce use of hard passwords (no human understandable words, no birthday dates, etc.)
Make LXC countainers, chroot or vserver jails for the “dangerous” applications
Install some IDS, e.g. Snort for the network traffic and OSSEC for the log analysis
Monitor the server
Encrypt your sensible datas (truecrypt is a gift of the gods)
Patch your kernel with GRSecurity : this add a really nice level of paranoïa

That’s more or less what I would do.

Edit : I added some ideas that I previously forgot to name …

share|improve this answer

edited May 15 ’14 at 20:03

answered Oct 9 ’08 at 13:05

edomauredomaur

1,33944 gold badges2222 silver badges3636 bronze badges

add a comment
 | 

1

1.) Enabling only necessary and relevant ports.

2.) Regular scan of the network data in – out

3.) Regular Scan of ip addresses accessing the server and verify if any unusual data activity associated with those ip address as found from logs/traces

4.) If some some critical and confidential data and code, needs to be present on the server , may be it can be encrypted

-AD

share|improve this answer

answered Oct 9 ’08 at 11:25

goldenmeangoldenmean

15.8k4747 gold badges138138 silver badges199199 bronze badges

add a comment
 | 

1

Goals:
The hardest part is always defining your security goals. Everything else is relatively easy at that point.

Probing/research:
Consider the same approach that attackers would take, ie network reconnaissance (namp is pretty helpful for that).

More information:
SELinux by example is a helpful book, finding a good centralized source for SELinux information is still hard.
I have a small list of helpful links that I find useful time to time http://delicious.com/reverand_13/selinux

Helpful solution/tools:
As with what most people will say less is more. For an out of the box stripped down box with SELinux I would suggest clip (http://oss.tresys.com/projects/clip). A friend of mine used it in an academic simulation in which the box was under direct attack from other participants. I recall the story concluded very favorably for said box.

You will want to become familiar with writing SELinux policy. Modular policy can also become helpful. such tools as SLIDE and seedit (have not tried) may help you.

share|improve this answer

answered Jun 20 ’09 at 0:34

user125959user125959

add a comment
 | 

0

Don’t use a DNS Server unless you have to . BIND has been a hotspot of security issues and exploits.

share|improve this answer

answered Oct 9 ’08 at 13:29

Brian GBrian G

45.1k5555 gold badges117117 silver badges139139 bronze badges

And, if you need a DNS server for a local subnet but do not need to provide external DNS, then both configure BIND to not listen to external ports and firewall block external DNS incoming access.

– Eddie
Feb 23 ’09 at 20:56

add a comment
 | 

0

Hardening a Linux server is a vast topic and it primarily depend on your needs.

In general, you need to consider the following groups of concern (I’ll give example of best practices in each group):

Boot and Disk
Ex1: Disable booting from external devices.
Ex2: Set a password for the GRUB bootloader – Ref.
File system partitioning
Ex1: Separate user Partitions (/home, /tmp, /var) from OS Partitions.
Ex2: Setup nosuid on partitions – in order to prevent privilege escalation with the setuid bit.
Kernel
Ex1: Update security patches.
Ex2: Read more in here.
Networking
Ex1: Close unused ports.
Ex2: Disable IP forwarding.
Ex3: Disable send packet redirects.
Users / Accounts
Ex1 : Enforce strong passwords (SHA512).
Ex2: Set up password aging and expiration.
Ex3: Restrict Users to Use Old Passwords.
Auditing and logging
Ex1: Configure auditd – ref.
Ex2: Configure logging with journald – ref.
Services
Ex1: Remove unused services like: FTP, DNS, LDAP, SMB, DHCP, NFS, SNMP, etc’.
EX2: If you’re using a web server like Apache or nginx – don’t run them as root – read more here.
Ex3: Secure SSH ref.
Software
Make sure you remove unused packages.

Read more:

https://www.computerworld.com/article/3144985/linux-hardening-a-15-step-checklist-for-a-secure-linux-server.html

25 Hardening Security Tips for Linux Servers

https://cisofy.com/checklist/linux-security/

https://www.ucd.ie/t4cms/UCD%20Linux%20Security%20Checklist.pdf

https://www.cyberciti.biz/faq/linux-kernel-etcsysctl-conf-security-hardening/

https://securecompliance.co/linux-server-hardening-checklist/

Now specifically for SELinux:
First of all, make sure that SELinux is enabled in your machine.

Continue with the following guides:
https://www.digitalocean.com/community/tutorials/an-introduction-to-selinux-on-centos-7-part-1-basic-concepts

https://linuxtechlab.com/beginners-guide-to-selinux/

https://www.computernetworkingnotes.com/rhce-study-guide/selinux-explained-with-examples-in-easy-language.html

share|improve this answer

answered Oct 4 ’19 at 22:46

RtmYRtmY

2,45155 gold badges2121 silver badges3333 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged linux security selinux or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Linked

21

Securing a linux webserver for public access

Related

1391How do I prompt for Yes/No/Cancel input in a Linux shell script?1155Secure hash and salt for PHP passwords1630How to change the output color of echo in Linux1007How can I use grep to show just filenames on Linux?694Recursively counting files in a Linux directory5054How do I find all files containing specific text on Linux?

Hot Network Questions

Which mathematical property allows us to combine proportional relationships?

Why does the difference between 30 March and 1 March 2020 erroneously give 28 days instead of 29?

If police come to my house with a warrant for my arrest, can they break in?

Can you use your off-handed weapon for your main attack action?

Is Earth’s moon the only one where a total eclipse of the sun covers the entire sun?

Are there any planets or moons denser than Earth?

How can I get the current systemd log level and change it?

Is PCA always recommended?

I accidentally unset $PATH. Why did `echo` still work?

Easiest way to travel regularly from Essex to Cornwall

Why is 2019-nCoV prioritized over other infectious diseases?

Character ﷼ can not be pasted in front of a number

Would this hit/miss houserule be balanced with bounded accuracy?

How do I explain the long life spans of Elves?

Half my power out, but firing up an appliance turns it back on

Why were the Space Shuttle’s main engines placed on the orbiter?

Fifth year of my PhD and I hate my project. What should I do?

Who first understood the importance of poles?

What made Jesus question at Mt 21:25 a good example for Christians or was it a bad question because the Jews could not answer?

What is this large engine doing on a B52?

What does 「いねえのかよ」mean?

What is arbitrary code execution (ACE) and how does it affect speedrunning?

Casting creatures as spells – searching for the rules

Why does my tea periodically alternate its rotational speed after stirring? (Link to video below)

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Categories
askquestion

How to determine what log level to use? [closed]

How to determine what log level to use? [closed]

Ask Question

Asked
11 years, 4 months ago

Active
8 years ago

Viewed
9k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

60

32

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.

Closed 8 years ago.

The log levels WARN, ERROR and FATAL are pretty clear. But when is something DEBUG, and when INFO?

I’ve seen some projects that are annoyingly verbose on the INFO level, but I’ve also seen code that favors the DEBUG level too much. In both cases, useful information is hidden in the noise.

What are the criteria for determining log levels?

language-agnostic logging verbosity

share|improve this question

asked Oct 9 ’08 at 11:18

SietseSietse

7,2051010 gold badges4747 silver badges6262 bronze badges

add a comment
 | 

6 Answers
6

active

oldest

votes

114

I don’t think there are any hard-and-fast rules; using the log4j-type levels, my ‘rules of thumb’ are something like:

FATAL: the app (or at the very least a thread) is about to die horribly. This is where the info explaining why that’s happening goes.
ERROR: something that the app’s doing that it shouldn’t. This isn’t a user error (‘invalid search query’); it’s an assertion failure, network problem, etc etc., probably one that is going to abort the current operation
WARN: something that’s concerning but not causing the operation to abort; # of connections in the DB pool getting low, an unusual-but-expected timeout in an operation, etc. I often think of ‘WARN’ as something that’s useful in aggregate; e.g. grep, group, and count them to get a picture of what’s affecting the system health
INFO: Normal logging that’s part of the normal operation of the app; diagnostic stuff so you can go back and say ‘how often did this broad-level operation happen?’, or ‘how did the user’s data get into this state?’
DEBUG: Off by default, able to be turned on for debugging specific unexpected problems. This is where you might log detailed information about key method parameters or other information that is useful for finding likely problems in specific ‘problematic’ areas of the code.
TRACE: “Seriously, WTF is going on here?!?! I need to log every single statement I execute to find this @#[email protected] memory corruption bug before I go insane”

Not set in stone, but a rough idea of how I think of it.

share|improve this answer

answered Oct 9 ’08 at 11:33

CowanCowan

33.8k1010 gold badges6161 silver badges6363 bronze badges

add a comment
 | 

7

Informally I use this sort of hierarchy,

DEBUG – actual trace values
INFO – Something just happened – nothing important, just a flag
WARN – everything’s working, but something isn’t quite what was expected
ERROR – something has happened that will need to be fixed, but we can carry on and do other (independent) activities
FATAL – a serious enough problem that we shouldn’t even carry on

I’ll generally release with INFO being logged, but only if I know that log files are actually reviewed (and size isn’t an issue), otherwise it’s WARN.

share|improve this answer

edited Oct 9 ’08 at 11:40

answered Oct 9 ’08 at 11:27

UnslicedUnsliced

9,46088 gold badges4646 silver badges7878 bronze badges

add a comment
 | 

5

Think about who needs to use each level.
In my code I keep DEBUG reserved for a developer output, e.g. output that would only help a developer.
VERBOSE is used for a normal user when alot of info is needed.
INFO I use to normally show major events (e.g. sending a webpage, checking something important).

And FAIL and WARN are pretty self explanatory.

share|improve this answer

answered Oct 9 ’08 at 11:22

GavinCattellGavinCattell

3,4731616 silver badges2020 bronze badges

I think a lot of the INFO or WARN would only help a developers

– Casebash
May 14 ’10 at 3:12

add a comment
 | 

4

The convention in my team is to use debug if something is calculated in the message, whereas info is used for plain text. So in effect info will show you what’s happening and debug will show the values of the things that are happening.

share|improve this answer

answered Oct 9 ’08 at 11:28

slashnickslashnick

23.3k99 gold badges5151 silver badges6666 bronze badges

add a comment
 | 

1

I tend to target INFO towards the user to give them messages that aren’t even warnings. DEBUG tends to be for developer use where I output messages to help trace the flow through the code (with values of variables as well).

I also like another level of DEBUG (DEBUG2?) which gives absolute bucketloads of debug information such as hex dumps of all buffers and so on.

share|improve this answer

answered Oct 9 ’08 at 12:02

paxdiablopaxdiablo

696k193193 gold badges13631363 silver badges17471747 bronze badges

add a comment
 | 

0

There’s no need for a DEBUG2 level. That’s what ‘TRACE’ is for. TRACE is intended to be the absolute lowest level of logging outputting every possible piece of information you might want to see.

To avoid a deluge of information, it is generally not recommended that you enable trace-level logging across an entire project. Instead use ‘DEBUG’ to find out general information about the bug and where it occurs (hence the name), and then enable TRACE only for that component if you still can’t figure it out.

share|improve this answer

answered Jan 10 ’12 at 19:11

AlaskaAlaska

32922 silver badges1313 bronze badges

add a comment
 | 

Not the answer you’re looking for? Browse other questions tagged language-agnostic logging verbosity or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Visit chat

Linked

0

When and Where to apply logging in spring-boot application

Related

1644What is tail recursion?7948What and where are the stack and heap?3025What is dependency injection?1210Determine Whether Two Date Ranges Overlap1004What is the difference between concurrency and parallelism?948How to have git log show filenames like svn log -v489When to use the different log levels252Logging levels – Logback – rule-of-thumb to assign log levels207Spring RestTemplate – how to enable full debugging/logging of requests/responses?3879How to pair socks from a pile efficiently?

Hot Network Questions

Is it bad to use special characters in passwords?

Problem with reference image – Changes to alpha does not change transparency

Is there an online list of Perakim of Mishnayos arranged alphabetically?

Does gravity increase the closer to the core you get?

Half my power out, but firing up an appliance turns it back on

Why is aluminium body considered better than magnesium?

How does “It’s totally fucked” translate to Latin?

Debt management: 0% CC APR for 15 months vs 7% student loan debt

What will happen if someone/a group can’t be confirmed that they commited a crime?

The use of the adjective “taken” in context

Being asked to sign a “termination certificate” 6 months after resigning

The Magical Piper

Medical provider is threatening to send me to collections over a debt I do not owe

How to get a Real ID in California with my married name, when I am divorced?

Story about a boy who could wish to be someone else and would gain their skills

A word like ethereal that also means quickly vanishing

Perform a Caesar Cipher Shift on a given string

How to generate a random integer array satisfying complex constraints

U.S. Army/Military’s response time to an army appearing in the middle of a major city

Is there any connector for SMD components

Why wouldn’t dragon-hide make me fire-resistant?

How to avoid comments about one line of code for cleanliness

Character ﷼ can not be pasted in front of a number

How often should I clean my water bladder/reservoir while on a thru-hike, extended backpacking trip, or survival scenario?

more hot questions

Categories
askquestion

ResultSet: Retrieving column values by index versus retrieving by label

ResultSet: Retrieving column values by index versus retrieving by label

Ask Question

Asked
11 years, 4 months ago

Active
19 days ago

Viewed
92k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

51

7

When using JDBC, I often come across constructs like

ResultSet rs = ps.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
// Some other actions
}

I asked myself (and authors of code too) why not to use labels for retrieving column values:

int id = rs.getInt(“CUSTOMER_ID”);

The best explanation I’ve heard is something concerning performance. But actually, does it make processing extremely fast? I don’t believe so, though I have never performed measurements. Even if retrieving by label would be a bit slower, nevertheless, it provide better readability and flexibility, in my opinion.
So could someone give me good explanation of avoiding to retrieve column values by column index instead of column label? What are pros and cons of both approaches (maybe, concerning certain DBMS)?

java optimization jdbc resultset maintenance

share|improve this question

edited Oct 16 ’15 at 18:12

pyb

2,75911 gold badge1717 silver badges3333 bronze badges

asked Oct 9 ’08 at 11:18

RorickRorick

8,32133 gold badges2929 silver badges3636 bronze badges

Is there any constants for using it? Something like ‘ResultSet.CUSTOMER_ID’

– EliuX
Feb 18 ’15 at 18:05

add a comment
 | 

13 Answers
13

active

oldest

votes

47

You should use string labels by default.

Pros:

Independence of column order
Better readability/maintainability

Cons:

You have no control over the column names (access via stored procedures)

Which would you prefer?

ints?

int i = 1;
customerId = resultSet.getInt(i++);
customerName = resultSet.getString(i++);
customerAddress = resultSet.getString(i++);

or Strings?

customerId = resultSet.getInt(“customer_id”);
customerName = resultSet.getString(“customer_name”);
customerAddress = resultSet.getString(“customer_address”);

And what if there is a new column inserted at position 1? Which code would you prefer? Or if the order of the columns is changed, which code version would you need to change at all?

That’s why you should use string labels by default.

share|improve this answer

edited Jan 18 at 11:11

Mark Rotteveel

69.4k1515 gold badges9292 silver badges132132 bronze badges

answered Oct 9 ’08 at 14:07

Martin KlinkeMartin Klinke

6,75055 gold badges3636 silver badges5757 bronze badges

Always use strings as your first choice, there is one place where the indexed based access makes sense is when you are just dumping a file to CSV though however the caveat here is that all columns must be dumped as strings.

– Namphibian
Nov 17 ’15 at 22:40

1

Well, that didn’t answer the question even slightly. How has this gotten so many up votes? If you’re going to throw something like this in, that’s fine (I even appreciate it in many cases), but at least answer the original question.

– searchengine27
Jul 5 ’18 at 15:42

add a comment
 | 

56

Warning: I’m going to get bombastic here, because this drives me crazy.

99%* of the time, it’s a ridiculous micro-optimization that people have some vague idea makes things ‘better’. This completely ignores the fact that, unless you’re in an extremely tight and busy loop over millions of SQL results all the time, which is hopefully rare, you’ll never notice it. For everyone who’s not doing that, the developer time cost of maintaing, updating, and fixing bugs in the column indexing are far greater than the incremental cost of hardware for your infinitesimally-worse-performing application.

Don’t code optimizations like this in. Code for the person maintaining it. Then observe, measure, analyse, and optimize. Observe again, measure again, analyse again, and optimize again.

Optimization is pretty much the last step in development, not the first.

* Figure is made up.

share|improve this answer

answered Oct 9 ’08 at 11:26

CowanCowan

33.8k1010 gold badges6161 silver badges6363 bronze badges

No. Absolutely not. I hate the way people talk about pre-optimization. Java is a safe language – that isn’t a licence for spaghetti code. You still should be mindful of the Java specification and grammar, along with any other APIs or specs you’re using. When you’re writing a 1000 line micro-program and you can make concessions like this, then sure – go for it. But anything larger than that and working on a real product, you better be 100 percent aware of the implications of the code you’re writing, and you better be able to explain why this performance loss is acceptable.

– searchengine27
Jul 5 ’18 at 15:44

add a comment
 | 

6

The answer has been accepted, none-the-less, here is some additional information and personal experience that I have not seen put forward yet.

Use column names (constants and not literals is preferred) in general and if possible. This is both clearer, is easier to maintain, and future changes are less likely to break the code.

There is, however, a use for column indexes. In some cases these are faster, but not sufficiently that this should override the above reasons for names*. These are very valuable when developing tools and general methods dealing with ResultSets. Finally, an index may be required because the column does not have a name (such as an unnamed aggregate) or there are duplicate names so there is no easy way to reference both.

*Note that I have written some JDBC drivers and looked inside some open sources one and internally these use column indexes to reference the result columns. In all cases I have worked with, the internal driver first maps a column name to an index. Thus, you can easily see that the column name, in all those cases, would always take longer. This may not be true for all drivers though.

share|improve this answer

answered Feb 4 ’10 at 5:10

Kevin BrockKevin Brock

8,02911 gold badge2929 silver badges3636 bronze badges

add a comment
 | 

6

From the java documentation:

The ResultSet interface provides getter methods (getBoolean, getLong, and so on) for retrieving column values from the current row. Values can be retrieved using either the index number of the column or the name of the column. In general, using the column index will be more efficient. Columns are numbered from 1. For maximum portability, result set columns within each row should be read in left-to-right order, and each column should be read only once.

Of course each method (named or indexed) has its place. I agree that named columns should be the default. However, in cases where a huge number of loops are required, and where the SELECT statement is defined and maintained in the same section of code (or class), indexes should be ok – it is advisable to list the columns being selected, not just “SELECT * FROM…”, since any table change will break the code.

share|improve this answer

answered Jun 26 ’13 at 6:27

JasonJason

10.8k33 gold badges3737 silver badges4545 bronze badges

add a comment
 | 

4

Sure, using column names increases readibility and makes maintenance easy. But using column names has a flipside. As you know, SQL allows multiple column names with same name, there’s no guarantee that the column name you typed in the getter method of resultSet actually points to the column name you intend to access. In theory, using index numbers instead of column names is preffered, but it reduces the readability…

Thanks

share|improve this answer

answered Feb 4 ’10 at 4:57

user228462user228462

add a comment
 | 

2

I don’t think using the labels impacts performance by much. But there is another reason not to use Strings. Or ints, for that matter.

Consider using constants. Using an int constant makes the code more readably, but also less likely to have errors.

Besides being more readable, the constant also prevents you from making typo’s in the label names – the compiler will throw an error if you do. And any IDE worth anything will pick it up. This is not the case if you use Strings or ints.

share|improve this answer

answered Oct 9 ’08 at 11:27

SietseSietse

7,2051010 gold badges4747 silver badges6262 bronze badges

2

See your point, but I don’t think this really helps that much. int COLUMN_FIRST_NAME = 13; int COLUMN_SURNAME = 14; could have a bug; maye FIRST name is 14 and SURNAME is 13. And you still have to adjust when columns are added etc. If you must use constants, I’d use Strings anyway to avoid this.

– Cowan
Oct 9 ’08 at 11:38

int constants solve readability problem, but previous comment stresses that flexibility problem remains. I also would prefer String constants. But I didn’t use constants in examples considering that it would make my point clearer.

– Rorick
Oct 9 ’08 at 12:02

Rorick, I see what you mean, and I agree. But using constants solves at least the readability problem. The problem of using the correct int for the column you want is the same in both cases.

– Sietse
Oct 9 ’08 at 12:07

what happens if you make a typo in the string constant? maybe you should just make each a constant of a constant? that would save you some time debugging errors

– jasonk
Aug 1 ’12 at 12:32

add a comment
 | 

2

I did some performance profiling on this exact subject on an Oracle database. In our code we have a ResultSet with numerous colums and a huge number of rows. Of the 20 seconds (!) the request takes to execute method oracle.jdbc.driver.ScrollableResultSet.findColumn(String name) takes about 4 seconds.

Obviously there’s something wrong with the overall design, but using indexes instead of the column names would probably take this 4 seconds away.

share|improve this answer

answered Dec 31 ’08 at 9:06

Marko UllgrenMarko Ullgren

add a comment
 | 

2

You can have the best of both! The speed of using indexes with the maintainability and security of using column names.

First – unless you are looping thru a result set just use column names.

Define a set of integer variables, one for each column you will access. The names of the variables can include the name of the column: e.g. iLast_Name.
Before the result set loop iterate thru the column metadata and set the value of each integer variable to the column index of the corresponding column name. If the index of the ‘Last_Name’ column is 3 then set the value of ‘iLast_Name’ to 3.
In the result set loop use the integer variable names in the GET/SET methods. The variable name is a visual clue to the developer/maintainer as to the actual column name being accessed but the value is the column index and will give the best performance.

NOTE: the initial mapping (i.e. column name to index mapping) is only done once before the loop rather than for every record and column in the loop.

share|improve this answer

answered Nov 28 ’10 at 21:00

Rick PostRick Post

3111 bronze badge

add a comment
 | 

1

The JDBC driver takes care for the column to index look-up. So if you extract values by column name each time the driver makes a look-up (usually in hash map) to check the corresponding index for the column name.

share|improve this answer

answered Oct 9 ’08 at 11:24

zlosterzloster

1,0361111 silver badges2424 bronze badges

add a comment
 | 

0

I agree with previous answers that performance is not something that can force us to select either of the approaches. It would be good to consider the following things instead:

Code readability: for every developer reading your code labels have much more sense than indexes.
Maintenance: think of the SQL query and the way it is maintained. What is more likely to happen in your case after fixing/improving/refactoring SQL query: changing the order of the columns extracted or changing result column names. It seems for me that changing the order of the columns extracted (as the results of adding/deleting new columns in result set) has greater probability to happen.
Encapsulation: in spite of the way you choose try to isolate the code where you run SQL query and parse result set in the same component and make only this component aware about the column names and their mapping to the indexes (if you decided to use them).

share|improve this answer

answered Oct 9 ’08 at 12:20

Cha2lengerCha2lenger

3833 bronze badges

add a comment
 | 

0

Using the index is an attempt at optimization.

The time saved by this is wasted by the extra effort it takes the developer to look up the necessary data to check if their code will work properly after the changes.

I think it’s our built-in instinct to use numbers instead of text.

share|improve this answer

answered Oct 9 ’08 at 12:29

databyssdatabyss

4,94211 gold badge1818 silver badges2323 bronze badges

add a comment
 | 

0

Besides the look up in Map for labels it also leads to an extra String creation. Though it will happens on stack but still it caries a cost with it.

It all depends on the individual choice and till date I have used only indexes 🙂

share|improve this answer

answered Dec 19 ’08 at 9:20

Vinod SinghVinod Singh

11911 silver badge33 bronze badges

add a comment
 | 

0

As it is pointed out by other posters, I would stick to column names unless you have a really powerful reason not to do so. The impact in performance is negligible compared to, for example, query optimization. In this case, maintenance is much more important than an small optmization.

share|improve this answer

answered Apr 15 ’19 at 14:47

Rober2D2Rober2D2

40433 silver badges77 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged java optimization jdbc resultset maintenance or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Linked

9

Performance comparison of result set extracting data using index vs column name

0

Which one is performance for database?

-2

how to get all rows in one column using jdbc

-4

NullPointerException when using String from SQL database

0

Why this mysql find max value stament won’t run in Java JDBC

0

JAVA: get String value from Class1 and call to the other Class2

0

Fetch data through column number not column name in JAVA from mysql database?

Related

225Retrieve column names from java.sql.ResultSet1Displaying entity-attribute-value data in JTable?86How to get the number of columns from a JDBC ResultSet?272Checking for a null int value from a Java ResultSet65How can I determine if the column name exist in the ResultSet?2Test ResultSet to see if it contains a column label15Retrieve entire row with ResultSet0ResultSet not iterating values of specified column0ResultSet is Closed Error on retrieval1JDBC — ResultSet values for column functions

Hot Network Questions

Was Rami Malek singing or lipsyncing?

How does a Coronavirus “test kit” work?

What went wrong with my DIY project?

Easiest way to travel regularly from Essex to Cornwall

Problem with reference image – Changes to alpha does not change transparency

Using generic SMPS adaptor on old IBM Thinkpad makes strange symptoms

I accidentally unset $PATH. Why did `echo` still work?

Is Earth’s moon the only one where a total eclipse of the sun covers the entire sun?

Half my power out, but firing up an appliance turns it back on

What made Jesus question at Mt 21:25 a good example for Christians or was it a bad question because the Jews could not answer?

Ukranian зозуля cuckoo

It’s all about the sum of the digits

What are credit cards, debit cards, and other types of cards?

Does gravity increase the closer to the core you get?

The Magical Piper

U.S. Army/Military’s response time to an army appearing in the middle of a major city

How does the DA 40 NG automatically control the mixture, pitch and power by just providing one throttle?

Doubt on how move as black after pawn in e5

Large subgroups of Symmetric Group

Can you use your off-handed weapon for your main attack action?

Mountain range numbers

Are screened transistors an endangered species?

Which mathematical property allows us to combine proportional relationships?

What is the purpose of the ferrite bead on DC Adaptors?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-java

Categories
askquestion

Is it possible to specify proxy credentials in your web.config?

Is it possible to specify proxy credentials in your web.config?

Ask Question

Asked
11 years, 4 months ago

Active
2 years, 3 months ago

Viewed
94k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

59

38

I need to configure a website to access a webservice on another machine, via a proxy. I can configure the website to use a proxy, but I can’t find a way of specifying the credentials that the proxy requires, is that possible? Here is my current configuration:

<defaultProxy useDefaultCredentials=”false”>
<proxy usesystemdefault=”true” proxyaddress=”<proxy address>” bypassonlocal=”true” />
</defaultProxy>

I know you can do this via code, but the software the website is running is a closed-source CMS so I can’t do this.

Is there any way to do this? MSDN isn’t helping me much..

c# web-services proxy

share|improve this question

edited Oct 9 ’08 at 11:31

spmason

asked Oct 9 ’08 at 11:19

spmasonspmason

3,83322 gold badges2020 silver badges1818 bronze badges

add a comment
 | 

4 Answers
4

active

oldest

votes

101

Yes, it is possible to specify your own credentials without modifying the current code. It requires a small piece of code from your part though.

Create an assembly called SomeAssembly.dll with this class :

namespace SomeNameSpace
{
public class MyProxy : IWebProxy
{
public ICredentials Credentials
{
get { return new NetworkCredential(“user”, “password”); }
//or get { return new NetworkCredential(“user”, “password”,”domain”); }
set { }
}

public Uri GetProxy(Uri destination)
{
return new Uri(“http://my.proxy:8080″);
}

public bool IsBypassed(Uri host)
{
return false;
}
}
}

Add this to your config file :

<defaultProxy enabled=”true” useDefaultCredentials=”false”>
<module type = “SomeNameSpace.MyProxy, SomeAssembly” />
</defaultProxy>

This “injects” a new proxy in the list, and because there are no default credentials, the WebRequest class will call your code first and request your own credentials. You will need to place the assemble SomeAssembly in the bin directory of your CMS application.

This is a somehow static code, and to get all strings like the user, password and URL, you might either need to implement your own ConfigurationSection, or add some information in the AppSettings, which is far more easier.

share|improve this answer

edited Aug 3 ’12 at 13:22

niarbrnd

322 bronze badges

answered Oct 11 ’08 at 18:29

Jerome LabanJerome Laban

3,59133 gold badges1515 silver badges1212 bronze badges

I’m going to mark this as the answer, because it looks as if it should work, but I’m still having issues connecting which seem to be down to ISA Server more than anything..

– spmason
Oct 13 ’08 at 20:09

We’re not supposed to do +1, etc, but this is a really easy and elegant solution!!

– Nick Patsaris
Dec 17 ’14 at 12:20

Any idea how to pass credentials to the assembly? I don’t want to hardcode those information as the users should be able to change those later on without recompiling the code.

– F.H.
Nov 14 ’18 at 14:38

add a comment
 | 

19

While I haven’t found a good way to specify proxy network credentials in the web.config, you might find that you can still use a non-coding solution, by including this in your web.config:

<system.net>
<defaultProxy useDefaultCredentials=”true”>
<proxy proxyaddress=”proxyAddress” usesystemdefault=”True”/>
</defaultProxy>
</system.net>

The key ingredient in getting this going, is to change the IIS settings, ensuring the account that runs the process has access to the proxy server.
If your process is running under LocalService, or NetworkService, then this probably won’t work. Chances are, you’ll want a domain account.

share|improve this answer

answered May 17 ’09 at 23:03

Scott FergusonScott Ferguson

6,88177 gold badges3232 silver badges6161 bronze badges

add a comment
 | 

7

You can specify credentials by adding a new Generic Credential of your proxy server in Windows Credentials Manager:

1 In Web.config

<system.net>
<defaultProxy enabled=”true” useDefaultCredentials=”true”>
<proxy usesystemdefault=”True” />
</defaultProxy>
</system.net>

In Credential Manager >> Add a Generic Credential

Internet or network address: your proxy address
User name: your user name
Password: you pass

This configuration worked for me, without change the code.

share|improve this answer

answered Jun 26 ’15 at 21:28

Silas Humberto SouzaSilas Humberto Souza

10611 silver badge22 bronze badges

Control PanelAll Control Panel ItemsCredential Manager

– jerone
Jan 28 ’18 at 10:50

Works for me behind a Microsoft ISA proxy

– Hintham
Jun 28 ’19 at 10:56

add a comment
 | 

1

Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision

share|improve this answer

answered Oct 9 ’08 at 11:38

questzenquestzen

2,9861515 silver badges2020 bronze badges

I’ve not idea how this would help. The server’s aren’t on the same domain if that matters..

– spmason
Oct 9 ’08 at 12:31

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged c# web-services proxy or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

Did Stack Exchange cut the number of negative comments nearly in half between…

An account of my meeting with the Stack Overflow management team

Linked

5

Proxy server authentication for WCF service

3

Proxy Authentication Required (Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied.)

1

send message to azure service bus queue from web api

4

reCaptcha validation with timeout exception

2

Use svcutil.exe with a webproxy

3

Communicating with WCF service via Web Proxy; from within a Windows Service

2

MetadataExchangeClient using Web Proxy

2

Cannot access rss feed from MVC application on IIS though proxy

0

Sending eMail Through Visual C++/Cli Not Working

0

Access SmartSheet API behind corporate firewall .Net C#

see more linked questions…

Related

1744What’s the difference between a proxy server and a reverse proxy server?2155How do I get a consistent byte representation of strings in C# without manually specifying an encoding?904Getting Git to work with a proxy server – fails with “Request timed out”776Reading settings from app.config or web.config in .NET4System.Net defaultProxy section in web.config151Gradle proxy configuration18How to authenticate against a proxy when using the HttpClient class?1Supplying credentials for a proxy server and WCF service in one call?0Using cURL, can I test if proxy credentials are valid without pinging a random server?

Hot Network Questions

Ukranian зозуля cuckoo

Best ways to learn all the illustrator tools and commands

Why moving a label in QGIS sets the label rotation to 0° and how to avoid that?

Visual indicator for a file that doesn’t end in newline

problem with the reference image

Would this hit/miss houserule be balanced with bounded accuracy?

I accidentally unset $PATH. Why did `echo` still work?

What do the green, white and yellow bands mean on an airspeed indicator?

How does a Coronavirus “test kit” work?

Gender-specific verbs mess

U.S. Army/Military’s response time to an army appearing in the middle of a major city

How to Force Evaluation of Derivative in a Pure Function Definition

How often should I clean my water bladder/reservoir while on a thru-hike, extended backpacking trip, or survival scenario?

What was so different about “Night of the Living Dead” from previous zombie movies?

How wasteful is a voltage transformer?

c++ Threads inside for loop print wrong values

What made Jesus question at Mt 21:25 a good example for Christians or was it a bad question because the Jews could not answer?

What is arbitrary code execution (ACE) and how does it affect speedrunning?

Why does the difference between 30 March and 1 March 2020 erroneously give 28 days instead of 29?

Concentric rings on a snub square tiling

Did Sauron have the military power to control all Middle-earth?

Do German professors in a Master’s program respond to students who email them interested in their research work?

should we manully clear out the “Workflow History” list inside our online sharepoint site collection

Does gravity increase the closer to the core you get?

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

lang-cs

Categories
askquestion

How to extract common named_scopes from ActiveRecord models

How to extract common named_scopes from ActiveRecord models

Ask Question

Asked
11 years, 4 months ago

Active
7 years, 3 months ago

Viewed
1k times

.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{
margin-bottom:0;
}

12

7

I have named_scope which is reused in multiple ActiveRecord models.
For example:

named_scope :limit, lambda {|limit| {:limit => limit}}

What is the best practice to extract this code to be shared across models.
Is it possible to extract it to a module or should I rather reopen ActiveRecord::Base class?

ruby-on-rails activerecord named-scope

share|improve this question

asked Oct 9 ’08 at 11:19

Bartosz BlimkeBartosz Blimke

5,92033 gold badges2121 silver badges1919 bronze badges

add a comment
 | 

2 Answers
2

active

oldest

votes

21

Use a module. Something like this should work:

module CommonScopes
def self.included(base)
base.class_eval do
named_scope :limit, lambda {|limit| {:limit => limit}}
end
end
end

Then just include CommonScopes and you’ll be good to go.

share|improve this answer

answered Oct 9 ’08 at 12:47

Ben ScofieldBen Scofield

6,24822 gold badges2020 silver badges2222 bronze badges

1

This seems to work for the class-level, but not the instance-level. For example: User.limit(1) works, but the second call to limit here raises an error: users=User.limit(5); users.limit(1). Any solution for the instance level?

– Matt Huggins
Apr 18 ’11 at 17:14

add a comment
 | 

0

@Matt via instance_eval, @see Shared scopes via module?

share|improve this answer

edited May 23 ’17 at 12:08

Community♦

111 silver badge

answered Oct 17 ’12 at 10:32

Hugo StieglitzHugo Stieglitz

5733 bronze badges

add a comment
 | 

Your Answer

Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.

Draft saved
Draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email
Required, but never shown

Post Your Answer

Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you’re looking for? Browse other questions tagged ruby-on-rails activerecord named-scope or ask your own question.

Blog

The 2020 Developer Survey is now open!

How Shapeways’ software enables 3D printing at scale

Featured on Meta

TLS 1.0 and TLS 1.1 removal for Stack Exchange services

An account of my meeting with the Stack Overflow management team

Did Stack Exchange cut the number of negative comments nearly in half between…

Linked

22

Shared scopes via module?

Related

81Best Practices for reusing code between controllers in Ruby on Rails8Reusing named_scope to define another named_scope2Rails controller when no ActiveRecord model?34Understanding how establish_connection works in ActiveRecord0Rails 2.3 – implement dynamic named_scope using mixin2How to extend the “save!” method on ActiveRecord?24Get table name from ActiveRecord5How to share activerecord models via Ruby Gem0How to use Kaminari in an ActiveRecord dependent Gem that does not necessarily use Rails

Hot Network Questions

What will happen if someone/a group can’t be confirmed that he/she/they commited a crime?

Can a deterministic finite automaton ever go into an infinite loop?

How to show a “Yes” for a negative occurrence and “No” for a positive occurrence

How to deal with a promotion if you are not sure you want it?

Why do Counter-Strike players switch weapons so frequently?

Odds of rolling the same results twice on advantage rolls

What do the green, white and yellow bands mean on an airspeed indicator?

How to Force Evaluation of Derivative in a Pure Function Definition

Why is 2019-nCoV prioritized over other infectious diseases?

U.S. Army/Military’s response time to an army appearing in the middle of a major city

Arachnid fingers

Would this hit/miss houserule be balanced with bounded accuracy?

What made Jesus question at Mt 21:25 a good example for Christians or was it a bad question because the Jews could not answer?

Is Earth’s moon the only one where a total eclipse of the sun covers the entire sun?

Fifth year of my PhD and I hate my project. What should I do?

Why is it so difficult to collect Iowa caucus results as opposed to election results?

Is it bad to use special characters in passwords?

Concentric rings on a snub square tiling

It’s all about the sum of the digits

What happened to the WCC?

Why does the difference between 30 March and 1 March 2020 erroneously give 28 days instead of 29?

Is it neccessary to clear browser cache periodically?

94 Toyota Pickup hard to put into gear after clutch in too long

c++ Threads inside for loop print wrong values

more hot questions

Question feed

Subscribe to RSS

Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

default