Programs & Examples On #Uimodaltransitionstyle

The UIModalTransitionStlye is a enum created by Apple to set the transition style of the ViewController when "modally" presented.

UIAlertView first deprecated IOS 9

From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

So you should use something like this

UIAlertController * alert = [UIAlertController
                alertControllerWithTitle:@"Title"
                                 message:@"Message"
                          preferredStyle:UIAlertControllerStyleAlert];



UIAlertAction* yesButton = [UIAlertAction
                    actionWithTitle:@"Yes, please"
                              style:UIAlertActionStyleDefault
                            handler:^(UIAlertAction * action) {
                                //Handle your yes please button action here
                            }];

UIAlertAction* noButton = [UIAlertAction
                        actionWithTitle:@"No, thanks"
                                  style:UIAlertActionStyleDefault
                                handler:^(UIAlertAction * action) {
                                   //Handle no, thanks button                
                                }];

[alert addAction:yesButton];
[alert addAction:noButton];

[self presentViewController:alert animated:YES completion:nil];

How to check if a view controller is presented modally or pushed on a navigation stack?

If you are using ios 5.0 or later than please use this code

-(BOOL)isPresented
{
    if ([self isBeingPresented]) {
        // being presented
         return YES;
    } else if ([self isMovingToParentViewController]) {
        // being pushed
         return NO;
    } else {
        // simply showing again because another VC was dismissed
         return NO;
    }
}

modal View controllers - how to display and dismiss

This line:

[self dismissViewControllerAnimated:YES completion:nil];

isn't sending a message to itself, it's actually sending a message to its presenting VC, asking it to do the dismissing. When you present a VC, you create a relationship between the presenting VC and the presented one. So you should not destroy the presenting VC while it is presenting (the presented VC can't send that dismiss message back…). As you're not really taking account of it you are leaving the app in a confused state. See my answer Dismissing a Presented View Controller in which I recommend this method is more clearly written:

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

In your case, you need to ensure that all of the controlling is done in mainVC . You should use a delegate to send the correct message back to MainViewController from ViewController1, so that mainVC can dismiss VC1 and then present VC2.

In VC2 VC1 add a protocol in your .h file above the @interface:

@protocol ViewController1Protocol <NSObject>

    - (void)dismissAndPresentVC2;

@end

and lower down in the same file in the @interface section declare a property to hold the delegate pointer:

@property (nonatomic,weak) id <ViewController1Protocol> delegate;

In the VC1 .m file, the dismiss button method should call the delegate method

- (IBAction)buttonPressedFromVC1:(UIButton *)sender {
    [self.delegate dissmissAndPresentVC2]
}

Now in mainVC, set it as VC1's delegate when creating VC1:

- (IBAction)present1:(id)sender {
    ViewController1* vc = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil];
    vc.delegate = self;
    [self present:vc];
}

and implement the delegate method:

- (void)dismissAndPresent2 {
    [self dismissViewControllerAnimated:NO completion:^{
        [self present2:nil];
    }];
}

present2: can be the same method as your VC2Pressed: button IBAction method. Note that it is called from the completion block to ensure that VC2 is not presented until VC1 is fully dismissed.

You are now moving from VC1->VCMain->VC2 so you will probably want only one of the transitions to be animated.

update

In your comments you express surprise at the complexity required to achieve a seemingly simple thing. I assure you, this delegation pattern is so central to much of Objective-C and Cocoa, and this example is about the most simple you can get, that you really should make the effort to get comfortable with it.

In Apple's View Controller Programming Guide they have this to say:

Dismissing a Presented View Controller

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers.”

If you really think through what you want to achieve, and how you are going about it, you will realise that messaging your MainViewController to do all of the work is the only logical way out given that you don't want to use a NavigationController. If you do use a NavController, in effect you are 'delegating', even if not explicitly, to the navController to do all of the work. There needs to be some object that keeps a central track of what's going on with your VC navigation, and you need some method of communicating with it, whatever you do.

In practice Apple's advice is a little extreme... in normal cases, you don't need to make a dedicated delegate and method, you can rely on [self presentingViewController] dismissViewControllerAnimated: - it's when in cases like yours that you want your dismissing to have other effects on remote objects that you need to take care.

Here is something you could imagine to work without all the delegate hassle...

- (IBAction)dismiss:(id)sender {
    [[self presentingViewController] dismissViewControllerAnimated:YES 
                                                        completion:^{
        [self.presentingViewController performSelector:@selector(presentVC2:) 
                                            withObject:nil];
    }];

}

After asking the presenting controller to dismiss us, we have a completion block which calls a method in the presentingViewController to invoke VC2. No delegate needed. (A big selling point of blocks is that they reduce the need for delegates in these circumstances). However in this case there are a few things getting in the way...

  • in VC1 you don't know that mainVC implements the method present2 - you can end up with difficult-to-debug errors or crashes. Delegates help you to avoid this.
  • once VC1 is dismissed, it's not really around to execute the completion block... or is it? Does self.presentingViewController mean anything any more? You don't know (neither do I)... with a delegate, you don't have this uncertainty.
  • When I try to run this method, it just hangs with no warning or errors.

So please... take the time to learn delegation!

update2

In your comment you have managed to make it work by using this in VC2's dismiss button handler:

 [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil]; 

This is certainly much simpler, but it leaves you with a number of issues.

Tight coupling
You are hard-wiring your viewController structure together. For example, if you were to insert a new viewController before mainVC, your required behaviour would break (you would navigate to the prior one). In VC1 you have also had to #import VC2. Therefore you have quite a lot of inter-dependencies, which breaks OOP/MVC objectives.

Using delegates, neither VC1 nor VC2 need to know anything about mainVC or it's antecedents so we keep everything loosely-coupled and modular.

Memory
VC1 has not gone away, you still hold two pointers to it:

  • mainVC's presentedViewController property
  • VC2's presentingViewController property

You can test this by logging, and also just by doing this from VC2

[self dismissViewControllerAnimated:YES completion:nil]; 

It still works, still gets you back to VC1.

That seems to me like a memory leak.

The clue to this is in the warning you are getting here:

[self presentViewController:vc2 animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
 // Attempt to dismiss from view controller <VC1: 0x715e460>
 // while a presentation or dismiss is in progress!

The logic breaks down, as you are attempting to dismiss the presenting VC of which VC2 is the presented VC. The second message doesn't really get executed - well perhaps some stuff happens, but you are still left with two pointers to an object you thought you had got rid of. (edit - I've checked this and it's not so bad, both objects do go away when you get back to mainVC)

That's a rather long-winded way of saying - please, use delegates. If it helps, I made another brief description of the pattern here:
Is passing a controller in a construtor always a bad practice?

update 3
If you really want to avoid delegates, this could be the best way out:

In VC1:

[self presentViewController:VC2
                   animated:YES
                 completion:nil];

But don't dismiss anything... as we ascertained, it doesn't really happen anyway.

In VC2:

[self.presentingViewController.presentingViewController 
    dismissViewControllerAnimated:YES
                       completion:nil];

As we (know) we haven't dismissed VC1, we can reach back through VC1 to MainVC. MainVC dismisses VC1. Because VC1 has gone, it's presented VC2 goes with it, so you are back at MainVC in a clean state.

It's still highly coupled, as VC1 needs to know about VC2, and VC2 needs to know that it was arrived at via MainVC->VC1, but it's the best you're going to get without a bit of explicit delegation.

presentViewController and displaying navigation bar

All a [self.navigationController pushViewController:controller animated:YES]; does is animate a transition, and add it to the navigation controller stack, and some other cool navigation bar animation stuffs. If you don't care about the bar animation, then this code should work. The bar does appear on the new controller, and you get an interactive pop gesture!

//Make Controller
DetailViewController *controller = [[DetailViewController alloc] initWithNibName:nil                                                                                 
                                    bundle:[NSBundle mainBundle]];  
//Customize presentation
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
controller.modalPresentationStyle = UIModalPresentationCurrentContext;

//Present controller
[self presentViewController:controller 
                   animated:YES 
                 completion:nil];
//Add to navigation Controller
[self navigationController].viewControllers = [[self navigationController].viewControllers arrayByAddingObject:controller];
//You can't just [[self navigationController].viewControllers addObject:controller] because viewControllers are for some reason not a mutable array.

Edit: Sorry, presentViewController will fill the full screen. You will need to make a custom transition, with CGAffineTransform.translation or something, animate the controller with the transition, then add it to the navigationController's viewControllers.

What should I set JAVA_HOME environment variable on macOS X 10.6?

For me maven seems to work off the .mavenrc file:

echo "export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)" > ~/.mavenrc

I'm sure I picked it up on SO too, just can't remember where.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

I solved the same problem by changing this from false to true. in the end I went into the database and changed my bit field to allow null, and then refreshed my xsd, and refreshed my wsdl and reference.cs and now all is well.

this.columnAttachPDFToEmailFlag.AllowDBNull = true;

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

xml.LoadData - Data at the root level is invalid. Line 1, position 1

If your xml is in a string use the following to remove any byte order mark:

        xml = new Regex("\\<\\?xml.*\\?>").Replace(xml, "");

Scrollview vertical and horizontal in android

since the Two Dimensional Scrollview link is dead I could not get it so I created my own component. It handles flinging and works properly for me. The only restriction is that wrap_content might not work properly for that component.

https://gist.github.com/androidseb/9902093

How to write to a file in Scala?

Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:

// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")

It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations

List of ANSI color escape sequences

The ANSI escape sequences you're looking for are the Select Graphic Rendition subset. All of these have the form

\033[XXXm

where XXX is a series of semicolon-separated parameters.

To say, make text red, bold, and underlined (we'll discuss many other options below) in C you might write:

printf("\033[31;1;4mHello\033[0m");

In C++ you'd use

std::cout<<"\033[31;1;4mHello\033[0m";

In Python3 you'd use

print("\033[31;1;4mHello\033[0m")

and in Bash you'd use

echo -e "\033[31;1;4mHello\033[0m"

where the first part makes the text red (31), bold (1), underlined (4) and the last part clears all this (0).

As described in the table below, there are a large number of text properties you can set, such as boldness, font, underlining, &c. (Isn't it silly that StackOverflow doesn't allow you to put proper tables in answers?)

Font Effects

Code Effect Note
0 Reset / Normal all attributes off
1 Bold or increased intensity
2 Faint (decreased intensity) Not widely supported.
3 Italic Not widely supported. Sometimes treated as inverse.
4 Underline
5 Slow Blink less than 150 per minute
6 Rapid Blink MS-DOS ANSI.SYS; 150+ per minute; not widely supported
7 [[reverse video]] swap foreground and background colors
8 Conceal Not widely supported.
9 Crossed-out Characters legible, but marked for deletion. Not widely supported.
10 Primary(default) font
11–19 Alternate font Select alternate font n-10
20 Fraktur hardly ever supported
21 Bold off or Double Underline Bold off not widely supported; double underline hardly ever supported.
22 Normal color or intensity Neither bold nor faint
23 Not italic, not Fraktur
24 Underline off Not singly or doubly underlined
25 Blink off
27 Inverse off
28 Reveal conceal off
29 Not crossed out
30–37 Set foreground color See color table below
38 Set foreground color Next arguments are 5;<n> or 2;<r>;<g>;<b>, see below
39 Default foreground color implementation defined (according to standard)
40–47 Set background color See color table below
48 Set background color Next arguments are 5;<n> or 2;<r>;<g>;<b>, see below
49 Default background color implementation defined (according to standard)
51 Framed
52 Encircled
53 Overlined
54 Not framed or encircled
55 Not overlined
60 ideogram underline hardly ever supported
61 ideogram double underline hardly ever supported
62 ideogram overline hardly ever supported
63 ideogram double overline hardly ever supported
64 ideogram stress marking hardly ever supported
65 ideogram attributes off reset the effects of all of 60-64
90–97 Set bright foreground color aixterm (not in standard)
100–107 Set bright background color aixterm (not in standard)

2-bit Colours

You've got this already!

4-bit Colours

The standards implementing terminal colours began with limited (4-bit) options. The table below lists the RGB values of the background and foreground colours used for these by a variety of terminal emulators:

Table of ANSI colours implemented by various terminal emulators

Using the above, you can make red text on a green background (but why?) using:

\033[31;42m

11 Colours (An Interlude)

In their book "Basic Color Terms: Their Universality and Evolution", Brent Berlin and Paul Kay used data collected from twenty different languages from a range of language families to identify eleven possible basic color categories: white, black, red, green, yellow, blue, brown, purple, pink, orange, and gray.

Berlin and Kay found that, in languages with fewer than the maximum eleven color categories, the colors followed a specific evolutionary pattern. This pattern is as follows:

  1. All languages contain terms for black (cool colours) and white (bright colours).
  2. If a language contains three terms, then it contains a term for red.
  3. If a language contains four terms, then it contains a term for either green or yellow (but not both).
  4. If a language contains five terms, then it contains terms for both green and yellow.
  5. If a language contains six terms, then it contains a term for blue.
  6. If a language contains seven terms, then it contains a term for brown.
  7. If a language contains eight or more terms, then it contains terms for purple, pink, orange or gray.

This may be why story Beowulf only contains the colours black, white, and red. It may also be why the Bible does not contain the colour blue. Homer's Odyssey contains black almost 200 times and white about 100 times. Red appears 15 times, while yellow and green appear only 10 times. (More information here)

Differences between languages are also interesting: note the profusion of distinct colour words used by English vs. Chinese. However, digging deeper into these languages shows that each uses colour in distinct ways. (More information)

Chinese vs English colour names. Image adapted from "muyueh.com"

Generally speaking, the naming, use, and grouping of colours in human languages is fascinating. Now, back to the show.

8-bit (256) colours

Technology advanced, and tables of 256 pre-selected colours became available, as shown below.

256-bit colour mode for ANSI escape sequences

Using these above, you can make pink text like so:

\033[38;5;206m     #That is, \033[38;5;<FG COLOR>m

And make an early-morning blue background using

\033[48;5;57m      #That is, \033[48;5;<BG COLOR>m

And, of course, you can combine these:

\033[38;5;206;48;5;57m

The 8-bit colours are arranged like so:

0x00-0x07:  standard colors (same as the 4-bit colours)
0x08-0x0F:  high intensity colors
0x10-0xE7:  6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 = r, g, b = 5)
0xE8-0xFF:  grayscale from black to white in 24 steps

ALL THE COLOURS

Now we are living in the future, and the full RGB spectrum is available using:

\033[38;2;<r>;<g>;<b>m     #Select RGB foreground color
\033[48;2;<r>;<g>;<b>m     #Select RGB background color

So you can put pinkish text on a brownish background using

\033[38;2;255;82;197;48;2;155;106;0mHello

Support for "true color" terminals is listed here.

Much of the above is drawn from the Wikipedia page "ANSI escape code".

A Handy Script to Remind Yourself

Since I'm often in the position of trying to remember what colours are what, I have a handy script called: ~/bin/ansi_colours:

#!/usr/bin/python

print "\\033[XXm"

for i in range(30,37+1):
    print "\033[%dm%d\t\t\033[%dm%d" % (i,i,i+60,i+60);

print "\033[39m\\033[39m - Reset colour"
print "\\033[2K - Clear Line"
print "\\033[<L>;<C>H OR \\033[<L>;<C>f puts the cursor at line L and column C."
print "\\033[<N>A Move the cursor up N lines"
print "\\033[<N>B Move the cursor down N lines"
print "\\033[<N>C Move the cursor forward N columns"
print "\\033[<N>D Move the cursor backward N columns"
print "\\033[2J Clear the screen, move to (0,0)"
print "\\033[K Erase to end of line"
print "\\033[s Save cursor position"
print "\\033[u Restore cursor position"
print " "
print "\\033[4m  Underline on"
print "\\033[24m Underline off"
print "\\033[1m  Bold on"
print "\\033[21m Bold off"

This prints

Simple ANSI colours

What is the difference between a static and a non-static initialization code block

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

Get IFrame's document, from JavaScript in main document

The problem is that in IE (which is what I presume you're testing in), the <iframe> element has a document property that refers to the document containing the iframe, and this is getting used before the contentDocument or contentWindow.document properties. What you need is:

function GetDoc(x) {
    return x.contentDocument || x.contentWindow.document;
}

Also, document.all is not available in all browsers and is non-standard. Use document.getElementById() instead.

DB query builder toArray() laravel 4

try this one

DB::table('user')->where('name','Jhon')->get();

just remove the "=" sign . . . .because you are trying to array just the name 'jhon' . . . . . . . .I hope it's help you . .

how to set image from url for imageView

EDIT:

Create a class that extends AsyncTask

public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {

    private String url;
    private ImageView imageView;

    public ImageLoadTask(String url, ImageView imageView) {
        this.url = url;
        this.imageView = imageView;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        try {
            URL urlConnection = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) urlConnection
                    .openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap myBitmap = BitmapFactory.decodeStream(input);
            return myBitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        imageView.setImageBitmap(result);
    }

}

And call this like new ImageLoadTask(url, imageView).execute();

Direct method:

Use this method and pass your url as string. It returns a bitmap. Set the bitmap to your ImageView.

public static Bitmap getBitmapFromURL(String src) {
    try {
        Log.e("src",src);
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        Log.e("Bitmap","returned");
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e("Exception",e.getMessage());
        return null;
    }
}

And then this to ImageView like so:

imageView.setImageBitmap(getBitmapFromURL(url));

And dont forget about this permission in maifest.

<uses-permission android:name="android.permission.INTERNET" />

NOTE:

Try to call this method from another thread or AsyncTask because we are performing networking operations.

How can I get LINQ to return the object which has the max value for a given property?

In LINQ you can solve it the following way:

Item itemMax = (from i in items
     let maxId = items.Max(m => m.ID)
     where i.ID == maxId
     select i).FirstOrDefault();

SSL: CERTIFICATE_VERIFY_FAILED with Python3

I had this problem in MacOS, and I solved it by linking the brew installed python 3 version, with

brew link python3

After that, it worked without a problem.

Remove an element from a Bash array

#/bin/bash

echo "# define array with six elements"
arr=(zero one two three 'four 4' five)

echo "# unset by index: 0"
unset -v 'arr[0]'
for i in ${!arr[*]}; do echo "arr[$i]=${arr[$i]}"; done

arr_delete_by_content() { # value to delete
        for i in ${!arr[*]}; do
                [ "${arr[$i]}" = "$1" ] && unset -v 'arr[$i]'
        done
        }

echo "# unset in global variable where value: three"
arr_delete_by_content three
for i in ${!arr[*]}; do echo "arr[$i]=${arr[$i]}"; done

echo "# rearrange indices"
arr=( "${arr[@]}" )
for i in ${!arr[*]}; do echo "arr[$i]=${arr[$i]}"; done

delete_value() { # value arrayelements..., returns array decl.
        local e val=$1; new=(); shift
        for e in "${@}"; do [ "$val" != "$e" ] && new+=("$e"); done
        declare -p new|sed 's,^[^=]*=,,'
        }

echo "# new array without value: two"
declare -a arr="$(delete_value two "${arr[@]}")"
for i in ${!arr[*]}; do echo "arr[$i]=${arr[$i]}"; done

delete_values() { # arraydecl values..., returns array decl. (keeps indices)
        declare -a arr="$1"; local i v; shift
        for v in "${@}"; do 
                for i in ${!arr[*]}; do
                        [ "$v" = "${arr[$i]}" ] && unset -v 'arr[$i]'
                done
        done
        declare -p arr|sed 's,^[^=]*=,,'
        }
echo "# new array without values: one five (keep indices)"
declare -a arr="$(delete_values "$(declare -p arr|sed 's,^[^=]*=,,')" one five)"
for i in ${!arr[*]}; do echo "arr[$i]=${arr[$i]}"; done

# new array without multiple values and rearranged indices is left to the reader

Bootstrap 3: How do you align column content to bottom of row

You can use display: table-cell and vertical-align: bottom, on the 2 columns that you want to be aligned bottom, like so:

.bottom-column
{
    float: none;
    display: table-cell;
    vertical-align: bottom;
}

Working example here.

Also, this might be a possible duplicate question.

Do I need <class> elements in persistence.xml?

In Java SE environment, by specification you have to specify all classes as you have done:

A list of all named managed persistence classes must be specified in Java SE environments to insure portability

and

If it is not intended that the annotated persistence classes contained in the root of the persistence unit be included in the persistence unit, the exclude-unlisted-classes element should be used. The exclude-unlisted-classes element is not intended for use in Java SE environments.

(JSR-000220 6.2.1.6)

In Java EE environments, you do not have to do this as the provider scans for annotations for you.

Unofficially, you can try to set <exclude-unlisted-classes>false</exclude-unlisted-classes> in your persistence.xml. This parameter defaults to false in EE and truein SE. Both EclipseLink and Toplink supports this as far I can tell. But you should not rely on it working in SE, according to spec, as stated above.

You can TRY the following (may or may not work in SE-environments):

<persistence-unit name="eventractor" transaction-type="RESOURCE_LOCAL">
     <exclude-unlisted-classes>false</exclude-unlisted-classes>

    <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate" />
            <property name="hibernate.show_sql" value="true" />
    </properties>
</persistence-unit>

Real time data graphing on a line chart with html5

This thread is perhaps very very old now. But want to share these results for someone who see this thread. Ran a comparison betn. Flotr2, ChartJS, highcharts asynchronously. Flotr2 seems to be the quickest. Tested this by passing a new data point every 50ms upto 1000 data points totally. Flotr2 was the quickest for me though it appears to be redrawing charts regularly.

http://jsperf.com/async-charts-test/2

Python CSV error: line contains NULL byte

For all those 'rU' filemode haters: I just tried opening a CSV file from a Windows machine on a Mac with the 'rb' filemode and I got this error from the csv module:

Error: new-line character seen in unquoted field - do you need to 
open the file in universal-newline mode?

Opening the file in 'rU' mode works fine. I love universal-newline mode -- it saves me so much hassle.

How to pass a value from one Activity to another in Android?

Thats trivial, use Intent.putExtra to pass data to activity you start. Use then Bundle.getExtra to retrieve it.

There are lots of such questions already https://stackoverflow.com/search?q=How+to+pass+a+value+from+one+Activity+to+another+in+Android be sure to use search first next time.

typescript - cloning object

Solving The Specific Issue

You can use a type assertion to tell the compiler that you know better:

public clone(): any {
    var cloneObj = new (this.constructor() as any);
    for (var attribut in this) {
        if (typeof this[attribut] === "object") {
            cloneObj[attribut] = this[attribut].clone();
        } else {
            cloneObj[attribut] = this[attribut];
        }
    }
    return cloneObj;
}

Cloning

Bear in mind that sometimes it is better to write your own mapping - rather than being totally dynamic. However, there are a few "cloning" tricks you can use that give you difference effects.

I will use the following code for all the subsequent examples:

class Example {
  constructor(public type: string) {

  }
}

class Customer {
  constructor(public name: string, public example: Example) {

  }

  greet() {
    return 'Hello ' + this.name;
  }
}

var customer = new Customer('David', new Example('DavidType'));

Option 1: Spread

Properties: Yes
Methods: No
Deep Copy: No

var clone = { ...customer };

alert(clone.name + ' ' + clone.example.type); // David DavidType
//alert(clone.greet()); // Not OK

clone.name = 'Steve';
clone.example.type = 'SteveType';

alert(customer.name + ' ' + customer.example.type); // David SteveType

Option 2: Object.assign

Properties: Yes
Methods: No
Deep Copy: No

var clone = Object.assign({}, customer);

alert(clone.name + ' ' + clone.example.type); // David DavidType
alert(clone.greet()); // Not OK, although compiler won't spot it

clone.name = 'Steve';
clone.example.type = 'SteveType';

alert(customer.name + ' ' + customer.example.type); // David SteveType

Option 3: Object.create

Properties: Inherited
Methods: Inherited
Deep Copy: Shallow Inherited (deep changes affect both original and clone)

var clone = Object.create(customer);

alert(clone.name + ' ' + clone.example.type); // David DavidType
alert(clone.greet()); // OK

customer.name = 'Misha';
customer.example = new Example("MishaType");

// clone sees changes to original 
alert(clone.name + ' ' + clone.example.type); // Misha MishaType

clone.name = 'Steve';
clone.example.type = 'SteveType';

// original sees changes to clone
alert(customer.name + ' ' + customer.example.type); // Misha SteveType

Option 4: Deep Copy Function

Properties: Yes
Methods: No
Deep Copy: Yes

function deepCopy(obj) {
    var copy;

    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = deepCopy(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = deepCopy(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

var clone = deepCopy(customer) as Customer;

alert(clone.name + ' ' + clone.example.type); // David DavidType
// alert(clone.greet()); // Not OK - not really a customer

clone.name = 'Steve';
clone.example.type = 'SteveType';

alert(customer.name + ' ' + customer.example.type); // David DavidType

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

Please find below codes for ios 10 request permission sample for info.plist.
You can modify for your custom message.

    <key>NSCameraUsageDescription</key>
    <string>${PRODUCT_NAME} Camera Usage</string>

    <key>NSBluetoothPeripheralUsageDescription</key>
    <string>${PRODUCT_NAME} BluetoothPeripheral</string>

    <key>NSCalendarsUsageDescription</key>
    <string>${PRODUCT_NAME} Calendar Usage</string>

    <key>NSContactsUsageDescription</key>
    <string>${PRODUCT_NAME} Contact fetch</string>

    <key>NSHealthShareUsageDescription</key>
    <string>${PRODUCT_NAME} Health Description</string>

    <key>NSHealthUpdateUsageDescription</key>
    <string>${PRODUCT_NAME} Health Updates</string>

    <key>NSHomeKitUsageDescription</key>
    <string>${PRODUCT_NAME} HomeKit Usage</string>

    <key>NSLocationAlwaysUsageDescription</key>
    <string>${PRODUCT_NAME} Use location always</string>

    <key>NSLocationUsageDescription</key>
    <string>${PRODUCT_NAME} Location Updates</string>

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>${PRODUCT_NAME} WhenInUse Location</string>

    <key>NSAppleMusicUsageDescription</key>
    <string>${PRODUCT_NAME} Music Usage</string>

    <key>NSMicrophoneUsageDescription</key>
    <string>${PRODUCT_NAME} Microphone Usage</string>

    <key>NSMotionUsageDescription</key>
    <string>${PRODUCT_NAME} Motion Usage</string>

    <key>kTCCServiceMediaLibrary</key>
    <string>${PRODUCT_NAME} MediaLibrary Usage</string>

    <key>NSPhotoLibraryUsageDescription</key>
    <string>${PRODUCT_NAME} PhotoLibrary Usage</string>

    <key>NSRemindersUsageDescription</key>
    <string>${PRODUCT_NAME} Reminder Usage</string>

    <key>NSSiriUsageDescription</key>
    <string>${PRODUCT_NAME} Siri Usage</string>

    <key>NSSpeechRecognitionUsageDescription</key>
    <string>${PRODUCT_NAME} Speech Recognition Usage</string>

    <key>NSVideoSubscriberAccountUsageDescription</key>
    <string>${PRODUCT_NAME} Video Subscribe Usage</string>

iOS 11 and plus, If you want to add photo/image to your library then you must add this key

    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>${PRODUCT_NAME} library Usage</string>

'uint32_t' identifier not found error

There is an implementation available at the msinttypes project page - "This project fills the absence of stdint.h and inttypes.h in Microsoft Visual Studio".

I don't have experience with this implementation, but I've seen it recommended by others on SO.

SQL Server - SELECT FROM stored procedure

You can

  1. create a table variable to hold the result set from the stored proc and then
  2. insert the output of the stored proc into the table variable, and then
  3. use the table variable exactly as you would any other table...

... sql ....

Declare @T Table ([column definitions here])
Insert @T Exec storedProcname params 
Select * from @T Where ...

Check that an email address is valid on iOS

to validate the email string you will need to write a regular expression to check it is in the correct form. there are plenty out on the web but be carefull as some can exclude what are actually legal addresses.

essentially it will look something like this

^((?>[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+\x20*|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*"\x20*)*(?<angle><))?((?!\.)(?>\.?[a-zA-Z\d!#$%&'*+\-/=?^_`{|}~]+)+|"((?=[\x01-\x7f])[^"\\]|\\[\x01-\x7f])*")@(((?!-)[a-zA-Z\d\-]+(?<!-)\.)+[a-zA-Z]{2,}|\[(((?(?<!\[)\.)(25[0-5]|2[0-4]\d|[01]?\d?\d)){4}|[a-zA-Z\d\-]*[a-zA-Z\d]:((?=[\x01-\x7f])[^\\\[\]]|\\[\x01-\x7f])+)\])(?(angle)>)$

Actually checking if the email exists and doesn't bounce would mean sending an email and seeing what the result was. i.e. it bounced or it didn't. However it might not bounce for several hours or not at all and still not be a "real" email address. There are a number of services out there which purport to do this for you and would probably be paid for by you and quite frankly why bother to see if it is real?

It is good to check the user has not misspelt their email else they could enter it incorrectly, not realise it and then get hacked of with you for not replying. However if someone wants to add a bum email address there would be nothing to stop them creating it on hotmail or yahoo (or many other places) to gain the same end.

So do the regular expression and validate the structure but forget about validating against a service.

How to duplicate sys.stdout to a log file?

(Ah, just re-read your question and see that this doesn't quite apply.)

Here is a sample program that makes uses the python logging module. This logging module has been in all versions since 2.3. In this sample the logging is configurable by command line options.

In quite mode it will only log to a file, in normal mode it will log to both a file and the console.

import os
import sys
import logging
from optparse import OptionParser

def initialize_logging(options):
    """ Log information based upon users options"""

    logger = logging.getLogger('project')
    formatter = logging.Formatter('%(asctime)s %(levelname)s\t%(message)s')
    level = logging.__dict__.get(options.loglevel.upper(),logging.DEBUG)
    logger.setLevel(level)

    # Output logging information to screen
    if not options.quiet:
        hdlr = logging.StreamHandler(sys.stderr)
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)

    # Output logging information to file
    logfile = os.path.join(options.logdir, "project.log")
    if options.clean and os.path.isfile(logfile):
        os.remove(logfile)
    hdlr2 = logging.FileHandler(logfile)
    hdlr2.setFormatter(formatter)
    logger.addHandler(hdlr2)

    return logger

def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    # Setup command line options
    parser = OptionParser("usage: %prog [options]")
    parser.add_option("-l", "--logdir", dest="logdir", default=".", help="log DIRECTORY (default ./)")
    parser.add_option("-v", "--loglevel", dest="loglevel", default="debug", help="logging level (debug, info, error)")
    parser.add_option("-q", "--quiet", action="store_true", dest="quiet", help="do not log to console")
    parser.add_option("-c", "--clean", dest="clean", action="store_true", default=False, help="remove old log file")

    # Process command line options
    (options, args) = parser.parse_args(argv)

    # Setup logger format and output locations
    logger = initialize_logging(options)

    # Examples
    logger.error("This is an error message.")
    logger.info("This is an info message.")
    logger.debug("This is a debug message.")

if __name__ == "__main__":
    sys.exit(main())

How to push local changes to a remote git repository on bitbucket

Meaning the 2nd parameter('master') of the "git push" command -

$ git push origin master

can be made clear by initiating "push" command from 'news-item' branch. It caused local "master" branch to be pushed to the remote 'master' branch. For more information refer

https://git-scm.com/docs/git-push

where <refspec> in

[<repository> [<refspec>…?]

is written to mean "specify what destination ref to update with what source object."

For your reference, here is a screen capture how I verified this statement.

<code>enter image description here</code>

Difference between margin and padding?

Padding is the space between you content and the border. Where as Margin is the space between the border and the other element.

Disposing WPF User Controls

I use the following Interactivity Behavior to provide an unloading event to WPF UserControls. You can include the behavior in the UserControls XAML. So you can have the functionality without placing the logic it in every single UserControl.

XAML declaration:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

<i:Interaction.Behaviors>
    <behaviors:UserControlSupportsUnloadingEventBehavior UserControlClosing="UserControlClosingHandler" />
</i:Interaction.Behaviors>

CodeBehind handler:

private void UserControlClosingHandler(object sender, EventArgs e)
{
    // to unloading stuff here
}

Behavior Code:

/// <summary>
/// This behavior raises an event when the containing window of a <see cref="UserControl"/> is closing.
/// </summary>
public class UserControlSupportsUnloadingEventBehavior : System.Windows.Interactivity.Behavior<UserControl>
{
    protected override void OnAttached()
    {
        AssociatedObject.Loaded += UserControlLoadedHandler;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Loaded -= UserControlLoadedHandler;
        var window = Window.GetWindow(AssociatedObject);
        if (window != null)
            window.Closing -= WindowClosingHandler;
    }

    /// <summary>
    /// Registers to the containing windows Closing event when the UserControl is loaded.
    /// </summary>
    private void UserControlLoadedHandler(object sender, RoutedEventArgs e)
    {
        var window = Window.GetWindow(AssociatedObject);
        if (window == null)
            throw new Exception(
                "The UserControl {0} is not contained within a Window. The UserControlSupportsUnloadingEventBehavior cannot be used."
                    .FormatWith(AssociatedObject.GetType().Name));

        window.Closing += WindowClosingHandler;
    }

    /// <summary>
    /// The containing window is closing, raise the UserControlClosing event.
    /// </summary>
    private void WindowClosingHandler(object sender, CancelEventArgs e)
    {
        OnUserControlClosing();
    }

    /// <summary>
    /// This event will be raised when the containing window of the associated <see cref="UserControl"/> is closing.
    /// </summary>
    public event EventHandler UserControlClosing;

    protected virtual void OnUserControlClosing()
    {
        var handler = UserControlClosing;
        if (handler != null) 
            handler(this, EventArgs.Empty);
    }
}

window.open(url, '_blank'); not working on iMac/Safari

window.location.assign(url) this fixs the window.open(url) issue in ios devices

Iterating through all nodes in XML file

You can use XmlDocument. Also some XPath can be useful.

Just a simple example

XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
   // use node variable here for your beeds
}

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Use data type 'MultilineText':

[DataType(DataType.MultilineText)]
public string Text { get; set; }

See ASP.NET MVC3 - textarea with @Html.EditorFor

Stopping Excel Macro executution when pressing Esc won't work

Sometimes, the right set of keys (Pause, Break or ScrLk) are not available on the keyboard (mostly happens with laptop users) and pressing Esc 2, 3 or multiple times doesn't halt the macro too.

I got stuck too and eventually found the solution in accessibility feature of Windows after which I tried all the researched options and 3 of them worked for me in 3 different scenarios.

Step #01: If your keyboard does not have a specific key, please do not worry and open the 'OnScreen Keyboard' from Windows Utilities by pressing Win + U.

Step #02: Now, try any of the below option and of them will definitely work depending on your system architecture i.e. OS and Office version

  • Ctrl + Pause
  • Ctrl + ScrLk
  • Esc + Esc (Press twice consecutively)

You will be put into break mode using the above key combinations as the macro suspends execution immediately finishing the current task. For eg. if it is pulling the data from web then it will halt immediately before execting any next command but after pulling the data, following which one can press F5 or F8 to continue the debugging.

How to track down access violation "at address 00000000"

An access violation at anywhere near adress '00000000' indicates a null pointer access. You're using something before it's ever been created, most likely, or after it's been FreeAndNil()'d.

A lot of times this is caused by accessing a component in the wrong place during form creation, or by having your main form try and access something in a datamodule that hasn't been created yet.

MadExcept makes it pretty easy to track these things down, and is free for non-commercial use. (Actually, a commercial use license is pretty inexpensive as well, and well worth the money.)

Validation of radio button group using jQuery validation plugin

Another way to validate is like this.

var $radio = $('input:radio[name="nameRadioButton"]');
$radio.addClass("validate[required]");

I hope my example will help you

What's the difference between :: (double colon) and -> (arrow) in PHP?

:: is used in static context, ie. when some method or property is declared as static:

class Math {
    public static function sin($angle) {
        return ...;
    }
}

$result = Math::sin(123);

Also, the :: operator (the Scope Resolution Operator, a.k.a Paamayim Nekudotayim) is used in dynamic context when you invoke a method/property of a parent class:

class Rectangle {
     protected $x, $y;

     public function __construct($x, $y) {
         $this->x = $x;
         $this->y = $y;
     }
}

class Square extends Rectangle {
    public function __construct($x) {
        parent::__construct($x, $x);
    }
}

-> is used in dynamic context, ie. when you deal with some instance of some class:

class Hello {
    public function say() {
       echo 'hello!';
    }
}

$h = new Hello();
$h->say();

By the way: I don't think that using Symfony is a good idea when you don't have any OOP experience.

How to tell which disk Windows Used to Boot

That depends on your definition of which disk drive Windows used to boot. I can think of 3 different answers on a standard BIOS system (who knows what an EFI system does):

  1. The drive that contains the active MBR
  2. The active partition, with NTLDR (the system partition)
  3. The partition with Windows on it (the boot partition)

2 and 3 should be easy to find - I'm not so sure about 1. Though you can raw disk read to find an MBR, that doesn't mean it's the BIOS boot device this time or even next time (you could have multiple disks with MBRs).

You really can't even be sure that the PC was started from a hard drive - it's perfectly possible to boot Windows from a floppy. In that case, both 1 and 2 would technically be a floppy disk, though 3 would remain C:\Windows.

You might need to be a bit more specific in your requirements or goals.

PHP Sort a multidimensional array by element containing date

Use usort() and a custom comparison function:

function date_compare($a, $b)
{
    $t1 = strtotime($a['datetime']);
    $t2 = strtotime($b['datetime']);
    return $t1 - $t2;
}    
usort($array, 'date_compare');

EDIT: Your data is organized in an array of arrays. To better distinguish those, let's call the inner arrays (data) records, so that your data really is an array of records.

usort will pass two of these records to the given comparison function date_compare() at a a time. date_compare then extracts the "datetime" field of each record as a UNIX timestamp (an integer), and returns the difference, so that the result will be 0 if both dates are equal, a positive number if the first one ($a) is larger or a negative value if the second argument ($b) is larger. usort() uses this information to sort the array.

Make new column in Panda dataframe by adding values from other columns

Concerning n00b's comment: "I get the following warning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead"

I was getting the same error. In my case it was because I was trying to perform the column addition on a dataframe that was created like this:

df_b = df[['colA', 'colB', 'colC']]

instead of:

df_c = pd.DataFrame(df, columns=['colA', 'colB', 'colC'])

df_b is a copy of a slice from df
df_c is an new dataframe. So

df_c['colD'] = df['colA'] + df['colB']+ df['colC']

will add the columns and won't raise any warning. Same if .sum(axis=1) is used.

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

When you see "Verify return code: 19 (self signed certificate in certificate chain)", then, either the servers is really trying to use a self-signed certificate (which a client is never going to be able to verify), or OpenSSL hasn't got access to the necessary root but the server is trying to provide it itself (which it shouldn't do because it's pointless - a client can never trust a server to supply the root corresponding to the server's own certificate).

Again, adding -showcerts will help you diagnose which.

Does an HTTP Status code of 0 have any meaning?

Know it's an old post. But these issues still exist.

Here are some of my findings on the subject, grossly explained.

"Status" 0 means one of 3 things, as per the XMLHttpRequest spec:

  • dns name resolution failed (that's for instance when network plug is pulled out)

  • server did not answer (a.k.a. unreachable or unresponding)

  • request was aborted because of a CORS issue (abortion is performed by the user-agent and follows a failing OPTIONS pre-flight).

If you want to go further, dive deep into the inners of XMLHttpRequest. I suggest reading the ready-state update sequence ([0,1,2,3,4] is the normal sequence, [0,1,4] corresponds to status 0, [0,1,2,4] means no content sent which may be an error or not). You may also want to attach listeners to the xhr (onreadystatechange, onabort, onerror, ontimeout) to figure out details.

From the spec (XHR Living spec):

const unsigned short UNSENT = 0;
const unsigned short OPENED = 1;
const unsigned short HEADERS_RECEIVED = 2;
const unsigned short LOADING = 3;
const unsigned short DONE = 4;

How do I compare a value to a backslash?

When you only need to check for equality, you can also simply use the in operator to do a membership test in a sequence of accepted elements:

if message.value[0] in ('/', '\\'):
    do_stuff()

Making the Android emulator run faster

Edit Although using the Intel images gets some performance gains, the performance gained by using Genymotion is much greater. See Paul Lammertsma's answer.

Previous Answer

With ADT rev 17 the emulator supports running x86 system images in virtualization mode on Windows and Mac OS X. This has a noticeable impact on performance.

ADT rev 17 notes: http://android-developers.blogspot.jp/2012/03/updated-sdk-tools-and-adt-revision-17.html

Configuring Virtual Machine Acceleration: http://developer.android.com/guide/developing/devices/emulator.html#accel-vm

MVC 5 Access Claims Identity User Data

You can also do this.

IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;

Use of Application.DoEvents()

Yes, there is a static DoEvents method in the Application class in the System.Windows.Forms namespace. System.Windows.Forms.Application.DoEvents() can be used to process the messages waiting in the queue on the UI thread when performing a long-running task in the UI thread. This has the benefit of making the UI seem more responsive and not "locked up" while a long task is running. However, this is almost always NOT the best way to do things. According to Microsoft calling DoEvents "...causes the current thread to be suspended while all waiting window messages are processed." If an event is triggered there is a potential for unexpected and intermittent bugs that are difficult to track down. If you have an extensive task it is far better to do it in a separate thread. Running long tasks in a separate thread allows them to be processed without interfering with the UI continuing to run smoothly. Look here for more details.

Here is an example of how to use DoEvents; note that Microsoft also provides a caution against using it.

What characters are valid for JavaScript variable names?

Javascript Variables

You can start a variable with any letter, $, or _ character. As long as it doesn't start with a number, you can include numbers as well.

Start: [a-z], $, _

Contain: [a-z], [0-9], $, _

jQuery

You can use _ for your library so that it will stand side-by-side with jQuery. However, there is a configuration you can set so that jQuery will not use $. It will instead use jQuery. To do this, simply set:

jQuery.noConflict();

This page explains how to do this.

Printing Even and Odd using two Threads in Java

Here is the working code to print odd even no alternatively using wait and notify mechanism. I have restrict the limit of numbers to print 1 to 50.

public class NotifyTest {
    Object ob=new Object(); 

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    NotifyTest nt=new NotifyTest();

    even e=new even(nt.ob);     
    odd o=new odd(nt.ob);

    Thread t1=new Thread(e);
    Thread t2=new Thread(o);

    t1.start();     
    t2.start();
    }
}    

class even implements Runnable
{
    Object lock;        
    int i=2;

    public even(Object ob)
    {
        this.lock=ob;       
    }

    @Override
    public void run() {
    // TODO Auto-generated method stub      
        while(i<=50)
        {
            synchronized (lock) {               
            try {
                lock.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("Even Thread Name-->>" + Thread.currentThread().getName() + "Value-->>" + i);
            i=i+2;              
        }           
    }       
} 

class odd implements Runnable
{

    Object lock;
    int i=1;    

    public odd(Object ob)
    {
        this.lock=ob;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while(i<=49)
        {
            synchronized (lock) {               
            System.out.println("Odd Thread Name-->>" + Thread.currentThread().getName() + "Value-->>" + i);
            i=i+2;              
            lock.notify();
            }
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }       
}

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

please add these codes to your dependencies. It will work.

implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    implementation 'com.android.support:appcompat-v7:23.1.0'
    implementation 'com.android.support:design:23.1.0'
    implementation 'com.android.support:cardview-v7:23.1.0'
    implementation 'com.android.support:recyclerview-v7:23.1.0'

    implementation 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}

How do ports work with IPv6?

I'm pretty certain that ports only have a part in tcp and udp. So it's exactly the same even if you use a new IP protocol

How to use an array list in Java?

A three line solution, but works quite well:

int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
    target_list.add(random_array[i]);
}

What is the difference between a URI, a URL and a URN?

URIs came about from the need to identify resources on the Web, and other Internet resources such as electronic mailboxes in a uniform and coherent way. So, one can introduce a new type of widget: URIs to identify widget resources or use tel: URIs to have web links cause telephone calls to be made when invoked.

Some URIs provide information to locate a resource (such as a DNS host name and a path on that machine), while some are used as pure resource names. The URL is reserved for identifiers that are resource locators, including 'http' URLs such as http://stackoverflow.com, which identifies the web page at the given path on the host. Another example is 'mailto' URLs, such as mailto:[email protected], which identifies the mailbox at the given address.

URNs are URIs that are used as pure resource names rather than locators. For example, the URI: mid:[email protected] is a URN that identifies the email message containing it in its 'Message-Id' field. The URI serves to distinguish that message from any other email message. But it does not itself provide the message's address in any store.

Get Memory Usage in Android

enter the android terminal and then you can type the following commands :dumpsys cpuinfo

shell@android:/ $ dumpsys cpuinfo                                              
Load: 0.8 / 0.75 / 1.15
CPU usage from 69286ms to 9283ms ago with 99% awake:
  47% 1118/com.wxg.sodproject: 12% user + 35% kernel
  1.6% 1225/android.process.media: 1% user + 0.6% kernel
  1.3% 263/mpdecision: 0.1% user + 1.2% kernel
  0.1% 32747/kworker/u:1: 0% user + 0.1% kernel
  0.1% 883/com.android.systemui: 0.1% user + 0% kernel
  0.1% 521/system_server: 0.1% user + 0% kernel / faults: 14 minor
  0.1% 1826/com.quicinc.trepn: 0.1% user + 0% kernel
  0.1% 2462/kworker/0:2: 0.1% user + 0% kernel
  0.1% 32649/kworker/0:0: 0% user + 0.1% kernel
  0% 118/mmcqd/0: 0% user + 0% kernel
  0% 179/surfaceflinger: 0% user + 0% kernel
  0% 46/kinteractiveup: 0% user + 0% kernel
  0% 141/jbd2/mmcblk0p26: 0% user + 0% kernel
  0% 239/sdcard: 0% user + 0% kernel
  0% 1171/com.xiaomi.channel:pushservice: 0% user + 0% kernel / faults: 1 minor
  0% 1207/com.xiaomi.channel: 0% user + 0% kernel / faults: 1 minor
  0% 32705/kworker/0:1: 0% user + 0% kernel
12% TOTAL: 3.2% user + 9.4% kernel + 0% iowait

Reset select value to default

A simple way that runs is

 var myselect = $("select.SimpleAddAClass");
 myselect[0].selectedIndex = 0;
 myselect.selectmenu("refresh");

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

Reimport a module in python while interactive

This should work:

reload(my.module)

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

If running Python 3.4 and up, do import importlib, then do importlib.reload(nameOfModule).

Don't forget the caveats of using this method:

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

  • If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

As mentioned in the comments, the Starting Guide is the place to start with Java 11 and JavaFX 11.

The key to work as you did before Java 11 is to understand that:

  • JavaFX 11 is not part of the JDK anymore
  • You can get it in different flavors, either as an SDK or as regular dependencies (maven/gradle).
  • You will need to include it to the module path of your project, even if your project is not modular.

JavaFX project

If you create a regular JavaFX default project in IntelliJ (without Maven or Gradle) I'd suggest you download the SDK from here. Note that there are jmods as well, but for a non modular project the SDK is preferred.

These are the easy steps to run the default project:

  1. Create a JavaFX project
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 SDK as a library. The URL could be something like /Users/<user>/Downloads/javafx-sdk-11/lib/. Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Project

  1. Before you run the default project, you just need to add these to the VM options:

    --module-path /Users/<user>/Downloads/javafx-sdk-11/lib --add-modules=javafx.controls,javafx.fxml

  2. Run

Maven

If you use Maven to build your project, follow these steps:

  1. Create a Maven project with JavaFX archetype
  2. Set JDK 11 (point to your local Java 11 version)
  3. Add the JavaFX 11 dependencies.

    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>11</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>11</version>
        </dependency>
    </dependencies>
    

Once you do this you will notice that the JavaFX classes are now recognized in the editor.

JavaFX 11 Maven project

You will notice that Maven manages the required dependencies for you: it will add javafx.base and javafx.graphics for javafx.controls, but most important, it will add the required classifier based on your platform. In my case, Mac.

This is why your jars org.openjfx:javafx-controls:11 are empty, because there are three possible classifiers (windows, linux and mac platforms), that contain all the classes and the native implementation.

In case you still want to go to your .m2 repo and take the dependencies from there manually, make sure you pick the right one (for instance .m2/repository/org/openjfx/javafx-controls/11/javafx-controls-11-mac.jar)

  1. Replace default maven plugins with those from here.

  2. Run mvn compile javafx:run, and it should work.

Similar works as well for Gradle projects, as explained in detail here.

EDIT

The mentioned Getting Started guide contains updated documentation and sample projects for IntelliJ:

Submit form using a button outside the <form> tag

Similar to another solution here, with minor modification:

<form method="METHOD" id="FORMID">
   <!-- ...your inputs -->
</form>
<button type="submit" form="FORMID" value="Submit">Submit</button>

https://www.w3schools.com/tags/att_form.asp

Remove a cookie

Set the value to "" and the expiry date to yesterday (or any date in the past)

setcookie("hello", "", time()-3600);

Then the cookie will expire the next time the page loads.

Getting the computer name in Java

I agree with peterh's answer, so for those of you who like to copy and paste instead of 60 more seconds of Googling:

private String getComputerName()
{
    Map<String, String> env = System.getenv();
    if (env.containsKey("COMPUTERNAME"))
        return env.get("COMPUTERNAME");
    else if (env.containsKey("HOSTNAME"))
        return env.get("HOSTNAME");
    else
        return "Unknown Computer";
}

I have tested this in Windows 7 and it works. If peterh was right the else if should take care of Mac and Linux. Maybe someone can test this? You could also implement Brian Roach's answer inside the else if you wanted extra robustness.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

You can use below command to open it in VIM editor.

export VISUAL=vim; crontab -e

Note: Please make sure VIM editor is installed on your server.

PHP send mail to multiple email addresses

Try this. It works for me.

$to = $email1 .','. $email2 .','. $email3;

What processes are using which ports on unix?

Which process uses port in unix;

1. netstat -Aan | grep port

root> netstat -Aan | grep 3872

output> f1000e000bb5c3b8 tcp 0 0 *.3872 . LISTEN

2. rmsock f1000e000bb5c3b8 tcpcb

output> The socket 0xf1000e000bb5c008 is being held by proccess 13959354 (java).

3. ps -ef | grep 13959354

Ellipsis for overflow text in dropdown boxes

You can use this jQuery function instead of plus Bootstrap tooltip

function DDLSToolTipping(ddlsArray) {
    $(ddlsArray).each(function (index, ddl) {
        DDLToolTipping(ddl)
    });
}

function DDLToolTipping(ddlID, maxLength, allowDots) {
    if (maxLength == null) { maxLength = 12 }
    if (allowDots == null) { allowDots = true }

    var selectedOption = $(ddlID).find('option:selected').text();

    if (selectedOption.length > maxLength) {
        $(ddlID).attr('data-toggle', "tooltip")
                .attr('title', selectedOption);

        if (allowDots) {
            $(ddlID).prev('sup').remove();
            $(ddlID).before(
            "<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
               )
        }
    }

    else if ($(ddlID).attr('title') != null) {
        $(ddlID).removeAttr('data-toggle')
                .removeAttr('title');
    }
}

How to ignore ansible SSH authenticity checking?

Two options - the first, as you said in your own answer, is setting the environment variable ANSIBLE_HOST_KEY_CHECKING to False.

The second way to set it is to put it in an ansible.cfg file, and that's a really useful option because you can either set that globally (at system or user level, in /etc/ansible/ansible.cfg or ~/.ansible.cfg), or in an config file in the same directory as the playbook you are running.

To do that, make an ansible.cfg file in one of those locations, and include this:

[defaults]
host_key_checking = False

You can also set a lot of other handy defaults there, like whether or not to gather facts at the start of a play, whether to merge hashes declared in multiple places or replace one with another, and so on. There's a whole big list of options here in the Ansible docs.


Edit: a note on security.

SSH host key validation is a meaningful security layer for persistent hosts - if you are connecting to the same machine many times, it's valuable to accept the host key locally.

For longer-lived EC2 instances, it would make sense to accept the host key with a task run only once on initial creation of the instance:

  - name: Write the new ec2 instance host key to known hosts
    connection: local
    shell: "ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts"

There's no security value for checking host keys on instances that you stand up dynamically and remove right after playbook execution, but there is security value in checking host keys for persistent machines. So you should manage host key checking differently per logical environment.

  • Leave checking enabled by default (in ~/.ansible.cfg)
  • Disable host key checking in the working directory for playbooks you run against ephemeral instances (./ansible.cfg alongside the playbook for unit tests against vagrant VMs, automation for short-lived ec2 instances)

Create code first, many to many, with additional fields in association table

I want to propose a solution where both flavors of a many-to-many configuration can be achieved.

The "catch" is we need to create a view that targets the Join Table, since EF validates that a schema's table may be mapped at most once per EntitySet.

This answer adds to what's already been said in previous answers and doesn't override any of those approaches, it builds upon them.

The model:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<Member> Members { get; set; }
    public virtual ICollection<MemberCommentView> MemberComments { get; set; }
}

public class MemberCommentView
{
    public int MemberID { get; set; }
    public int CommentID { get; set; }
    public int Something { get; set; }
    public string SomethingElse { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }
}

The configuration:

using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;

public class MemberConfiguration : EntityTypeConfiguration<Member>
{
    public MemberConfiguration()
    {
        HasKey(x => x.MemberID);

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.FirstName).HasColumnType("varchar(512)");
        Property(x => x.LastName).HasColumnType("varchar(512)")

        // configure many-to-many through internal EF EntitySet
        HasMany(s => s.Comments)
            .WithMany(c => c.Members)
            .Map(cs =>
            {
                cs.ToTable("MemberComment");
                cs.MapLeftKey("MemberID");
                cs.MapRightKey("CommentID");
            });
    }
}

public class CommentConfiguration : EntityTypeConfiguration<Comment>
{
    public CommentConfiguration()
    {
        HasKey(x => x.CommentID);

        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Message).HasColumnType("varchar(max)");
    }
}

public class MemberCommentViewConfiguration : EntityTypeConfiguration<MemberCommentView>
{
    public MemberCommentViewConfiguration()
    {
        ToTable("MemberCommentView");
        HasKey(x => new { x.MemberID, x.CommentID });

        Property(x => x.MemberID).HasColumnType("int").IsRequired();
        Property(x => x.CommentID).HasColumnType("int").IsRequired();
        Property(x => x.Something).HasColumnType("int");
        Property(x => x.SomethingElse).HasColumnType("varchar(max)");

        // configure one-to-many targeting the Join Table view
        // making all of its properties available
        HasRequired(a => a.Member).WithMany(b => b.MemberComments);
        HasRequired(a => a.Comment).WithMany(b => b.MemberComments);
    }
}

The context:

using System.Data.Entity;

public class MyContext : DbContext
{
    public DbSet<Member> Members { get; set; }
    public DbSet<Comment> Comments { get; set; }
    public DbSet<MemberCommentView> MemberComments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Configurations.Add(new MemberConfiguration());
        modelBuilder.Configurations.Add(new CommentConfiguration());
        modelBuilder.Configurations.Add(new MemberCommentViewConfiguration());

        OnModelCreatingPartial(modelBuilder);
     }
}

From Saluma's (@Saluma) answer

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

This still works...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

...but could now also be...

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.Comments)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

This still works...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

...but could now also be...

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        m.Comments
    })
        .ToList();

If you want to remove a comment from a member

var comment = ... // assume comment from member John Smith
var member = ... // assume member John Smith

member.Comments.Remove(comment);

If you want to Include() a member's comments

var member = context.Members
    .Where(m => m.FirstName == "John", m.LastName == "Smith")
    .Include(m => m.Comments);

This all feels like syntactic sugar, however it does get you a few perks if you're willing to go through the additional configuration. Either way you seem to be able to get the best of both approaches.

Placeholder in IE9

HTML5 Placeholder jQuery Plugin
- by Mathias Bynens (a collaborator on HTML5 Boilerplate and jsPerf)

https://github.com/mathiasbynens/jquery-placeholder

Demo & Examples

http://mathiasbynens.be/demo/placeholder

p.s
I have used this plugin many times and it works a treat. Also it doesn't submit the placeholder text as a value when you submit your form (... a real pain I found with other plugins).

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

It seems to me you are using the wrong version...

TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!

String.equals() with multiple conditions (and one action on result)

No,its check like if string is "john" OR "mary" OR "peter" OR "etc."

you should check using ||

Like.,,if(str.equals("john") || str.equals("mary") || str.equals("peter"))

HashMap to return default value for non-found keys?

/**
 * Extension of TreeMap to provide default value getter/creator.
 * 
 * NOTE: This class performs no null key or value checking.
 * 
 * @author N David Brown
 *
 * @param <K>   Key type
 * @param <V>   Value type
 */
public abstract class Hash<K, V> extends TreeMap<K, V> {

    private static final long serialVersionUID = 1905150272531272505L;

    /**
     * Same as {@link #get(Object)} but first stores result of
     * {@link #create(Object)} under given key if key doesn't exist.
     * 
     * @param k
     * @return
     */
    public V getOrCreate(final K k) {
        V v = get(k);
        if (v == null) {
            v = create(k);
            put(k, v);
        }
        return v;
    }

    /**
     * Same as {@link #get(Object)} but returns specified default value
     * if key doesn't exist. Note that default value isn't automatically
     * stored under the given key.
     * 
     * @param k
     * @param _default
     * @return
     */
    public V getDefault(final K k, final V _default) {
        V v = get(k);
        return v == null ? _default : v;
    }

    /**
     * Creates a default value for the specified key.
     * 
     * @param k
     * @return
     */
    abstract protected V create(final K k);
}

Example Usage:

protected class HashList extends Hash<String, ArrayList<String>> {
    private static final long serialVersionUID = 6658900478219817746L;

    @Override
        public ArrayList<Short> create(Short key) {
            return new ArrayList<Short>();
        }
}

final HashList haystack = new HashList();
final String needle = "hide and";
haystack.getOrCreate(needle).add("seek")
System.out.println(haystack.get(needle).get(0));

Java and HTTPS url connection without downloading certificate

Java and HTTPS url connection without downloading certificate

If you really want to avoid downloading the server's certificate, then use an anonymous protocol like Anonymous Diffie-Hellman (ADH). The server's certificate is not sent with ADH and friends.

You select an anonymous protocol with setEnabledCipherSuites. You can see the list of cipher suites available with getEnabledCipherSuites.

Related: that's why you have to call SSL_get_peer_certificate in OpenSSL. You'll get a X509_V_OK with an anonymous protocol, and that's how you check to see if a certificate was used in the exchange.

But as Bruno and Stephed C stated, its a bad idea to avoid the checks or use an anonymous protocol.


Another option is to use TLS-PSK or TLS-SRP. They don't require server certificates either. (But I don't think you can use them).

The rub is, you need to be pre-provisioned in the system because TLS-PSK is Pres-shared Secret and TLS-SRP is Secure Remote Password. The authentication is mutual rather than server only.

In this case, the mutual authentication is provided by a property that both parties know the shared secret and arrive at the same premaster secret; or one (or both) does not and channel setup fails. Each party proves knowledge of the secret is the "mutual" part.

Finally, TLS-PSK or TLS-SRP don't do dumb things, like cough up the user's password like in a web app using HTTP (or over HTTPS). That's why I said each party proves knowledge of the secret...

force css grid container to fill full screen of device

You can add position: fixed; with top left right bottom 0 attribute, that solution work on older browsers too.

If you want to embed it, add position: absolute; to the wrapper, and position: relative to the div outside of the wrapper.

_x000D_
_x000D_
.wrapper {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
_x000D_
  display: grid;_x000D_
  border-style: solid;_x000D_
  border-color: red;_x000D_
  grid-template-columns: repeat(3, 1fr);_x000D_
  grid-template-rows: repeat(3, 1fr);_x000D_
  grid-gap: 10px;_x000D_
}_x000D_
.one {_x000D_
  border-style: solid;_x000D_
  border-color: blue;_x000D_
  grid-column: 1 / 3;_x000D_
  grid-row: 1;_x000D_
}_x000D_
.two {_x000D_
  border-style: solid;_x000D_
  border-color: yellow;_x000D_
  grid-column: 2 / 4;_x000D_
  grid-row: 1 / 3;_x000D_
}_x000D_
.three {_x000D_
  border-style: solid;_x000D_
  border-color: violet;_x000D_
  grid-row: 2 / 5;_x000D_
  grid-column: 1;_x000D_
}_x000D_
.four {_x000D_
  border-style: solid;_x000D_
  border-color: aqua;_x000D_
  grid-column: 3;_x000D_
  grid-row: 3;_x000D_
}_x000D_
.five {_x000D_
  border-style: solid;_x000D_
  border-color: green;_x000D_
  grid-column: 2;_x000D_
  grid-row: 4;_x000D_
}_x000D_
.six {_x000D_
  border-style: solid;_x000D_
  border-color: purple;_x000D_
  grid-column: 3;_x000D_
  grid-row: 4;_x000D_
}
_x000D_
<html>_x000D_
<div class="wrapper">_x000D_
  <div class="one">One</div>_x000D_
  <div class="two">Two</div>_x000D_
  <div class="three">Three</div>_x000D_
  <div class="four">Four</div>_x000D_
  <div class="five">Five</div>_x000D_
  <div class="six">Six</div>_x000D_
</div>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What does the following Oracle error mean: invalid column index

I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this

SELECT * FROM EMPLOYE E WHERE E.ID = ?

and for the preparedStatement object (JDBC) if you set the parameters like

preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)

then it results in SQLException: Invalid column index

So, I removed that second parameter setting to prepared statement then problem solved

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

How to split data into trainset and testset randomly?

A quick note for the answer from @subin sahayam

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int(len(data)*.80+1):] #Splits 20% data to test set

If your list size is a even number, you should not add the 1 in the code below. Instead, you need to check the size of the list first and then determine if you need to add the 1.

test_data = data[int(len(data)*.80+1):]

Git error: "Host Key Verification Failed" when connecting to remote repository

I was facing the same error inside DockerFile during build time while the image was public. I did little modification in Dockerfile.

 RUN git clone  https://github.com/kacole2/express-node-mongo-skeleton.git /www/nodejs

This would be because using the [email protected]:... syntax ends up > using SSH to clone, and inside the container, your private key is not > available. You'll want to use RUN git clone > https://github.com/edenhill/librdkafka.git instead.

How to use global variables in React Native?

You can consider leveraging React's Context feature.

class NavigationContainer extends React.Component {
    constructor(props) {
        super(props);
        this.goTo = this.goTo.bind(this);
    }
    goTo(location) {
        ...
    }
    getChildContext() {
        // returns the context to pass to children
        return {
            goTo: this.goTo
        }
    }
    ...
}

// defines the context available to children
NavigationContainer.childContextTypes = {
    goTo: PropTypes.func
}

class SomeViewContainer extends React.Component {
    render() {
        // grab the context provided by ancestors
        const {goTo} = this.context;
        return <button onClick={evt => goTo('somewhere')}>
            Hello
        </button>
    }
}

// Define the context we want from ancestors
SomeViewContainer.contextTypes = {
    goTo: PropTypes.func
}

With context, you can pass data through the component tree without having to pass the props down manually at every level. There is a big warning on this being an experimental feature and may break in the future, but I would imagine this feature to be around given the majority of the popular frameworks like Redux use context extensively.

The main advantage of using context v.s. a global variable is context is "scoped" to a subtree (this means you can define different scopes for different subtrees).

Do note that you should not pass your model data via context, as changes in context will not trigger React's component render cycle. However, I do find it useful in some use case, especially when implementing your own custom framework or workflow.

How to parse month full form string using DateFormat in Java?

val currentTime = Calendar.getInstance().time
SimpleDateFormat("MMMM", Locale.getDefault()).format(date.time)

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

I suggest using moment.js which provides an easy to use method for doing this.

interactive demo

function validate(date){
    var eighteenYearsAgo = moment().subtract(18, "years");
    var birthday = moment(date);

    if (!birthday.isValid()) {
        return "invalid date";    
    }
    else if (eighteenYearsAgo.isAfter(birthday)) {
        return "okay, you're good";    
    }
    else {
        return "sorry, no";    
    }
}

To include moment in your page, you can use CDNJS:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.4.0/moment.min.js"></script>

How add unique key to existing table (with non uniques rows)

You can do as yAnTar advised

ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY

OR

You can add a constraint

ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)

But I think to not lose your existing data, you can add an indentity column and then make a composite key.

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Easily measure elapsed time

The reason both values are the same is because your long procedure doesn't take that long - less than one second. You can try just adding a long loop (for (int i = 0; i < 100000000; i++) ; ) at the end of the function to make sure this is the issue, then we can go from there...

In case the above turns out to be true, you will need to find a different system function (I understand you work on linux, so I can't help you with the function name) to measure time more accurately. I am sure there is a function simular to GetTickCount() in linux, you just need to find it.

Which Python memory profiler is recommended?

guppy3 is quite simple to use. At some point in your code, you have to write the following:

from guppy import hpy
h = hpy()
print(h.heap())

This gives you some output like this:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.

There is a graphical browser as well, written in Tk.

For Python 2.x, use Heapy.

What is the "Upgrade-Insecure-Requests" HTTP header?

This explains the whole thing:

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

The upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. It is recommended to set one directive or the other, but not both.

The upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to HTTPS for the top-level navigation and thus does not replace the Strict-Transport-Security (HSTS) header, which should still be set with an appropriate max-age to ensure that users are not subject to SSL stripping attacks.

Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

How does Python manage int and long?

Interesting. On my 64-bit (i7 Ubuntu) box:

>>> print type(0x7FFFFFFF)
<type 'int'>
>>> print type(0x7FFFFFFF+1)
<type 'int'>

Guess it steps up to 64 bit ints on a larger machine.

MYSQL Truncated incorrect DOUBLE value

I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.

One column was a CHAR (90) and the other was a BIGINT (20).

One table was InnoDB and the other was MEMORY.

Part of query:

[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );

Changing the column type on the one column from BIGINT to CHAR solved the issue.

How to remove the left part of a string?

How about..

>>> line = r'path=c:\path'
>>> line.partition('path=')
('', 'path=', 'c:\\path')

This triplet is the head, separator, and tail.

Access mysql remote database from command line

You should put your password with 'p'

mysql -u root -u 1.1.1.1 -p'MyPass'

What is the best way to parse html in C#?

The Html Agility Pack has been mentioned before - if you are going for speed, you might also want to check out the Majestic-12 HTML parser. Its handling is rather clunky, but it delivers a really fast parsing experience.

CSS Div stretch 100% page height

With HTML5, the easiest way is simply to do height: 100vh. Where 'vh' stands for viewport height of the browser window. Responsive to resizing of browser and mobile devices.

Console.WriteLine and generic List

        List<int> a = new List<int>() { 1, 2, 3, 4, 5 };
        a.ForEach(p => Console.WriteLine(p));

edit: ahhh he beat me to it.

How to make script execution wait until jquery is loaded

Check this:

https://jsfiddle.net/neohunter/ey2pqt5z/

It will create a fake jQuery object, that allows you to use the onload methods of jquery, and they will be executed as soon as jquery is loaded.

It's not perfect.

_x000D_
_x000D_
// This have to be on <HEAD> preferibly inline_x000D_
var delayed_jquery = [];_x000D_
jQuery = function() {_x000D_
  if (typeof arguments[0] == "function") {_x000D_
    jQuery(document).ready(arguments[0]);_x000D_
  } else {_x000D_
    return {_x000D_
      ready: function(fn) {_x000D_
        console.log("registering function");_x000D_
        delayed_jquery.push(fn);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
};_x000D_
$ = jQuery;_x000D_
var waitForLoad = function() {_x000D_
  if (typeof jQuery.fn != "undefined") {_x000D_
    console.log("jquery loaded!!!");_x000D_
    for (k in delayed_jquery) {_x000D_
      delayed_jquery[k]();_x000D_
    }_x000D_
  } else {_x000D_
    console.log("jquery not loaded..");_x000D_
    window.setTimeout(waitForLoad, 500);_x000D_
  }_x000D_
};_x000D_
window.setTimeout(waitForLoad, 500);_x000D_
// end_x000D_
_x000D_
_x000D_
_x000D_
// now lets use jQuery (the fake version)_x000D_
jQuery(document).ready(function() {_x000D_
  alert('Jquery now exists!');_x000D_
});_x000D_
_x000D_
jQuery(function() {_x000D_
  alert('Jquery now exists, this is using an alternative call');_x000D_
})_x000D_
_x000D_
// And lets load the real jquery after 3 seconds.._x000D_
window.setTimeout(function() {_x000D_
  var newscript = document.createElement('script');_x000D_
  newscript.type = 'text/javascript';_x000D_
  newscript.async = true;_x000D_
  newscript.src = 'https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js';_x000D_
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(newscript);_x000D_
}, 3000);
_x000D_
_x000D_
_x000D_

Get UTC time and local time from NSDate object

The documentation says that the date method returns a new date set to the current date and time regardless of the language used.

The issue probably sits somewhere where you present the date using NSDateFormatter. NSDate is just a point on a time line. There is no time zones when talking about NSDate. I made a test.

Swift

print(NSDate())

Output: 2014-07-23 17:56:45 +0000

Objective-C

NSLog(@"%@", [NSDate date]);

Output: 2014-07-23 17:58:15 +0000

Result - No difference.

Linux command (like cat) to read a specified quantity of characters

Even though this was answered/accepted years ago, the presently accepted answer is only correct for one-byte-per-character encodings like iso-8859-1, or for the single-byte subsets of variable-byte character sets (like Latin characters within UTF-8). Even using multiple-byte splices instead would still only work for fixed-multibyte encodings like UTF-16. Given that now UTF-8 is well on its way to being a universal standard, and when looking at this list of languages by number of native speakers and this list of top 30 languages by native/secondary usage, it is important to point out a simple variable-byte character-friendly (not byte-based) technique, using cut -c and tr/sed with character-classes.

Compare the following which doubly fails due to two common Latin-centric mistakes/presumptions regarding the bytes vs. characters issue (one is head vs. cut, the other is [a-z][A-Z] vs. [:upper:][:lower:]):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     head -c 1 | \
$     sed -e 's/[A-Z]/[a-z]/g'
[[unreadable binary mess, or nothing if the terminal filtered it]]

to this (note: this worked fine on FreeBSD, but both cut & tr on GNU/Linux still mangled Greek in UTF-8 for me though):

$ printf '??? µp??? ?a µ??? sa?s???t???;\n' | \
$     cut -c 1 | \
$     tr '[:upper:]' '[:lower:]'
p

Another more recent answer had already proposed "cut", but only because of the side issue that it can be used to specify arbitrary offsets, not because of the directly relevant character vs. bytes issue.

If your cut doesn't handle -c with variable-byte encodings correctly, for "the first X characters" (replace X with your number) you could try:

  • sed -E -e '1 s/^(.{X}).*$/\1/' -e q - which is limited to the first line though
  • head -n 1 | grep -E -o '^.{X}' - which is limited to the first line and chains two commands though
  • dd - which has already been suggested in other answers, but is really cumbersome
  • A complicated sed script with sliding window buffer to handle characters spread over multiple lines, but that is probably more cumbersome/fragile than just using something like dd

If your tr doesn't handle character-classes with variable-byte encodings correctly you could try:

  • sed -E -e 's/[[:upper:]]/\L&/g (GNU-specific)

How to get store information in Magento?

To get information about the current store from anywhere in Magento, use:

<?php
$store = Mage::app()->getStore();

This will give you a Mage_Core_Model_Store object, which has some of the information you need:

<?php
$name = $store->getName();

As for your other question about line number, I'm not sure what you mean. If you mean that you want to know what line number in the code you are on (for error handling, for instance), try:

<?php
$line      = __LINE__;
$file      = __FILE__;
$class     = __CLASS__;
$method    = __METHOD__;
$namespace = __NAMESPACE__;

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

How to fix .pch file missing on build?

I was searching for the iOS PCH file having the same problem, if you got here like me too, the solution that I've found is by clearing derived data; Close Simulator(s), go to xCode prefs -> locations -> go to the derived data file path, close xCode, delete the files in the derived data folder, re launch and cheers :)

Where can I view Tomcat log files in Eclipse?

Go to the "Server" view, then double-click the Tomcat server you're running. The access log files are stored relative to the path in the "Server path" field, which itself is relative to the workspace path.

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

Check if a div does NOT exist with javascript

var myElem = document.getElementById('myElementId');
if (myElem === null) alert('does not exist!');

How do I rename the extension for a bunch of files?

The command mmv seems to do this task very efficiently on a huge number of files (tens of thousands in a second). For example, to rename all .xml files to .html files, use this:

mmv ";*.xml" "#1#2.html"

the ; will match the path, the * will match the filename, and these are referred to as #1 and #2 in the replacement name.

Answers based on exec or pipes were either too slow or failed on a very large number of files.

In Visual Basic how do you create a block comment

Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.

http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment

http://forums.asp.net/t/1011404.aspx/1

Can't find System.Windows.Media namespace?

You should add reference to PresentationCore.dll.

Set HTML element's style property in javascript

If you just want to change the color of the row, you could just access the style.backgroundColor property and set it.

Here is a quick link to a CSS property to JS conversion.

pandas: best way to select all columns whose names start with X

You can try the regex here to filter out the columns starting with "foo"

df.filter(regex='^foo*')

If you need to have the string foo in your column then

df.filter(regex='foo*')

would be appropriate.

For the next step, you can use

df[df.filter(regex='^foo*').values==1]

to filter out the rows where one of the values of 'foo*' column is 1.

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

Switch to an older openssl package

brew switch openssl 1.0.2s

Or, depending on your exact system configuration, you may need to switch to a different version. Check the output of ls -al /usr/local/Cellar/openssl for the version number to switch to.

brew switch openssl 1.0.2q
# or
brew switch openssl 1.0.2r
# or 
brew switch openssl 1.0.2s
# or
brew switch openssl 1.0.2t
# etc...

Multiple variables in a 'with' statement?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax such as:

with (
    A() as a,
    B() as b
):
    do_something(a, b)

Can we create an instance of an interface in Java?

No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.

How can I find out what version of git I'm running?

Or even just

git version

Results in something like

git version 1.8.3.msysgit.0

How to pass parameters to a partial view in ASP.NET MVC?

Following is working for me on dotnet 1.0.1:

./ourView.cshtml

@Html.Partial(
  "_ourPartial.cshtml",
  new ViewDataDictionary(this.Vi??ewData) {
    {
      "hi", "hello" 
    } 
  }
);

./_ourPartial.cshtml

<h1>@this.ViewData["hi"]</h1>

jQuery/JavaScript: accessing contents of an iframe

I prefer to use other variant for accessing. From parent you can have a access to variable in child iframe. $ is a variable too and you can receive access to its just call window.iframe_id.$

For example, window.view.$('div').hide() - hide all divs in iframe with id 'view'

But, it doesn't work in FF. For better compatibility you should use

$('#iframe_id')[0].contentWindow.$

How do I create a branch?

If you even plan on merging your branch, I highly suggest you look at this:

Svnmerge.py

I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!

CRON command to run URL address every 5 minutes

To run a URL simply use command below easy yess CPanel 100%

/usr/bin/php -q /home/CpanelUsername/public_html/RootFolder/cronjob/fetch.php

I hope this help.

How do you execute SQL from within a bash script?

Here is a simple way of running MySQL queries in the bash shell

mysql -u [database_username] -p [database_password] -D [database_name] -e "SELECT * FROM [table_name]"

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

How does Tomcat find the HOME PAGE of my Web App?

I already had index.html in the WebContent folder but it was not showing up , finally i added the following piece of code in my projects web.xml and it started showing up

  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping> 

Python Create unix timestamp five minutes in the future

The following is based on the answers above (plus a correction for the milliseconds) and emulates datetime.timestamp() for Python 3 before 3.3 when timezones are used.

def datetime_timestamp(datetime):
    '''
    Equivalent to datetime.timestamp() for pre-3.3
    '''
    try:
        return datetime.timestamp()
    except AttributeError:
        utc_datetime = datetime.astimezone(utc)
        return timegm(utc_datetime.timetuple()) + utc_datetime.microsecond / 1e6

To strictly answer the question as asked, you'd want:

datetime_timestamp(my_datetime) + 5 * 60

datetime_timestamp is part of simple-date. But if you were using that package you'd probably type:

SimpleDate(my_datetime).timestamp + 5 * 60

which handles many more formats / types for my_datetime.

How to pass the password to su/sudo/ssh without overriding the TTY?

Building on @Jahid's answer, this worked for me on macOS 10.13:

ssh <remote_username>@<remote_server> sudo -S <<< <remote_password> cat /etc/sudoers

Bootstrap DatePicker, how to set the start date for tomorrow?

this.$('#datepicker').datepicker({minDate: 1});

minDate:0 - Enable dates in the calender from the current date. MinDate:1 enable dates in the calender currentDate+1

To Restrict date between from tomorrow and the same day next month u need to give something like

$( "#datepicker" ).datepicker({ minDate: 1, maxDate: "+1M" });

Display curl output in readable JSON format in Unix shell script

A few solutions to choose from:

json_pp: command utility available in Linux systems for JSON decoding/encoding

echo '{"type":"Bar","id":"1","title":"Foo"}' | json_pp -json_opt pretty,canonical
{
   "id" : "1",
   "title" : "Foo",
   "type" : "Bar"
}

You may want to keep the -json_opt pretty,canonical argument for predictable ordering.


: lightweight and flexible command-line JSON processor. It is written in portable C, and it has zero runtime dependencies.

echo '{"type":"Bar","id":"1","title":"Foo"}' | jq '.'
{
  "type": "Bar",
  "id": "1",
  "title": "Foo"
}

The simplest jq program is the expression ., which takes the input and produces it unchanged as output.

For additinal jq options check the manual


with :

echo '{"type":"Bar","id":"1","title":"Foo"}' | python -m json.tool
{
    "id": "1",
    "title": "Foo",
    "type": "Bar"
}

with and :

echo '{"type":"Bar","id":"1","title":"Foo"}' | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"
{
 "type": "Bar",
 "id": "1",
 "title": "Foo"
}

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

Configuring so that pip install can work from github

you can try this way in Colab

!git clone https://github.com/UKPLab/sentence-transformers.git
!pip install -e /content/sentence-transformers
import sentence_transformers

Setting graph figure size

 figure (1)
 hFig = figure(1);
 set(gcf,'PaperPositionMode','auto')
 set(hFig, 'Position', [0 0 xwidth ywidth])
 plot(x,y)
 print -depsc2 correlation.eps;       % for saving in eps, look up options for saving as png or other formats you may need

This saves the figure in the dimensions specified

Export a graph to .eps file with R

Another way is to use Cairographics-based SVG, PDF and PostScript Graphics Devices. This way you don't need to setEPS()

cairo_ps("image.eps")
plot(1, 10)
dev.off()

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM

  • eclipse.ini : the memory for the VM running eclipse
  • jre setting : the memory for java programs run from eclipse
  • catalina.sh : the memory for your tomcat server

What is the (function() { } )() construct in JavaScript?

Self-executing anonymous function. It's executed as soon as it is created.

One short and dummy example where this is useful is:

function prepareList(el){
  var list = (function(){
    var l = []; 
    for(var i = 0; i < 9; i++){
     l.push(i);
    }
    return l;
  })();

  return function (el){
    for(var i = 0, l = list.length; i < l; i++){
      if(list[i] == el) return list[i];
    }
    return null;
  }; 
} 

var search = prepareList();
search(2);
search(3);

So instead of creating a list each time, you create it only once (less overhead).

What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?

Process GET parameters

The <f:viewParam> manages the setting, conversion and validation of GET parameters. It's like the <h:inputText>, but then for GET parameters.

The following example

<f:metadata>
    <f:viewParam name="id" value="#{bean.id}" />
</f:metadata>

does basically the following:

  • Get the request parameter value by name id.
  • Convert and validate it if necessary (you can use required, validator and converter attributes and nest a <f:converter> and <f:validator> in it like as with <h:inputText>)
  • If conversion and validation succeeds, then set it as a bean property represented by #{bean.id} value, or if the value attribute is absent, then set it as request attribtue on name id so that it's available by #{id} in the view.

So when you open the page as foo.xhtml?id=10 then the parameter value 10 get set in the bean this way, right before the view is rendered.

As to validation, the following example sets the param to required="true" and allows only values between 10 and 20. Any validation failure will result in a message being displayed.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
</f:metadata>
<h:message for="id" />

Performing business action on GET parameters

You can use the <f:viewAction> for this.

<f:metadata>
    <f:viewParam id="id" name="id" value="#{bean.id}" required="true">
        <f:validateLongRange minimum="10" maximum="20" />
    </f:viewParam>
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
<h:message for="id" />

with

public void onload() {
    // ...
}

The <f:viewAction> is however new since JSF 2.2 (the <f:viewParam> already exists since JSF 2.0). If you can't upgrade, then your best bet is using <f:event> instead.

<f:event type="preRenderView" listener="#{bean.onload}" />

This is however invoked on every request. You need to explicitly check if the request isn't a postback:

public void onload() {
    if (!FacesContext.getCurrentInstance().isPostback()) {
        // ...
    }
}

When you would like to skip "Conversion/Validation failed" cases as well, then do as follows:

public void onload() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.isPostback() && !facesContext.isValidationFailed()) {
        // ...
    }
}

Using <f:event> this way is in essence a workaround/hack, that's exactly why the <f:viewAction> was introduced in JSF 2.2.


Pass view parameters to next view

You can "pass-through" the view parameters in navigation links by setting includeViewParams attribute to true or by adding includeViewParams=true request parameter.

<h:link outcome="next" includeViewParams="true">
<!-- Or -->
<h:link outcome="next?includeViewParams=true">

which generates with the above <f:metadata> example basically the following link

<a href="next.xhtml?id=10">

with the original parameter value.

This approach only requires that next.xhtml has also a <f:viewParam> on the very same parameter, otherwise it won't be passed through.


Use GET forms in JSF

The <f:viewParam> can also be used in combination with "plain HTML" GET forms.

<f:metadata>
    <f:viewParam id="query" name="query" value="#{bean.query}" />
    <f:viewAction action="#{bean.search}" />
</f:metadata>
...
<form>
    <label for="query">Query</label>
    <input type="text" name="query" value="#{empty bean.query ? param.query : bean.query}" />
    <input type="submit" value="Search" />
    <h:message for="query" />
</form>
...
<h:dataTable value="#{bean.results}" var="result" rendered="#{not empty bean.results}">
     ...
</h:dataTable>

With basically this @RequestScoped bean:

private String query;
private List<Result> results;

public void search() {
    results = service.search(query);
}

Note that the <h:message> is for the <f:viewParam>, not the plain HTML <input type="text">! Also note that the input value displays #{param.query} when #{bean.query} is empty, because the submitted value would otherwise not show up at all when there's a validation or conversion error. Please note that this construct is invalid for JSF input components (it is doing that "under the covers" already).


See also:

global variable for all controller and views

In file - \vendor\autoload.php, define your gobals variable as follows, should be in the topmost line.

$global_variable = "Some value";//the global variable

Access that global variable anywhere as :-

$GLOBALS['global_variable'];

Enjoy :)

Directly export a query to CSV using SQL Developer

Click in the grid so it has focus.

Ctrl+End

This will force the rest of the records back into the grid.

All credit to http://www.thatjeffsmith.com/archive/2012/03/how-to-export-sql-developer-query-results-without-re-running-the-query/

Static Block in Java

It is a static initializer. It's executed when the class is loaded and a good place to put initialization of static variables.

From http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

If you have a class with a static look-up map it could look like this

class MyClass {
    static Map<Double, String> labels;
    static {
        labels = new HashMap<Double, String>();
        labels.put(5.5, "five and a half");
        labels.put(7.1, "seven point 1");
    }
    //...
}

It's useful since the above static field could not have been initialized using labels = .... It needs to call the put-method somehow.

comparing strings in vb

Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))

returns a bool True. This comparison is case-sensitive.

So in your example,

if String.Equals(string1, string2) and String.Equals(string3, string4) then
  ' do something
else
  ' do something else
end if

How to enable cURL in PHP / XAMPP

Since XAMPP went through some modifications, the file is now at xampp/php/php.ini.

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

Value cannot be null. Parameter name: source

I had this one a while back, and the answer isn't necessarily what you'd expect. This error message often crops up when your connection string is wrong.

At a guess, you'll need something like this:

<connectionStrings>
    <add name="hublisherEntities" connectionString="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
        <parameters>
            <parameter value="Data Source=localhost;Initial Catalog=hublisher;Integrated Security=True" />
        </parameters>
    </defaultConnectionFactory>
</entityFramework>

What's happening is that it's looking for a data source in the wrong place; Entity Framework specifies it slightly differently. If you post your connection string and EF config then we can check.

How to check Oracle patches are installed?

I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.

Under Oracle 12c, I found that that my registry$history is empty. This works instead:

select * from registry$sqlpatch;

How to config Tomcat to serve images from an external folder outside webapps?

This is very simple and straight forward to server the static content from outside webapps folder in tomcat.

Simply edit the server.xml under $CATALINA_HOME/config/server.xml as below and restart the tomcat.

<Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        **<Context docBase="C:\Ankur\testFiles"  path="/companyLogo" />**

       <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

</Host>

Add the context element inside the host element with two attribute docBase and path.

1) docBase: represents the hard drive directory 2) path: represents the uri on which you want to serve the static content.

For example:If you have 7.png inside the C:\Ankur\testFiles directory then you can access the 7.png file like below:

http://localhost:8081/companyLogo/7.png

For more details, check the blog

Detect click outside Angular component

Above mentioned answers are correct but what if you are doing a heavy process after losing the focus from the relevant component. For that, I came with a solution with two flags where the focus out event process will only take place when losing the focus from relevant component only.

isFocusInsideComponent = false;
isComponentClicked = false;

@HostListener('click')
clickInside() {
    this.isFocusInsideComponent = true;
    this.isComponentClicked = true;
}

@HostListener('document:click')
clickout() {
    if (!this.isFocusInsideComponent && this.isComponentClicked) {
        // do the heavy process

        this.isComponentClicked = false;
    }
    this.isFocusInsideComponent = false;
}

Hope this will help you. Correct me If have missed anything.

jQuery exclude elements with certain class in selector

use this..

$(".content_box a:not('.button')")

Accessing Redux state in an action creator?

When your scenario is simple you can use

import store from '../store';

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
  return {
    type: SOME_ACTION,
    items: store.getState().otherReducer.items,
  }
}

But sometimes your action creator need to trigger multi actions

for example async request so you need REQUEST_LOAD REQUEST_LOAD_SUCCESS REQUEST_LOAD_FAIL actions

export const [REQUEST_LOAD, REQUEST_LOAD_SUCCESS, REQUEST_LOAD_FAIL] = [`REQUEST_LOAD`
    `REQUEST_LOAD_SUCCESS`
    `REQUEST_LOAD_FAIL`
]
export function someAction() {
    return (dispatch, getState) => {
        const {
            items
        } = getState().otherReducer;
        dispatch({
            type: REQUEST_LOAD,
            loading: true
        });
        $.ajax('url', {
            success: (data) => {
                dispatch({
                    type: REQUEST_LOAD_SUCCESS,
                    loading: false,
                    data: data
                });
            },
            error: (error) => {
                dispatch({
                    type: REQUEST_LOAD_FAIL,
                    loading: false,
                    error: error
                });
            }
        })
    }
}

Note: you need redux-thunk to return function in action creator

Parse date string and change format

datetime module could help you with that:

datetime.datetime.strptime(date_string, format1).strftime(format2)

For the specific example you could do

>>> datetime.datetime.strptime('Mon Feb 15 2010', '%a %b %d %Y').strftime('%d/%m/%Y')
'15/02/2010'
>>>

git command to move a folder inside another

I solved this on windows by doing this:

  • Open Power shell console
  • run dir
  • Alt-click and drag over the file/folder name column, then copy
  • Paste to notepad++
  • run replace with regex: replace (.*) with git mv ".\\\1" ".\\<New_Folder_Here>\"
  • copy all text from notepad++ into powershell
  • hit enter

Setting Remote Webdriver to run tests in a remote computer using Java

You have to install a Selenium Server (a Hub) and register your remote WebDriver to it. Then, your client will talk to the Hub which will find a matching WebDriver to execute your test.

You can have a look at here for more information.

How can I use regex to get all the characters after a specific character, e.g. comma (",")

Another idea is to do myVar.split(',')[1];

For simple case, not using a regexp is a good idea...

Git diff against a stash

I believe git diff <current-branchname>..stash@{0} is the most intuitive way to compare the changes between the local working tree and the most recent stash. Replace stash@{0} with the applicable stash number as needed.

Beware that git diff stash@{0} may produce misleading results. If the two histories of your stash and current branch have diverged, the diff will look like you’re adding all the new stuff in your stash and removing everything unique to the current branch.

answer based on the git book

Also, note that double dot .. and triple dot ... specify different commit comparisons, and I am referring to the double dot for this answer. See the git book for details

What's the best way to check if a String represents an integer in Java?

I copied the code from rally25rs answer and added some tests for non-integer data. The results are undeniably in favor of the method posted by Jonas Klemming. The results for the Exception method that I originally posted are pretty good when you have integer data, but they're the worst when you don't, while the results for the RegEx solution (that I'll bet a lot of people use) were consistently bad. See Felipe's answer for a compiled regex example, which is much faster.

public void runTests()
{
    String big_int = "1234567890";
    String non_int = "1234XY7890";

    long startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(big_int);
    long endTime = System.currentTimeMillis();
    System.out.print("ByException - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByException(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByException - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByRegex - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByRegex(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByRegex - non-integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(big_int);
    endTime = System.currentTimeMillis();
    System.out.print("\nByJonas - integer data: ");
    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    for(int i = 0; i < 100000; i++)
        IsInt_ByJonas(non_int);
    endTime = System.currentTimeMillis();
    System.out.print("ByJonas - non-integer data: ");
    System.out.println(endTime - startTime);
}

private boolean IsInt_ByException(String str)
{
    try
    {
        Integer.parseInt(str);
        return true;
    }
    catch(NumberFormatException nfe)
    {
        return false;
    }
}

private boolean IsInt_ByRegex(String str)
{
    return str.matches("^-?\\d+$");
}

public boolean IsInt_ByJonas(String str)
{
    if (str == null) {
            return false;
    }
    int length = str.length();
    if (length == 0) {
            return false;
    }
    int i = 0;
    if (str.charAt(0) == '-') {
            if (length == 1) {
                    return false;
            }
            i = 1;
    }
    for (; i < length; i++) {
            char c = str.charAt(i);
            if (c <= '/' || c >= ':') {
                    return false;
            }
    }
    return true;
}

Results:

ByException - integer data: 47
ByException - non-integer data: 547

ByRegex - integer data: 390
ByRegex - non-integer data: 313

ByJonas - integer data: 0
ByJonas - non-integer data: 16

Highlight text similar to grep, but don't filter out text

You can make sure that all lines match but there is nothing to highlight on irrelevant matches

egrep --color 'apple|' test.txt 

Notes:

  • egrep may be spelled also grep -E
  • --color is usually default in most distributions
  • some variants of grep will "optimize" the empty match, so you might want to use "apple|$" instead (see: https://stackoverflow.com/a/13979036/939457)

Launch Minecraft from command line - username and password as prefix

Just create this batch command file in your game directory. Bat file takes one argument %1 as the username.

Also, I use a splash screen to make pretty. You will NOT be able to play online, but who cares.

Adjust your memory usage to fit your machine (-Xmx & -Xmns).

NOTE: this is for version of minecraft as of 2016-06-27

@ECHO OFF
SET DIR=%cd%
SET JAVA_HOME=%DIR%\runtime\jre-x64\1.8.0_25
SET JAVA=%JAVA_HOME%\bin\java.exe
SET LOW_MEM=768M
SET MAX_MEM=2G
SET LIBRARIES=versions\1.10.2\1.10.2-natives-59894925878961
SET MAIN_CLASS=net.minecraft.client.main.Main
SET CLASSPATH=libraries\com\mojang\netty\1.6\netty-1.6.jar;libraries\oshi-project\oshi-core\1.1\oshi-core-1.1.jar;libraries\net\java\dev\jna\jna\3.4.0\jna-3.4.0.jar;libraries\net\java\dev\jna\platform\3.4.0\platform-3.4.0.jar;libraries\com\ibm\icu\icu4j-core-mojang\51.2\icu4j-core-mojang-51.2.jar;libraries\net\sf\jopt-simple\jopt-simple\4.6\jopt-simple-4.6.jar;libraries\com\paulscode\codecjorbis\20101023\codecjorbis-20101023.jar;libraries\com\paulscode\codecwav\20101023\codecwav-20101023.jar;libraries\com\paulscode\libraryjavasound\20101123\libraryjavasound-20101123.jar;libraries\com\paulscode\librarylwjglopenal\20100824\librarylwjglopenal-20100824.jar;libraries\com\paulscode\soundsystem\20120107\soundsystem-20120107.jar;libraries\io\netty\netty-all\4.0.23.Final\netty-all-4.0.23.Final.jar;libraries\com\google\guava\guava\17.0\guava-17.0.jar;libraries\org\apache\commons\commons-lang3\3.3.2\commons-lang3-3.3.2.jar;libraries\commons-io\commons-io\2.4\commons-io-2.4.jar;libraries\commons-codec\commons-codec\1.9\commons-codec-1.9.jar;libraries\net\java\jinput\jinput\2.0.5\jinput-2.0.5.jar;libraries\net\java\jutils\jutils\1.0.0\jutils-1.0.0.jar;libraries\com\google\code\gson\gson\2.2.4\gson-2.2.4.jar;libraries\com\mojang\authlib\1.5.22\authlib-1.5.22.jar;libraries\com\mojang\realms\1.9.3\realms-1.9.3.jar;libraries\org\apache\commons\commons-compress\1.8.1\commons-compress-1.8.1.jar;libraries\org\apache\httpcomponents\httpclient\4.3.3\httpclient-4.3.3.jar;libraries\commons-logging\commons-logging\1.1.3\commons-logging-1.1.3.jar;libraries\org\apache\httpcomponents\httpcore\4.3.2\httpcore-4.3.2.jar;libraries\it\unimi\dsi\fastutil\7.0.12_mojang\fastutil-7.0.12_mojang.jar;libraries\org\apache\logging\log4j\log4j-api\2.0-beta9\log4j-api-2.0-beta9.jar;libraries\org\apache\logging\log4j\log4j-core\2.0-beta9\log4j-core-2.0-beta9.jar;libraries\org\lwjgl\lwjgl\lwjgl\2.9.4-nightly-20150209\lwjgl-2.9.4-nightly-20150209.jar;libraries\org\lwjgl\lwjgl\lwjgl_util\2.9.4-nightly-20150209\lwjgl_util-2.9.4-nightly-20150209.jar;versions\1.10.2\1.10.2.jar
SET JAVA_OPTIONS=-server -splash:splash.png -d64 -da -dsa -Xrs -Xms%LOW_MEM% -Xmx%MAX_MEM% -XX:NewSize=%LOW_MEM% -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -XX:+DisableExplicitGC -Djava.library.path=%LIBRARIES% -cp %CLASSPATH%  %MAIN_CLASS%

start /D %DIR% /I /HIGH %JAVA% %JAVA_OPTIONS% --username %1 --version 1.10.2 --gameDir %DIR% --assetsDir assets --assetIndex 1.10 --uuid 2536abce90e8476a871679918164abc5 --accessToken 99abe417230342cb8e9e2168ab46297a --userType legacy --versionType release --nativeLauncherVersion 307


delete vs delete[] operators in C++

delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.

Java - sending HTTP parameters via POST method easily

I higly recomend http-request built on apache http api.

For your case you can see example:

private static final HttpRequest<String.class> HTTP_REQUEST = 
      HttpRequestBuilder.createPost("http://example.com/index.php", String.class)
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .build();

public void sendRequest(String request){
     String parameters = request.split("\\?")[1];
     ResponseHandler<String> responseHandler = 
            HTTP_REQUEST.executeWithQuery(parameters);

   System.out.println(responseHandler.getStatusCode());
   System.out.println(responseHandler.get()); //prints response body
}

If you are not interested in the response body

private static final HttpRequest<?> HTTP_REQUEST = 
     HttpRequestBuilder.createPost("http://example.com/index.php").build();

public void sendRequest(String request){
     ResponseHandler<String> responseHandler = 
           HTTP_REQUEST.executeWithQuery(parameters);
}

For general sending post request with http-request: Read the documentation and see my answers HTTP POST request with JSON String in JAVA, Sending HTTP POST Request In Java, HTTP POST using JSON in Java

Is it a bad practice to use break in a for loop?

I did some analysis on the codebase I'm currently working on (40,000 lines of JavaScript).

I found only 22 break statements, of those:

  • 19 were used inside switch statements (we only have 3 switch statements in total!).
  • 2 were used inside for loops - a code that I immediately classified as to be refactored into separate functions and replaced with return statement.
  • As for the final break inside while loop... I ran git blame to see who wrote this crap!

So according to my statistics: If break is used outside of switch, it is a code smell.

I also searched for continue statements. Found none.

Get the first element of an array

PHP 5.4+:

array_values($array)[0];

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

The simplest code would be like, keep your properties files into resources folder, either in src/main/resource or in src/test/resource. Then use below code to read properties files:

public class Utilities {
    static {
        rb1 = ResourceBundle.getBundle("fileNameWithoutExtension"); 
              // do not use .properties extension
    }
    public static String getConfigProperties(String keyString) {
        return rb1.getString(keyString);
    }
}

How do I get Maven to use the correct repositories?

Basically, all Maven is telling you is that certain dependencies in your project are not available in the central maven repository. The default is to look in your local .m2 folder (local repository), and then any configured repositories in your POM, and then the central maven repository. Look at the repositories section of the Maven reference.

The problem is that the project that was checked in didn't configure the POM in such a way that all the dependencies could be found and the project could be built from scratch.

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

Check if program is running with bash shell script?

PROCESS="process name shown in ps -ef"
START_OR_STOP=1        # 0 = start | 1 = stop

MAX=30
COUNT=0

until [ $COUNT -gt $MAX ] ; do
        echo -ne "."
        PROCESS_NUM=$(ps -ef | grep "$PROCESS" | grep -v `basename $0` | grep -v "grep" | wc -l)
        if [ $PROCESS_NUM -gt 0 ]; then
            #runs
            RET=1
        else
            #stopped
            RET=0
        fi

        if [ $RET -eq $START_OR_STOP ]; then
            sleep 5 #wait...
        else
            if [ $START_OR_STOP -eq 1 ]; then
                    echo -ne " stopped"
            else
                    echo -ne " started"
            fi
            echo
            exit 0
        fi
        let COUNT=COUNT+1
done

if [ $START_OR_STOP -eq 1 ]; then
    echo -ne " !!$PROCESS failed to stop!! "
else
    echo -ne " !!$PROCESS failed to start!! "
fi
echo
exit 1

How to clear input buffer in C?

The program will not work properly because at Line 1, when the user presses Enter, it will leave in the input buffer 2 character: Enter key (ASCII code 13) and \n (ASCII code 10). Therefore, at Line 2, it will read the \n and will not wait for the user to enter a character.

The behavior you see at line 2 is correct, but that's not quite the correct explanation. With text-mode streams, it doesn't matter what line-endings your platform uses (whether carriage return (0x0D) + linefeed (0x0A), a bare CR, or a bare LF). The C runtime library will take care of that for you: your program will see just '\n' for newlines.

If you typed a character and pressed enter, then that input character would be read by line 1, and then '\n' would be read by line 2. See I'm using scanf %c to read a Y/N response, but later input gets skipped. from the comp.lang.c FAQ.

As for the proposed solutions, see (again from the comp.lang.c FAQ):

which basically state that the only portable approach is to do:

int c;
while ((c = getchar()) != '\n' && c != EOF) { }

Your getchar() != '\n' loop works because once you call getchar(), the returned character already has been removed from the input stream.

Also, I feel obligated to discourage you from using scanf entirely: Why does everyone say not to use scanf? What should I use instead?

How to quickly test some javascript code?

Following is a free list of tools you can use to check, test and verify your JS code:

  1. Google Code Playground
  2. JavaScript Sandbox
  3. jsbin
  4. jsfiddle
  5. pastebin
  6. jsdo.it
  7. firebug
  8. html5snippet.net

Hope this helps.

What is setup.py?

To install a Python package you've downloaded, you extract the archive and run the setup.py script inside:

python setup.py install

To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem

A package manager is more comfortable too, because it's familiar and reliable. On the other hand, each setup.py is novel, because it's specific to the package. It demands faith in convention "I trust this setup.py takes the same commands as others I have used in the past". That's a regrettable tax on mental willpower.

I'm not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it's awkard and jarring. There's a harmony to commands all being to the same package manager application. You might even grow fond it.

How to write log base(2) in c/c++

C99 has log2 (as well as log2f and log2l for float and long double).

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

Using JQuery hover with HTML image map

You should check out this plugin:

https://github.com/kemayo/maphilight

and the demo:

http://davidlynch.org/js/maphilight/docs/demo_usa.html

if anything, you might be able to borrow some code from it to fix yours.

Is there a java setting for disabling certificate validation?

In addition to the answers above. You can do it programmatically by implementing the TrustManager:

TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
          public java.security.cert.X509Certificate[] getAcceptedIssuers() {
           return null;
          }
          @Override
          public void checkClientTrusted(X509Certificate[] arg0, String arg1)
           throws CertificateException {}

          @Override
          public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {}
          }
     };

  SSLContext sc=null;
  try {
   sc = SSLContext.getInstance("SSL");
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  try {
   sc.init(null, trustAllCerts, new java.security.SecureRandom());
  } catch (KeyManagementException e) {
   e.printStackTrace();
  }
  HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
  // Create all-trusting host name verifier
  HostnameVerifier validHosts = new HostnameVerifier() {
  @Override
  public boolean verify(String arg0, SSLSession arg1) {
   return true;
  }
  };
  // All hosts will be valid
  HttpsURLConnection.setDefaultHostnameVerifier(validHosts);

However this is not a good practice for production.

This example on How to disable SSL certificat validation in Java contains a utility class you can copy in your project.

console.log(result) returns [object Object]. How do I get result.name?

Use console.log(JSON.stringify(result)) to get the JSON in a string format.

EDIT: If your intention is to get the id and other properties from the result object and you want to see it console to know if its there then you can check with hasOwnProperty and access the property if it does exist:

var obj = {id : "007", name : "James Bond"};
console.log(obj);                    // Object { id: "007", name: "James Bond" }
console.log(JSON.stringify(obj));    //{"id":"007","name":"James Bond"}
if (obj.hasOwnProperty("id")){
    console.log(obj.id);             //007
}

How to convert Blob to String and String to Blob in java

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

How to convert password into md5 in jquery?

jQuery doesnt have a method to provide the md5 of a string. So you need to use some external script. There is a plugin called jQuery MD5. and it gives you number of methods to achieve md5. Few of those are

Create (hex-encoded) MD5 hash of a given string value:

var md5 = $.md5('value');

Create (hex-encoded) HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key');

Create raw MD5 hash of a given string value:

var md5 = $.md5('value', null, true);

Create raw HMAC-MD5 hash of a given string value and key:

var md5 = $.md5('value', 'key', true);

This might do what you want... Check the snippet here. jQuery MD5

SyntaxError: Cannot use import statement outside a module

just add --presets '@babel/preset-env'

e.g.

babel-node --trace-deprecation --presets '@babel/preset-env' ./yourscript.js

OR

in babel.config.js

module.exports = {
  presets: ['@babel/preset-env'],
};

Time complexity of Euclid's Algorithm

Here's intuitive understanding of runtime complexity of Euclid's algorithm. The formal proofs are covered in various texts such as Introduction to Algorithms and TAOCP Vol 2.

First think about what if we tried to take gcd of two Fibonacci numbers F(k+1) and F(k). You might quickly observe that Euclid's algorithm iterates on to F(k) and F(k-1). That is, with each iteration we move down one number in Fibonacci series. As Fibonacci numbers are O(Phi ^ k) where Phi is golden ratio, we can see that runtime of GCD was O(log n) where n=max(a, b) and log has base of Phi. Next, we can prove that this would be the worst case by observing that Fibonacci numbers consistently produces pairs where the remainders remains large enough in each iteration and never become zero until you have arrived at the start of the series.

We can make O(log n) where n=max(a, b) bound even more tighter. Assume that b >= a so we can write bound at O(log b). First, observe that GCD(ka, kb) = GCD(a, b). As biggest values of k is gcd(a,c), we can replace b with b/gcd(a,b) in our runtime leading to more tighter bound of O(log b/gcd(a,b)).

Change Spinner dropdown icon

We can manage it by hiding the icon as i did:

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Spinner android:id="@+id/fragment_filter_sp_users"
             android:layout_width="match_parent"
             android:background="@color/colorTransparent"
             android:layout_height="wrap_content"/>

    <ImageView
            android:layout_gravity="end|bottom"
            android:contentDescription="@null"
            android:layout_marginBottom="@dimen/_5sdp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_arrow_bottom"
    />
</FrameLayout>

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

For Intellij IDEA version 11.0.2

File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.

Next goto Build | Build artifacts --> choose your artifact.

source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/

Create a list from two object lists with linq

You need something like a full outer join. System.Linq.Enumerable has no method that implements a full outer join, so we have to do it ourselves.

var dict1 = list1.ToDictionary(l1 => l1.Name);
var dict2 = list2.ToDictionary(l2 => l2.Name);
    //get the full list of names.
var names = dict1.Keys.Union(dict2.Keys).ToList();
    //produce results
var result = names
.Select( name =>
{
  Person p1 = dict1.ContainsKey(name) ? dict1[name] : null;
  Person p2 = dict2.ContainsKey(name) ? dict2[name] : null;
      //left only
  if (p2 == null)
  {
    p1.Change = 0;
    return p1;
  }
      //right only
  if (p1 == null)
  {
    p2.Change = 0;
    return p2;
  }
      //both
  p2.Change = p2.Value - p1.Value;
  return p2;
}).ToList();

Check if Python Package is installed

Hmmm ... the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.

How about 'pip freeze | grep pkgname'? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).

Using varchar(MAX) vs TEXT on SQL Server

  • Basic Definition

TEXT and VarChar(MAX) are Non-Unicode large Variable Length character data type, which can store maximum of 2147483647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).

  • Which one to Use?

As per MSDN link Microsoft is suggesting to avoid using the Text datatype and it will be removed in a future versions of Sql Server. Varchar(Max) is the suggested data type for storing the large string values instead of Text data type.

  • In-Row or Out-of-Row Storage

Data of a Text type column is stored out-of-row in a separate LOB data pages. The row in the table data page will only have a 16 byte pointer to the LOB data page where the actual data is present. While Data of a Varchar(max) type column is stored in-row if it is less than or equal to 8000 byte. If Varchar(max) column value is crossing the 8000 bytes then the Varchar(max) column value is stored in a separate LOB data pages and row will only have a 16 byte pointer to the LOB data page where the actual data is present. So In-Row Varchar(Max) is good for searches and retrieval.

  • Supported/Unsupported Functionalities

Some of the string functions, operators or the constructs which doesn’t work on the Text type column, but they do work on VarChar(Max) type column.

  1. = Equal to Operator on VarChar(Max) type column
  2. Group by clause on VarChar(Max) type column

    • System IO Considerations

As we know that the VarChar(Max) type column values are stored out-of-row only if the length of the value to be stored in it is greater than 8000 bytes or there is not enough space in the row, otherwise it will store it in-row. So if most of the values stored in the VarChar(Max) column are large and stored out-of-row, the data retrieval behavior will almost similar to the one that of the Text type column.

But if most of the values stored in VarChar(Max) type columns are small enough to store in-row. Then retrieval of the data where LOB columns are not included requires the more number of data pages to read as the LOB column value is stored in-row in the same data page where the non-LOB column values are stored. But if the select query includes LOB column then it requires less number of pages to read for the data retrieval compared to the Text type columns.

Conclusion

Use VarChar(MAX) data type rather than TEXT for good performance.

Source

How to vertically center a container in Bootstrap?

If you're using Bootstrap 4, you just have to add 2 divs:

_x000D_
_x000D_
.jumbotron{_x000D_
  height:100%;_x000D_
  width:100%;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>    _x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
  <div class="jumbotron">_x000D_
    <div class="d-table w-100 h-100">_x000D_
      <div class="d-table-cell w-100 h-100 align-middle">_x000D_
        <h5>_x000D_
          your stuff..._x000D_
        </h5>_x000D_
        <div class="container">_x000D_
          <div class="row">_x000D_
            <div class="col-12">_x000D_
              <p>_x000D_
                More stuff..._x000D_
              </p>_x000D_
            </div>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

The classes: d-table, d-table-cell, w-100, h-100 and align-middle will do the job

How do I share a global variable between c files?

using extern <variable type> <variable name> in a header or another C file.

How to convert text to binary code in JavaScript?

  1. traverse the string
  2. convert every character to their char code
  3. convert the char code to binary
  4. push it into an array and add the left 0s
  5. return a string separated by space

Code:

function textToBin(text) {
  var length = text.length,
      output = [];
  for (var i = 0;i < length; i++) {
    var bin = text[i].charCodeAt().toString(2);
    output.push(Array(8-bin.length+1).join("0") + bin);
  } 
  return output.join(" ");
}
textToBin("!a") => "00100001 01100001"

Another way

function textToBin(text) {
  return (
    Array
      .from(text)
      .reduce((acc, char) => acc.concat(char.charCodeAt().toString(2)), [])
      .map(bin => '0'.repeat(8 - bin.length) + bin )
      .join(' ')
  );
}

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Unable to create/open lock file: /data/mongod.lock errno:13 Permission denied

Removing the mongodb.lock file was not the issue in my case. I did so and got an error about the port being in use: [initandlisten] listen(): bind() failed errno:98 Address already in use for socket: 0.0.0.0:27017. I found another solution here: unable to start mongodb local server with instructions to kill the process:

  1. Find out from netstat which process is running mongodb port (27017)

    sudo netstat -tulpn | grep :27017

    Output will be: tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 1412/mongod

  2. Kill the appropriate process.

    sudo kill 1412 (replace 1412 with your process ID found in step 1)

And I was able to successfully start mongodb again. I believe mine was still running from an improper shut down.

How to flip background image using CSS?

According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

HTML:

<footer>
<p><a href="page">Footer Link</a></p>
<p>&copy; 2014 Company</p>
</footer>

CSS:

footer {
background:url(/img/headerbg.png) repeat-x 0 0;

/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

Converting VS2012 Solution to VS2010

Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx

Android MediaPlayer Stop and Play

You should use only one mediaplayer object

    public class PlayaudioActivity extends Activity {

        private MediaPlayer mp;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button b = (Button) findViewById(R.id.button1);
            Button b2 = (Button) findViewById(R.id.button2);
            final TextView t = (TextView) findViewById(R.id.textView1);

            b.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.far);
                    mp.start();
                }

            });

            b2.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    stopPlaying();
                    mp = MediaPlayer.create(PlayaudioActivity.this, R.raw.beet);
                    mp.start();
                }
            });
        }

        private void stopPlaying() {
            if (mp != null) {
                mp.stop();
                mp.release();
                mp = null;
           }
        }
    }

Padding between ActionBar's home icon and title

For me only the following combination worked, tested from API 18 to 24

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp"

where in "app" is : xmlns:app="http://schemas.android.com/apk/res-auto"

for example.

 <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/SE_Life_Green"
                app:contentInsetLeft="0dp"
                app:contentInsetStart="0dp"
                app:contentInsetStartWithNavigation="0dp"
                >
                .......
                .......
                .......
            </android.support.v7.widget.Toolbar>

Give all permissions to a user on a PostgreSQL database

I did the following to add a role 'eSumit' on PostgreSQL 9.4.15 database and provide all permission to this role :

CREATE ROLE eSumit;

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO eSumit;

GRANT ALL PRIVILEGES ON DATABASE "postgres" to eSumit;

ALTER USER eSumit WITH SUPERUSER;

Also checked the pg_table enteries via :

select * from pg_roles; enter image description here

Database queries snapshot : enter image description here

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

How to use null in switch

switch (String.valueOf(value)){
    case "null":
    default: 
}

IsNullOrEmpty with Object

IsNullOrEmpty is essentially shorthand for the following:

return str == null || str == String.Empty;

So, no there is no function that just checks for nulls because it would be too simple. obj != null is the correct way. But you can create such a (superfluous) function yourself using the following extension:

public bool IsNull(this object obj)
{
    return obj == null;
}

Then you are able to run anyObject.IsNull().

Set database from SINGLE USER mode to MULTI USER

I googled for the solution for a while and finally came up with the below solution,

SSMS in general uses several connections to the database behind the scenes.

You will need to kill these connections before changing the access mode.(I have done it with EXEC(@kill); in the code template below.)

Then,

Run the following SQL to set the database in MULTI_USER mode.

USE master
GO
DECLARE @kill varchar(max) = '';
SELECT @kill = @kill + 'KILL ' + CONVERT(varchar(10), spid) + '; '
FROM master..sysprocesses 
WHERE spid > 50 AND dbid = DB_ID('<Your_DB_Name>')
EXEC(@kill);

GO
SET DEADLOCK_PRIORITY HIGH
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

To switch back to Single User mode, you can use:

ALTER DATABASE [<Your_DB_Name>] SET SINGLE_USER

This should work. Happy coding!!

Thanks!!

Debug assertion failed. C++ vector subscript out of range

v has 10 element, the index starts from 0 to 9.

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}

you should update for loop to

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}

Or use reverse iterator to print element in reverse order

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}

Floating point inaccuracy examples

Another example, in C

printf (" %.20f \n", 3.6);

incredibly gives

3.60000000000000008882

How to check version of python modules?

To get a list of non-standard (pip) modules imported in the current module:

[{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() 
   if pkg.key in set(sys.modules) & set(globals())]

Result:

>>> import sys, pip, nltk, bs4
>>> [{pkg.key : pkg.version} for pkg in pip.get_installed_distributions() if pkg.key in set(sys.modules) & set(globals())]
[{'pip': '9.0.1'}, {'nltk': '3.2.1'}, {'bs4': '0.0.1'}]

Note:

This code was put together from solutions both on this page and from How to list imported modules?

Add values to app.config and retrieve them

Are you missing the reference to System.Configuration.dll? ConfigurationManager class lies there.

EDIT: The System.Configuration namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default...

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

Regex to validate JSON

I realize that this is from over 6 years ago. However, I think there is a solution that nobody here has mentioned that is way easier than regexing

function isAJSON(string) {
    try {
        JSON.parse(string)  
    } catch(e) {
        if(e instanceof SyntaxError) return false;
    };  
    return true;
}

Creating an empty file in C#

Path.GetTempFileName() will create a uniquly named empty file and return the path to it.

If you want to control the path but get a random file name you can use GetRandomFileName to just return a file name string and use it with Create

For example:

string fileName=Path.GetRandomFileName();
File.Create("custom\\path\\" + fileName);