Programs & Examples On #Final

final is a common keyword specifying that the reference declared as final cannot be modified once it is initialized. In Java the keyword final is roughly equivalent to const in C++. In C++ the final keyword allows you to declare a virtual method, override it N times and then mandate that 'this can no longer be overridden'.

What is the point of "final class" in Java?

One advantage of keeping a class as final :-

String class is kept final so that no one can override its methods and change the functionality. e.g no one can change functionality of length() method. It will always return length of a string.

Developer of this class wanted no one to change functionality of this class, so he kept it as final.

Why should I use the keyword "final" on a method parameter in Java?

Since Java passes copies of arguments I feel the relevance of final is rather limited. I guess the habit comes from the C++ era where you could prohibit reference content from being changed by doing a const char const *. I feel this kind of stuff makes you believe the developer is inherently stupid as f*** and needs to be protected against truly every character he types. In all humbleness may I say, I write very few bugs even though I omit final (unless I don't want someone to override my methods and classes). Maybe I'm just an old-school dev.

final keyword in method parameters

@stuXnet, I could make the exact opposite argument. If you pass an object to a function, and you change the properties of the passed object then the caller of the function will see the changed value in its variable. This implies a pass by reference system, not pass by value.

What is confusing is the definition of pass by value or pass by reference in a system where the use of pointers is completely hidden to the end user.

Java is definitely NOT pass by value, as to be such, would mean one could mutate the passed object and the original would be unaffected.

Notice you cannot mutate primitives you can only assign them to variables. So testing a Pass by reference or by value by using primitives is not a test.

What you cannot do in Java that can be done in other languages is to reassign the caller's variables to a new value because there are no pointers in Java, so this makes it confusing.

What is the purpose of the "final" keyword in C++11 for functions?

Nothing to add to the semantic aspects of "final".

But I'd like to add to chris green's comment that "final" might become a very important compiler optimization technique in the not so distant future. Not only in the simple case he mentioned, but also for more complex real-world class hierarchies which can be "closed" by "final", thus allowing compilers to generate more efficient dispatching code than with the usual vtable approach.

One key disadvantage of vtables is that for any such virtual object (assuming 64-bits on a typical Intel CPU) the pointer alone eats up 25% (8 of 64 bytes) of a cache line. In the kind of applications I enjoy to write, this hurts very badly. (And from my experience it is the #1 argument against C++ from a purist performance point of view, i.e. by C programmers.)

In applications which require extreme performance, which is not so unusual for C++, this might indeed become awesome, not requiring to workaround this problem manually in C style or weird Template juggling.

This technique is known as Devirtualization. A term worth remembering. :-)

There is a great recent speech by Andrei Alexandrescu which pretty well explains how you can workaround such situations today and how "final" might be part of solving similar cases "automatically" in the future (discussed with listeners):

http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly

Difference between final and effectively final

If you could add the final modifier to a local variable, it was effectively final.

Lambda expressions can access

  • static variables,

  • instance variables,

  • effectively final method parameters, and

  • effectively final local variables.

Source: OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide, Jeanne Boyarsky, Scott Selikoff

Additionally,

An effectively final variable is a variable whose value is never changed, but it isn’t declared with the final keyword.

Source: Starting Out with Java: From Control Structures through Objects (6th Edition), Tony Gaddis

Furthermore, don't forget the meaning of final that it is initialized exactly once before it is used for the first time.

How does the "final" keyword in Java work? (I can still modify an object.)

The final keyword indicates that a variable may only be initialized once. In your code you are only performing one initialization of final so the terms are satisfied. This statement performs the lone initialization of foo. Note that final != immutable, it only means that the reference cannot change.

foo = new ArrayList();

When you declare foo as static final the variable must be initialized when the class is loaded and cannot rely on instantiation (aka call to constructor) to initialize foo since static fields must be available without an instance of a class. There is no guarantee that the constructor will have been called prior to using the static field.

When you execute your method under the static final scenario the Test class is loaded prior to instantiating t at this time there is no instantiation of foo meaning it has not been initialized so foo is set to the default for all objects which is null. At this point I assume your code throws a NullPointerException when you attempt to add an item to the list.

private final static attribute vs private final attribute

If you mark this variable static then as you know, you would be requiring static methods to again access these values,this will be useful if you already think of using these variables only in static methods. If this is so then this would be the best one.

You can however make the variable now as public since no one can modify it just like "System.out", it again depends upon your intentions and what you want to achieve.

Cannot refer to a non-final variable inside an inner class defined in a different method

When I stumble upon this issue, I just pass the objects to the inner class through the constructor. If I need to pass primitives or immutable objects (as in this case), a wrapper class is needed.

Edit: Actually, I don't use an anonymous class at all, but a proper subclass:

public class PriceData {
        private double lastPrice = 0;
        private double price = 0;

        public void setlastPrice(double lastPrice) {
            this.lastPrice = lastPrice;
        }

        public double getLastPrice() {
            return lastPrice;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public double getPrice() {
            return price;
        }
    }

    public class PriceTimerTask extends TimerTask {
        private PriceData priceData;
        private Price priceObject;

        public PriceTimerTask(PriceData priceData, Price priceObject) {
            this.priceData = priceData;
            this.priceObject = priceObject;
        }

        public void run() {
            priceData.setPrice(priceObject.getNextPrice(lastPrice));
            System.out.println();
            priceData.setLastPrice(priceData.getPrice());

        }
    }

    public static void main(String args[]) {

        int period = 2000;
        int delay = 2000;

        PriceData priceData = new PriceData();
        Price priceObject = new Price();

        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new PriceTimerTask(priceData, priceObject), delay, period);
    }

Why is there no Constant feature in Java?

There is a way to create "const" variables in Java, but only for specific classes. Just define a class with final properties and subclass it. Then use the base class where you would want to use "const". Likewise, if you need to use "const" methods, add them to the base class. The compiler will not allow you to modify what it thinks is the final methods of the base class, but it will read and call methods on the subclass.

Change private static final field using Java reflection

Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field.

Here's an example:

import java.lang.reflect.*;

public class EverythingIsTrue {
   static void setFinalStatic(Field field, Object newValue) throws Exception {
      field.setAccessible(true);

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }
   public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);

      System.out.format("Everything is %s", false); // "Everything is true"
   }
}

Assuming no SecurityException is thrown, the above code prints "Everything is true".

What's actually done here is as follows:

  • The primitive boolean values true and false in main are autoboxed to reference type Boolean "constants" Boolean.TRUE and Boolean.FALSE
  • Reflection is used to change the public static final Boolean.FALSE to refer to the Boolean referred to by Boolean.TRUE
  • As a result, subsequently whenever a false is autoboxed to Boolean.FALSE, it refers to the same Boolean as the one refered to by Boolean.TRUE
  • Everything that was "false" now is "true"

Related questions


Caveats

Extreme care should be taken whenever you do something like this. It may not work because a SecurityManager may be present, but even if it doesn't, depending on usage pattern, it may or may not work.

JLS 17.5.3 Subsequent Modification of Final Fields

In some cases, such as deserialization, the system will need to change the final fields of an object after construction. final fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then the final fields of the object are updated. The object should not be made visible to other threads, nor should the final fields be read, until all updates to the final fields of the object are complete. Freezes of a final field occur both at the end of the constructor in which the final field is set, and immediately after each modification of a final field via reflection or other special mechanism.

Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant.

Another problem is that the specification allows aggressive optimization of final fields. Within a thread, it is permissible to reorder reads of a final field with those modifications of a final field that do not take place in the constructor.

See also

  • JLS 15.28 Constant Expression
    • It's unlikely that this technique works with a primitive private static final boolean, because it's inlineable as a compile-time constant and thus the "new" value may not be observable

Appendix: On the bitwise manipulation

Essentially,

field.getModifiers() & ~Modifier.FINAL

turns off the bit corresponding to Modifier.FINAL from field.getModifiers(). & is the bitwise-and, and ~ is the bitwise-complement.

See also


Remember Constant Expressions

Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?

public class A {
    private final String myVar = "Some Value";
}

Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:

public class A {
    private final String myVar;

    private A() {
        myVar = "Some Value";
    }
}

if you are not the owner of the class... I feel you!

For more details about why this behavior read this?

Why would one mark local variables and method parameters as "final" in Java?

I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.

Static Final Variable in Java

For the primitive types, the 'final static' will be a proper declaration to declare a constant. A non-static final variable makes sense when it is a constant reference to an object. In this case each instance can contain its own reference, as shown in JLS 4.5.4.

See Pavel's response for the correct answer.

when exactly are we supposed to use "public static final String"?

static means that the object will only be created once, and does not have an instance object containing it. The way you have written is best used when you have something that is common for all objects of the class and will never change. It even could be used without creating an object at all.

Usually it's best to use final when you expect it to be final so that the compiler will enforce that rule and you know for sure. static ensures that you don't waste memory creating many of the same thing if it will be the same value for all objects.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

The final keyword is used to declare constants.

final int FILE_TYPE = 3;

The finally keyword is used in a try catch statement to specify a block of code to execute regardless of thrown exceptions.

try
{
  //stuff
}
catch(Exception e)
{
  //do stuff
}
finally
{
  //this is always run
}

And finally (haha), finalize im not entirely sure is a keyword, but there is a finalize() function in the Object class.

How to set image to UIImage

just change this line

[img setImage:[UIImage imageNamed:@"anyImageName"]];

with following line

img = [UIImage imageNamed:@"anyImageName"];

Code for download video from Youtube on Java, Android

METHOD 1 ( Recommanded )

Library YouTubeExtractor

Add into your gradle file

 allprojects {
        repositories {
            maven { url "https://jitpack.io" }
        }
    }

And dependencies

 compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'

Add this small code and you done. Demo HERE

public class MainActivity extends AppCompatActivity {

    private static final String YOUTUBE_ID = "ea4-5mrpGfE";

    private final YouTubeExtractor mExtractor = YouTubeExtractor.create();


    private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
        @Override
        public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
            bindVideoResult(response.body());
        }

        @Override
        public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
            onError(t);
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


//        For android youtube extractor library  com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
        mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);

    }


    private void onError(Throwable t) {
        t.printStackTrace();
        Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
    }


    private void bindVideoResult(YouTubeExtractionResult result) {

//        Here you can get download url link
        Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());

        Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
    }
}

You can get download link in bindVideoResult() method.

METHOD 2

Using this library android-youtubeExtractor

Add into gradle file

repositories {
    maven { url "https://jitpack.io" }
}

compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'

Here is the code for getting download url.

       String youtubeLink = "http://youtube.com/watch?v=xxxx";

    YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
        @Override
        public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
            if (ytFiles != null) {
                int itag = 22;
// Here you can get download url
                String downloadUrl = ytFiles.get(itag).getUrl();
            }
        }
    };

    ytEx.execute(youtubeLink);

Function of Project > Clean in Eclipse

It removes whatever already-compiled files are in your project so that you can do a complete fresh rebuild.

How can I make an EXE file from a Python program?

Also known as Frozen Binaries but not the same as as the output of a true compiler- they run byte code through a virtual machine (PVM). Run the same as a compiled program just larger because the program is being compiled along with the PVM. Py2exe can freeze standalone programs that use the tkinter, PMW, wxPython, and PyGTK GUI libraties; programs that use the pygame game programming toolkit; win32com client programs; and more. The Stackless Python system is a standard CPython implementation variant that does not save state on the C language call stack. This makes Python more easy to port to small stack architectures, provides efficient multiprocessing options, and fosters novel programming structures such as coroutines. Other systems of study that are working on future development: Pyrex is working on the Cython system, the Parrot project, the PyPy is working on replacing the PVM altogether, and of course the founder of Python is working with Google to get Python to run 5 times faster than C with the Unladen Swallow project. In short, py2exe is the easiest and Cython is more efficient for now until these projects improve the Python Virtual Machine (PVM) for standalone files.

HttpServletRequest - Get query string parameters, no form data

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

SQL Server - Convert date field to UTC

I do not believe the above code will work. The reason is that it depends upon the difference between the current date in local and UTC times. For example, here in California we are now in PDT (Pacific Daylight Time); the difference between this time and UTC is 7 hours. The code provided will, if run now, add 7 hours to every date which is desired to be converted. But if a historical stored date, or a date in the future, is converted, and that date is not during daylight savings time, it will still add 7, when the correct offset is 8. Bottom line: you cannot convert date/times properly between time zones (including UTC, which does not obey daylight savings time) by only looking at the current date. You must consider the date itself that you are converting, as to whether daylight time was in force on that date. Furthermore, the dates at which daylight and standard times change themselves have changed (George Bush changed the dates during his administration for the USA!). In other words, any solution which even references getdate() or getutcdate() does not work. It must parse the actual date to be converted.

Sorting an ArrayList of objects using a custom sorting order

BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.

I just want to add that google-collections has an Ordering class which is more "powerful" than the standard Comparators. It might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects...

Here is a blog post that mentions some of its benefits.

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

List of ANSI color escape sequences

How about:

ECMA-48 - Control Functions for Coded Character Sets, 5th edition (June 1991) - A standard defining the color control codes, that is apparently supported also by xterm.

SGR 38 and 48 were originally reserved by ECMA-48, but were fleshed out a few years later in a joint ITU, IEC, and ISO standard, which comes in several parts and which (amongst a whole lot of other things) documents the SGR 38/48 control sequences for direct colour and indexed colour:

There's a column for xterm in this table on the Wikipedia page for ANSI escape codes

How to add DOM element script to head section?

As per the author, they want to create a script in the head, not a link to a script file. Also, to avoid complications from jQuery (which provides little useful functionality in this case), vanilla javascript is likely the better option.

That may possibly be done as such:

var script = document.createTextNode("<script>alert('Hi!');</script>");   
document.getElementsByTagName('head')[0].appendChild(script);

Handling a Menu Item Click Event - Android

This is how it looks like in Kotlin

main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    app:showAsAction="never" />
<item
    android:id="@+id/action_logout"
    android:orderInCategory="101"
    android:title="@string/sign_out"
    app:showAsAction="never" />

Then in MainActivity

override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.main, menu)
    return true
}

This is onOptionsItemSelected function

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    return when(item.itemId){
        R.id.action_settings -> {
            true
        }
        R.id.action_logout -> {
            signOut()
            true
        }
        else -> return super.onOptionsItemSelected(item)
    }
}

For starting new activity

private fun signOut(){
    MySharedPreferences.clearToken()
    startSplashScreenActivity()
}

private fun startSplashScreenActivity(){
    val intent = Intent(GrepToDo.applicationContext(), SplashScreenActivity::class.java)
    startActivity(intent)
    finish()
}

Should I use Vagrant or Docker for creating an isolated environment?

There is a really informative article in the actual Oracle Java magazine about using Docker in combination with Vagrant (and Puppet):

Conclusion

Docker’s lightweight containers are faster compared with classic VMs and have become popular among developers and as part of CD and DevOps initiatives. If your purpose is isolation, Docker is an excellent choice. Vagrant is a VM manager that enables you to script configurations of individual VMs as well as do the provisioning. However, it is sill a VM dependent on VirtualBox (or another VM manager) with relatively large overhead. It requires you to have a hard drive idle that can be huge, it takes a lot of RAM, and performance can be suboptimal. Docker uses kernel cgroups and namespace isolation via LXC. This means that you are using the same kernel as the host and the same ile system. Vagrant is a level above Docker in terms of abstraction, so they are not really comparable. Configuration management tools such as Puppet are widely used for provisioning target environments. Reusing existing Puppet-based solutions is easy with Docker. You can also slice your solution, so the infrastructure is provisioned with Puppet; the middleware, the business application itself, or both are provisioned with Docker; and Docker is wrapped by Vagrant. With this range of tools, you can do what’s best for your scenario.

How to build, use and orchestrate Docker containers in DevOps http://www.javamagazine.mozaicreader.com/JulyAug2015#&pageSet=34&page=0

"Cross origin requests are only supported for HTTP." error when loading a local file

Use http:// or https:// to create url

error: localhost:8080

solution: http://localhost:8080

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

Compute row average in pandas

If you are looking to average column wise. Try this,

df.drop('Region', axis=1).apply(lambda x: x.mean())

# it drops the Region column
df.drop('Region', axis=1,inplace=True)

Convert UTF-8 encoded NSData to NSString

If the data is not null-terminated, you should use -initWithData:encoding:

NSString* newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];

If the data is null-terminated, you should instead use -stringWithUTF8String: to avoid the extra \0 at the end.

NSString* newStr = [NSString stringWithUTF8String:[theData bytes]];

(Note that if the input is not properly UTF-8-encoded, you will get nil.)


Swift variant:

let newStr = String(data: data, encoding: .utf8)
// note that `newStr` is a `String?`, not a `String`.

If the data is null-terminated, you could go though the safe way which is remove the that null character, or the unsafe way similar to the Objective-C version above.

// safe way, provided data is \0-terminated
let newStr1 = String(data: data.subdata(in: 0 ..< data.count - 1), encoding: .utf8)
// unsafe way, provided data is \0-terminated
let newStr2 = data.withUnsafeBytes(String.init(utf8String:))

Undefined behavior and sequence points

I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:

f (a,b)

previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.

Good PHP ORM Library?

I am currently working on phpDataMapper, which is an ORM designed to have simple syntax like Ruby's Datamapper project. It's still in early development as well, but it works great.

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).

Please verify cell values either are null or do handle Exception and see.

Best, Shahid

Test file upload using HTTP PUT method

For curl, how about using the -d switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

What is the cleanest way to ssh and run multiple commands in Bash?

The posted answers using multiline strings and multiple bash scripts did not work for me.

  • Long multiline strings are hard to maintain.
  • Separate bash scripts do not maintain local variables.

Here is a functional way to ssh and run multiple commands while keeping local context.

LOCAL_VARIABLE=test

run_remote() {
    echo "$LOCAL_VARIABLE"
    ls some_folder; 
    ./someaction.sh 'some params'
    ./some_other_action 'other params'
}

ssh otherhost "$(set); run_remote"

How to disable/enable select field using jQuery?

Just simply use:

var update_pizza = function () {
     $("#pizza_kind").prop("disabled", !$('#pizza').prop('checked'));
};

update_pizza();
$("#pizza").change(update_pizza);

DEMO ?

Why would one mark local variables and method parameters as "final" in Java?

Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.

The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.

Edit

In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.

Java Strings: "String s = new String("silly");"

Just because you have the word String in your class, does not mean you get all the special features of the built-in String class.

angular 2 ngIf and CSS transition/animation

In my case I declared the animation on the wrong component by mistake.

app.component.html

  <app-order-details *ngIf="orderDetails" [@fadeInOut] [orderDetails]="orderDetails">
  </app-order-details>

The animation needs to be declared on the component where the element is used in (appComponent.ts). I was declaring the animation on OrderDetailsComponent.ts instead.

Hopefully it will help someone making the same mistake

Requested bean is currently in creation: Is there an unresolvable circular reference?

@Resource annotation on field level also could be used to declare look up at runtime

Output Django queryset as JSON

To return the queryset you retrieved with queryset = Users.objects.all(), you first need to serialize them.

Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.

from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View

class JSONListView(View):
    def get(self, request, *args, **kwargs):
        qs = User.objects.all()
        data = serialize("json", qs)
        return JsonResponse(data)

This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.

Operation must use an updatable query. (Error 3073) Microsoft Access

There is another scenario here that would apply. A file that was checked out of Visual Source Safe, for anyone still using it, that was not given "Writeablity", either in the View option or Check Out, will also recieve this error message.

Solution is to re-acquire the file from Source Safe and apply the Writeability setting.

"ssl module in Python is not available" when installing package with pip3

I encountered the same problem on windows 10. My very specific issue is due to my installation of Anaconda. I installed Anaconda and under the path Path/to/Anaconda3/, there comes the python.exe. Thus, I didn't install python at all because Anaconda includes python. When using pip to install packages, I found the same error report, pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available..

The solution was the following:

1) you can download python again on the official website;

2) Navigate to the directory where "Python 3.7 (64-bit).lnk"is located

3) import ssl and exit()

4) type in cmd, "Python 3.7 (64-bit).lnk" -m pip install tensorflow for instance.

Here, you're all set.

SSIS cannot convert because a potential loss of data

This might not be the best method, but you can ignore the conversion error if all else fails. Mine was an issue of nulls not converting properly, so I just ignored the error and the dates came in as dates and the nulls came in as nulls, so no data quality issues--not that this would always be the case. To do this, right click on your source, click Edit, then Error Output. Go to the column that's giving you grief and under Error change it to Ignore Failure.

How to find text in a column and saving the row number where it is first found - Excel VBA

A few comments:

  1. Since the search position is important you should specify where you start the search. I use ws.[a1] and xlNext below so my search starts in A2 of the specified sheet.
  2. Some of Finds arguments - including lookat use the prior search settings. So you should always specify xlWhole or xlPart to match all or part a string respectively.
  3. You can do all you want - including inserting a row, and prompting the user for a new value (my code will suggest 20 if the prior value was 19) without using Select or Activate

suggested code

Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub

Plotting categorical data with pandas and matplotlib

You can simply use value_counts on the series:

df['colour'].value_counts().plot(kind='bar')

enter image description here

Get lengths of a list in a jinja2 template

I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()

My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:

{{'0' if linked_contacts == None else linked_contacts|length}}

How to sort dates from Oldest to Newest in Excel?

Here's how to sort unsorted dates:

Drag down the column to select the dates you want to sort.

Click Home tab > arrow under Sort & Filter, and then click Sort Oldest to Newest, or Sort Newest to Oldest.

NOTE: If the results aren't what you expected, the column might have dates that are stored as text instead of dates. Convert dates stored as text to dates.

Contains method for a slice

Not sure generics are needed here. You just need a contract for your desired behavior. Doing the following is no more than what you would have to do in other languages if you wanted your own objects to behave themselves in collections, by overriding Equals() and GetHashCode() for instance.

type Identifiable interface{
    GetIdentity() string
}

func IsIdentical(this Identifiable, that Identifiable) bool{
    return (&this == &that) || (this.GetIdentity() == that.GetIdentity())
}

func contains(s []Identifiable, e Identifiable) bool {
    for _, a := range s {
        if IsIdentical(a,e) {
            return true
        }
    }
    return false
}

Add views below toolbar in CoordinatorLayout

I managed to fix this by adding:

android:layout_marginTop="?android:attr/actionBarSize"

to the FrameLayout like so:

 <FrameLayout
        android:id="@+id/content"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />

Setting a spinner onClickListener() in Android

I suggest that all events for Spinner are divided on two types:

  1. User events (you meant as "click" event).

  2. Program events.

I also suggest that when you want to catch user event you just want to get rid off "program events". So it's pretty simple:

private void setSelectionWithoutDispatch(Spinner spinner, int position) {
    AdapterView.OnItemSelectedListener onItemSelectedListener = spinner.getOnItemSelectedListener();
    spinner.setOnItemSelectedListener(null);
    spinner.setSelection(position, false);
    spinner.setOnItemSelectedListener(onItemSelectedListener);
}

There's a key moment: you need setSelection(position, false). "false" in animation parameter will fire event immediately. The default behaviour is to push event to event queue.

How to change default timezone for Active Record in Rails?

If you want local time to set, add the following text in application.rb

config.time_zone = 'Chennai'

# WARNING: This changes the way times are stored in the database (not recommended)
config.active_record.default_timezone = :local

Then restart your server

ORA-01882: timezone region not found

In my case I could get the query working by changing "TZR" with "TZD"..

String query = "select * from table1 to_timestamp_tz(origintime,'dd-mm-yyyy hh24:mi:ss TZD') between ?  and ?";

good example of Javadoc

If you are using Eclipse, then you can setup your JDK (not JRE) in Installed JREs, and then use Open Type (Ctrl + Shift + T), give something like java.util.Collections

pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available

Worked for me.

apt-get install libssl-dev

Use this to enable ssl for pip. Let me know if someone encounters issues.

How can I label points in this scatterplot?

For just plotting a vector, you should use the following command:

text(your.vector, labels=your.labels, cex= labels.size, pos=labels.position)

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Comments in Markdown

kramdown—the Ruby-based markdown engine that is the default for Jekyll and thus GitHub Pages—has built-in comment support through its extension syntax:

{::comment}
This text is completely ignored by kramdown - a comment in the text.
{:/comment}

Do you see {::comment}this text{:/comment}?
{::comment}some other comment{:/}

This has the benefit of allowing in-line comments, but the downside of not being portable to other Markdown engines.

How to remove unwanted space between rows and columns in table?

For standards compliant HTML5 add all this css to remove all space between images in tables:

table { 
    border-spacing: 0;
    border-collapse: collapse;
}
td {
    padding:0px;
}
td img {
    display:block;
}

How to get year and month from a date - PHP

Using date() and strtotime() from the docs.

$date = "2012-01-05";

$year = date('Y', strtotime($date));

$month = date('F', strtotime($date));

echo $month

Replace all double quotes within String

Would not that have to be:

.replaceAll("\"","\\\\\"")

FIVE backslashes in the replacement String.

How to format numbers as currency string?

Numeral.js - a js library for easy number formatting by @adamwdraper

numeral(23456.789).format('$0,0.00'); // = "$23,456.79"

C# Error: Parent does not contain a constructor that takes 0 arguments

You need to change your child's constructor to:

public child(int i) : base(i)
{
    // etc...
}

You were getting the error because your parent class's constructor takes a parameter but you are not passing that parameter from the child to the parent.

Constructors are not inherited in C#, you have to chain them manually.

C++ Fatal Error LNK1120: 1 unresolved externals

You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.

How to declare variable and use it in the same Oracle SQL script?

Here's your answer:

DEFINE num := 1;       -- The semi-colon is needed for default values.
SELECT &num FROM dual;

Waiting for HOME ('android.process.acore') to be launched

It worked for me when I selected 'Use Host GPU' option under 'Emulation Options:'.

You can find the option under Edit window of the virtual device.

enter image description here

how to get session id of socket.io client in Client

Try from your code socket.socket.sessionid ie.

    var socket = io.connect('http://localhost');
alert(socket.socket.sessionid);
  var sendBtn= document.getElementById('btnSend');
  sendBtn.onclick= function(){
var userId=document.getElementById('txt1').value;
var userMsg = document.getElementById('txt2').value;
socket.emit('sendto',{username: userId, message: userMsg});
};

  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
  socket.on('message',function(data){ console.log(data);});

How do I redirect with JavaScript?

  • If you want to simulate someone clicking on a link, use location.href.
  • If you want to simulate an HTTP redirect, use location.replace.

For example:

// Similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// Similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

Information copied from this answer to a duplicate question

Android camera intent

try this code

Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
                    startActivityForResult(photo, CAMERA_PIC_REQUEST);

how to replace characters in hive?

There is no OOTB feature at this moment which allows this. One way to achieve that could be to write a custom InputFormat and/or SerDe that will do this for you. You might this JIRA useful : https://issues.apache.org/jira/browse/HIVE-3751. (not related directly to your problem though).

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

Multiple IF statements between number ranges

It's a little tricky because of the nested IFs but here is my answer (confirmed in Google Spreadsheets):

=IF(AND(A2>=0,    A2<500),  "Less than 500", 
 IF(AND(A2>=500,  A2<1000), "Between 500 and 1000", 
 IF(AND(A2>=1000, A2<1500), "Between 1000 and 1500", 
 IF(AND(A2>=1500, A2<2000), "Between 1500 and 2000", "Undefined"))))

Spring Boot: How can I set the logging level with application.properties?

The proper way to set the root logging level is using the property logging.level.root. See documentation, which has been updated since this question was originally asked.

Example:

logging.level.root=WARN

Javascript Cookie with no expiration date

You could possibly set a cookie at an expiration date of a month or something and then reassign the cookie every time the user visits the website again

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

What are good grep tools for Windows?

Well, beside the Windows port of the GNU grep at:

http://gnuwin32.sourceforge.net/

there's also Borland's grep (very similar to GNU one) available in the freeware Borland's Free C++ Compiler (it's a freeware with command line tools).

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

How do I call a SQL Server stored procedure from PowerShell?

This answer was pulled from http://www.databasejournal.com/features/mssql/article.php/3683181

This same example can be used for any adhoc queries. Let us execute the stored procedure “sp_helpdb” as shown below.

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=HOME\SQLEXPRESS;Database=master;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "sp_helpdb"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$DataSet.Tables[0]

How to find the port for MS SQL Server 2008?

This works for SQL Server 2005 - 2012. Look for event id = 26022 in the error log under applications. That will show the port number of sql server as well as what ip addresses are allowed to access.

Python - Using regex to find multiple matches and print them out

Do not use regular expressions to parse HTML.

But if you ever need to find all regexp matches in a string, use the findall function.

import re
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
matches = re.findall('<form>(.*?)</form>', line, re.DOTALL)
print(matches)

# Output: ['Form 1', 'Form 2']

How to submit a form with JavaScript by clicking a link?

The best way

The best way is to insert an appropriate input tag:

<input type="submit" value="submit" />

The best JS way

<form id="form-id">
  <button id="your-id">submit</button>
</form>
var form = document.getElementById("form-id");

document.getElementById("your-id").addEventListener("click", function () {
  form.submit();
});

Enclose the latter JavaScript code by an DOMContentLoaded event (choose only load for backward compatiblity) if you haven't already done so:

window.addEventListener("DOMContentLoaded", function () {
  var form = document.... // copy the last code block!
});

The easy, not recommandable way (the former answer)

Add an onclick attribute to the link and an id to the form:

<form id="form-id">

  <a href="#" onclick="document.getElementById('form-id').submit();"> submit </a>

</form>

All ways

Whatever way you choose, you have call formObject.submit() eventually (where formObject is the DOM object of the <form> tag).

You also have to bind such an event handler, which calls formObject.submit(), so it gets called when the user clicked a specific link or button. There are two ways:

  • Recommended: Bind an event listener to the DOM object.

    // 1. Acquire a reference to our <form>.
    //    This can also be done by setting <form name="blub">:
    //       var form = document.forms.blub;
    
    var form = document.getElementById("form-id");
    
    
    // 2. Get a reference to our preferred element (link/button, see below) and
    //    add an event listener for the "click" event.
    document.getElementById("your-id").addEventListener("click", function () {
      form.submit();
    });
    
  • Not recommended: Insert inline JavaScript. There are several reasons why this technique is not recommendable. One major argument is that you mix markup (HTML) with scripts (JS). The code becomes unorganized and rather unmaintainable.

    <a href="#" onclick="document.getElementById('form-id').submit();">submit</a>
    
    <button onclick="document.getElementById('form-id').submit();">submit</button>
    

Now, we come to the point at which you have to decide for the UI element which triggers the submit() call.

  1. A button

    <button>submit</button>
    
  2. A link

    <a href="#">submit</a>
    

Apply the aforementioned techniques in order to add an event listener.

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays have numerical indexes. So,

a = new Array();
a['a1']='foo';
a['a2']='bar';

and

b = new Array(2);
b['b1']='foo';
b['b2']='bar';

are not adding elements to the array, but adding .a1 and .a2 properties to the a object (arrays are objects too). As further evidence, if you did this:

a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length);   // outputs zero because there are no items in the array

Your third option:

c=['c1','c2','c3'];

is assigning the variable c an array with three elements. Those three elements can be accessed as: c[0], c[1] and c[2]. In other words, c[0] === 'c1' and c.length === 3.

Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.

a = {};
a['a1']='foo';
a['a2']='bar';

It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.

Mac OS X and multiple Java versions

As found on this website So Let’s begin by installing jEnv

  1. Run this in the terminal

    brew install https://raw.github.com/gcuisinier/jenv/homebrew/jenv.rb
    
  2. Add jEnv to the bash profile

    if which jenv > /dev/null; then eval "$(jenv init -)"; fi
    
  3. When you first install jEnv will not have any JDK associated with it.

    For example, I just installed JDK 8 but jEnv does not know about it. To check Java versions on jEnv

    At the moment it only found Java version(jre) on the system. The * shows the version currently selected. Unlike rvm and rbenv, jEnv cannot install JDK for you. You need to install JDK manually from Oracle website.

  4. Install JDK 6 from Apple website. This will install Java in /System/Library/Java/JavaVirtualMachines/. The reason we are installing Java 6 from Apple website is that SUN did not come up with JDK 6 for MAC, so Apple created/modified its own deployment version.

  5. Similarly install JDK7 and JDK8.

  6. Add JDKs to jEnv.

    JDK 6:

    JDK 7: http://javahabi@javahabit.com/wp-content/uploads/2015/03/img_5518ab9bc47d4.png

    JDK 8: http://javahabi@javahabit.com/wp-content/uploads/2015/03/img_5518abb2c1217.png

  7. Check the java versions installed using jenv

    http://javahabi@javahabit.com/wp-content/uploads/2015/03/img_5518abceb0deb.png

  8. So now we have 3 versions of Java on our system. To set a default version use the command

    jenv local <jenv version>
    

    Ex – I wanted Jdk 1.6 to start IntelliJ

    jenv local oracle64-1.6.0.65
    
  9. check the java version

    java -version http://javahabi@javahabit.com/wp-content/uploads/2015/03/img_5518abe376dd0.png

That’s it. We now have multiple versions of java and we can switch between them easily. jEnv also has some other features, such as wrappers for Gradle, Ant, Maven, etc, and the ability to set JVM options globally or locally. Check out the documentation for more information.

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

The solution that worked for me was to: Close the VS project In File Explorer, navigate to the project and delete the entire ".vs" folder Restart the project Run as "Debug" Works Apparently, it has something to do with the "applicationhost.config" file.

Enjoy!

How to un-commit last un-pushed git commit without losing the changes

2020 simple way :

git reset <commit_hash>

Commit hash of the last commit you want to keep.

PHP: How to check if image file exists?

if (file_exists('http://www.mydomain.com/images/'.$filename)) {}

This didn't work for me. The way I did it was using getimagesize.

$src = 'http://www.mydomain.com/images/'.$filename;

if (@getimagesize($src)) {

Note that the '@' will mean that if the image does not exist (in which case the function would usually throw an error: getimagesize(http://www.mydomain.com/images/filename.png) [function.getimagesize]: failed) it will return false.

Disable native datepicker in Google Chrome

You could use:

jQuery('input[type="date"]').live('click', function(e) {e.preventDefault();}).datepicker();

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Image re-size to 50% of original size in HTML

You did not do anything wrong here, it will any other thing that is overriding the image size.

You can check this working fiddle.

And in this fiddle I have alter the image size using %, and it is working.

Also try using this code:

<img src="image.jpg" style="width: 50%; height: 50%"/>?

Here is the example fiddle.

Auto detect mobile browser (via user-agent?)

Just a thought but what if you worked this problem from the opposite direction? Rather than determining which browsers are mobile why not determine which browsers are not? Then code your site to default to the mobile version and redirect to the standard version. There are two basic possibilities when looking at a mobile browser. Either it has javascript support or it doesn't. So if the browser does not have javascript support it will default to the mobile version. If it does have JavaScript support, check the screen size. Anything below a certain size will likely also be a mobile browser. Anything larger will get redirected to your standard layout. Then all you need to do is determine if the user with JavaScript disabled is mobile or not.
According to the W3C the number of users with JavaScript disabled was about 5% and of those users most have turned it off which implies that they actually know what they are doing with a browser. Are they a large part of your audience? If not then don't worry about them. If so, whats the worst case scenario? You have those users browsing the mobile version of your site, and that's a good thing.

How can we print line numbers to the log in java

I use this little method that outputs the trace and line number of the method that called it.

 Log.d(TAG, "Where did i put this debug code again?   " + Utils.lineOut());

Double click the output to go to that source code line!

You might need to adjust the level value depending on where you put your code.

public static String lineOut() {
    int level = 3;
    StackTraceElement[] traces;
    traces = Thread.currentThread().getStackTrace();
    return (" at "  + traces[level] + " " );
}

System.MissingMethodException: Method not found?

For posterity, I ran into this with an azure function, using the azure durable function / durable tasks framework. It turns out I had an outdated version of the azure functions runtime installed locally. updating it fixed it.

How do I invert BooleanToVisibilityConverter?

You can use QuickConverter.

With QuickConverter you can write the converter logic inline with your BindingExpression

Here is an inverted BooleanToVisibility converter:

Visibility="{qc:Binding '!$P ? Visibility.Visible : Visibility.Collapsed', P={Binding Example}}"

You can add QuickConverter via NuGet. Have a look at the documentation for setup. Link: https://quickconverter.codeplex.com/

Char Comparison in C

A char variable is actually an 8-bit integral value. It will have values from 0 to 255. These are ASCII codes. 0 stands for the C-null character, and 255 stands for an empty symbol.

So, when you write the following assignment:

char a = 'a'; 

It is the same thing as:

char a = 97;

So, you can compare two char variables using the >, <, ==, <=, >= operators:

char a = 'a';
char b = 'b';

if( a < b ) printf("%c is smaller than %c", a, b);
if( a > b ) printf("%c is smaller than %c", a, b);
if( a == b ) printf("%c is equal to %c", a, b);

What does (function($) {})(jQuery); mean?

Type 3, in order to work would have to look like this:

(function($){
    //Attach this new method to jQuery
    $.fn.extend({     
        //This is where you write your plugin's name
        'pluginname': function(_options) {
            // Put defaults inline, no need for another variable...
            var options =  $.extend({
                'defaults': "go here..."
            }, _options);

            //Iterate over the current set of matched elements
            return this.each(function() {

                //code to be inserted here

            });
        }
    }); 
})(jQuery);

I am unsure why someone would use extend over just directly setting the property in the jQuery prototype, it is doing the same exact thing only in more operations and more clutter.

jQuery: Get height of hidden element in jQuery

Building further on user Nick's answer and user hitautodestruct's plugin on JSBin, I've created a similar jQuery plugin which retrieves both width and height and returns an object containing these values.

It can be found here: http://jsbin.com/ikogez/3/

Update

I've completely redesigned this tiny little plugin as it turned out that the previous version (mentioned above) wasn't really usable in real life environments where a lot of DOM manipulation was happening.

This is working perfectly:

/**
 * getSize plugin
 * This plugin can be used to get the width and height from hidden elements in the DOM.
 * It can be used on a jQuery element and will retun an object containing the width
 * and height of that element.
 *
 * Discussed at StackOverflow:
 * http://stackoverflow.com/a/8839261/1146033
 *
 * @author Robin van Baalen <[email protected]>
 * @version 1.1
 * 
 * CHANGELOG
 *  1.0 - Initial release
 *  1.1 - Completely revamped internal logic to be compatible with javascript-intense environments
 *
 * @return {object} The returned object is a native javascript object
 *                  (not jQuery, and therefore not chainable!!) that
 *                  contains the width and height of the given element.
 */
$.fn.getSize = function() {    
    var $wrap = $("<div />").appendTo($("body"));
    $wrap.css({
        "position":   "absolute !important",
        "visibility": "hidden !important",
        "display":    "block !important"
    });

    $clone = $(this).clone().appendTo($wrap);

    sizes = {
        "width": $clone.width(),
        "height": $clone.height()
    };

    $wrap.remove();

    return sizes;
};

SQL time difference between two dates result in hh:mm:ss

It's A Script Write Copy then write in your script file and change your requered field and get out put

DECLARE @Sdate DATETIME, @Edate DATETIME, @Timediff VARCHAR(100)
SELECT @Sdate = '02/12/2014 08:40:18.000',@Edate='02/13/2014 09:52:48.000'
SET @Timediff=DATEDIFF(s, @Sdate, @Edate)
SELECT CONVERT(VARCHAR(5),@Timediff/3600)+':'+convert(varchar(5),@Timediff%3600/60)+':'+convert(varchar(5),@Timediff%60) AS TimeDiff

Server configuration by allow_url_fopen=0 in

@blytung Has a nice function to replace that function

<?php
$url = "http://www.example.org/";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$contents = curl_exec($ch);
if (curl_errno($ch)) {
  echo curl_error($ch);
  echo "\n<br />";
  $contents = '';
} else {
  curl_close($ch);
}

if (!is_string($contents) || !strlen($contents)) {
echo "Failed to get contents.";
$contents = '';
}

echo $contents;
?>    

C# : assign data to properties via constructor vs. instantiating

Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:

public class Album 
{
    // Note that we make the setter 'private'
    public string Name { get; private set; }
    public string Artist { get; private set; }
    public int Year { get; private set; }

    public Album(string name, string artist, int year)
    {
        this.Name = name;
        this.Artist = artist;
        this.Year = year;
    }
}

If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:

new { 
    Name = "Some Name",
    Artist = "Some Artist",
    Year = 1994
};

the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.

That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:

public void Configure(ConfigurationSetup setup);

and I have a class that has a number of members such as:

class ConfigurationSetup {
    public String Name { get; set; }
    public String Location { get; set; }
    public Int32 Size { get; set; }
    public DateTime Time { get; set; }

    // ... and some other configuration stuff... 
}

Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:

ConfigurationSetup setup = new ConfigurationSetup {
    Name = "Some Name",
    Location = "San Jose"
};

and this allows me to set up some combination without having to define a new constructor for every possibly permutation.

On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to convert string into float in JavaScript?

If you extend String object like this..

String.prototype.float = function() { 
  return parseFloat(this.replace(',', '.')); 
}

.. you can run it like this

"554,20".float()
> 554.20

works with dot as well

"554.20".float()
> 554.20

typeof "554,20".float()
> "number"

Jquery click not working with ipad

I found that when I made my binding more specific, it began to work on iOS. I had:

$(document).on('click tap', 'span.clickable', function(e){ ... });

When I changed it to:

$("div.content").on('click tap', 'span.clickable', function(e){ ... });

iOS began responding.

Ways to save enums in database

For a large database, I am reluctant to lose the size and speed advantages of the numeric representation. I often end up with a database table representing the Enum.

You can enforce database consistency by declaring a foreign key -- although in some cases it might be better to not declare that as a foreign key constraint, which imposes a cost on every transaction. You can ensure consistency by periodically doing a check, at times of your choosing, with:

SELECT reftable.* FROM reftable
  LEFT JOIN enumtable ON reftable.enum_ref_id = enumtable.enum_id
WHERE enumtable.enum_id IS NULL;

The other half of this solution is to write some test code that checks that the Java enum and the database enum table have the same contents. That's left as an exercise for the reader.

Empty an array in Java / processing

You can simply assign null to the reference. (This will work for any type of array, not just ints)

int[] arr = new int[]{1, 2, 3, 4};
arr = null;

This will 'clear out' the array. You can also assign a new array to that reference if you like:

int[] arr = new int[]{1, 2, 3, 4};
arr = new int[]{6, 7, 8, 9};

If you are worried about memory leaks, don't be. The garbage collector will clean up any references left by the array.

Another example:

float[] arr = ;// some array that you want to clear
arr = new float[arr.length];

This will create a new float[] initialized to the default value for float.

Open web in new tab Selenium + Python

In a discussion, Simon clearly mentioned that:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.


Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for number_of_windows_to_be(2) and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo().window(newly_opened) as required. Here is a solution where you can open http://www.google.co.in in the initial TAB and https://www.yahoo.com in the adjacent TAB:

  • Code Block:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_argument('disable-infobars')
    driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get("http://www.google.co.in")
    print("Initial Page Title is : %s" %driver.title)
    windows_before  = driver.current_window_handle
    print("First Window Handle is : %s" %windows_before)
    driver.execute_script("window.open('https://www.yahoo.com')")
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    driver.switch_to_window(new_window)
    print("Page Title after Tab Switching is : %s" %driver.title)
    print("Second Window Handle is : %s" %new_window)
    
  • Console Output:

    Initial Page Title is : Google
    First Window Handle is : CDwindow-B2B3DE3A222B3DA5237840FA574AF780
    Page Title after Tab Switching is : Yahoo
    Second Window Handle is : CDwindow-D7DA7666A0008ED91991C623105A2EC4
    
  • Browser Snapshot:

multiple__tabs


Outro

You can find the based discussion in Best way to keep track and iterate through tabs and windows using WindowHandles using Selenium

How link to any local file with markdown syntax?

Thank you drifty0pine!

The first solution, it´s works!

[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)

but I had need put more ../ until the folder where was my file, like this:

[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

Find the most frequent number in a NumPy array

If you're willing to use SciPy:

>>> from scipy.stats import mode
>>> mode([1,2,3,1,2,1,1,1,3,2,2,1])
(array([ 1.]), array([ 6.]))
>>> most_frequent = mode([1,2,3,1,2,1,1,1,3,2,2,1])[0][0]
>>> most_frequent
1.0

HTML/CSS: how to put text both right and left aligned in a paragraph

enter image description here

If the texts has different sizes and they must be underlined this is the solution:

<table>
  <tr>
    <td class='left'>January</td>
    <td class='right'>2014</td>
  </tr>
</table>

css:

table{
    width: 100%;
    border-bottom: 2px solid black;
    /*this is the size of the small text's baseline over part  (˜25px*3/4)*/
    line-height: 19.5px; 
}
table td{
    vertical-align: baseline;
}
.left{
    font-family: Arial;
    font-size: 40px;
    text-align: left;

}
.right{
    font-size: 25px;
    text-align: right;
}

demo here

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

Java out.println() how is this possible?

static imports do the trick:

import static java.lang.System.out;

or alternatively import every static method and field using

import static java.lang.System.*;

Addendum by @Steve C: note that @sfussenegger said this in a comment on my Answer.

"Using such a static import of System.out isn't suited for more than simple run-once code."

So please don't imagine that he (or I) think that this solution is Good Practice.

setting content between div tags using javascript

See Creating and modifying HTML at what used to be called the Web Standards Curriculum.

Use the createElement, createTextNode and appendChild methods.

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

Using Spring RestTemplate in generic method with generic parameter

As Sotirios explains, you can not use the ParameterizedTypeReference, but ParameterizedTypeReference is used only to provide Type to the object mapper, and as you have the class that is removed when type erasure happens, you can create your own ParameterizedType and pass that to RestTemplate, so that the object mapper can reconstruct the object you need.

First you need to have the ParameterizedType interface implemented, you can find an implementation in Google Gson project here. Once you add the implementation to your project, you can extend the abstract ParameterizedTypeReference like this:

class FakeParameterizedTypeReference<T> extends ParameterizedTypeReference<T> {

@Override
public Type getType() {
    Type [] responseWrapperActualTypes = {MyClass.class};
    ParameterizedType responseWrapperType = new ParameterizedTypeImpl(
        ResponseWrapper.class,
        responseWrapperActualTypes,
        null
        );
    return responseWrapperType;
    }
}

And then you can pass that to your exchange function:

template.exchange(
    uri,
    HttpMethod.POST,
    null,
    new FakeParameterizedTypeReference<ResponseWrapper<T>>());

With all the type information present object mapper will properly construct your ResponseWrapper<MyClass> object

Command-line tool for finding out who is locking a file

Download Handle.

https://technet.microsoft.com/en-us/sysinternals/bb896655.aspx

If you want to find what program has a handle on a certain file, run this from the directory that Handle.exe is extracted to. Unless you've added Handle.exe to the PATH environment variable. And the file path is C:\path\path\file.txt", run this:

handle "C:\path\path\file.txt"

This will tell you what process(es) have the file (or folder) locked.

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

Show/hide widgets in Flutter programmatically

bool _visible = false;

 void _toggle() {
    setState(() {
      _visible = !_visible;
    });
  }

onPressed: _toggle,

Visibility(
            visible:_visible,
            child: new Container(
            child: new  Container(
              padding: EdgeInsets.fromLTRB(15.0, 0.0, 15.0, 10.0),
              child: new Material(
                elevation: 10.0,
                borderRadius: BorderRadius.circular(25.0),
                child: new ListTile(
                  leading: new Icon(Icons.search),
                  title: new TextField(
                    controller: controller,
                    decoration: new InputDecoration(
                        hintText: 'Search for brands and products', border: InputBorder.none,),
                    onChanged: onSearchTextChanged,
                  ),
                  trailing: new IconButton(icon: new Icon(Icons.cancel), onPressed: () {
                    controller.clear();
                    onSearchTextChanged('');
                  },),
                ),
              ),
            ),
          ),
          ),

Handling back button in Android Navigation Component

In 2.1.0-alpha06

If you want to handle backpress only in current fragment

requireActivity().onBackPressedDispatcher.addCallback(this@LoginFragment) {
    // handle back event
}

For whole Activity

requireActivity().onBackPressedDispatcher.addCallback() {
    // handle back event
}

Python not working in the command line of git bash

I know this is an old post, but I just came across this problem on Windows 10 running Python 3.8.5 and Git 2.28.0.windows.1

Somehow I had several different 2.7x versions of Python installed as well. I removed every version of Python (3x and 2x), downloaded the official installer here, installed 3.8.5 fresh (just used the defaults) which installed Python 3.8.5 at this location:

C:\Users\(my username)\AppData\Local\Programs\Python\Python38

Then to get the command python to work in my git bash shell, I had to manually add the path to Python38 to my path variable following the instructions listed here. This is important to note because on the python installer at the bottom of the first modal that comes up it asks if you want to add the python path to your PATH environment variable. I clicked the checkbox next to this but it didn't actually add the path, hence the need to manually add the path to my PATH environment variable.

Now using my gitbash shell I can browse to a directory with a python script in it and just type python theScriptName.py and it runs no problem.

I wanted to post this because this is all I had to do to get my gitbash shell to allow me to run python scripts. I think there might have been some updates so I didn't need to do any of the other solutions listed here. At any rate, this is another thing to try if you are having issues running python scripts in your gitbash shell on a Windows 10 machine.

Enjoy.

How do I get the height of a div's full content with jQuery?

scrollHeight is a property of a DOM object, not a function:

Height of the scroll view of an element; it includes the element padding but not its margin.

Given this:

<div id="x" style="height: 100px; overflow: hidden;">
    <div style="height: 200px;">
        pancakes
    </div>
</div>

This yields 200:

$('#x')[0].scrollHeight

For example: http://jsfiddle.net/ambiguous/u69kQ/2/ (run with the JavaScript console open).

Configuring Hibernate logging using Log4j XML config file?

In response to homaxto's comment, this is what I have right now.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug"/>
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n"/>
        </layout>
    </appender>
    <appender name="rolling-file" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="Program-Name.log"/>
        <param name="MaxFileSize" value="500KB"/>
        <param name="MaxBackupIndex" value="4"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %l - %m%n"/>
        </layout>
    </appender>

    <logger name="org.hibernate">
        <level value="info" />
    </logger>

    <root>
        <priority value ="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="rolling-file" />
    </root>
</log4j:configuration>

The key part being

<logger name="org.hibernate">
    <level value="info" />
</logger>

Hope this helps.

Styling a input type=number

I modified @LcSalazar's answer a bit... it's still not perfect because the background of the default buttons can still be seen in both Firefox, Chrome & Opera (not tested in Safari); but clicking on the arrows still works

Notes:

  • Adding pointer-events: none; allows you to click through the overlapping button, but then you can not style the button while hovered.
  • The arrows are visible in Edge, but don't work because Edge doesn't use arrows. It only adds an "x" to clear the input.

_x000D_
_x000D_
.number-wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.number-wrapper:after,_x000D_
.number-wrapper:before {_x000D_
  position: absolute;_x000D_
  right: 5px;_x000D_
  width: 1.6em;_x000D_
  height: .9em;_x000D_
  font-size: 10px;_x000D_
  pointer-events: none;_x000D_
  background: #fff;_x000D_
}_x000D_
_x000D_
.number-wrapper:after {_x000D_
  color: blue;_x000D_
  content: "\25B2";_x000D_
  margin-top: 1px;_x000D_
}_x000D_
_x000D_
.number-wrapper:before {_x000D_
  color: red;_x000D_
  content: "\25BC";_x000D_
  margin-bottom: 5px;_x000D_
  bottom: -.5em;_x000D_
}
_x000D_
<span class='number-wrapper'>_x000D_
    <input type="number" />_x000D_
</span>
_x000D_
_x000D_
_x000D_

SELECT where row value contains string MySQL

My suggestion would be

$value = $_POST["myfield"];

$Query = Database::Prepare("SELECT * FROM TABLE WHERE MYFIELD LIKE ?");
$Query->Execute(array("%".$value."%"));

Launch custom android application from android browser

In my case I had to set two categories for the <intent-filter> and then it worked:

<intent-filter>
<data android:scheme="my.special.scheme" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

What is the difference between 'my' and 'our' in Perl?

I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:

1. Definition or declaration?

local $var = 42;
print "var: $var\n";

The output is var: 42. However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:

use strict;
use warnings;

local $var = 42;
print "var: $var\n";

The second program will throw an error:

Global symbol "$var" requires explicit package name.

$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.

But why this won't fail?

use strict;
use warnings;

local $a = 42;
print "var: $a\n";

The output is: var: 42.

That's because $a, as well as $b, is a global variable pre-defined in Perl. Remember the sort function?

2. Lexical or global?

I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: it just corresponds to auto and external variables in C. But there're small differences:

In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:

int global;

int main(void) {
    int local;
}

While in Perl, things are subtle:

sub main {
    $var = 42;
}

&main;

print "var: $var\n";

The output is var: 42. $var is a global variable even if it's defined in a function block! Actually in Perl, any variable is declared as global by default.

The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.

Difference between numpy.array shape (R, 1) and (R,)

There are a lot of good answers here already. But for me it was hard to find some example, where the shape or array can break all the program.

So here is the one:

import numpy as np
a = np.array([1,2,3,4])
b = np.array([10,20,30,40])


from sklearn.linear_model import LinearRegression
regr = LinearRegression()
regr.fit(a,b)

This will fail with error:

ValueError: Expected 2D array, got 1D array instead

but if we add reshape to a:

a = np.array([1,2,3,4]).reshape(-1,1)

this works correctly!

What is the purpose of XSD files?

The xsd file is the schema of the xml file - it defines which elements may occur and their restrictions (like amount, order, boundaries, relationships,...)

.NET data structures: ArrayList, List, HashTable, Dictionary, SortedList, SortedDictionary -- Speed, memory, and when to use each?

Here are a few general tips for you:

  • You can use foreach on types that implement IEnumerable. IList is essentially an IEnumberable with Count and Item (accessing items using a zero-based index) properties. IDictionary on the other hand means you can access items by any-hashable index.

  • Array, ArrayList and List all implement IList. Dictionary, SortedDictionary, and Hashtable implement IDictionary.

  • If you are using .NET 2.0 or higher, it is recommended that you use generic counterparts of mentioned types.

  • For time and space complexity of various operations on these types, you should consult their documentation.

  • .NET data structures are in System.Collections namespace. There are type libraries such as PowerCollections which offer additional data structures.

  • To get a thorough understanding of data structures, consult resources such as CLRS.

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

What is the difference between C and embedded C?

1: C is a type of computer programming language. While embedded C is a set of language extensions for the C Programming language.

2: C has a free-format program source code, in a desktop computer. while embedded C has different format based on embedded processor (micro- controllers/microprocessors).

3: C have normal optimization, in programming. while embedded C high level optimization in programming.

4: C programming must have required operating system. while embedded C may or may not be required operating system.

5: C can use resources from OS, memory, etc, i.e all resources from desktop computer can be used by C. while embedded C can use limited resources, like RAM, ROM, and I/Os on an embedded processor.

How to generate a random number between 0 and 1?

Here's a general procedure for producing a random number in a specified range:

int randInRange(int min, int max)
{
  return min + (int) (rand() / (double) (RAND_MAX + 1) * (max - min + 1));
}

Depending on the PRNG algorithm being used, the % operator may result in a very non-random sequence of numbers.

"Couldn't read dependencies" error with npm


Problem with not reading the json is linked to permission issues with the file.

Using this command will do the trick:

sudo chown -R $USER:$GROUP ~/.npm

How can I jump to class/method definition in Atom text editor?

I also had the same problem. And I find the solution:

CTRL+ALT+G

Update:

Thanks to @Joost, install Atom package python-tools to make it work

Change header background color of modal of twitter bootstrap

A little late to the party, but here's another solution.

Simply adjusting the class of the modal to something like alert-danger does work, however it removes the top rounded corners of the modal.

A workaround is to give the element with modal-header an additional class of panel-heading, e.g.

<div class="modal fade" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header panel-heading"> <!-- change here -->
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

Then, to change the heading color you can do something like (assuming you're using jQUery)

jQuery('.modal-content').addClass('panel-danger')

Array versus linked-list

as arrays are static in nature, therefore all operations like memory allocation occur at the time of compilation only. So processor has to put less effort at its runtime .

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

How to destroy a JavaScript object?

While the existing answers have given solutions to solve the issue and the second half of the question, they do not provide an answer to the self discovery aspect of the first half of the question that is in bold:

"How can I see which variable causes memory overhead...?"

It may not have been as robust 3 years ago, but the Chrome Developer Tools "Profiles" section is now quite powerful and feature rich. The Chrome team has an insightful article on using it and thus also how garbage collection (GC) works in javascript, which is at the core of this question.

Since delete is basically the root of the currently accepted answer by Yochai Akoka, it's important to remember what delete does. It's irrelevant if not combined with the concepts of how GC works in the next two answers: if there's an existing reference to an object it's not cleaned up. The answers are more correct, but probably not as appreciated because they require more thought than just writing 'delete'. Yes, one possible solution may be to use delete, but it won't matter if there's another reference to the memory leak.

Another answer appropriately mentions circular references and the Chrome team documentation can provide much more clarity as well as the tools to verify the cause.

Since delete was mentioned here, it also may be useful to provide the resource Understanding Delete. Although it does not get into any of the actual solution which is really related to javascript's garbage collector.

How to get selected path and name of the file opened with file dialog?

Sub GetFilePath()

Set myFile = Application.FileDialog(msoFileDialogOpen)

With myFile

.Title = "Choose File"

.AllowMultiSelect = False

If .Show <> -1 Then

Exit Sub

End If

FileSelected = Replace(.SelectedItems(1), .InitialFileName, "")

End With

ActiveSheet.Range("A1") = FileSelected

End Sub

Easiest way to develop simple GUI in Python

Try with Kivy! kivy.org It's quite easy, multi platform and a really good documentation

SQL Server SELECT into existing table

It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration 
from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""

Input type=password, don't let browser remember the password

Here's the best answer, and the easiest! Put an extra password field in front of your input field and set the display:none , so that when the browser fills it in, it does it in an input that you don't care about.

Change this:

<input type="password" name="password" size="25" class="input" id="password" value="">

to this:

<input type="password" style="display:none;">
<input type="password" name="password" size="25" class="input" id="password" value="">

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your content files to this folder.
  3. Right click on your folder and click on Details.
  4. Copy Hosting URL and paste it on your browser.(e.g. https://googledrive.com/host/0B716ywBKT84AcHZfMWgtNk5aeXM)
  5. It will launch index.html if it exist in your folder other wise list all files in your folder.

How to show current user name in a cell?

The simplest way is to create a VBA macro that wraps that function, like so:

Function UserNameWindows() As String
    UserName = Environ("USERNAME")
End Function

Then call it from the cell:

=UserNameWindows()

See this article for more details, and other ways.

"Could not load type [Namespace].Global" causing me grief

I had converted my solution from VS2003 to VS2010 and had had problems converting the web application project.

I experienced the exact same problem and none of the answers worked for me.

What worked for me was:

  • Right Click on the solution and select Configuration Manager
  • Looked at each of the configurations in the 'Active solution configuration' drop down list.
  • Included the web application in the build by ticking the 'Build' check-box.

it would seem that the problems I had during the conversion had removed the web application project from the build for some reason.

Hopefully this answer helps anyone else that has the same problem...

How do you test to see if a double is equal to NaN?

If your value under test is a Double (not a primitive) and might be null (which is obviously not a number too), then you should use the following term:

(value==null || Double.isNaN(value))

Since isNaN() wants a primitive (rather than boxing any primitive double to a Double), passing a null value (which can't be unboxed to a Double) will result in an exception instead of the expected false.

SQL Server: Difference between PARTITION BY and GROUP BY

It provides rolled-up data without rolling up

i.e. Suppose I want to return the relative position of sales region

Using PARTITION BY, I can return the sales amount for a given region and the MAX amount across all sales regions in the same row.

This does mean you will have repeating data, but it may suit the end consumer in the sense that data has been aggregated but no data has been lost - as would be the case with GROUP BY.

How do I remove packages installed with Python's easy_install?

I ran into the same problem on my MacOS X Leopard 10.6.blah.

Solution is to make sure you're calling the MacPorts Python:

sudo port install python26
sudo port install python_select
sudo python_select python26
sudo port install py26-mysql

Hope this helps.

Java synchronized block vs. Collections.synchronizedMap

If you are using JDK 6 then you might want to check out ConcurrentHashMap

Note the putIfAbsent method in that class.

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Find Number of CPUs and Cores per CPU using Command Prompt

If you want to find how many processors (or CPUs) a machine has the same way %NUMBER_OF_PROCESSORS% shows you the number of cores, save the following script in a batch file, for example, GetNumberOfCores.cmd:

@echo off
for /f "tokens=*" %%f in ('wmic cpu get NumberOfCores /value ^| find "="') do set %%f

And then execute like this:

GetNumberOfCores.cmd

echo %NumberOfCores%

The script will set a environment variable named %NumberOfCores% and it will contain the number of processors.

Drop all duplicate rows across multiple columns in Python Pandas

Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Drop duplicates except for the first occurrence.

  • last : Drop duplicates except for the last occurrence.

  • False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with duplicate rows removed, optionally only considering certain columns

Parameters: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. take_last : deprecated inplace : boolean, default False Whether to drop duplicates in place or to return a copy cols : kwargs only argument of subset [deprecated] Returns: deduplicated : DataFrame

How to install package from github repo in Yarn

For ssh style urls just add ssh before the url:

yarn add ssh://<whatever>@<xxx>#<branch,tag,commit>

Remove excess whitespace from within a string

To expand on Sandip’s answer, I had a bunch of strings showing up in the logs that were mis-coded in bit.ly. They meant to code just the URL but put a twitter handle and some other stuff after a space. It looked like this

? productID =26%20via%20@LFS

Normally, that would‘t be a problem, but I’m getting a lot of SQL injection attempts, so I redirect anything that isn’t a valid ID to a 404. I used the preg_replace method to make the invalid productID string into a valid productID.

$productID=preg_replace('/[\s]+.*/','',$productID);

I look for a space in the URL and then remove everything after it.

How to calculate age (in years) based on Date of Birth and getDate()

What about a solution with only date functions, not math, not worries about leap year

CREATE FUNCTION dbo.getAge(@dt datetime) 
RETURNS int
AS
BEGIN
    RETURN 
        DATEDIFF(yy, @dt, getdate())
        - CASE 
            WHEN 
                MONTH(@dt) > MONTH(GETDATE()) OR 
                (MONTH(@dt) = MONTH(GETDATE()) AND DAY(@dt) > DAY(GETDATE())) 
            THEN 1 
            ELSE 0 
        END
END

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

Disable cache for some images

A common and simple solution to this problem that feels like a hack but is fairly portable is to add a randomly generated query string to each request for the dynamic image.

So, for example -

<img src="image.png" />

Would become

<img src="image.png?dummy=8484744" />

Or

<img src="image.png?dummy=371662" />

From the point of view of the web-server the same file is accessed, but from the point of view of the browser no caching can be performed.

The random number generation can happen either on the server when serving the page (just make sure the page itself isn't cached...), or on the client (using JavaScript).

You will need to verify whether your web-server can cope with this trick.

Letter Count on a string

One problem is that you are using count to refer both to the position in the word that you are checking, and the number of char you have seen, and you are using char to refer both to the input character you are checking, and the current character in the string. Use separate variables instead.

Also, move the return statement outside the loop; otherwise you will always return after checking the first character.

Finally, you only need one loop to iterate over the string. Get rid of the outer while loop and you will not need to track the position in the string.

Taking these suggestions, your code would look like this:

def count_letters(word, char):
  count = 0
  for c in word:
    if char == c:
      count += 1
  return count

how to set length of an column in hibernate with maximum length

You can use Length annotation for a column. By using it you can maximize or minimize column length. Length annotation only be used for Strings.

@Column(name = "NAME", nullable = false, length = 50)  
@Length(max = 50)
public String getName() {
    return this.name;
}

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

Find all elements on a page whose element ID contains a certain text using jQuery

This selects all DIVs with an ID containing 'foo' and that are visible

$("div:visible[id*='foo']");

Java string replace and the NUL (NULL, ASCII 0) character?

This does cause "funky characters":

System.out.println( "Mr. Foo".trim().replace('.','\0'));

produces:

Mr[] Foo

in my Eclipse console, where the [] is shown as a square box. As others have posted, use String.replace().

Matching a space in regex

I am using a regex to make sure that I only allow letters, number and a space

Then it is as simple as adding a space to what you've already got:

$newtag = preg_replace("/[^a-zA-Z0-9 ]/", "", $tag);

(note, I removed the s| which seemed unintentional? Certainly the s was redundant; you can restore the | if you need it)

If you specifically want *a* space, as in only a single one, you will need a more complex expression than this, and might want to consider a separate non-regex piece of logic.

Setting up SSL on a local xampp/apache server

I did all of the suggested stuff here and my code still did not work because I was using curl

If you are using curl in the php file, curl seems to reject all ssl traffic by default. A quick-fix that worked for me was to add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

before calling:

 curl_exec():

in the php file.

I believe that this disables all verification of SSL certificates.

Regular Expressions: Is there an AND operator?

Is it not possible in your case to do the AND on several matching results? in pseudocode

regexp_match(pattern1, data) && regexp_match(pattern2, data) && ...

How can I get npm start at a different directory?

npm start --prefix path/to/your/app

& inside package.json add the following script

"scripts": {
   "preinstall":"cd $(pwd)"
}

How to vertically align <li> elements in <ul>?

You can use flexbox for this.

ul {
    display: flex;
    align-items: center;
}

A detailed explanation of how to use flexbox can be found here.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Sorry its late, but I guess it would be of help to those who land here finding a solution to similar problem. The set clause should come right after the update clause. So rearranging your query with a bit change does the work.

UPDATE DHE.dbo.tblAccounts 
SET DHE.dbo.tblAccounts.ControllingSalesRep
    = DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
from DHE.dbo.tblAccounts 
INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink 
    ON DHE.dbo.tblAccounts.AccountCode
        = DHE_Import.tblSalesRepsAccountsLink.AccountCode 

Will iOS launch my app into the background if it was force-quit by the user?

For iOS13

For background pushes in iOS13, you must set below parameters:

apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms 

Background PUSHES The video link: https://developer.apple.com/videos/play/wwdc2019/707/

How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

Length of the String without using length() method

String blah = "HellO";
int count = 0;
for (char c : blah.toCharArray()) {
    count++;
}
System.out.println("blah's length: " + count);

Horizontal swipe slider with jQuery and touch devices support?

This one could fit your need:
http://caroufredsel.frebsite.nl/

Add jquery Touchwipe for touch support

Then in the configuration add

scroll : {
wipe: true
}

Convert String to Double - VB

The international versions:

    Public Shared Function GetDouble(ByVal doublestring As String) As Double
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval)
        Return retval
    End Function

    ' NULLABLE VERSION:
    Public Shared Function GetDoubleNullable(ByVal doublestring As String) As Double?
        Dim retval As Double
        Dim sep As String = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator

        If Double.TryParse(Replace(Replace(doublestring, ".", sep), ",", sep), retval) Then
            Return retval
        Else
            Return Nothing
        End If
    End Function

Results:

        ' HUNGARIAN REGIONAL SETTINGS (NumberDecimalSeparator: ,)

        ' Clean Double.TryParse
        ' -------------------------------------------------
        Double.TryParse("1.12", d1)     ' Type: DOUBLE     Value: d1 = 0.0
        Double.TryParse("1,12", d2)     ' Type: DOUBLE     Value: d2 = 1.12
        Double.TryParse("abcd", d3)     ' Type: DOUBLE     Value: d3 = 0.0

        ' GetDouble() method
        ' -------------------------------------------------
        d1 = GetDouble("1.12")          ' Type: DOUBLE     Value: d1 = 1.12
        d2 = GetDouble("1,12")          ' Type: DOUBLE     Value: d2 = 1.12
        d3 = GetDouble("abcd")          ' Type: DOUBLE     Value: d3 = 0.0

        ' Nullable version - GetDoubleNullable() method
        ' -------------------------------------------------
        d1n = GetDoubleNullable("1.12") ' Type: DOUBLE?    Value: d1n = 1.12
        d2n = GetDoubleNullable("1,12") ' Type: DOUBLE?    Value: d2n = 1.12
        d3n = GetDoubleNullable("abcd") ' Type: DOUBLE?    Value: d3n = Nothing

Git - Pushing code to two remotes

In recent versions of Git you can add multiple pushurls for a given remote. Use the following to add two pushurls to your origin:

git remote set-url --add --push origin git://original/repo.git
git remote set-url --add --push origin git://another/repo.git

So when you push to origin, it will push to both repositories.

UPDATE 1: Git 1.8.0.1 and 1.8.1 (and possibly other versions) seem to have a bug that causes --add to replace the original URL the first time you use it, so you need to re-add the original URL using the same command. Doing git remote -v should reveal the current URLs for each remote.

UPDATE 2: Junio C. Hamano, the Git maintainer, explained it's how it was designed. Doing git remote set-url --add --push <remote_name> <url> adds a pushurl for a given remote, which overrides the default URL for pushes. However, you may add multiple pushurls for a given remote, which then allows you to push to multiple remotes using a single git push. You can verify this behavior below:

$ git clone git://original/repo.git
$ git remote -v
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.'
remote.origin.url=git://original/repo.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*

Now, if you want to push to two or more repositories using a single command, you may create a new remote named all (as suggested by @Adam Nelson in comments), or keep using the origin, though the latter name is less descriptive for this purpose. If you still want to use origin, skip the following step, and use origin instead of all in all other steps.

So let's add a new remote called all that we'll reference later when pushing to multiple repositories:

$ git remote add all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)               <-- ADDED
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git            <-- ADDED
remote.all.fetch=+refs/heads/*:refs/remotes/all/* <-- ADDED

Then let's add a pushurl to the all remote, pointing to another repository:

$ git remote set-url --add --push all git://another/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)                 <-- CHANGED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git         <-- ADDED

Here git remote -v shows the new pushurl for push, so if you do git push all master, it will push the master branch to git://another/repo.git only. This shows how pushurl overrides the default url (remote.all.url).

Now let's add another pushurl pointing to the original repository:

$ git remote set-url --add --push all git://original/repo.git
$ git remote -v
all git://original/repo.git (fetch)
all git://another/repo.git (push)
all git://original/repo.git (push)                <-- ADDED
origin  git://original/repo.git (fetch)
origin  git://original/repo.git (push)
$ git config -l | grep '^remote\.all'
remote.all.url=git://original/repo.git
remote.all.fetch=+refs/heads/*:refs/remotes/all/*
remote.all.pushurl=git://another/repo.git
remote.all.pushurl=git://original/repo.git        <-- ADDED

You see both pushurls we added are kept. Now a single git push all master will push the master branch to both git://another/repo.git and git://original/repo.git.

Received fatal alert: handshake_failure through SSLHandshakeException

I am using com.google.api http client. When I communicate with an internal company site, I got this problem when I mistakenly used https, instead of http.

main, READ: TLSv1.2 Alert, length = 2
main, RECV TLSv1.2 ALERT:  fatal, handshake_failure
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
main, IOException in getSession():  javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
main, called close()
main, called closeInternal(true)
262 [main] DEBUG org.apache.http.impl.conn.DefaultClientConnection  - Connection shut down
main, called close()
main, called closeInternal(true)
263 [main] DEBUG org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager  - Released connection is not reusable.
263 [main] DEBUG org.apache.http.impl.conn.tsccm.ConnPoolByRoute  - Releasing connection [HttpRoute[{s}->https://<I-replaced>]][null]
263 [main] DEBUG org.apache.http.impl.conn.tsccm.ConnPoolByRoute  - Notifying no-one, there are no waiting threads
Exception in thread "main" javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
    at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:431)
    at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
    at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:339)
    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:123)
    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:147)
    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
    at com.google.api.client.http.apache.ApacheHttpRequest.execute(ApacheHttpRequest.java:67)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:960)

What represents a double in sql server?

Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.

From that post (by David): enter image description here

How to call loading function with React useEffect only once

If you only want to run the function given to useEffect after the initial render, you can give it an empty array as second argument.

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return <div> {/* ... */} </div>;
}

Set UITableView content inset permanently

After one hour of tests the only way that works 100% is this one:

-(void)hideSearchBar
{
    if([self.tableSearchBar.text length]<=0 && !self.tableSearchBar.isFirstResponder)
    {
        self.tableView.contentOffset = CGPointMake(0, self.tableSearchBar.bounds.size.height);
        self.edgesForExtendedLayout = UIRectEdgeBottom;
    }
}

-(void)viewDidLayoutSubviews
{
    [self hideSearchBar];
}

with this approach you can always hide the search bar if is empty

Header and footer in CodeIgniter

Using This Helper For Dynamic Template Loading

//  get  Template 
    function get_template($template_name, $vars = array(), $return = FALSE) {
        $CI = & get_instance();

        $content = "";
        $last = $CI - > uri - > total_segments();

        if ($CI - > uri - > segment($last) != 'tab') {
            $content = $CI - > load - > view('Header', $vars, $return);
            $content. = $CI - > load - > view('Sidebar', $vars, $return);
        }

        $content. = $CI - > load - > view($template_name, $vars, $return);

        if ($CI - > uri - > segment($last) != 'tab') {
            $content. = $CI - > load - > view('Footer', $vars, $return);
        }

        if ($return) {
            return $content;
        }
    }

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

Format an Integer using Java String Format

If you are using a third party library called apache commons-lang, the following solution can be useful:

Use StringUtils class of apache commons-lang :

int i = 5;
StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"

As StringUtils.leftPad() is faster than String.format()

What are the differences between numpy arrays and matrices? Which one should I use?

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product.

import numpy as np

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.

In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise (except for the new @ operator). Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot (or @ in Python >= 3.5, as shown above):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise.

There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).

The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.

Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.

In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.

If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.

PS. Of course, you really don't have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).


There is a synopsis of the differences between NumPy arrays vs NumPy matrixes here.

How do you change the text in the Titlebar in Windows Forms?

If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.

  static Form f0;
  public OrdUpdate()
  {
   InitializeComponent();
   f0=this;
  }
  // then later you can say
  f0.Text="New text";

Where and why do I have to put the "template" and "typename" keywords?

C++11

Problem

While the rules in C++03 about when you need typename and template are largely reasonable, there is one annoying disadvantage of its formulation

template<typename T>
struct A {
  typedef int result_type;

  void f() {
    // error, "this" is dependent, "template" keyword needed
    this->g<float>();

    // OK
    g<float>();

    // error, "A<T>" is dependent, "typename" keyword needed
    A<T>::result_type n1;

    // OK
    result_type n2; 
  }

  template<typename U>
  void g();
};

As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that A::result_type can only be int (and is hence a type), and this->g can only be the member template g declared later (even if A is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of A!).

Current instantiation

To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, A, A<T>, ::A<T>). A type referenced by such a name is known to be the current instantiation. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, A::NestedClass and A are both current instantiations).

Based on this notion, the language says that CurrentInstantiation::Foo, Foo and CurrentInstantiationTyped->Foo (such as A *a = this; a->Foo) are all member of the current instantiation if they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).

The keywords typename and template are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that A<T> is still a type-dependent name (after all T is also type dependent). But A<T>::result_type is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.

struct B {
  typedef int result_type;
};

template<typename T>
struct C { }; // could be specialized!

template<typename T>
struct D : B, C<T> {
  void f() {
    // OK, member of current instantiation!
    // A::result_type is not dependent: int
    D::result_type r1;

    // error, not a member of the current instantiation
    D::questionable_type r2;

    // OK for now - relying on C<T> to provide it
    // But not a member of the current instantiation
    typename D::questionable_type r3;        
  }
};

That's impressive, but can we do better? The language even goes further and requires that an implementation again looks up D::result_type when instantiating D::f (even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined C like this

template<>
struct C<int> {
  typedef bool result_type;
  typedef int questionable_type;
};

A compiler is required to catch the error when instantiating D<int>::f. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from typename and template.

Unknown specializations

In the code of D, the name typename D::questionable_type is not a member of the current instantiation. Instead the language marks it as a member of an unknown specialization. In particular, this is always the case when you are doing DependentTypeName::Foo or DependentTypedName->Foo and either the dependent type is not the current instantiation (in which case the compiler can give up and say "we will look later what Foo is) or it is the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.

Imagine what happens if we had a member function h within the above defined A class template

void h() {
  typename A<T>::questionable_type x;
}

In C++03, the language allowed to catch this error because there could never be a valid way to instantiate A<T>::h (whatever argument you give to T). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since A has no dependent base classes, and A declares no member questionable_type, the name A<T>::questionable_type is neither a member of the current instantiation nor a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).

Examples and trivia

You can try this knowledge on this answer and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).

The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)

struct B { void f(); };
struct A : virtual B { void f(); };

template<typename T>
struct C : virtual B, T {
  void g() { this->f(); }
};

int main() { 
  C<A> c; c.g(); 
}

This valid C++03 code would bind this->f to A::f at instantiation time and everything is fine. C++11 however immediately binds it to B::f and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating C<A>::g, the Dominance Rule applies and lookup will find A::f instead.

Zip lists in Python

In Python 3 zip returns an iterator instead and needs to be passed to a list function to get the zipped tuples:

x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]

Then to unzip them back just conjugate the zipped iterator:

x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')

If the original form of list is needed instead of tuples:

x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']

Performance of Java matrix math libraries?

Linalg code that relies heavily on Pentiums and later processors' vector computing capabilities (starting with the MMX extensions, like LAPACK and now Atlas BLAS) is not "fantastically optimized", but simply industry-standard. To replicate that perfomance in Java you are going to need native libraries. I have had the same performance problem as you describe (mainly, to be able to compute Choleski decompositions) and have found nothing really efficient: Jama is pure Java, since it is supposed to be just a template and reference kit for implementers to follow... which never happened. You know Apache math commons... As for COLT, I have still to test it but it seems to rely heavily on Ninja improvements, most of which were reached by building an ad-hoc Java compiler, so I doubt it's going to help. At that point, I think we "just" need a collective effort to build a native Jama implementation...

Resetting a multi-stage form with jQuery

document.getElementById('frm').reset()

Delete column from pandas DataFrame

TL;DR

A lot of effort to find a marginally more efficient solution. Difficult to justify the added complexity while sacrificing the simplicity of df.drop(dlst, 1, errors='ignore')

df.reindex_axis(np.setdiff1d(df.columns.values, dlst), 1)

Preamble
Deleting a column is semantically the same as selecting the other columns. I'll show a few additional methods to consider.

I'll also focus on the general solution of deleting multiple columns at once and allowing for the attempt to delete columns not present.

Using these solutions are general and will work for the simple case as well.


Setup
Consider the pd.DataFrame df and list to delete dlst

df = pd.DataFrame(dict(zip('ABCDEFGHIJ', range(1, 11))), range(3))
dlst = list('HIJKLM')

df

   A  B  C  D  E  F  G  H  I   J
0  1  2  3  4  5  6  7  8  9  10
1  1  2  3  4  5  6  7  8  9  10
2  1  2  3  4  5  6  7  8  9  10

dlst

['H', 'I', 'J', 'K', 'L', 'M']

The result should look like:

df.drop(dlst, 1, errors='ignore')

   A  B  C  D  E  F  G
0  1  2  3  4  5  6  7
1  1  2  3  4  5  6  7
2  1  2  3  4  5  6  7

Since I'm equating deleting a column to selecting the other columns, I'll break it into two types:

  1. Label selection
  2. Boolean selection

Label Selection

We start by manufacturing the list/array of labels that represent the columns we want to keep and without the columns we want to delete.

  1. df.columns.difference(dlst)

    Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
    
  2. np.setdiff1d(df.columns.values, dlst)

    array(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype=object)
    
  3. df.columns.drop(dlst, errors='ignore')

    Index(['A', 'B', 'C', 'D', 'E', 'F', 'G'], dtype='object')
    
  4. list(set(df.columns.values.tolist()).difference(dlst))

    # does not preserve order
    ['E', 'D', 'B', 'F', 'G', 'A', 'C']
    
  5. [x for x in df.columns.values.tolist() if x not in dlst]

    ['A', 'B', 'C', 'D', 'E', 'F', 'G']
    

Columns from Labels
For the sake of comparing the selection process, assume:

 cols = [x for x in df.columns.values.tolist() if x not in dlst]

Then we can evaluate

  1. df.loc[:, cols]
  2. df[cols]
  3. df.reindex(columns=cols)
  4. df.reindex_axis(cols, 1)

Which all evaluate to:

   A  B  C  D  E  F  G
0  1  2  3  4  5  6  7
1  1  2  3  4  5  6  7
2  1  2  3  4  5  6  7

Boolean Slice

We can construct an array/list of booleans for slicing

  1. ~df.columns.isin(dlst)
  2. ~np.in1d(df.columns.values, dlst)
  3. [x not in dlst for x in df.columns.values.tolist()]
  4. (df.columns.values[:, None] != dlst).all(1)

Columns from Boolean
For the sake of comparison

bools = [x not in dlst for x in df.columns.values.tolist()]
  1. df.loc[: bools]

Which all evaluate to:

   A  B  C  D  E  F  G
0  1  2  3  4  5  6  7
1  1  2  3  4  5  6  7
2  1  2  3  4  5  6  7

Robust Timing

Functions

setdiff1d = lambda df, dlst: np.setdiff1d(df.columns.values, dlst)
difference = lambda df, dlst: df.columns.difference(dlst)
columndrop = lambda df, dlst: df.columns.drop(dlst, errors='ignore')
setdifflst = lambda df, dlst: list(set(df.columns.values.tolist()).difference(dlst))
comprehension = lambda df, dlst: [x for x in df.columns.values.tolist() if x not in dlst]

loc = lambda df, cols: df.loc[:, cols]
slc = lambda df, cols: df[cols]
ridx = lambda df, cols: df.reindex(columns=cols)
ridxa = lambda df, cols: df.reindex_axis(cols, 1)

isin = lambda df, dlst: ~df.columns.isin(dlst)
in1d = lambda df, dlst: ~np.in1d(df.columns.values, dlst)
comp = lambda df, dlst: [x not in dlst for x in df.columns.values.tolist()]
brod = lambda df, dlst: (df.columns.values[:, None] != dlst).all(1)

Testing

res1 = pd.DataFrame(
    index=pd.MultiIndex.from_product([
        'loc slc ridx ridxa'.split(),
        'setdiff1d difference columndrop setdifflst comprehension'.split(),
    ], names=['Select', 'Label']),
    columns=[10, 30, 100, 300, 1000],
    dtype=float
)

res2 = pd.DataFrame(
    index=pd.MultiIndex.from_product([
        'loc'.split(),
        'isin in1d comp brod'.split(),
    ], names=['Select', 'Label']),
    columns=[10, 30, 100, 300, 1000],
    dtype=float
)

res = res1.append(res2).sort_index()

dres = pd.Series(index=res.columns, name='drop')

for j in res.columns:
    dlst = list(range(j))
    cols = list(range(j // 2, j + j // 2))
    d = pd.DataFrame(1, range(10), cols)
    dres.at[j] = timeit('d.drop(dlst, 1, errors="ignore")', 'from __main__ import d, dlst', number=100)
    for s, l in res.index:
        stmt = '{}(d, {}(d, dlst))'.format(s, l)
        setp = 'from __main__ import d, dlst, {}, {}'.format(s, l)
        res.at[(s, l), j] = timeit(stmt, setp, number=100)

rs = res / dres

rs

                          10        30        100       300        1000
Select Label                                                           
loc    brod           0.747373  0.861979  0.891144  1.284235   3.872157
       columndrop     1.193983  1.292843  1.396841  1.484429   1.335733
       comp           0.802036  0.732326  1.149397  3.473283  25.565922
       comprehension  1.463503  1.568395  1.866441  4.421639  26.552276
       difference     1.413010  1.460863  1.587594  1.568571   1.569735
       in1d           0.818502  0.844374  0.994093  1.042360   1.076255
       isin           1.008874  0.879706  1.021712  1.001119   0.964327
       setdiff1d      1.352828  1.274061  1.483380  1.459986   1.466575
       setdifflst     1.233332  1.444521  1.714199  1.797241   1.876425
ridx   columndrop     0.903013  0.832814  0.949234  0.976366   0.982888
       comprehension  0.777445  0.827151  1.108028  3.473164  25.528879
       difference     1.086859  1.081396  1.293132  1.173044   1.237613
       setdiff1d      0.946009  0.873169  0.900185  0.908194   1.036124
       setdifflst     0.732964  0.823218  0.819748  0.990315   1.050910
ridxa  columndrop     0.835254  0.774701  0.907105  0.908006   0.932754
       comprehension  0.697749  0.762556  1.215225  3.510226  25.041832
       difference     1.055099  1.010208  1.122005  1.119575   1.383065
       setdiff1d      0.760716  0.725386  0.849949  0.879425   0.946460
       setdifflst     0.710008  0.668108  0.778060  0.871766   0.939537
slc    columndrop     1.268191  1.521264  2.646687  1.919423   1.981091
       comprehension  0.856893  0.870365  1.290730  3.564219  26.208937
       difference     1.470095  1.747211  2.886581  2.254690   2.050536
       setdiff1d      1.098427  1.133476  1.466029  2.045965   3.123452
       setdifflst     0.833700  0.846652  1.013061  1.110352   1.287831

fig, axes = plt.subplots(2, 2, figsize=(8, 6), sharey=True)
for i, (n, g) in enumerate([(n, g.xs(n)) for n, g in rs.groupby('Select')]):
    ax = axes[i // 2, i % 2]
    g.plot.bar(ax=ax, title=n)
    ax.legend_.remove()
fig.tight_layout()

This is relative to the time it takes to run df.drop(dlst, 1, errors='ignore'). It seems like after all that effort, we only improve performance modestly.

enter image description here

If fact the best solutions use reindex or reindex_axis on the hack list(set(df.columns.values.tolist()).difference(dlst)). A close second and still very marginally better than drop is np.setdiff1d.

rs.idxmin().pipe(
    lambda x: pd.DataFrame(
        dict(idx=x.values, val=rs.lookup(x.values, x.index)),
        x.index
    )
)

                      idx       val
10     (ridx, setdifflst)  0.653431
30    (ridxa, setdifflst)  0.746143
100   (ridxa, setdifflst)  0.816207
300    (ridx, setdifflst)  0.780157
1000  (ridxa, setdifflst)  0.861622

Can anyone explain IEnumerable and IEnumerator to me?

Implementing IEnumerable essentially means that the object can be iterated over. This doesn't necessarily mean it is an array as there are certain lists that can't be indexed but you can enumerate them.

IEnumerator is the actual object used to perform the iterations. It controls moving from one object to the next in the list.

Most of the time, IEnumerable & IEnumerator are used transparently as part of a foreach loop.

Curl to return http status code along with the response

My way to achieve this:

To get both (header and body), I usually perform a curl -D- <url> as in:

$ curl -D- http://localhost:1234/foo
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 20:59:21 GMT

{"data":["out.csv"]}

This will dump headers (-D) to stdout (-) (Look for --dump-header in man curl).

IMHO also very handy in this context:

I often use jq to get that json data (eg from some rest APIs) formatted. But as jq doesn't expect a HTTP header, the trick is to print headers to stderr using -D/dev/stderr. Note that this time we also use -sS (--silent, --show-errors) to suppress the progress meter (because we write to a pipe).

$ curl -sSD/dev/stderr http://localhost:1231/foo | jq .
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:08:22 GMT

{
  "data": [
    "out.csv"
  ]
}

I guess this also can be handy if you'd like to print headers (for quick inspection) to console but redirect body to a file (eg when its some kind of binary to not mess up your terminal):

$ curl -sSD/dev/stderr http://localhost:1231 > /dev/null
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:20:02 GMT

Be aware: This is NOT the same as curl -I <url>! As -I will perform a HEAD request and not a GET request (Look for --head in man curl. Yes: For most HTTP servers this will yield same result. But I know a lot of business applications which don't implement HEAD request at all ;-P

What does "if (rs.next())" mean?

As to the concrete problem with that SQLException, you need to replace

ResultSet rs = stmt.executeQuery(sql);

by

ResultSet rs = stmt.executeQuery();

because you're using the PreparedStatement subclass instead of Statement. When using PreparedStatement, you've already passed in the SQL string to Connection#prepareStatement(). You just have to set the parameters on it and then call executeQuery() method directly without re-passing the SQL string.

See also:


As to the concrete question about rs.next(), it shifts the cursor to the next row of the result set from the database and returns true if there is any row, otherwise false. In combination with the if statement (instead of the while) this means that the programmer is expecting or interested in only one row, the first row.

See also:

How to update RecyclerView Adapter Data?

I found out that a really simple way to reload the RecyclerView is to just call

recyclerView.removeAllViews();

This will first remove all content of the RecyclerView and then add it again with the updated values.

SQL Server insert if not exists best practice

Don't know why anyone else hasn't said this yet;

NORMALISE.

You've got a table that models competitions? Competitions are made up of Competitors? You need a distinct list of Competitors in one or more Competitions......

You should have the following tables.....

CREATE TABLE Competitor (
    [CompetitorID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitorName] NVARCHAR(255)
    )

CREATE TABLE Competition (
    [CompetitionID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitionName] NVARCHAR(255)
    )

CREATE TABLE CompetitionCompetitors (
    [CompetitionID] INT
    , [CompetitorID] INT
    , [Score] INT

    , PRIMARY KEY (
        [CompetitionID]
        , [CompetitorID]
        )
    )

With Constraints on CompetitionCompetitors.CompetitionID and CompetitorID pointing at the other tables.

With this kind of table structure -- your keys are all simple INTS -- there doesn't seem to be a good NATURAL KEY that would fit the model so I think a SURROGATE KEY is a good fit here.

So if you had this then to get the the distinct list of competitors in a particular competition you can issue a query like this:

DECLARE @CompetitionName VARCHAR(50) SET @CompetitionName = 'London Marathon'

    SELECT
        p.[CompetitorName] AS [CompetitorName]
    FROM
        Competitor AS p
    WHERE
        EXISTS (
            SELECT 1
            FROM
                CompetitionCompetitor AS cc
                JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]
            WHERE
                cc.[CompetitorID] = p.[CompetitorID]
                AND cc.[CompetitionName] = @CompetitionNAme
        )

And if you wanted the score for each competition a competitor is in:

SELECT
    p.[CompetitorName]
    , c.[CompetitionName]
    , cc.[Score]
FROM
    Competitor AS p
    JOIN CompetitionCompetitor AS cc ON cc.[CompetitorID] = p.[CompetitorID]
    JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]

And when you have a new competition with new competitors then you simply check which ones already exist in the Competitors table. If they already exist then you don't insert into Competitor for those Competitors and do insert for the new ones.

Then you insert the new Competition in Competition and finally you just make all the links in CompetitionCompetitors.

Add one day to date in javascript

Just for the sake of adding functions to the Date prototype:

In a mutable fashion / style:

Date.prototype.addDays = function(n) {
   this.setDate(this.getDate() + n);
};

// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
   this.addDays(1);
};

Date.prototype.addMonths = function(n) {
   this.setMonth(this.getMonth() + n);
};

Date.prototype.addYears = function(n) {
   this.setFullYear(this.getFullYear() + n);
}

// etc...

var currentDate = new Date();
currentDate.nextDay();

Transfer data between databases with PostgreSQL

Just like leonbloy suggested, using two schemas in a database is the way to go. Suppose a source schema (old DB) and a target schema (new DB), you can try something like this (you should consider column names, types, etc.):

INSERT INTO target.Awards SELECT * FROM source.Nominations;

How to execute a stored procedure inside a select query

Thanks @twoleggedhorse.

Here is the solution.

  1. First we created a function

    CREATE FUNCTION GetAIntFromStoredProc(@parm Nvarchar(50)) RETURNS INTEGER
    
    AS
    BEGIN
       DECLARE @id INTEGER
    
       set @id= (select TOP(1) id From tbl where col=@parm)
    
       RETURN @id
    END
    
  2. then we do the select query

    Select col1, col2, col3,
    GetAIntFromStoredProc(T.col1) As col4
    From Tbl as T
    Where col2=@parm
    

Handle Button click inside a row in RecyclerView

this is how I handle multiple onClick events inside a recyclerView:

Edit : Updated to include callbacks (as mentioned in other comments). I have used a WeakReference in the ViewHolder to eliminate a potential memory leak.

Define interface :

public interface ClickListener {

    void onPositionClicked(int position);
    
    void onLongClicked(int position);
}

Then the Adapter :

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    
    private final ClickListener listener;
    private final List<MyItems> itemsList;

    public MyAdapter(List<MyItems> itemsList, ClickListener listener) {
        this.listener = listener;
        this.itemsList = itemsList;
    }

    @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.my_row_layout), parent, false), listener);
    }

    @Override public void onBindViewHolder(MyViewHolder holder, int position) {
        // bind layout and data etc..
    }

    @Override public int getItemCount() {
        return itemsList.size();
    }

    public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {

        private ImageView iconImageView;
        private TextView iconTextView;
        private WeakReference<ClickListener> listenerRef;

        public MyViewHolder(final View itemView, ClickListener listener) {
            super(itemView);

            listenerRef = new WeakReference<>(listener);
            iconImageView = (ImageView) itemView.findViewById(R.id.myRecyclerImageView);
            iconTextView = (TextView) itemView.findViewById(R.id.myRecyclerTextView);

            itemView.setOnClickListener(this);
            iconTextView.setOnClickListener(this);
            iconImageView.setOnLongClickListener(this);
        }

        // onClick Listener for view
        @Override
        public void onClick(View v) {

            if (v.getId() == iconTextView.getId()) {
                Toast.makeText(v.getContext(), "ITEM PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(v.getContext(), "ROW PRESSED = " + String.valueOf(getAdapterPosition()), Toast.LENGTH_SHORT).show();
            }
            
            listenerRef.get().onPositionClicked(getAdapterPosition());
        }


        //onLongClickListener for view
        @Override
        public boolean onLongClick(View v) {

            final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
            builder.setTitle("Hello Dialog")
                    .setMessage("LONG CLICK DIALOG WINDOW FOR ICON " + String.valueOf(getAdapterPosition()))
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.create().show();
            listenerRef.get().onLongClicked(getAdapterPosition());
            return true;
        }
    }
}

Then in your activity/fragment - whatever you can implement : Clicklistener - or anonymous class if you wish like so :

MyAdapter adapter = new MyAdapter(myItems, new ClickListener() {
            @Override public void onPositionClicked(int position) {
                // callback performed on click
            }

            @Override public void onLongClicked(int position) {
                // callback performed on click
            }
        });

To get which item was clicked you match the view id i.e. v.getId() == whateverItem.getId()

Hope this approach helps!

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

How to play a sound in C#, .NET

You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.

Change onclick action with a Javascript function

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

document.getElementById("a").onclick = Bar;

Looking at your other code you probably want to do something like this:

document.getElementById(id+"Button").onclick = function() { HideError(id); }

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Just import following package,

import org.hibernate.cfg.Configuration;

Add alternating row color to SQL Server Reporting services report

I think this trick is not discussed here. So here it is,

In any type of complex matrix, when you want alternate cell colors, either row wise or column wise, the working solution is,

If you want a alternate color of cells coloumn wise then,

  1. At the bottom right corner of a report design view, in "Column Groups", create a fake parent group on 1 (using expression), named "FakeParentGroup".
  2. Then, in the report design, for cells that to be colored alternatively, use following background color expression

=IIF(RunningValue( Fields![ColumnGroupField].Value, countDistinct, "FakeParentGroup" ) MOD 2, "White", "LightGrey")

Thats all.

Same for the alternate color row wise, just you have to edit solution accordingly.

NOTE: Here, sometimes you need to set border of cells accordingly, usually it vanishes.

Also dont forget to delete value 1 in report that came into pic when you created fake parent group.

What is the first character in the sort order used by Windows Explorer?

Although the answer with "!" was chosen as the correct answer, this is NOT true. I´m not sure about Windows Explorer in Windows 10/8.1/8, but I am certain concerning Windows 7 and XP.

The character that moves your filename to the very top is "'" (alt+39), and second best is "-" (the minus sign).

But sorting order in Windows Explorer is more complicated - it depends on the filename-lenght also, and numbers are treated very special.

The second character (and the following) is treated different. Here you often go best with a " " (spacebar), followed by the characters mentioned above, but you´ll have to try out, because it´s not so easy to find out the exact algorithm:

Here is an example for the correct sorting order for your understanding:

  1. file: "'"
  2. file: "''" (longer filename)
  3. file: "'''" (and so on)
  4. file: "-"
  5. file: "--"
  6. file: "---" (and so on)
  7. file: "- -" (spacebar used)
  8. file: "' '" (spacebar two times, therefore longer filename)
  9. file: "' ' '" (most top character, but longer filename!)
  10. file: "'' 0" (shorter filename, but chars like numbers came in)

Another example:

  1. "'' aaaa" ("'" is better than spacebar and spacebar is better than "a")
  2. "'' aaaaa"
  3. "' aaaaaa"

Same filelenght:

  1. "-- aa" (spacebar comes before "-" in this case!)
  2. "---aa"
  3. "--aaa"

Finally the very special logic when it comes to numbers:

  1. "0000000"
  2. "0"
  3. "00001"

But nevertheless: Renaming folders or files this way, you can quickly find what you are searching for.

How can I produce an effect similar to the iOS 7 blur view?

Every response here is using vImageBoxConvolve_ARGB8888 this function is really, really slow, that is fine, if the performance is not a high priority requirement, but if you are using this for transitioning between two View Controllers (for example) this approach means times over 1 second or maybe more, that is very bad to the user experience of your application.

If you prefer leave all this image processing to the GPU (And you should) you can get a much better effect and also awesome times rounding 50ms (supposing that you have a time of 1 second in the first approach), so, lets do it.

First download the GPUImage Framework (BSD Licensed) here.

Next, Add the following classes (.m and .h) from the GPUImage (I'm not sure that these are the minimum needed for the blur effect only)

  • GPUImage.h
  • GPUImageAlphaBlendFilter
  • GPUImageFilter
  • GPUImageFilterGroup
  • GPUImageGaussianBlurPositionFilter
  • GPUImageGaussianSelectiveBlurFilter
  • GPUImageLuminanceRangeFilter
  • GPUImageOutput
  • GPUImageTwoInputFilter
  • GLProgram
  • GPUImageBoxBlurFilter
  • GPUImageGaussianBlurFilter
  • GPUImageiOSBlurFilter
  • GPUImageSaturationFilter
  • GPUImageSolidColorGenerator
  • GPUImageTwoPassFilter
  • GPUImageTwoPassTextureSamplingFilter

  • iOS/GPUImage-Prefix.pch

  • iOS/GPUImageContext
  • iOS/GPUImageMovieWriter
  • iOS/GPUImagePicture
  • iOS/GPUImageView

Next, create a category on UIImage, that will add a blur effect to an existing UIImage:

#import "UIImage+Utils.h"

#import "GPUImagePicture.h"
#import "GPUImageSolidColorGenerator.h"
#import "GPUImageAlphaBlendFilter.h"
#import "GPUImageBoxBlurFilter.h"

@implementation UIImage (Utils)

- (UIImage*) GPUBlurredImage
{
    GPUImagePicture *source =[[GPUImagePicture alloc] initWithImage:self];

    CGSize size = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale);

    GPUImageBoxBlurFilter *blur = [[GPUImageBoxBlurFilter alloc] init];
    [blur setBlurRadiusInPixels:4.0f];
    [blur setBlurPasses:2.0f];
    [blur forceProcessingAtSize:size];
    [source addTarget:blur];

    GPUImageSolidColorGenerator * white = [[GPUImageSolidColorGenerator alloc] init];

    [white setColorRed:1.0f green:1.0f blue:1.0f alpha:0.1f];
    [white forceProcessingAtSize:size];

    GPUImageAlphaBlendFilter * blend = [[GPUImageAlphaBlendFilter alloc] init];
    blend.mix = 0.9f;

    [blur addTarget:blend];
    [white addTarget:blend];

    [blend forceProcessingAtSize:size];
    [source processImage];

    return [blend imageFromCurrentlyProcessedOutput];
}

@end

And last, add the following frameworks to your project:

AVFoundation CoreMedia CoreVideo OpenGLES

Yeah, got fun with this much faster approach ;)

Count number of rows within each group

An alternative to the aggregate() function in this case would be table() with as.data.frame(), which would also indicate which combinations of Year and Month are associated with zero occurrences

df<-data.frame(x=rep(1:6,rep(c(1,2,3),2)),year=1993:2004,month=c(1,1:11))

myAns<-as.data.frame(table(df[,c("year","month")]))

And without the zero-occurring combinations

myAns[which(myAns$Freq>0),]

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.