Programs & Examples On #Yguard

Adb install failure: INSTALL_CANCELED_BY_USER

Im using Xiaomi Redmi Prime 3S, Non of the above method worked for me. This frustrated me

what i tried was, i signed out from Mi Account and then created new account. tada... after that i can enable USB Debugging. Hope this helps.

Android: Unable to add window. Permission denied for this window type

I struggled to find the working solution with ApplicationContext and TYPE_SYSTEM_ALERT and found confusing solutions, In case you want the dialog should be opened from any activity even the dialog is a singleton you have to use getApplicationContext(), and if want the dialog should be TYPE_SYSTEM_ALERT you will need the following steps:

first get the instance of dialog with correct theme, also you need to manage the version compatibility as I did in my following snippet:

AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), R.style.Theme_AppCompat_Light);

After setting the title, message and buttons you have to build the dialog as:

AlertDialog alert = builder.create();

Now the type plays the main roll here, since this is the reason of crash, I handled the compatibility as following:

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        alert.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);

    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    }

Note: if you are using a custom dialog with AppCompatDialog as below:

AppCompatDialog dialog = new AppCompatDialog(getApplicationContext(), R.style.Theme_AppCompat_Light);

you can directly define your type to the AppCompatDialog instance as following:

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY - 1);

    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
    }

Don't forget to add the manifest permission:

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

What is the keyguard in Android?

Keyguard basically refers to the code that handles the unlocking of the phone. it's like the keypad lock on your nokia phone a few years back just with the utility on a touchscreen.

you can find more info it you look in android/app or com\android\internal\policy\impl

Good Luck !

Detect home button press in android

enter image description here Android Home Key handled by the framework layer you can't able to handle this in the application layer level. Because the home button action is already defined in the below level. But If you are developing your custom ROM, then It might be possible. Google restricted the HOME BUTTON override functions because of security reasons.

How do you get the footer to stay at the bottom of a Web page?

For this question many of the answers I have seen are clunky, hard to implement and inefficient so I thought I'd take a shot at it and come up with my own solution which is just a tiny bit of css and html

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
}_x000D_
.body {_x000D_
  min-height: calc(100% - 2rem);_x000D_
  width: 100%;_x000D_
  background-color: grey;_x000D_
}_x000D_
.footer {_x000D_
  height: 2rem;_x000D_
  width: 100%;_x000D_
  background-color: yellow;_x000D_
}
_x000D_
<body>_x000D_
  <div class="body">test as body</div>_x000D_
  <div class="footer">test as footer</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

this works by setting the height of the footer and then using css calc to work out the minimum height the page can be with the footer still at the bottom, hope this helps some people :)

Change working directory in my current shell context when running Node script

Short answer: no (easy?) way, but you can do something that serves your purpose.

I've done a similar tool (a small command that, given a description of a project, sets environment, paths, directories, etc.). What I do is set-up everything and then spawn a shell with:

spawn('bash', ['-i'], {
  cwd: new_cwd,
  env: new_env,
  stdio: 'inherit'
});

After execution, you'll be on a shell with the new directory (and, in my case, environment). Of course you can change bash for whatever shell you prefer. The main differences with what you originally asked for are:

  • There is an additional process, so...
  • you have to write 'exit' to come back, and then...
  • after existing, all changes are undone.

However, for me, that differences are desirable.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

Message 'src refspec master does not match any' when pushing commits in Git

Maybe GitHub doesn't know who you are.

First you have to run:

git config --global user.email "[email protected]"
git config --global user.name "Your Name"

How to check type of variable in Java?

Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:

int x;

You can be sure it will only ever hold int values.

If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.

If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:

List y;
...
if (y instanceof ArrayList) { 
  ...its and ArrayList...
}

However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.

Hidden features of Python

Getter functions in module operator

The functions attrgetter() and itemgetter() in module operator can be used to generate fast access functions for use in sorting and search objects and dictionaries

Chapter 6.7 in the Python Library Docs

What is difference between monolithic and micro kernel?

Microkernel:

Moves as much from the kernel into “user” space.

Communication takes place between user modules using message passing.

Benefits:

1-Easier to extend a microkernel

2-Easier to port the operating system to new architectures

3-More reliable (less code is running in kernel mode)

4-More secure

Detriments:

1-Performance overhead of user space to kernel space communication

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

if you are using tomcat you may try this

<servlet-mapping>

    <http-method>POST</http-method>

</servlet-mapping>

in addition to <servlet-name> and <url-mapping>

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

Find the nth occurrence of substring in a string

Building on modle13's answer, but without the re module dependency.

def iter_find(haystack, needle):
    return [i for i in range(0, len(haystack)) if haystack[i:].startswith(needle)]

I kinda wish this was a builtin string method.

>>> iter_find("http://stackoverflow.com/questions/1883980/", '/')
[5, 6, 24, 34, 42]

Android how to convert int to String?

You called an incorrect method of String class, try:

int tmpInt = 10;
String tmpStr10 = String.valueOf(tmpInt);

You can also do:

int tmpInt = 10;
String tmpStr10 = Integer.toString(tmpInt);

How can I convert an RGB image into grayscale in Python?

The tutorial is cheating because it is starting with a greyscale image encoded in RGB, so they are just slicing a single color channel and treating it as greyscale. The basic steps you need to do are to transform from the RGB colorspace to a colorspace that encodes with something approximating the luma/chroma model, such as YUV/YIQ or HSL/HSV, then slice off the luma-like channel and use that as your greyscale image. matplotlib does not appear to provide a mechanism to convert to YUV/YIQ, but it does let you convert to HSV.

Try using matplotlib.colors.rgb_to_hsv(img) then slicing the last value (V) from the array for your grayscale. It's not quite the same as a luma value, but it means you can do it all in matplotlib.

Background:

Alternatively, you could use PIL or the builtin colorsys.rgb_to_yiq() to convert to a colorspace with a true luma value. You could also go all in and roll your own luma-only converter, though that's probably overkill.

How to use boolean 'and' in Python

You can also test them as a couple.

if (i,ii)==(5,10):
    print "i is 5 and ii is 10"

How to call VS Code Editor from terminal / command line

I use the following command to load a project quickly (in linux)

  1. cd into the project cd /project
  2. run command code pwd

similar steps can be used in other Os too.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Make sure you have the latest values in your gradle files. As of this writing:

  • buildToolsVersion "21.1.2"

  • dependencies { classpath 'com.android.tools.build:gradle:1.1.0' }

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

Getting unix timestamp from Date()

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

Do I commit the package-lock.json file created by npm 5?

Yes, you can commit this file. From the npm's official docs:

package-lock.json is automatically generated for any operations where npm modifies either the node_modules tree, or package.json. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.

This file is intended to be committed into source repositories[.]

Hot to get all form elements values using jQuery?

If you want to use $(formName).serializeArray() or $(formName).serialize(), you must add name='inputName' on your input element. or will not work!

Determining type of an object in ruby

you could also try: instance_of?

p 1.instance_of? Fixnum    #=> True
p "1".instance_of? String  #=> True
p [1,2].instance_of? Array #=> True

jquery's append not working with svg element?

The increasingly popular D3 library handles the oddities of appending/manipulating svg very nicely. You may want to consider using it as opposed to the jQuery hacks mentioned here.

HTML

<svg xmlns="http://www.w3.org/2000/svg"></svg>

Javascript

var circle = d3.select("svg").append("circle")
    .attr("r", "10")
    .attr("style", "fill:white;stroke:black;stroke-width:5");

Compare a date string to datetime in SQL Server?

Technique 1:

 DECLARE @p_date DATETIME
 SET     @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

 SELECT  *
 FROM    table1
 WHERE   column_datetime >= @p_date
 AND     column_datetime < DATEADD(d, 1, @p_date)

The advantage of this is that it will use any index on 'column_datetime' if it exists.

String replace a Backslash

To Replace backslash at particular location:

if ((stringValue.contains("\\"))&&(stringValue.indexOf("\\", location-1)==(location-1))) {
    stringValue=stringValue.substring(0,location-1);
}

SQL Case Sensitive String Compare

Just as another alternative you could use HASHBYTES, something like this:

SELECT * 
FROM a_table 
WHERE HASHBYTES('sha1', attribute) = HASHBYTES('sha1', 'k')

LaTeX Optional Arguments

Example from the guide:

\newcommand{\example}[2][YYY]{Mandatory arg: #2;
                                 Optional arg: #1.}

This defines \example to be a command with two arguments, 
referred to as #1 and #2 in the {<definition>}--nothing new so far. 
But by adding a second optional argument to this \newcommand 
(the [YYY]) the first argument (#1) of the newly defined 
command \example is made optional with its default value being YYY.

Thus the usage of \example is either:

   \example{BBB}
which prints:
Mandatory arg: BBB; Optional arg: YYY.
or:
   \example[XXX]{AAA}
which prints:
Mandatory arg: AAA; Optional arg: XXX.

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Get RETURN value from stored procedure in SQL

The accepted answer is invalid with the double EXEC (only need the first EXEC):

DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue

And you still need to call PRINT (at least in Visual Studio).

Adding multiple class using ng-class

Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.

ng-class="{'active' : itemCount, 'activemenu' : showCart}"

firestore: PERMISSION_DENIED: Missing or insufficient permissions

Your rules should be like this for this case however the message says that it is not the suggested way, but if you do this you can do inserts with no permission error

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

Why is the use of alloca() not considered good practice?

All of the other answers are correct. However, if the thing you want to alloc using alloca() is reasonably small, I think that it's a good technique that's faster and more convenient than using malloc() or otherwise.

In other words, alloca( 0x00ffffff ) is dangerous and likely to cause overflow, exactly as much as char hugeArray[ 0x00ffffff ]; is. Be cautious and reasonable and you'll be fine.

How to Define Callbacks in Android?

Example to implement callback method using interface.

Define the interface, NewInterface.java.

package javaapplication1;

public interface NewInterface {
    void callback();
}

Create a new class, NewClass.java. It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;
    }

    public void calledFromMain(){
        //Do somthing...

        //call back main
        mainClass.callback();
    }
}

The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {

        System.out.println("test...");

        JavaApplication1 myApplication = new JavaApplication1();
        myApplication.doSomething();

    }

    private void doSomething(){
        newClass = new NewClass(this);
        newClass.calledFromMain();
    }

    @Override
    public void callback() {
        System.out.println("callback");
    }

}

What is the difference between association, aggregation and composition?

From: Remo H. Jansen book “Beginning React: Learning TypeScript 2.x - Second Edition” :

We call association those relationships whose objects have an independent life cycle where there is no ownership of the objects. Let's take a look at an example of a teacher and a student. Multiple students can be associated with a single teacher, and a single student can be associated with multiple teachers, but both have independent life cycles (both can create and delete independently). So, when a teacher leaves the school, we don't need to delete any students, and when a student leaves the school, we don't need to delete any teachers.

We call aggregation those relationships whose objects have an independent life cycle, but there is ownership, and child objects cannot belong to another parent object. Let's take an example of a cell phone and a cell phone battery. A single battery can belong to a phone, but if the phone stops working, and we delete it from our database, the phone battery will not be deleted because it may still be functional. So, in aggregation, while there is ownership, objects have their life cycle

We use the term composition to refer to relationships whose objects don't have an independent life cycle, and if the parent object is deleted, all child objects will also be deleted. Let's take an example of the relationship between questions and answers. Single questions can have multiple answers, and answers cannot belong to multiple questions. If we delete questions, answers will automatically be deleted.

How to call shell commands from Ruby

This is not really an answer but maybe someone will find it useful:

When using TK GUI on Windows, and you need to call shell commands from rubyw, you will always have an annoying CMD window popping up for less then a second.

To avoid this you can use:

WIN32OLE.new('Shell.Application').ShellExecute('ipconfig > log.txt','','','open',0)

or

WIN32OLE.new('WScript.Shell').Run('ipconfig > log.txt',0,0)

Both will store the ipconfig output inside log.txt, but no windows will come up.

You will need to require 'win32ole' inside your script.

system(), exec() and spawn() will all pop up that annoying window when using TK and rubyw.

How can I label points in this scatterplot?

Your call to text() doesn't output anything because you inverted your x and your y:

plot(abs_losses, percent_losses, 
     main= "Absolute Losses vs. Relative Losses(in%)",
     xlab= "Losses (absolute, in miles of millions)",
     ylab= "Losses relative (in % of January´2007 value)",
     col= "blue", pch = 19, cex = 1, lty = "solid", lwd = 2)

text(abs_losses, percent_losses, labels=namebank, cex= 0.7)

Now if you want to move your labels down, left, up or right you can add argument pos= with values, respectively, 1, 2, 3 or 4. For instance, to place your labels up:

 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=3)

enter image description here

You can of course gives a vector of value to pos if you want some of the labels in other directions (for instance for Goldman_Sachs, UBS and Société_Generale since they are overlapping with other labels):

 pos_vector <- rep(3, length(namebank))
 pos_vector[namebank %in% c("Goldman_Sachs", "Societé_Generale", "UBS")] <- 4
 text(abs_losses, percent_losses, labels=namebank, cex= 0.7, pos=pos_vector)

enter image description here

Python: Select subset from list based on index set

Matlab and Scilab languages offer a simpler and more elegant syntax than Python for the question you're asking, so I think the best you can do is to mimic Matlab/Scilab by using the Numpy package in Python. By doing this the solution to your problem is very concise and elegant:

from numpy import *
property_a = array([545., 656., 5.4, 33.])
property_b = array([ 1.2,  1.3, 2.3, 0.3])
good_objects = [True, False, False, True]
good_indices = [0, 3]
property_asel = property_a[good_objects]
property_bsel = property_b[good_indices]

Numpy tries to mimic Matlab/Scilab but it comes at a cost: you need to declare every list with the keyword "array", something which will overload your script (this problem doesn't exist with Matlab/Scilab). Note that this solution is restricted to arrays of number, which is the case in your example.

Swift - How to detect orientation changes

let const = "Background" //image name
let const2 = "GreyBackground" // image name
    @IBOutlet weak var imageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()

        imageView.image = UIImage(named: const)
        // Do any additional setup after loading the view.
    }

    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        if UIDevice.current.orientation.isLandscape {
            print("Landscape")
            imageView.image = UIImage(named: const2)
        } else {
            print("Portrait")
            imageView.image = UIImage(named: const)
        }
    }

how does Request.QueryString work?

The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.

Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.

  • Assign and implement tableview dataSource and delegate
  • Assign UITableViewAutomaticDimension to rowHeight & estimatedRowHeight
  • Implement delegate/dataSource methods (i.e. heightForRowAt and return a value UITableViewAutomaticDimension to it)

-

Objective C:

// in ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

  @property IBOutlet UITableView * table;

@end

// in ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    self.table.dataSource = self;
    self.table.delegate = self;

    self.table.rowHeight = UITableViewAutomaticDimension;
    self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return UITableViewAutomaticDimension;
}

Swift:

@IBOutlet weak var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()

    // Don't forget to set dataSource and delegate for table
    table.dataSource = self
    table.delegate = self

    // Set automatic dimensions for row height
    // Swift 4.2 onwards
    table.rowHeight = UITableView.automaticDimension
    table.estimatedRowHeight = UITableView.automaticDimension


    // Swift 4.1 and below
    table.rowHeight = UITableViewAutomaticDimension
    table.estimatedRowHeight = UITableViewAutomaticDimension

}



// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // Swift 4.2 onwards
    return UITableView.automaticDimension

    // Swift 4.1 and below
    return UITableViewAutomaticDimension
}

For label instance in UITableviewCell

  • Set number of lines = 0 (& line break mode = truncate tail)
  • Set all constraints (top, bottom, right left) with respect to its superview/ cell container.
  • Optional: Set minimum height for label, if you want minimum vertical area covered by label, even if there is no data.

enter image description here

Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.

Accessing SQL Database in Excel-VBA

I'm sitting at a computer with none of the relevant bits of software, but from memory that code looks wrong. You're executing the command but discarding the RecordSet that objMyCommand.Execute returns.

I'd do:

Set objMyRecordset = objMyCommand.Execute

...and then lose the "open recordset" part.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

Working fiddle:

http://jsfiddle.net/repjt/

$.ajax({
    url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
    dataType: 'JSONP',
    jsonpCallback: 'callback',
    type: 'GET',
    success: function (data) {
        console.log(data);
    }
});

I had to manually set the callback to callback, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.

Find unique lines

uniq -u < file will do the job.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

The common name in the certicate for api.evercam.io is for *.herokuapp.com and there are no alternative subject names in the certificate. This means, that the certificate for api.evercam.io does not match the hostname and therefore the certificate verification fails. Same as true for www.evercam.io, e.g. try https://www.evercam.io with a browser and you get the error message, that the name in the certificate does not match the hostname.

So it is a problem which needs to be fixed by evercam.io. If you don't care about security, man-in-the-middle attacks etc you might disable verification of the certificate (curl --insecure), but then you should ask yourself why you use https instead of http at all.

Access Controller method from another controller in Laravel 5

You shouldn’t. It’s an anti-pattern. If you have a method in one controller that you need to access in another controller, then that’s a sign you need to re-factor.

Consider re-factoring the method out in to a service class, that you can then instantiate in multiple controllers. So if you need to offer print reports for multiple models, you could do something like this:

class ExampleController extends Controller
{
    public function printReport()
    {
        $report = new PrintReport($itemToReportOn);
        return $report->render();
    }
}

android View not attached to window manager

If you have an Activity object hanging around, you can use the isDestroyed() method:

Activity activity;

// ...

if (!activity.isDestroyed()) {
    // ...
}

This is nice if you have a non-anonymous AsyncTask subclass that you use in various places.

<ng-container> vs <template>

A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

Redis command to get all available keys?

SCAN doesn't require the client to load all the keys into memory like KEYS does. SCAN gives you an iterator you can use. I had a 1B records in my redis and I could never get enough memory to return all the keys at once.

Here is a python snippet to get all keys from the store matching a pattern and delete them:

import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for key in r.scan_iter("key_pattern*"):
    print key

Query for documents where array size is greater than 1

You can use aggregate, too:

db.accommodations.aggregate(
[
     {$project: {_id:1, name:1, zipcode:1, 
                 size_of_name: {$size: "$name"}
                }
     },
     {$match: {"size_of_name": {$gt: 1}}}
])

// you add "size_of_name" to transit document and use it to filter the size of the name

Download File to server from URL

A PHP 4 & 5 Solution:

readfile() will not present any memory issues, even when sending large files, on its own. A URL can be used as a filename with this function if the fopen wrappers have been enabled.

http://php.net/manual/en/function.readfile.php

How do you remove an invalid remote branch reference from Git?

I didn't know about git branch -rd, so the way I have solved issues like this for myself is to treat my repo as a remote repo and do a remote delete. git push . :refs/remotes/public/master. If the other ways don't work and you have some weird reference you want to get rid of, this raw way is surefire. It gives you the exact precision to remove (or create!) any kind of reference.

In c# is there a method to find the max of 3 numbers?

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

Java how to sort a Linked List?

If you'd like to know how to sort a linked list without using standard Java libraries, I'd suggest looking at different algorithms yourself. Examples here show how to implement an insertion sort, another StackOverflow post shows a merge sort, and ehow even gives some examples on how to create a custom compare function in case you want to further customize your sort.

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

Obviously you can't parse N/A to int value. you can do something like following to handle that NumberFormatException .

   String str="N/A";
   try {
        int val=Integer.parseInt(str);
   }catch (NumberFormatException e){
       System.out.println("not a number"); 
   } 

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

Firefox setting to enable cross domain Ajax request

You can check out my add on for firefox. It allows to cross domain in the lastest firefox version: https://addons.mozilla.org/en-US/firefox/addon/cross-domain-cors/

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

php & mysql query not echoing in html with tags?

You need to append your variables to the echoed string. For example:

echo 'This is a string '.$PHPvariable.' and this is more string'; 

How to find the Target *.exe file of *.appref-ms

Simple answer to this; I was trying to figure out the same thing, and it just hit me.

GitHub IS a program installed on your computer, and when it runs, it WILL use threads and RAM. So that makes it a process. All you have to do is open Task Manager, click the Processes tab, find 'Github.exe', right click, Open File Location. Voila! Mine is in some App folder in Local, about 4 layers deep.

Screenshot

Create iOS Home Screen Shortcuts on Chrome for iOS

The is no API for adding a shortcut to the home screen in iOS, so no third-party browser is capable of providing that functionality.

Excel Date to String conversion

If you are not using programming then do the following (1) select the column (2) right click and select Format Cells (3) Select "Custom" (4) Just Under "Type:" type dd/mm/yyyy hh:mm:ss

Have border wrap around text

The easiest way to do it is to make the display an inline block

<div id='page' style='width: 600px'>
  <h1 style='border:2px black solid; font-size:42px; display: inline-block;'>Title</h1>
</div>

if you do this it should work

When to use "ON UPDATE CASCADE"

I think you've pretty much nailed the points!

If you follow database design best practices and your primary key is never updatable (which I think should always be the case anyway), then you never really need the ON UPDATE CASCADE clause.

Zed made a good point, that if you use a natural key (e.g. a regular field from your database table) as your primary key, then there might be certain situations where you need to update your primary keys. Another recent example would be the ISBN (International Standard Book Numbers) which changed from 10 to 13 digits+characters not too long ago.

This is not the case if you choose to use surrogate (e.g. artifically system-generated) keys as your primary key (which would be my preferred choice in all but the most rare occasions).

So in the end: if your primary key never changes, then you never need the ON UPDATE CASCADE clause.

Marc

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

how to compare two string dates in javascript?

If your date is not in format standar yyyy-mm-dd (2017-02-06) for example 20/06/2016. You can use this code

var parts ='01/07/2016'.val().split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts ='20/06/2016'.val().split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 > d2

Python conversion from binary string to hexadecimal

This overview can be useful for someone: bin, dec, hex in python to convert between bin, dec, hex in python.

I would do:

dec_str = format(int('0000010010001101', 2),'x')
dec_str.rjust(4,'0')

Result: '048d'

How do I create a sequence in MySQL?

This is a solution suggested by the MySQl manual:

If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID(). This can be used to simulate sequences:

Create a table to hold the sequence counter and initialize it:

    mysql> CREATE TABLE sequence (id INT NOT NULL);
    mysql> INSERT INTO sequence VALUES (0);

Use the table to generate sequence numbers like this:

    mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
    mysql> SELECT LAST_INSERT_ID();

The UPDATE statement increments the sequence counter and causes the next call to LAST_INSERT_ID() to return the updated value. The SELECT statement retrieves that value. The mysql_insert_id() C API function can also be used to get the value. See Section 23.8.7.37, “mysql_insert_id()”.

You can generate sequences without calling LAST_INSERT_ID(), but the utility of using the function this way is that the ID value is maintained in the server as the last automatically generated value. It is multi-user safe because multiple clients can issue the UPDATE statement and get their own sequence value with the SELECT statement (or mysql_insert_id()), without affecting or being affected by other clients that generate their own sequence values.

How do I clear my local working directory in Git?

All the answers so far retain local commits. If you're really serious, you can discard all local commits and all local edits by doing:

git reset --hard origin/branchname

For example:

git reset --hard origin/master

This makes your local repository exactly match the state of the origin (other than untracked files).

If you accidentally did this after just reading the command, and not what it does :), use git reflog to find your old commits.

Enter triggers button click

Dom example

  <button onclick="anotherFoo()"> Add new row</button>
  <input type="text" name="xxx" onclick="foo(event)">

javascript

function foo(event){
   if(event.which == 13 || event.keyCode == 13) // for crossbrowser
   {
     event.preventDefault(); // this code prevents other buttons triggers use this
     // do stuff
   }
}

function anotherFoo(){
  // stuffs.
}

if you don't use preventDefault(), other buttons will triggered.

Read from database and fill DataTable

Private Function LoaderData(ByVal strSql As String) As DataTable
    Dim cnn As SqlConnection
    Dim dad As SqlDataAdapter

    Dim dtb As New DataTable
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        dad = New SqlDataAdapter(strSql, cnn)
        dad.Fill(dtb)
        cnn.Close()
        dad.Dispose()
    Catch ex As Exception
        cnn.Close()
        MsgBox(ex.Message)
    End Try
    Return dtb
End Function

View more than one project/solution in Visual Studio

Just right click on the Visual Studio icon and then select "New Window" from the contextual toolbar that appears on the bottom in Windows 8. A new instance of Visual Studio will launch and then you can open your second project.

Configuring Git over SSH to login once

Make sure that when you cloned the repository, you did so with the SSH URL and not the HTTPS; in the clone URL box of the repo, choose the SSH protocol before copying the URL. See image below:

enter image description here

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you have multiples docker containers launched, use this

$ docker rm $(docker ps -aq)

It will remove all the current dockers listed in the "ps -aq" command.

Source : aaam on https://github.com/docker/docker/issues/12487

How do I collapse a table row in Bootstrap?

I just came up with the same problem since we still use bootstrap 2.3.2.

My solution for this: http://jsfiddle.net/KnuU6/281/

css:

.myCollapse {
    display: none;
}
.myCollapse.in {
    display: block;
}

javascript:

 $("[data-toggle=myCollapse]").click(function( ev ) {
   ev.preventDefault();
   var target;
   if (this.hasAttribute('data-target')) {
 target = $(this.getAttribute('data-target'));
   } else {
 target = $(this.getAttribute('href'));
   };
   target.toggleClass("in");
 });

html:

<table>
  <tr><td><a href="#demo" data-toggle="myCollapse">Click me to toggle next row</a></td></tr>
  <tr class="collapse" id="#demo"><td>You can collapse and expand me.</td></tr>
</table>

How to export a MySQL database to JSON?

The simplest solution I found was combination of mysql and jq commands with JSON_OBJECT query. Actually jq is not required if JSON Lines format is good enough.

Dump from remote server to local file example.

ssh remote_server \
    "mysql \
        --silent \
        --raw \
        --host "" --port 3306 \
        --user "" --password="" \
        table \
        -e \"SELECT JSON_OBJECT('key', value) FROM table\" |
    jq --slurp --ascii-output ." \
> dump.json

books table example

+----+-------+
| id | book  | 
+----+-------+
| 1  | book1 | 
| 2  | book2 | 
| 3  | book3 | 
+----+-------+

Query would looks like:

SELECT JSON_OBJECT('id', id, 'book', book) FROM books;

dump.json output

[
    {
        "id": "1",
        "book": "book1"
    },
    {
        "id": "2",
        "book": "book2"
    },
    {
        "id": "3",
        "book": "book3"
    }
]

Converting List<String> to String[] in Java

public static void main(String[] args) {
    List<String> strlist = new ArrayList<String>();
    strlist.add("sdfs1");
    strlist.add("sdfs2");

    String[] strarray = new String[strlist.size()]
    strlist.toArray(strarray );

    System.out.println(strarray);


}

How I can check whether a page is loaded completely or not in web driver?

You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.

Export JAR with Netbeans

  1. Right click your project folder.
  2. Select Properties.
  3. Expand Build option.
  4. Select Packaging.
  5. Now Clean and Build your project (Shift +F11).
  6. jar file will be created at your_project_folder\dist folder.

jquery dialog save cancel button styling

Here is how to add custom classes in jQuery UI Dialog (Version 1.8+):

$('#foo').dialog({
    'buttons' : {
        'cancel' : {
            priority: 'secondary', class: 'foo bar baz', click: function() {
                ...
            },
        },
    }
}); 

Left Join With Where Clause

You might find it easier to understand by using a simple subquery

SELECT `settings`.*, (
    SELECT `value` FROM `character_settings`
    WHERE `character_settings`.`setting_id` = `settings`.`id`
      AND `character_settings`.`character_id` = '1') AS cv_value
FROM `settings`

The subquery is allowed to return null, so you don't have to worry about JOIN/WHERE in the main query.

Sometimes, this works faster in MySQL, but compare it against the LEFT JOIN form to see what works best for you.

SELECT s.*, c.value
FROM settings s
LEFT JOIN character_settings c ON c.setting_id = s.id AND c.character_id = '1'

mysql said: Cannot connect: invalid settings. xampp

I also had that problem and i did what hairul said:

  1. Go to localhost/security/
  2. Click the orange link localhost/security/xamppsecurity.php
  3. Change the password for superuser: 'root'"

then i restarted mysql on the xampp control panel and didn t work.

It only worked when i restarted my computer!!!!

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

Asp Net Web API 2.1 get client IP address

It's better to cast it to HttpContextBase, this way you can mock and test it more easily

public string GetUserIp(HttpRequestMessage request)
{
    if (request.Properties.ContainsKey("MS_HttpContext"))
    {
        var ctx = request.Properties["MS_HttpContext"] as HttpContextBase;
        if (ctx != null)
        {
            return ctx.Request.UserHostAddress;
        }
    }

    return null;
}

How do emulators work and how are they written?

A guy named Victor Moya del Barrio wrote his thesis on this topic. A lot of good information on 152 pages. You can download the PDF here.

If you don't want to register with scribd, you can google for the PDF title, "Study of the techniques for emulation programming". There are a couple of different sources for the PDF.

Split string to equal length substrings in Java

A StringBuilder version:

public static List<String> getChunks(String s, int chunkSize)
{
 List<String> chunks = new ArrayList<>();
 StringBuilder sb = new StringBuilder(s);

while(!(sb.length() ==0)) 
{           
   chunks.add(sb.substring(0, chunkSize));
   sb.delete(0, chunkSize);

}
return chunks;

}

How can I suppress column header output for a single SQL statement?

You can fake it like this:

-- with column headings 
select column1, column2 from some_table;

-- without column headings
select column1 as '', column2 as '' from some_table;

Using Python, find anagrams for a list of words

>>> words = ["car", "race", "rac", "ecar", "me", "em"]
>>> anagrams = {}
... for word in words:
...     reverse_word=word[::-1]
...     if reverse_word in words:
...         anagrams[word] = (words.pop(words.index(reverse_word)))
>>> anagrams
20: {'car': 'rac', 'me': 'em', 'race': 'ecar'}

Logic:

  1. Start from first word and reverse the word.
  2. Check the reversed word is present in the list.
  3. If present, find the index and pop the item and store it in the dictionary, word as key and reversed word as value.

What is a NullReferenceException, and how do I fix it?

Simon Mourier gave this example:

object o = null;
DateTime d = (DateTime)o;  // NullReferenceException

where an unboxing conversion (cast) from object (or from one of the classes System.ValueType or System.Enum, or from an interface type) to a value type (other than Nullable<>) in itself gives the NullReferenceException.

In the other direction, a boxing conversion from a Nullable<> which has HasValue equal to false to a reference type, can give a null reference which can then later lead to a NullReferenceException. The classic example is:

DateTime? d = null;
var s = d.ToString();  // OK, no exception (no boxing), returns ""
var t = d.GetType();   // Bang! d is boxed, NullReferenceException

Sometimes the boxing happens in another way. For example with this non-generic extension method:

public static void MyExtension(this object x)
{
  x.ToString();
}

the following code will be problematic:

DateTime? d = null;
d.MyExtension();  // Leads to boxing, NullReferenceException occurs inside the body of the called method, not here.

These cases arise because of the special rules the runtime uses when boxing Nullable<> instances.

iOS 6 apps - how to deal with iPhone 5 screen size?

You need to add a 640x1136 pixels PNG image ([email protected]) as a 4 inch default splash image of your project, and it will use extra spaces (without efforts on simple table based applications, games will require more efforts).

I've created a small UIDevice category in order to deal with all screen resolutions. You can get it here, but the code is as follows:

File UIDevice+Resolutions.h:

enum {
    UIDeviceResolution_Unknown           = 0,
    UIDeviceResolution_iPhoneStandard    = 1,    // iPhone 1,3,3GS Standard Display  (320x480px)
    UIDeviceResolution_iPhoneRetina4    = 2,    // iPhone 4,4S Retina Display 3.5"  (640x960px)
    UIDeviceResolution_iPhoneRetina5     = 3,    // iPhone 5 Retina Display 4"       (640x1136px)
    UIDeviceResolution_iPadStandard      = 4,    // iPad 1,2,mini Standard Display   (1024x768px)
    UIDeviceResolution_iPadRetina        = 5     // iPad 3 Retina Display            (2048x1536px)
}; typedef NSUInteger UIDeviceResolution;

@interface UIDevice (Resolutions)

- (UIDeviceResolution)resolution;

NSString *NSStringFromResolution(UIDeviceResolution resolution);

@end

File UIDevice+Resolutions.m:

#import "UIDevice+Resolutions.h"

@implementation UIDevice (Resolutions)

- (UIDeviceResolution)resolution
{
    UIDeviceResolution resolution = UIDeviceResolution_Unknown;
    UIScreen *mainScreen = [UIScreen mainScreen];
    CGFloat scale = ([mainScreen respondsToSelector:@selector(scale)] ? mainScreen.scale : 1.0f);
    CGFloat pixelHeight = (CGRectGetHeight(mainScreen.bounds) * scale);

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone){
        if (scale == 2.0f) {
            if (pixelHeight == 960.0f)
                resolution = UIDeviceResolution_iPhoneRetina4;
            else if (pixelHeight == 1136.0f)
                resolution = UIDeviceResolution_iPhoneRetina5;

        } else if (scale == 1.0f && pixelHeight == 480.0f)
            resolution = UIDeviceResolution_iPhoneStandard;

    } else {
        if (scale == 2.0f && pixelHeight == 2048.0f) {
            resolution = UIDeviceResolution_iPadRetina;

        } else if (scale == 1.0f && pixelHeight == 1024.0f) {
            resolution = UIDeviceResolution_iPadStandard;
        }
    }

    return resolution;
 }

 @end

This is how you need to use this code.

1) Add the above UIDevice+Resolutions.h & UIDevice+Resolutions.m files to your project

2) Add the line #import "UIDevice+Resolutions.h" to your ViewController.m

3) Add this code to check what versions of device you are dealing with

int valueDevice = [[UIDevice currentDevice] resolution];

    NSLog(@"valueDevice: %d ...", valueDevice);

    if (valueDevice == 0)
    {
        //unknow device - you got me!
    }
    else if (valueDevice == 1)
    {
        //standard iphone 3GS and lower
    }
    else if (valueDevice == 2)
    {
        //iphone 4 & 4S
    }
    else if (valueDevice == 3)
    {
        //iphone 5
    }
    else if (valueDevice == 4)
    {
        //ipad 2
    }
    else if (valueDevice == 5)
    {
        //ipad 3 - retina display
    }

Regular expression for extracting tag attributes

Extract the element:

var buttonMatcherRegExp=/<a[\s\S]*?>[\s\S]*?<\/a>/;
htmlStr=string.match( buttonMatcherRegExp )[0]

Then use jQuery to parse and extract the bit you want:

$(htmlStr).attr('style') 

Call of overloaded function is ambiguous

The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.

As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.

The easiest solution is to just cast the 0 to the right type.
Another option is to ensure the int overload is preferred, for example by making the other one a template:

class huge
{
 private:
  unsigned char data[BYTES];
 public:
  void setval(unsigned int);
  template <class T> void setval(const T *); // not implemented
  template <> void setval(const char*);
};

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

I had this problem, and turns out the problem was that I had used

new SimpleJdbcCall(jdbcTemplate)
    .withProcedureName("foo")

instead of

new SimpleJdbcCall(jdbcTemplate)
    .withFunctionName("foo")

Using a remote repository with non-standard port

SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

URL style:

url = ssh://[user@]host.xz[:port]/path/to/repo.git/

SCP style:

url = [user@]host.xz:path/to/repo.git/

Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user

Then you can test in a shell with:

ssh my_git_host

and alter your SCP-style URI in <repo_path>/.git/config as:

url = my_git_host:path/to/repo.git/

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

How to get label text value form a html page?

Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/

How do you list the primary key of a SQL Server table?

It's generally recommended practice now to use the sys.* views over INFORMATION_SCHEMA in SQL Server, so unless you're planning on migrating databases I would use those. Here's how you would do it with the sys.* views:

SELECT 
    c.name AS column_name,
    i.name AS index_name,
    c.is_identity
FROM sys.indexes i
    inner join sys.index_columns ic  ON i.object_id = ic.object_id AND i.index_id = ic.index_id
    inner join sys.columns c ON ic.object_id = c.object_id AND c.column_id = ic.column_id
WHERE i.is_primary_key = 1
    and i.object_ID = OBJECT_ID('<schema>.<tablename>');

The HTTP request is unauthorized with client authentication scheme 'Ntlm'. The authentication header received from the server was 'Negotiate,NTLM'

You can eliminate the client from the problem by using wftech, this is an old tool but I have found it useful in diagnosing authentication issues. wfetch allows you to specify NTLM, Negotiate and kerberos, this may well help you better understand your problem. As you are trying to call a service and wfetch knows nothing about WCF, I would suggest applying your endpoint binding (PROVIDERSSoapBinding) to the serviceMetadata then you can do an HTTP GET of the WSDL for the service with the same security settings.

Another option, which may be available to you is to force the server to use NTLM, you can do this by either editing the metabase (IIS 6) and removing the Negotiate setting, more details at http://support.microsoft.com/kb/215383.

If you are using IIS 7.x then the approach is slightly different, details of how to configure the authentication providers are here http://www.iis.net/configreference/system.webserver/security/authentication/windowsauthentication.

I notice that you have blocked out the server address with xxx.xx.xx.xxx, so I'm guessing that this is an IP address rather than a server name, this may cause issues with authentication, so if possible try targeting the machine name.

Sorry that I haven't given you the answer but rather pointers for getting closer to the issue, but I hope it helps.

I'll finish by saying that I have experienced this same issue and my only recourse was to use Kerberos rather than NTLM, don't forget you'll need to register an SPN for the service if you do go down this route.

How do I determine the size of my array in C?

The sizeof "trick" is the best way I know, with one small but (to me, this being a major pet peeve) important change in the use of parenthesis.

As the Wikipedia entry makes clear, C's sizeof is not a function; it's an operator. Thus, it does not require parenthesis around its argument, unless the argument is a type name. This is easy to remember, since it makes the argument look like a cast expression, which also uses parenthesis.

So: If you have the following:

int myArray[10];

You can find the number of elements with code like this:

size_t n = sizeof myArray / sizeof *myArray;

That, to me, reads a lot easier than the alternative with parenthesis. I also favor use of the asterisk in the right-hand part of the division, since it's more concise than indexing.

Of course, this is all compile-time too, so there's no need to worry about the division affecting the performance of the program. So use this form wherever you can.

It is always best to use sizeof on an actual object when you have one, rather than on a type, since then you don't need to worry about making an error and stating the wrong type.

For instance, say you have a function that outputs some data as a stream of bytes, for instance across a network. Let's call the function send(), and make it take as arguments a pointer to the object to send, and the number of bytes in the object. So, the prototype becomes:

void send(const void *object, size_t size);

And then you need to send an integer, so you code it up like this:

int foo = 4711;
send(&foo, sizeof (int));

Now, you've introduced a subtle way of shooting yourself in the foot, by specifying the type of foo in two places. If one changes but the other doesn't, the code breaks. Thus, always do it like this:

send(&foo, sizeof foo);

Now you're protected. Sure, you duplicate the name of the variable, but that has a high probability of breaking in a way the compiler can detect, if you change it.

Add a reference column migration in Rails 4

Another syntax of doing the same thing is:

rails g migration AddUserToUpload user:belongs_to

xls to csv converter

@andi I tested your code, it works great, BUT

In my sheets there's a column like this

2013-03-06T04:00:00

date and time in the same cell

It gets garbled during exportation, it's like this in the exported file

41275.0416667

other columns are ok.

csvkit, on the other side, does ok with that column but only exports ONE sheet, and my files have many.

css divide width 100% to 3 column

I do not think you can do it in CSS, but you can calculate a pixel perfect width with javascript. Let's say you use jQuery:

HTML code:

<div id="container">
   <div id="col1"></div>
   <div id="col2"></div>
   <div id="col3"></div>
</div>

JS Code:

$(function(){
   var total = $("#container").width();
   $("#col1").css({width: Math.round(total/3)+"px"});
   $("#col2").css({width: Math.round(total/3)+"px"});
   $("#col3").css({width: Math.round(total/3)+"px"});
});

Reading file input from a multipart/form-data POST

Another way would be to use .Net parser for HttpRequest. To do that you need to use a bit of reflection and simple class for WorkerRequest.

First create class that derives from HttpWorkerRequest (for simplicity you can use SimpleWorkerRequest):

public class MyWorkerRequest : SimpleWorkerRequest
{
    private readonly string _size;
    private readonly Stream _data;
    private string _contentType;

    public MyWorkerRequest(Stream data, string size, string contentType)
        : base("/app", @"c:\", "aa", "", null)
    {
        _size = size ?? data.Length.ToString(CultureInfo.InvariantCulture);
        _data = data;
        _contentType = contentType;
    }

    public override string GetKnownRequestHeader(int index)
    {
        switch (index)
        {
            case (int)HttpRequestHeader.ContentLength:
                return _size;
            case (int)HttpRequestHeader.ContentType:
                return _contentType;
        }
        return base.GetKnownRequestHeader(index);
    }

    public override int ReadEntityBody(byte[] buffer, int offset, int size)
    {
        return _data.Read(buffer, offset, size);
    }

    public override int ReadEntityBody(byte[] buffer, int size)
    {
        return ReadEntityBody(buffer, 0, size);
    }
}

Then wherever you have you message stream create and instance of this class. I'm doing it like that in WCF Service:

[WebInvoke(Method = "POST",
               ResponseFormat = WebMessageFormat.Json,
               BodyStyle = WebMessageBodyStyle.Bare)]
    public string Upload(Stream data)
    {
        HttpWorkerRequest workerRequest =
            new MyWorkerRequest(data,
                                WebOperationContext.Current.IncomingRequest.ContentLength.
                                    ToString(CultureInfo.InvariantCulture),
                                WebOperationContext.Current.IncomingRequest.ContentType
                );

And then create HttpRequest using activator and non public constructor

var r = (HttpRequest)Activator.CreateInstance(
            typeof(HttpRequest),
            BindingFlags.Instance | BindingFlags.NonPublic,
            null,
            new object[]
                {
                    workerRequest,
                    new HttpContext(workerRequest)
                },
            null);

var runtimeField = typeof (HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
if (runtimeField == null)
{
    return;
}

var runtime = (HttpRuntime) runtimeField.GetValue(null);
if (runtime == null)
{
    return;
}

var codeGenDirField = typeof(HttpRuntime).GetField("_codegenDir", BindingFlags.Instance | BindingFlags.NonPublic);
if (codeGenDirField == null)
{
    return;
}

codeGenDirField.SetValue(runtime, @"C:\MultipartTemp");

After that in r.Files you will have files from your stream.

Get Cell Value from a DataTable in C#

The DataRow has also an indexer:

Object cellValue = dt.Rows[i][j];

But i would prefer the strongly typed Field extension method which also supports nullable types:

int number = dt.Rows[i].Field<int>(j);

or even more readable and less error-prone with the name of the column:

double otherNumber = dt.Rows[i].Field<double>("DoubleColumn");

How to get single value from this multi-dimensional PHP array

Look at the keys and indentation in your print_r:

echo $myarray[0]['email'];

echo $myarray[0]['gender'];

...etc

Fixed width buttons with Bootstrap

To do this you can come up with a width you feel is ok for both buttons and then create a custom class with the width and add it to your buttons like so:

CSS

.custom {
    width: 78px !important;
}

I can then use this class and add it to the buttons like so:

<p><button href="#" class="btn btn-primary custom">Save</button></p>
<p><button href="#" class="btn btn-success custom">Download</button></p>

Demo: http://jsfiddle.net/yNsxU/

You can take that custom class you create and place it inside your own stylesheet, which you load after the bootstrap stylesheet. We do this because any changes you place inside the bootstrap stylesheet might get accidentally lost when you update the framework, we also want your changes to take precedence over the default values.

jQuery remove all list items from an unordered list

$("ul").empty() works fine. Is there some other error?

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('ul').empty()_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
  <li>test</li>_x000D_
  <li>test</li>_x000D_
</ul>_x000D_
_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/infernalbadger/D5ss8/

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Class JavaLaunchHelper is implemented in two places

This was an issue for me years ago and I'd previously fixed it in Eclipse by excluding 1.7 from my projects, but it became an issue again for IntelliJ, which I recently installed. I fixed it by:

  1. Uninstalling the JDK:

    cd /Library/Java/JavaVirtualMachines
    sudo rm -rf jdk1.8.0_45.jdk
    

    (I had jdk1.8.0_45.jdk installed; obviously you should uninstall whichever java version is listed in that folder. The offending files are located in that folder and should be deleted.)

  2. Downloading and installing JDK 9.

Note that the next time you create a new project, or open an existing project, you will need to set the project SDK to point to the new JDK install. You also may still see this bug or have it creep back if you have JDK 1.7 installed in your JavaVirtualMachines folder (which is what I believe happened to me).

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

After my initial struggle with the link and controller functions and reading quite a lot about them, I think now I have the answer.

First lets understand,

How do angular directives work in a nutshell:

  • We begin with a template (as a string or loaded to a string)

    var templateString = '<div my-directive>{{5 + 10}}</div>';

  • Now, this templateString is wrapped as an angular element

    var el = angular.element(templateString);

  • With el, now we compile it with $compile to get back the link function.

    var l = $compile(el)

    Here is what happens,

    • $compile walks through the whole template and collects all the directives that it recognizes.
    • All the directives that are discovered are compiled recursively and their link functions are collected.
    • Then, all the link functions are wrapped in a new link function and returned as l.
  • Finally, we provide scope function to this l (link) function which further executes the wrapped link functions with this scope and their corresponding elements.

    l(scope)

  • This adds the template as a new node to the DOM and invokes controller which adds its watches to the scope which is shared with the template in DOM.

enter image description here

Comparing compile vs link vs controller :

  • Every directive is compiled only once and link function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's compile function.

  • Now, after compilation we have link function which is executed while attaching the template to the DOM. So, therefore we perform everything that is specific to every instance of the directive. For eg: attaching events, mutating the template based on scope, etc.

  • Finally, the controller is meant to be available to be live and reactive while the directive works on the DOM (after getting attached). Therefore:

    (1) After setting up the view[V] (i.e. template) with link. $scope is our [M] and $controller is our [C] in M V C

    (2) Take advantage the 2-way binding with $scope by setting up watches.

    (3) $scope watches are expected to be added in the controller since this is what is watching the template during run-time.

    (4) Finally, controller is also used to be able to communicate among related directives. (Like myTabs example in https://docs.angularjs.org/guide/directive)

    (5) It's true that we could've done all this in the link function as well but its about separation of concerns.

Therefore, finally we have the following which fits all the pieces perfectly :

enter image description here

Program does not contain a static 'Main' method suitable for an entry point

In my case (after renaming application namespace manually) I had to reselect the Startup object in Project properties.

What are type hints in Python 3.5?

The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.

Additionally, it is supported in Python 2.7, as explained in this comment:

PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.

how to call an ASP.NET c# method using javascript

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

Javascript: Unicode string to hex

Here is a tweak of McDowell's algorithm that doesn't pad the result:

  function toHex(str) {
    var result = '';
    for (var i=0; i<str.length; i++) {
      result += str.charCodeAt(i).toString(16);
    }
    return result;
  }

How can I remove the last character of a string in python?

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]

Declaring multiple variables in JavaScript

Maybe like this

var variable1 = "Hello, World!"
, variable2 = 2
, variable3 = "How are you doing?"
, variable4 = 42;

Except when changing the first or last variable, it is easy to maintain and read.

How to identify platform/compiler from preprocessor macros?

Here's what I use:

#ifdef _WIN32 // note the underscore: without it, it's not msdn official!
    // Windows (x64 and x86)
#elif __unix__ // all unices, not all compilers
    // Unix
#elif __linux__
    // linux
#elif __APPLE__
    // Mac OS, not sure if this is covered by __posix__ and/or __unix__ though...
#endif

EDIT: Although the above might work for the basics, remember to verify what macro you want to check for by looking at the Boost.Predef reference pages. Or just use Boost.Predef directly.

How does a ArrayList's contains() method evaluate objects?

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    equals (Thing x) {
        if (x.value == value) return true;
        return false;
    }
}

You must write:

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    public boolean equals (Object o) {
    Thing x = (Thing) o;
        if (x.value == value) return true;
        return false;
    }
}

Now it works ;)

Is it better in C++ to pass by value or pass by constant reference?

As a rule of thumb, value for non-class types and const reference for classes. If a class is really small it's probably better to pass by value, but the difference is minimal. What you really want to avoid is passing some gigantic class by value and having it all duplicated - this will make a huge difference if you're passing, say, a std::vector with quite a few elements in it.

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

Compare if BigDecimal is greater than zero

Use compareTo() function that's built into the class.

How to overlay density plots in R?

That's how I do it in base (it's actually mentionned in the first answer comments but I'll show the full code here, including legend as I can not comment yet...)

First you need to get the info on the max values for the y axis from the density plots. So you need to actually compute the densities separately first

dta_A <- density(VarA, na.rm = TRUE)
dta_B <- density(VarB, na.rm = TRUE)

Then plot them according to the first answer and define min and max values for the y axis that you just got. (I set the min value to 0)

plot(dta_A, col = "blue", main = "2 densities on one plot"), 
     ylim = c(0, max(dta_A$y,dta_B$y)))  
lines(dta_B, col = "red")

Then add a legend to the top right corner

legend("topright", c("VarA","VarB"), lty = c(1,1), col = c("blue","red"))

javascript how to create a validation error message without using alert

I would strongly suggest you start using jQuery. Your code would look like:

$(function() {
    $('form[name="myform"]').submit(function(e) {
        var username = $('form[name="myform"] input[name="username"]').val();
        if ( username == '') {
            e.preventDefault();
            $('#errors').text('*Please enter a username*');
        }
    });
});

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

Just to add a solution here. This might help for LAMP users

Options +FollowSymLinks -SymLinksIfOwnerMatch

The above mentioned line in the virtual host configuration was the culprit.

Virtual Host Configuration when error

<VirtualHost *:80>
    DocumentRoot /var/www/html/load/web
    ServerName dev.load.com
    <Directory "/var/www/html/load/web">
        Options +FollowSymLinks -SymLinksIfOwnerMatch
        AllowOverride All
        Require all granted
        Order Allow,Deny
        Allow from All
    </Directory>
     RewriteEngine on
     RewriteCond %{SERVER_PORT} !^443$
     RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
</VirtualHost>

Working Configuration

<VirtualHost *:80>
    DocumentRoot /var/www/html/load/web

   ServerName dev.load.com
   <Directory "/var/www/html/load/web">

        AllowOverride All

        Options All

        Order Allow,Deny

        Allow from All

    </Directory>

    # To allow authorization header
    RewriteEngine On
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* - [e=HTTP_AUTHORIZATION:%1]

   # RewriteCond %{SERVER_PORT} !^443$
   # RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]


</VirtualHost>

Python function pointer

eval(compile(myvar,'<str>','eval'))(myargs)

compile(...,'eval') allows only a single statement, so that there can't be arbitrary commands after a call, or there will be a SyntaxError. Then a tiny bit of validation can at least constrain the expression to something in your power, like testing for 'mypackage' to start.

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Access parent URL from iframe

var url = (window.location != window.parent.location) ? document.referrer: document.location;

I found that the above example suggested previously worked when the script was being executed in an iframe however it did not retrieve the url when the script was executed outside of an iframe, a slight adjustment was required:

var url = (window.location != window.parent.location) ? document.referrer: document.location.href;

Are there constants in JavaScript?

Checkout https://www.npmjs.com/package/constjs, which provides three functions to create enum, string const and bitmap. The returned result is either frozen or sealed thus you can't change/delete the properties after they are created, you can neither add new properties to the returned result

create Enum:

var ConstJs = require('constjs');

var Colors = ConstJs.enum("blue red");

var myColor = Colors.blue;

console.log(myColor.isBlue()); // output true 
console.log(myColor.is('blue')); // output true 
console.log(myColor.is('BLUE')); // output true 
console.log(myColor.is(0)); // output true 
console.log(myColor.is(Colors.blue)); // output true 

console.log(myColor.isRed()); // output false 
console.log(myColor.is('red')); // output false 

console.log(myColor._id); // output blue 
console.log(myColor.name()); // output blue 
console.log(myColor.toString()); // output blue 

// See how CamelCase is used to generate the isXxx() functions 
var AppMode = ConstJs.enum('SIGN_UP, LOG_IN, FORGOT_PASSWORD');
var curMode = AppMode.LOG_IN;

console.log(curMode.isLogIn()); // output true 
console.log(curMode.isSignUp()); // output false 
console.log(curMode.isForgotPassword()); // output false 

Create String const:

var ConstJs = require('constjs');

var Weekdays = ConstJs.const("Mon, Tue, Wed");
console.log(Weekdays); // output {Mon: 'Mon', Tue: 'Tue', Wed: 'Wed'} 

var today = Weekdays.Wed;
console.log(today); // output: 'Wed'; 

Create Bitmap:

var ConstJs = require('constjs');

var ColorFlags = ConstJs.bitmap("blue red");
console.log(ColorFlags.blue); // output false 

var StyleFlags = ConstJs.bitmap(true, "rustic model minimalist");
console.log(StyleFlags.rustic); // output true 

var CityFlags = ConstJs.bitmap({Chengdu: true, Sydney: false});
console.log(CityFlags.Chengdu); //output true 
console.log(CityFlags.Sydney); // output false 

var DayFlags = ConstJs.bitmap(true, {Mon: false, Tue: true});
console.log(DayFlags.Mon); // output false. Default val wont override specified val if the type is boolean  

For more information please checkout

Disclaim: I am the author if this tool.

Skip download if files exist in wget?

The -nc, --no-clobber option isn't the best solution as newer files will not be downloaded. One should use -N instead which will download and overwrite the file only if the server has a newer version, so the correct answer is:

wget -N http://www.example.com/images/misc/pic.png

Then running Wget with -N, with or without -r or -p, the decision as to whether or not to download a newer copy of a file depends on the local and remote timestamp and size of the file. -nc may not be specified at the same time as -N.

-N, --timestamping: Turn on time-stamping.

How to add background image for input type="button"?

If this is a submit button, use <input type="image" src="..." ... />.

http://www.htmlcodetutorial.com/forms/_INPUT_TYPE_IMAGE.html

If you want to specify the image with CSS, you'll have to use type="submit".

Python3 project remove __pycache__ folders and .pyc files

Why not just use rm -rf __pycache__? Run git add -A afterwards to remove them from your repository and add __pycache__/ to your .gitignore file.

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

How to compare types

If your instance is a Type:

Type typeFiled;
if (typeField == typeof(string))
{ 
    ... 
}

but if your instance is an object and not a Type use the as operator:

object value;
string text = value as string;
if (text != null)
{
    // value is a string and you can do your work here
}

this has the advantage to convert value only once into the specified type.

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

In SSMS 2012, you'll have to use:

To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.

  1. Add "-m;" into parameters;
  2. Restart the service and logon this SQL instance by using windows authentication;
  3. The rest steps are same as above. Change your windows user account permission in security or reset SA account password.
  4. Last, remove "-m" parameter from "startup parameters";

How do I run a shell script without using "sh" or "bash" commands?

Enter "#!/bin/sh" before script. Then save it as script.sh for example. copy it to $HOME/bin or $HOME/usr/bin
The directory can be different on different linux distros but they end with 'bin' and are in home directory cd $HOME/bin or $HOME/usr/bin
Type chmod 700 script.sh
And you can run it just by typing run.sh on terminal. If it not work, try chmod +x run.sh instead of chmod 700 run.sh

Understanding slice notation

Enumerating the possibilities allowed by the grammar:

>>> seq[:]                # [seq[0],   seq[1],          ..., seq[-1]    ]
>>> seq[low:]             # [seq[low], seq[low+1],      ..., seq[-1]    ]
>>> seq[:high]            # [seq[0],   seq[1],          ..., seq[high-1]]
>>> seq[low:high]         # [seq[low], seq[low+1],      ..., seq[high-1]]
>>> seq[::stride]         # [seq[0],   seq[stride],     ..., seq[-1]    ]
>>> seq[low::stride]      # [seq[low], seq[low+stride], ..., seq[-1]    ]
>>> seq[:high:stride]     # [seq[0],   seq[stride],     ..., seq[high-1]]
>>> seq[low:high:stride]  # [seq[low], seq[low+stride], ..., seq[high-1]]

Of course, if (high-low)%stride != 0, then the end point will be a little lower than high-1.

If stride is negative, the ordering is changed a bit since we're counting down:

>>> seq[::-stride]        # [seq[-1],   seq[-1-stride],   ..., seq[0]    ]
>>> seq[high::-stride]    # [seq[high], seq[high-stride], ..., seq[0]    ]
>>> seq[:low:-stride]     # [seq[-1],   seq[-1-stride],   ..., seq[low+1]]
>>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]

Extended slicing (with commas and ellipses) are mostly used only by special data structures (like NumPy); the basic sequences don't support them.

>>> class slicee:
...     def __getitem__(self, item):
...         return repr(item)
...
>>> slicee()[0, 1:2, ::5, ...]
'(0, slice(1, 2, None), slice(None, None, 5), Ellipsis)'

Pandas join issue: columns overlap but no suffix specified

Your error on the snippet of data you posted is a little cryptic, in that because there are no common values, the join operation fails because the values don't overlap it requires you to supply a suffix for the left and right hand side:

In [173]:

df_a.join(df_b, on='mukey', how='left', lsuffix='_left', rsuffix='_right')
Out[173]:
       mukey_left  DI  PI  mukey_right  niccdcd
index                                          
0          100000  35  14          NaN      NaN
1         1000005  44  14          NaN      NaN
2         1000006  44  14          NaN      NaN
3         1000007  43  13          NaN      NaN
4         1000008  43  13          NaN      NaN

merge works because it doesn't have this restriction:

In [176]:

df_a.merge(df_b, on='mukey', how='left')
Out[176]:
     mukey  DI  PI  niccdcd
0   100000  35  14      NaN
1  1000005  44  14      NaN
2  1000006  44  14      NaN
3  1000007  43  13      NaN
4  1000008  43  13      NaN

MySQL vs MongoDB 1000 reads

MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL team could just incorporate it into their codebase.

People are seeing real world MongoDB performance largely because MongoDB allows you to query in a different manner that is more sensible to your workload.

For example, consider a design that persisted a lot of information about a complicated entity in a normalised fashion. This could easily use dozens of tables in MySQL (or any relational db) to store the data in normal form, with many indexes needed to ensure relational integrity between tables.

Now consider the same design with a document store. If all of those related tables are subordinate to the main table (and they often are), then you might be able to model the data such that the entire entity is stored in a single document. In MongoDB you can store this as a single document, in a single collection. This is where MongoDB starts enabling superior performance.

In MongoDB, to retrieve the whole entity, you have to perform:

  • One index lookup on the collection (assuming the entity is fetched by id)
  • Retrieve the contents of one database page (the actual binary json document)

So a b-tree lookup, and a binary page read. Log(n) + 1 IOs. If the indexes can reside entirely in memory, then 1 IO.

In MySQL with 20 tables, you have to perform:

  • One index lookup on the root table (again, assuming the entity is fetched by id)
  • With a clustered index, we can assume that the values for the root row are in the index
  • 20+ range lookups (hopefully on an index) for the entity's pk value
  • These probably aren't clustered indexes, so the same 20+ data lookups once we figure out what the appropriate child rows are.

So the total for mysql, even assuming that all indexes are in memory (which is harder since there are 20 times more of them) is about 20 range lookups.

These range lookups are likely comprised of random IO — different tables will definitely reside in different spots on disk, and it's possible that different rows in the same range in the same table for an entity might not be contiguous (depending on how the entity has been updated, etc).

So for this example, the final tally is about 20 times more IO with MySQL per logical access, compared to MongoDB.

This is how MongoDB can boost performance in some use cases.

To show only file name without the entire directory path

No need for Xargs and all , ls is more than enough.

ls -1 *.txt

displays row wise

How does one check if a table exists in an Android SQLite database?

You mentioned that you've created an class that extends SQLiteOpenHelper and implemented the onCreate method. Are you making sure that you're performing all your database acquire calls with that class? You should only be getting SQLiteDatabase objects via the SQLiteOpenHelper#getWritableDatabase and getReadableDatabase otherwise the onCreate method will not be called when necessary. If you are doing that already check and see if th SQLiteOpenHelper#onUpgrade method is being called instead. If so, then the database version number was changed at some point in time but the table was never created properly when that happened.

As an aside, you can force the recreation of the database by making sure all connections to it are closed and calling Context#deleteDatabase and then using the SQLiteOpenHelper to give you a new db object.

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

Get selected value of a dropdown's item using jQuery

$("select[id$=dropDownId]").val()
  • try this

Get filename in batch for loop

or Just %~F will give you the full path and full file name.

For example, if you want to register all *.ax files in the current directory....

FOR /R C:. %F in (*.ax) do regsvr32 "%~F"

This works quite nicely in Win7 (64bit) :-)

how to check for datatype in node js- specifically for integer

_x000D_
_x000D_
var val = ... //the value you want to check_x000D_
if(Number.isNaN(Number(val))){_x000D_
  console.log("This is NOT a number!");_x000D_
}else{_x000D_
  console.log("This IS a number!");_x000D_
}
_x000D_
_x000D_
_x000D_

Fatal error: Call to a member function bind_param() on boolean

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

Run chrome in fullscreen mode on Windows

I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...

  • Start chrome and navigate to page (www.youtube.com/tv)
  • Drag the address from the address bar (the lock icon) to the desktop. It will create a shortcut.
  • From chrome, open Apps (the icon with the multiple coloured dots)
  • From desktop, drag the shortcut into the Apps space
  • Right click on the new icon in Apps and select "Open fullscreen"
  • Right click again on the icon in Apps and select "Create shortcuts..."
  • Select for example Desktop and Create. A new shortcut will be created on desktop.

Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.

How do I see if Wi-Fi is connected on Android?

This is an easier solution. See Stack Overflow question Checking Wi-Fi enabled or not on Android.

P.S. Do not forget to add the code to the manifest.xml file to allow permission. As shown below.

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" >
</uses-permission>

Can I use break to exit multiple nested 'for' loops?

The break statement terminates the execution of the nearest enclosing do, for, switch, or while statement in which it appears. Control passes to the statement that follows the terminated statement.

from msdn.

How can I check if an array contains a specific value in php?

See in_array

<?php
    $arr = array(0 => "kitchen", 1 => "bedroom", 2 => "living_room", 3 => "dining_room");    
    if (in_array("kitchen", $arr))
    {
        echo sprintf("'kitchen' is in '%s'", implode(', ', $arr));
    }
?>

How to add favicon.ico in ASP.NET site

I have the same issue. My url is as below

http://somesite/someapplication

Below doesnot work

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

I got it to work like below

<link rel="shortcut icon" type="image/x-icon" href="/someapplication/favicon.ico" />

What does %~dp0 mean, and how does it work?

The variable %0 in a batch script is set to the name of the executing batch file.

The ~dp special syntax between the % and the 0 basically says to expand the variable %0 to show the drive letter and path, which gives you the current directory containing the batch file!

Help = Link

How do I hide an element on a click event anywhere outside of the element?

This following code example seems to work best for me. While you can use 'return false' that stops all handling of that event for the div or any of it's children. If you want to have controls on the pop-up div (a pop-up login form for example) you need to use event.stopPropogation().

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <a id="link" href="#">show box</a>
    <div id="box" style="background: #eee; display: none">
        <p>a paragraph of text</p>
        <input type="file"  />
    </div>

    <script src="jquery.js" type="text/javascript"></script>

    <script type="text/javascript">
        var box = $('#box');
        var link = $('#link');

        link.click(function() {
            box.show(); return false;
        });

        $(document).click(function() {
            box.hide();
        });

        box.click(function(e) {
            e.stopPropagation();
        });

    </script>
</body>
</html>

How to Customize the time format for Python logging?

To add to the other answers, here are the variable list from Python Documentation.

Directive   Meaning Notes

%a  Locale’s abbreviated weekday name.   
%A  Locale’s full weekday name.  
%b  Locale’s abbreviated month name.     
%B  Locale’s full month name.    
%c  Locale’s appropriate date and time representation.   
%d  Day of the month as a decimal number [01,31].    
%H  Hour (24-hour clock) as a decimal number [00,23].    
%I  Hour (12-hour clock) as a decimal number [01,12].    
%j  Day of the year as a decimal number [001,366].   
%m  Month as a decimal number [01,12].   
%M  Minute as a decimal number [00,59].  
%p  Locale’s equivalent of either AM or PM. (1)
%S  Second as a decimal number [00,61]. (2)
%U  Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0.    (3)
%w  Weekday as a decimal number [0(Sunday),6].   
%W  Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0.    (3)
%x  Locale’s appropriate date representation.    
%X  Locale’s appropriate time representation.    
%y  Year without century as a decimal number [00,99].    
%Y  Year with century as a decimal number.   
%z  Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z  Time zone name (no characters if no time zone exists).   
%%  A literal '%' character.     

Calculating the distance between 2 points

If you are using System.Windows.Point data type to represent a point, you can use

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distance = Point.Subtract(p2, p1).Length;

Update 2017-01-08:

  • Add reference to Microsoft documentation
  • Result of Point.Subtract is System.Windows.Vector and it has also property LengthSquared to save one sqrt calculation if you just need to compare distance.
  • Adding reference to WindowsBase assembly may be needed in your project
  • You can also use operators

Example with LengthSquared and operators

// assuming p1 and p2 data types
Point p1, p2;
// distanc can be calculated as follows
double distanceSquared = (p2 - p1).LengthSquared;

How to run function of parent window when child window closes?

Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer

Passing an array/list into a Python function

When you define your function using this syntax:

def someFunc(*args):
    for x in args
        print x

You're telling it that you expect a variable number of arguments. If you want to pass in a List (Array from other languages) you'd do something like this:

def someFunc(myList = [], *args):
    for x in myList:
        print x

Then you can call it with this:

items = [1,2,3,4,5]

someFunc(items)

You need to define named arguments before variable arguments, and variable arguments before keyword arguments. You can also have this:

def someFunc(arg1, arg2, arg3, *args, **kwargs):
    for x in args
        print x

Which requires at least three arguments, and supports variable numbers of other arguments and keyword arguments.

Command prompt won't change directory to another drive

You can change directory using this command like : currently if you current working directoris c:\ drive the if you want to go to your D:\ drive then type this command

cd /d D:\

now your current working directory is D:\ drive so you want go to Java directory under Docs so type below command :

cd Docs\Java

note : d stands for drive

Sort & uniq in Linux shell

I have worked on some servers where sort don't support '-u' option. there we have to use

sort xyz | uniq

Changing specific text's color using NSMutableAttributedString in Swift

I see you have answered the question somewhat, but to provide a slightly more concise way without using regex to answer to the title question:

To change the colour of a length of text you need to know the start and end index of the coloured-to-be characters in the string e.g.

var main_string = "Hello World"
var string_to_color = "World"

var range = (main_string as NSString).rangeOfString(string_to_color)

Then you convert to attributed string and use 'add attribute' with NSForegroundColorAttributeName:

var attributedString = NSMutableAttributedString(string:main_string)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

A list of further standard attributes you can set can be found in Apple's documentation

Dump a NumPy array into a csv file

In Python we use csv.writer() module to write data into csv files. This module is similar to the csv.reader() module.

import csv

person = [['SN', 'Person', 'DOB'],
['1', 'John', '18/1/1997'],
['2', 'Marie','19/2/1998'],
['3', 'Simon','20/3/1999'],
['4', 'Erik', '21/4/2000'],
['5', 'Ana', '22/5/2001']]

csv.register_dialect('myDialect',
delimiter = '|',
quoting=csv.QUOTE_NONE,
skipinitialspace=True)

with open('dob.csv', 'w') as f:
    writer = csv.writer(f, dialect='myDialect')
    for row in person:
       writer.writerow(row)

f.close()

A delimiter is a string used to separate fields. The default value is comma(,).

Python 3 sort a dict by its values

Another way is to use a lambda expression. Depending on interpreter version and whether you wish to create a sorted dictionary or sorted key-value tuples (as the OP does), this may even be faster than the accepted answer.

d = {'aa': 3, 'bb': 4, 'cc': 2, 'dd': 1}
s = sorted(d.items(), key=lambda x: x[1], reverse=True)

for k, v in s:
    print(k, v)

Where to put Gradle configuration (i.e. credentials) that should not be committed?

First answer is still valid, but the API has changed in the past. Since my edit there wasn't accepted I post it as separate answer.

The method authentication() is only used to provide the authentication method (e.g. Basic) but not any credentials.

You also shouldn't use it since it's printing the credentials plain on failure!

This his how it should look like in your build.gradle

    maven {
        credentials {
            username "$mavenUser"
            password "$mavenPassword"
        }
        url 'https://maven.yourcorp.net/'
   }

In gradle.properties in your userhome dir put:

mavenUser=admin
mavenPassword=admin123

Also ensure that the GRADLE_USER_HOME is set to ~/.gradle otherwise the properties file there won't be resolved.

See also:

https://docs.gradle.org/current/userguide/build_environment.html

and

https://docs.gradle.org/current/userguide/dependency_management.html (23.6.4.1)

What's the most efficient way to check if a record exists in Oracle?

select case 
            when exists (select 1 
                         from sales 
                         where sales_type = 'Accessories') 
            then 'Y' 
            else 'N' 
        end as rec_exists
from dual;

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

Find character position and update file name

If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)

How to disable registration new users in Laravel

add

use \Redirect;

at the top of the file

jQuery changing font family and font size

In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.

Fundamental difference between Hashing and Encryption algorithms

when it comes to security for transmitting data i.e Two way communication you use encryption.All encryption requires a key

when it comes to authorization you use hashing.There is no key in hashing

Hashing takes any amount of data (binary or text) and creates a constant-length hash representing a checksum for the data. For example, the hash might be 16 bytes. Different hashing algorithms produce different size hashes. You obviously cannot re-create the original data from the hash, but you can hash the data again to see if the same hash value is generated. One-way Unix-based passwords work this way. The password is stored as a hash value, and to log onto a system, the password you type is hashed, and the hash value is compared against the hash of the real password. If they match, then you must've typed the correct password

why is hashing irreversible :

Hashing isn't reversible because the input-to-hash mapping is not 1-to-1. Having two inputs map to the same hash value is usually referred to as a "hash collision". For security purposes, one of the properties of a "good" hash function is that collisions are rare in practical use.

How do I iterate through lines in an external file with shell?

I know the purists will hate this method, but you can cat the file.

NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
   echo "$NAME"
done

How do you set EditText to only accept numeric values in Android?

In code, you could do

ed_ins.setInputType(InputType.TYPE_CLASS_NUMBER);

Purpose of a constructor in Java?

I thought a constructor might work like a database in which only it defines variables and methods to control them

Then I saw objects that use variables and methods not defined in its constructor. So the discussion that makes the most sense to me is the one that tests variables values for validity, but the class can create variables and methods that are not defined in the constructor - less like a database and more like an over pressure valve on a steam locomotive. It doesn't control the wheels,etc.

Far less of a definition than I thought.

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

internet explorer 10 - how to apply grayscale filter?

Use this jQuery plugin https://gianlucaguarini.github.io/jQuery.BlackAndWhite/

That seems to be the only one cross-browser solution. Plus it has a nice fade in and fade out effect.

$('.bwWrapper').BlackAndWhite({
    hoverEffect : true, // default true
    // set the path to BnWWorker.js for a superfast implementation
    webworkerPath : false,
    // to invert the hover effect
    invertHoverEffect: false,
    // this option works only on the modern browsers ( on IE lower than 9 it remains always 1)
    intensity:1,
    speed: { //this property could also be just speed: value for both fadeIn and fadeOut
        fadeIn: 200, // 200ms for fadeIn animations
        fadeOut: 800 // 800ms for fadeOut animations
    },
    onImageReady:function(img) {
        // this callback gets executed anytime an image is converted
    }
});

Is JavaScript object-oriented?

JavaScript is a prototype-based programming language (probably prototype-based scripting language is more correct definition). It employs cloning and not inheritance. A prototype-based programming language is a style of object-oriented programming without classes. While object-oriented programming languages encourages development focus on taxonomy and relationships, prototype-based programming languages encourages to focus on behavior first and then later classify.

The term “object-oriented” was coined by Alan Kay in 1967, who explains it in 2003 to mean

only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. (source)

In object-oriented programming, each object is capable of receiving messages, processing data, and sending messages to other objects.

For a language to be object-oriented in may include features as encapsulation, modularity, polymorphism, and inheritance, but it is not a requirement. Object-oriented programming languages that make use of classes are often referred to as classed-based programming languages, but it is by no means a must to make use of classes to be object-oriented.

JavaScript uses prototypes to define object properties, including methods and inheritance.

Conclusion: JavaScript IS object-oriented.

ActionBarActivity cannot resolve a symbol

Make sure that in the path to the project there is no foldername having whitespace. While creating a project the specified path folders must not contain any space in their naming.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

This is all perfectly normal. Microsoft added sequences in SQL Server 2012, finally, i might add and changed the way identity keys are generated. Have a look here for some explanation.

If you want to have the old behaviour, you can:

  1. use trace flag 272 - this will cause a log record to be generated for each generated identity value. The performance of identity generation may be impacted by turning on this trace flag.
  2. use a sequence generator with the NO CACHE setting (http://msdn.microsoft.com/en-us/library/ff878091.aspx)

How do I do base64 encoding on iOS?

in iOS 7

        NSData *data=[[NSData alloc]init];
        [data base64Encoding];

JavaScript function in href vs. onclick

I use

Click <a nohref style="cursor:pointer;color:blue;text-decoration:underline"
onClick="alert('Hello World')">HERE</a>

A long way around but it gets the job done. use an A style to simplify then it becomes:

<style> A {cursor:pointer;color:blue;text-decoration:underline; } </style> 
<a nohref onClick="alert('Hello World')">HERE</a>

PHP foreach loop through multidimensional array

<?php
$php_multi_array = array("lang"=>"PHP", "type"=>array("c_type"=>"MULTI", "p_type"=>"ARRAY"));

//Iterate through an array declared above

foreach($php_multi_array as $key => $value)
{
    if (!is_array($value))
    {
        echo $key ." => ". $value ."\r\n" ;
    }
    else
    {
       echo $key ." => array( \r\n";

       foreach ($value as $key2 => $value2)
       {
           echo "\t". $key2 ." => ". $value2 ."\r\n";
       }

       echo ")";
    }
}
?>

OUTPUT:

lang => PHP
type => array( 
    c_type => MULTI
    p_type => ARRAY
)

Reference Source Code

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

If i were you @OP i would change my programming paradigm.

assuming you are getting these CORS blocked because you are making requests to localhost or something similar.

Eventually if you are going to deploy to production optoins like Google Cloud Platform or Heroku or , you will no have to worry about CORS like allow origin or whatever when in production.

so when testing the server just use postman and you will not get CORS blocked, after that deploy your server and then work on your client.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

Just install php5-cgi in debian

sudo apt-get install php5-cgi

in Centos

sudo yum install php5-cgi

"Field has incomplete type" error

You are using a forward declaration for the type MainWindowClass. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)

So, you either want:

// forward declaration, details unknown
class A;

class B {
  A *a;  // pointer to A, ok
};

Or, if you can't use a pointer or reference....

// declaration of A
#include "A.h"

class B {
  A a;  // ok, declaration of A is known
};

At some point, the compiler needs to know the details of A.

If you are only storing a pointer to A then it doesn't need those details when you declare B. It needs them at some point (whenever you actually dereference the pointer to A), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A.

// B.h
// header file

// forward declaration, details unknown
class A;

class B {
public: 
    void foo();
private:
  A *a;  // pointer to A, ok
};

// B.cpp
// implementation file

#include "B.h"
#include "A.h"  // declaration of A

B::foo() {
    // here we need to know the declaration of A
    a->whatever();
}

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

How to apply shell command to each line of a command output?

xargs fails with with backslashes, quotes. It needs to be something like

ls -1 |tr \\n \\0 |xargs -0 -iTHIS echo "THIS is a file."

xargs -0 option:

-0, --null
          Input  items are terminated by a null character instead of by whitespace, and the quotes and backslash are
          not special (every character is taken literally).  Disables the end of file string, which is treated  like
          any  other argument.  Useful when input items might contain white space, quote marks, or backslashes.  The
          GNU find -print0 option produces input suitable for this mode.

ls -1 terminates the items with newline characters, so tr translates them into null characters.

This approach is about 50 times slower than iterating manually with for ... (see Michael Aaron Safyans answer) (3.55s vs. 0.066s). But for other input commands like locate, find, reading from a file (tr \\n \\0 <file) or similar, you have to work with xargs like this.

Backbone.js fetch with parameters

try {
    // THIS for POST+JSON
    options.contentType = 'application/json';
    options.type = 'POST';
    options.data = JSON.stringify(options.data);

    // OR THIS for GET+URL-encoded
    //options.data = $.param(_.clone(options.data));

    console.log('.fetch options = ', options);
    collection.fetch(options);
} catch (excp) {
    alert(excp);
}

How do I calculate the percentage of a number?

Divide $percentage by 100 and multiply to $totalWidth. Simple maths.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

I have got this error report problem, too. My code is under below.

public static void getShop() throws Exception {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://10.0.2.2:8010/getShopInfo/aaa")
                        .build();
                Response response = client.newCall(request).execute();
                Log.d("response", response.body().string());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

I have my Springboot as my backend and use Android OKHttp to get information. The critical mistake i made was that i use a .url("https://10.0.2.2:8010/getShopInfo/aaa") in code of Android. But the my backend is not allowed https request. After i use .url("http://10.0.2.2:8010/getShopInfo/aaa"), then my code went well. So, i want to say my mistake is not the version of emulator, it about the request protocol. I meet another problem after doing what i said, but it's another problem, and i attach the resolve method of the new problem .
Good Luck!GUY!

Arraylist swap elements

In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:

String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)

How to handle ETIMEDOUT error?

This is caused when your request response is not received in given time(by timeout request module option).

Basically to catch that error first, you need to register a handler on error, so the unhandled error won't be thrown anymore: out.on('error', function (err) { /* handle errors here */ }). Some more explanation here.

In the handler you can check if the error is ETIMEDOUT and apply your own logic: if (err.message.code === 'ETIMEDOUT') { /* apply logic */ }.

If you want to request for the file again, I suggest using node-retry or node-backoff modules. It makes things much simpler.

If you want to wait longer, you can set timeout option of request yourself. You can set it to 0 for no timeout.

Jersey Exception : SEVERE: A message body reader for Java class

Some may be confused why add jersey-json jar can't solve this problem. I found out that this jar has to newer than jersey-json-1.7.jar( 1.7.0 doesn't work, but 1.7.1 works fine.). hope this can help

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

By default login failed error message is nothing but a client user connection has been refused by the server due to mismatch of login credentials. First task you might check is to see whether that user has relevant privileges on that SQL Server instance and relevant database too, thats good. Obviously if the necessary prvileges are not been set then you need to fix that issue by granting relevant privileges for that user login.

Althought if that user has relevant grants on database & server if the Server encounters any credential issues for that login then it will prevent in granting the authentication back to SQL Server, the client will get the following error message:

Msg 18456, Level 14, State 1, Server <ServerName>, Line 1
Login failed for user '<Name>'

Ok now what, by looking at the error message you feel like this is non-descriptive to understand the Level & state. By default the Operating System error will show 'State' as 1 regardless of nature of the issues in authenticating the login. So to investigate further you need to look at relevant SQL Server instance error log too for more information on Severity & state of this error. You might look into a corresponding entry in log as:

2007-05-17 00:12:00.34 Logon     Error: 18456, Severity: 14, State: 8.
or

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

As defined above the Severity & State columns on the error are key to find the accurate reflection for the source of the problem. On the above error number 8 for state indicates authentication failure due to password mismatch. Books online refers: By default, user-defined messages of severity lower than 19 are not sent to the Microsoft Windows application log when they occur. User-defined messages of severity lower than 19 therefore do not trigger SQL Server Agent alerts.

Sung Lee, Program Manager in SQL Server Protocols (Dev.team) has outlined further information on Error state description:The common error states and their descriptions are provided in the following table:

ERROR STATE       ERROR DESCRIPTION
------------------------------------------------------------------------------
2 and 5           Invalid userid
6                 Attempt to use a Windows login name with SQL Authentication
7                 Login disabled and password mismatch
8                 Password mismatch
9                 Invalid password
11 and 12         Valid login but server access failure
13                SQL Server service paused
18                Change password required


Well I'm not finished yet, what would you do in case of error:

2007-05-17 00:12:00.34 Logon     Login failed for user '<user name>'.

You can see there is no severity or state level defined from that SQL Server instance's error log. So the next troubleshooting option is to look at the Event Viewer's security log [edit because screen shot is missing but you get the

idea, look in the event log for interesting events].