Programs & Examples On #Timecodes

A timecode is a way of displaying time-only information as an offset from a starting point. Often used on audio and video as the time from the start of the media. Commonly displayed in HH:MM:SS

Performing a Stress Test on Web Application?

I second the opensta suggestion. I would just add that it allows you to do things to monitor the server you're testing using SMTP. We keep track of processor load, memory used, byes sent, etc. The only downside is that if you find something boken and want to do a fix it relies on several open-source libraries that are no longer kept up, so getting a compiling version of the source is more tricky than with most OSS.

Using success/error/finally/catch with Promises in AngularJS

Forget about using success and error method.

Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.

With the following example, I'll try to demonstrate what I mean about success and error being not chainable-friendly. Suppose we call an API that returns a user object with an address:

User object:

{name: 'Igor', address: 'San Francisco'}

Call to the API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

What happened?

Because success and error return the original promise, i.e. the one returned by $http.get, the object passed to the callback of the then is the whole user object, that is to say the same input to the preceding success callback.

If we had chained two then, this would have been less confusing:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

Cannot hide status bar in iOS7

The only thing that worked for me is to add the following in your plist

<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

@Column(name ="LEAD_ID")
private int leadId; 

Change to

@Column(name ="LEAD_ID")
private Integer leadId; 

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I had the same problem, I was storing session data in the database, the connection string had Encrypt=True in it, which I assume told the sql client to connect to the server in secure (SSL) mode, removing this helped!

Extract a single (unsigned) integer from a string

try this,use preg_replace

$string = "Hello! 123 test this? 456. done? 100%";
$int = intval(preg_replace('/[^0-9]+/', '', $string), 10);
echo $int;

DEMO

Change Bootstrap tooltip color

Bootstrap 3 + SASS for bottom tooltip :

.red-tooltip {
    & + .tooltip.bottom {
          .tooltip-inner{background-color:$red;}
          .tooltip-arrow {border-bottom-color: $red;}
    }
}

Node - how to run app.js?

The code downloaded may require you to install dependencies first. Try commands(in app.js directory): npm install then node app.js. This should install dependencies and then start the app.

How to quickly drop a user with existing privileges

The accepted answer resulted in errors for me when attempting REASSIGN OWNED BY or DROP OWNED BY. The following worked for me:

REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM username;
REVOKE ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public FROM username;
DROP USER username;

The user may have privileges in other schemas, in which case you will have to run the appropriate REVOKE line with "public" replaced by the correct schema. To show all of the schemas and privilege types for a user, I edited the \dp command to make this query:

SELECT 
  n.nspname as "Schema",
  CASE c.relkind 
    WHEN 'r' THEN 'table' 
    WHEN 'v' THEN 'view' 
    WHEN 'm' THEN 'materialized view' 
    WHEN 'S' THEN 'sequence' 
    WHEN 'f' THEN 'foreign table' 
  END as "Type"
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.array_to_string(c.relacl, E'\n') LIKE '%username%';

I'm not sure which privilege types correspond to revoking on TABLES, SEQUENCES, or FUNCTIONS, but I think all of them fall under one of the three.

How to display all elements in an arraylist?

It's not at all clear what you're up to. Your function getAll() should return a List<Car>, not a Car. Otherwise, why call it getAll?

If you have

Car[] arrayOfCars

and want a List, you can simply do this:

List<Car> listOfCars = Arrays.asList(arrayOfCars);

Arrays is documented Here.

Sleep function in Windows, using C

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleep for this function is misleading, since the CPU will not be sleeping at all.

How do I print the full value of a long string in gdb?

Just to complete it:

(gdb) p (char[10]) *($ebx)
$87 =   "asdfasdfe\n"

You must give a length, but may change the representation of that string:

(gdb) p/x (char[10]) *($ebx)
$90 =   {0x61,
  0x73,
  0x64,
  0x66,
  0x61,
  0x73,
  0x64,
  0x66,
  0x65,
  0xa}

This may be useful if you want to debug by their values

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

Setting the focus to a text field

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

Use cases for the 'setdefault' dict method

defaultdict is great when the default value is static, like a new list, but not so much if it's dynamic.

For example, I need a dictionary to map strings to unique ints. defaultdict(int) will always use 0 for the default value. Likewise, defaultdict(intGen()) always produces 1.

Instead, I used a regular dict:

nextID = intGen()
myDict = {}
for lots of complicated stuff:
    #stuff that generates unpredictable, possibly already seen str
    strID = myDict.setdefault(myStr, nextID())

Note that dict.get(key, nextID()) is insufficient because I need to be able to refer to these values later as well.

intGen is a tiny class I build that automatically increments an int and returns its value:

class intGen:
    def __init__(self):
        self.i = 0

    def __call__(self):
        self.i += 1
    return self.i

If someone has a way to do this with defaultdict I'd love to see it.

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

Compare two different files line by line in python

I have just been faced with the same challenge, but I thought "Why programming this in Python if you can solve it with a simple "grep"?, which led to the following Python code:

import subprocess
from subprocess import PIPE

try:
  output1, errors1 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file1.txt", "c:\\file2.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  output2, errors2 = subprocess.Popen(["c:\\cygwin\\bin\\grep", "-Fvf" ,"c:\\file2.txt", "c:\\file1.txt"], shell=True, stdout=PIPE, stderr=PIPE).communicate();
  if (len(output1) + len(output2) + len(errors1) + len(errors2) > 0):
    print ("Compare result : There are differences:");
    if (len(output1) + len(output2) > 0):
      print ("  Output differences : ");
      print (output1);
      print (output2);
    if (len(errors1) + len(errors2) > 0):
      print (" Errors : ");
      print (errors1);
      print (errors2);
  else:
    print ("Compare result : Both files are equal");
except Exception as ex:
  print("Compare result : Exception during comparison");
  print(ex);
  raise;

The trick behind this is the following: grep -Fvf file1.txt file2.txt verifies if all entries in file2.txt are present in file1.txt. By doing this in both directions we can see if the content of both files are "equal". I put "equal" between quotes because duplicate lines are disregarded in this way of working.

Obviously, this is just an example: you can replace grep by any commandline file comparison tool.

Why do multiple-table joins produce duplicate rows?

This might sound like a really basic "DUH" answer, but make sure that the column you're using to Lookup from on the merging file is actually full of unique values!

I noticed earlier today that PowerQuery won't throw you an error (like in PowerPivot) and will happily allow you to run a Many-Many merge. This will result in multiple rows being produced for each record that matches with a non-unique value.

How to add a bot to a Telegram Group?

Another way :

change BOT_USER_NAME before use

https://telegram.me/BOT_USER_NAME?startgroup=true

Easy way to export multiple data.frame to multiple Excel worksheets

You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:

library(xlsx)
write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:

wb = createWorkbook()

sheet = createSheet(wb, "Sheet 1")

addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)
addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)

sheet = createSheet(wb, "Sheet 2")

addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)

saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx: http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

Add and remove multiple classes in jQuery

You can separate multiple classes with the space:

$("p").addClass("myClass yourClass");

http://api.jquery.com/addClass/

What is setup.py?

setup.py is a Python file like any other. It can take any name, except by convention it is named setup.py so that there is not a different procedure with each script.

Most frequently setup.py is used to install a Python module but server other purposes:

Modules:

Perhaps this is most famous usage of setup.py is in modules. Although they can be installed using pip, old Python versions did not include pip by default and they needed to be installed separately.

If you wanted to install a module but did not want to install pip, just about the only alternative was to install the module from setup.py file. This could be achieved via python setup.py install. This would install the Python module to the root dictionary (without pip, easy_install ect).

This method is often used when pip will fail. For example if the correct Python version of the desired package is not available via pipperhaps because it is no longer maintained, , downloading the source and running python setup.py install would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).

Another use of setup.py is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.

Building Python extensions:

When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.

A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build (see link for all commands).

Once again it is named setup.py for ease of use and by convention, but can take any name.

Cython:

Another famous use of setup.py files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:

from distutils.core import setup
from Cython.Build import cythonize

setup(
    name = 'Hello world app',
    ext_modules = cythonize("hello.pyx"),
)

This can be compiled via python setup.py build

Cx_Freeze:

Another module requiring a setup script is cx_Freeze. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:

import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]} 

base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "guifoo",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("guifoo.py", base=base)])

This can be compiled via python setup.py build.

So what is a setup.py file?

Quite simply it is a script that builds or configures something in the Python environment.

A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.

It takes the name so the same command can always be used when building or installing.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

The import javax.servlet can't be resolved

You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar in Tomcat's lib folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.

If you want to leave the JAR in Tomcat's lib folder:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click the Libraries tab
  • Click Add External JARs...
  • Browse to find servlet-api.jar and select it.
  • Click OK to update the build path.

Or, if you copy the JAR into your project:

  • Right-click the project, click Properties.
  • Choose Java Build Path.
  • Click Add JARs...
  • Find servlet-api.jar in your project and select it.
  • Click OK to update the build path.

How to remove only 0 (Zero) values from column in excel 2010

Press Control + H, then select Options and check Match entire cell contents and Match case. In the Find what field type a 0, and leave the Replace with field blank. Then Replace All. This will remove all of the zeros that are stand alone.

"git rm --cached x" vs "git reset head --? x"?

There are three places where a file, say, can be - the (committed) tree, the index and the working copy. When you just add a file to a folder, you are adding it to the working copy.

When you do something like git add file you add it to the index. And when you commit it, you add it to the tree as well.

It will probably help you to know the three more common flags in git reset:

git reset [--<mode>] [<commit>]

This form resets the current branch head to <commit> and possibly updates the index (resetting it to the tree of <commit>) and the working tree depending on <mode>, which must be one of the following:
--soft

Does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--mixed

Resets the index but not the working tree (i.e., the changed files are preserved but not marked for commit) and reports what has not been updated. This is the default action.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since <commit> are discarded.

Now, when you do something like git reset HEAD, what you are actually doing is git reset HEAD --mixed and it will "reset" the index to the state it was before you started adding files / adding modifications to the index (via git add). In this case, no matter what the state of the working copy was, you didn't change it a single bit, but you changed the index in such a way that is now in sync with the HEAD of the tree. Whether git add was used to stage a previously committed but changed file, or to add a new (previously untracked) file, git reset HEAD is the exact opposite of git add.

git rm, on the other hand, removes a file from the working directory and the index, and when you commit, the file is removed from the tree as well. git rm --cached, however, removes the file from the index alone and keeps it in your working copy. In this case, if the file was previously committed, then you made the index to be different from the HEAD of the tree and the working copy, so that the HEAD now has the previously committed version of the file, the index has no file at all, and the working copy has the last modification of it. A commit now will sync the index and the tree, and the file will be removed from the tree (leaving it untracked in the working copy). When git add was used to add a new (previously untracked) file, then git rm --cached is the exact opposite of git add (and is pretty much identical to git reset HEAD).

Git 2.25 introduced a new command for these cases, git restore, but as of Git 2.28 it is described as “experimental” in the man page, in the sense that the behavior may change.

React native text going off my screen, refusing to wrap. What to do?

It works if you remove flexDirection: row from descriptionContainerVer and descriptionContainerVer2 respectively.

UPDATE (see comments)

I made a few changes to achieve what I think you're after. First of all I removed the descriptionContainerHor component. Then I set the flexDirection of the vertical views to row and added alignItems: 'center' and justifyContent: 'center'. Since the vertical views are now in fact stacked along the horizontal axis I removed the Ver part from the name.

So now you have a wrapper view that should vertically and horizontally align it's content and stack it along the x-axis. I then simply put two invisible View components on the left and right side of the Text component to do the padding.

Like this:

<View style={styles.descriptionContainer}>
  <View style={styles.padding}/>
    <Text style={styles.descriptionText} numberOfLines={5} >
      Here is a really long text that you can do nothing about, its gonna be long wether you like it or not, so be prepared for it to go off screen. Right? Right..!
    </Text>
  <View style={styles.padding}/>
</View>

And this:

descriptionContainer:{
  flex:0.5, //height (according to its parent),
  flexDirection: 'row',
  backgroundColor: 'blue',
  alignItems: 'center',
  justifyContent: 'center',
  // alignSelf: 'center',
},
padding: {
  flex: 0.1
},
descriptionText: {
  backgroundColor: 'green',//Colors.transparentColor,
  fontSize: 16,
  flex: 0.8,
  color: 'white',
  textAlign: 'center',
  flexWrap: 'wrap'
},

Then you get what I believe you were after.

FURTHER IMPROVEMENTS

Now if you would like to stack multiple text areas within the blue and orange views you can do something like this:

<View style={styles.descriptionContainer2}>
  <View style={styles.padding}/>
  <View style={styles.textWrap}>
    <Text style={styles.descriptionText} numberOfLines={5} >
      Some other long text which you can still do nothing about.. Off the screen we go then.
    </Text>
    <Text style={styles.descriptionText} numberOfLines={5} >
      Another column of text.
    </Text>
  </View>
  <View style={styles.padding}/>
</View>

Where textWrapis styled like this:

textWrap: {
  flexDirection: 'column',
  flex: 0.8
},

Hope this helps!

Display last git commit comment

You can use

git show -s --format=%s

Here --format enables various printing options, see documentation here. Specifically, %smeans 'subject'. In addition, -s stands for --no-patch, which suppresses the diff content.

I often use

git show -s --format='%h %s'

where %h denotes a short hash of the commit

Another way is

git show-branch --no-name HEAD

It seems to run faster than the other way.

I actually wrote a small tool to see the status of all my repos. You can find it on github.

enter image description here

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

SSRS chart does not show all labels on Horizontal axis

The problem here is that if there are too many data bars the labels will not show.

To fix this, under the "Chart Axis" properties set the Interval value to "=1". Then all the labels will be shown.

JQuery select2 set default value from an option in list?

Don't know others issue, Only this code worked for me.

$('select').val('').select2();

How to set env variable in Jupyter notebook

A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE (no blank lines or extra spaces). You can source this file in the .bashrc or .bash_profile files when beginning a new terminal session and you can read this into a notebook with something like,

import os
env_vars = !cat ../script/.env
for var in env_vars:
    key, value = var.split('=')
    os.environ[key] = value

I used a relative path to show that this .env file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

How do I find all the files that were created today in Unix/Linux?

Use ls or find to have all the files that were created today.

Using ls : ls -ltr | grep "$(date '+%b %e')"

Using find : cd $YOUR_DIRECTORY; find . -ls 2>/dev/null| grep "$(date '+%b %e')"

How to compile a c++ program in Linux?

g++ -o foo foo.cpp

g++ --> Driver for cc1plus compiler

-o --> Indicates the output file (foo is the name of output file here. Can be any name)

foo.cpp --> Source file to be compiled

To execute the compiled file simply type

./foo

Getting HTTP headers with Node.js

I had some problems with http.get; so I switched to the lib request:

var request = require('request');

var url = 'http://blog.mynotiz.de/';

var options = {
    url: url,
    method: 'HEAD'
};

request(options, function (error, response, body) {
        if (error) {
            return console.error('upload failed:', error);
        }

        if (response.headers['content-length']) {
            var file_size = response.headers['content-length'];
            console.log(file_size);
        }
    }
);

Why doesn't indexOf work on an array IE8?

Please careful with $.inArray if you want to use it. I just found out that the $.inArray is only works with "Array", not with String. That's why this function will not working in IE8!

The jQuery API make confusion

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0

--> They shouldn't say it "Similar". Since indexOf support "String" also!

JavaScript: clone a function

Being curious but still unable to find the answer to the performance topic of the question above, I wrote this gist for nodejs to test both the performance and reliability of all presented (and scored) solutions.

I've compared the wall times of a clone function creation and the execution of a clone. The results together with assertion errors are included in the gist's comment.

Plus my two cents (based on the author's suggestion):

clone0 cent (faster but uglier):

Function.prototype.clone = function() {
  var newfun;
  eval('newfun=' + this.toString());
  for (var key in this)
    newfun[key] = this[key];
  return newfun;
};

clone4 cent (slower but for those who dislike eval() for purposes known only to them and their ancestors):

Function.prototype.clone = function() {
  var newfun = new Function('return ' + this.toString())();
  for (var key in this)
    newfun[key] = this[key];
  return newfun;
};

As for the performance, if eval/new Function is slower than wrapper solution (and it really depends on the function body size), it gives you bare function clone (and I mean the true shallow clone with properties but unshared state) without unnecessary fuzz with hidden properties, wrapper functions and problems with stack.

Plus there is always one important factor you need to take into consideration: the less code, the less places for mistakes.

The downside of using the eval/new Function is that the clone and the original function will operate in different scopes. It won't work well with functions that are using scoped variables. The solutions using bind-like wrapping are scope independent.

Replace part of a string with another string

I'm just now learning C++, but editing some of the code previously posted, I'd probably use something like this. This gives you the flexibility to replace 1 or multiple instances, and also lets you specify the start point.

using namespace std;

// returns number of replacements made in string
long strReplace(string& str, const string& from, const string& to, size_t start = 0, long count = -1) {
    if (from.empty()) return 0;

    size_t startpos = str.find(from, start);
    long replaceCount = 0;

    while (startpos != string::npos){
        str.replace(startpos, from.length(), to);
        startpos += to.length();
        replaceCount++;

        if (count > 0 && replaceCount >= count) break;
        startpos = str.find(from, startpos);
    }

    return replaceCount;
}

The calling thread must be STA, because many UI components require this

If you call a new window UI statement in an existing thread, it throws an error. Instead of that create a new thread inside the main thread and write the window UI statement in the new child thread.

using jquery $.ajax to call a PHP function

You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).

If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:

function test() {
    // function code
}

test();

Or, use a PHP include:

include 'functions.php'; // functions.php has the test function
test();

Passing command line arguments in Visual Studio 2010?

Visual Studio 2015:

Project => Your Application Properties. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.

enter image description here

        static void Main(string[] args)
        {
            if(args == null || args.Length == 0)
            {
                Console.WriteLine("Please specify arguments!");
            }
            else
            {
                Console.WriteLine(args[0]);     // First
                Console.WriteLine(args[1]);     // Second Argument
            }
        }

Check if a String contains numbers Java

Try the following pattern:

.matches("[a-zA-Z ]*\\d+.*")

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
    window.onhashchange=hashTriggerTab;
    window.onload=hashTriggerTab;
    
    function hashTriggerTab(){
        var current_hash=window.location.hash;
        if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
        if(current_hash!=''){
            var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
            if(trigger)trigger.click();
        }
    }
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>

Unable to set variables in bash script

Five problems:

  1. Don't put a space before or after the equal sign.
  2. Use "$(...)" to get the output of a command as text.
  3. [ is a command. Put a space between it and the arguments.
  4. Commands are case-sensitive. You want echo.
  5. Use double quotes around variables. rm "$folderToBeMoved"

Call JavaScript function on DropDownList SelectedIndexChanged Event:

Or you can do it like as well:

<asp:DropDownList ID="ddl" runat="server"  AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>

how to run a winform from console application?

You should be able to use the Application class in the same way as Winform apps do. Probably the easiest way to start a new project is to do what Marc suggested: create a new Winform project, and then change it in the options to a console application

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

Better way to call javascript function in a tag

I’m tempted to say that both are bad practices.

The use of onclick or javascript: should be dismissed in favor of listening to events from outside scripts, allowing for a better separation between markup and logic and thus leading to less repeated code.

Note also that external scripts get cached by the browser.

Have a look at this answer.

Some good ways of implementing cross-browser event listeners here.

What is the { get; set; } syntax in C#?

That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.

You can read more on MSDN's Auto-Implemented Properties Programming Guide.

SQL - How do I get only the numbers after the decimal?

Make it very simple by query:

select substr('123.123',instr('123.123','.')+1, length('123.123')) from dual;

Put your number or column name instead 123.122

Most Useful Attributes

[XmlIgnore]

as this allows you to ignore (in any xml serialisation) 'parent' objects that would otherwise cause exceptions when saving.

Asp.net Validation of viewstate MAC failed

Microsoft says to never use a key generator web site.

Like everyone else here, I added this to my web.config.

<System.Web>
    <machineKey decryptionKey="ABC123...SUPERLONGKEY...5432JFEI242" 
                validationKey="XYZ234...SUPERLONGVALIDATIONKEY...FDA" 
                validation="SHA1" />
</system.web>

However, I used IIS as my machineKey generator like so:

  1. Open IIS and select a website to get this screen:

enter image description here

  1. Double click the Machine Key icon to get this screen:

enter image description here

  1. Click the "Generate Keys" link on the right which I outlined in the pic above.

Notes:

  • If you select the "Generate a unique key for each application" checkbox, ",IsolateApps" will be added to the end of your keys. I had to remove these to get the app to work. Obviously, they're not part of the key.
  • SHA1 was the default encryption method selected by IIS and if you change it, don't forget to change the validation property on machineKey in the web.config. However, encryption methods and algorithms evolve so please feel free to edit this post with the updated preferred Encryption method or mention it in the notes and I'll update.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

java_home environment variable should point to the location of the proper version of java installation directory, so that tomcat starts with the right version. for example it you built the project with java 1.7 , then make sure that JAVA_HOME environment variable points to the jdk 1.7 installation directory in your machine.

I had same problem , when i deploy the war in tomcat and run, the link throws the error. But pointing the variable - JAVA_HOME to jdk 1.7 resolved the issue, as my war file was built in java 1.7 environment.

How to plot ROC curve in Python

The previous answers assume that you indeed calculated TP/Sens yourself. It's a bad idea to do this manually, it's easy to make mistakes with the calculations, rather use a library function for all of this.

the plot_roc function in scikit_lean does exactly what you need: http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html

The essential part of the code is:

  for i in range(n_classes):
      fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
      roc_auc[i] = auc(fpr[i], tpr[i])

clientHeight/clientWidth returning different values on different browsers

The body element takes the available width, which is usually your browser viewport. As such, it will be different dimensions cross browser due to browser chrome borders, scrollbars, vertical space being take up by menus and whatnot...

The fact that the heights also vary, also tells me you set the body/html height to 100% through css since the height is usually dependant on elements inside the body..

Unless you set the width of the body element to a fixed value through css or it's style property, it's dimensions will as a rule, always vary cross browsers/versions and perhaps even depending on plugins you installed for the browser. Constant values in such a case is more an exception to the rule...

When you invoke .clientWidth on other elements that do not take the automatic width of the browser viewport, it will always return the elements 'width' + 'padding'. So a div with width 200 and a padding of 20 will have clientWidth = 240 (20 padding left and right).

The main reason however, why one would invoke clientWidth, is exactly due to possible expected discrepancies in results. If you know you will get a constant width and the value is known, then invoking clientWidth is redundant...

Can you recommend a free light-weight MySQL GUI for Linux?

I really like the MySQL collection of of GUI Tools. They aren't too large or resource hungry.

There are quite a few options here as well. Of the applications presented on that page, I like SQL Buddy - it does require a web server, however.

node.js shell command execution

I used this more concisely :

var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);

it works perfectly. :)

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

Saving and Reading Bitmaps/Images from Internal memory in Android

Came across this question today and this is how I do it. Just call this function with the required parameters

public void saveImage(Context context, Bitmap bitmap, String name, String extension){
    name = name + "." + extension;
    FileOutputStream fileOutputStream;
    try {
        fileOutputStream = context.openFileOutput(name, Context.MODE_PRIVATE);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fileOutputStream);
        fileOutputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Similarly, for reading the same, use this

public Bitmap loadImageBitmap(Context context,String name,String extension){
    name = name + "." + extension
    FileInputStream fileInputStream
    Bitmap bitmap = null;
    try{
        fileInputStream = context.openFileInput(name);
        bitmap = BitmapFactory.decodeStream(fileInputStream);
        fileInputStream.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
     return bitmap;
}

How to return data from promise

One of the fundamental principles behind a promise is that it's handled asynchronously. This means that you cannot create a promise and then immediately use its result synchronously in your code (e.g. it's not possible to return the result of a promise from within the function that initiated the promise).

What you likely want to do instead is to return the entire promise itself. Then whatever function needs its result can call .then() on the promise, and the result will be there when the promise has been resolved.

Here is a resource from HTML5Rocks that goes over the lifecycle of a promise, and how its output is resolved asynchronously:
http://www.html5rocks.com/en/tutorials/es6/promises/

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

JavaScript function to add X months to a date

Simple solution: 2678400000 is 31 day in milliseconds

var oneMonthFromNow = new Date((+new Date) + 2678400000);

Update:

Use this data to build our own function:

  • 2678400000 - 31 day
  • 2592000000 - 30 days
  • 2505600000 - 29 days
  • 2419200000 - 28 days

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Android: ProgressDialog.show() crashes with getApplicationContext

if you have a problem on groupActivity dont use this. PARENT is a static from the Parent ActivityGroup.

final AlertDialog.Builder builder = new AlertDialog.Builder(GroupActivityParent.PARENT);

instead of

final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());

Always pass weak reference of self into block in ARC?

This is how you can use the self inside the block:

//calling of the block

 NSString *returnedText= checkIfOutsideMethodIsCalled(self);

NSString* (^checkIfOutsideMethodIsCalled)(*)=^NSString*(id obj)
{
             [obj MethodNameYouWantToCall]; // this is how it will call the object 
            return @"Called";


};

invalid_grant trying to get oAuth token from google

This is a silly answer, but the problem for me was that I failed to realize I already had been issued an active oAuth token for my google user which I failed to store. The solution in this case is to go to the api console and reset the client secret.

There are numerous other answers on SO to this effect for example Reset Client Secret OAuth2 - Do clients need to re-grant access?

When do I need to use AtomicBoolean in Java?

Excerpt from the package description

Package java.util.concurrent.atomic description: A small toolkit of classes that support lock-free thread-safe programming on single variables.[...]

The specifications of these methods enable implementations to employ efficient machine-level atomic instructions that are available on contemporary processors.[...]

Instances of classes AtomicBoolean, AtomicInteger, AtomicLong, and AtomicReference each provide access and updates to a single variable of the corresponding type.[...]

The memory effects for accesses and updates of atomics generally follow the rules for volatiles:

  • get has the memory effects of reading a volatile variable.
  • set has the memory effects of writing (assigning) a volatile variable.
  • weakCompareAndSet atomically reads and conditionally writes a variable, is ordered with respect to other memory operations on that variable, but otherwise acts as an ordinary non-volatile memory operation.
  • compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

How do you read scanf until EOF in C?

Man, if you are using Windows, EOF is not reached by pressing enter, but by pressing Crtl+Z at the console. This will print "^Z", an indicator of EOF. The behavior of functions when reading this (the EOF or Crtl+Z):

Function: Output: scanf(...) EOF gets(<variable>) NULL feof(stdin) 1 getchar() EOF

Firebase cloud messaging notification not received by device

private void sendNotification(String message) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    int requestCode = 0;
    PendingIntent pendingIntent = PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.URI_COLUMN_INDEX);
    NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText(message)
            .setColor(getResources().getColor(R.color.colorPrimaryDark))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("FCM Message")
            .setContentText("hello").setLargeIcon(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap())
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .bigPicture(((BitmapDrawable) getResources().getDrawable(R.drawable.dog)).getBitmap()))
            .setAutoCancel(true)
            .setSound(sound)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, noBuilder.build());

Is it possible to apply CSS to half of a character?

If you are interested in this, then Lucas Bebber's Glitch is a very similar and super cool effect:

enter image description here

Created using a simple SASS Mixin such as

.example-one {
  font-size: 100px;
  @include textGlitch("example-one", 17, white, black, red, blue, 450, 115);
}

More details at Chris Coyer's CSS Tricks and Lucas Bebber's Codepen page

Sum columns with null values in oracle

Code:

select type, craft, sum(coalesce( regular + overtime, regular, overtime)) as total_hours
from hours_t
group by type, craft
order by type, craft

Can I Set "android:layout_below" at Runtime Programmatically?

While @jackofallcode answer is correct, it can be written in one line:

((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);

Count number of lines in a git repository

If you want this count because you want to get an idea of the project’s scope, you may prefer the output of CLOC (“Count Lines of Code”), which gives you a breakdown of significant and insignificant lines of code by language.

cloc $(git ls-files)

(This line is equivalent to git ls-files | xargs cloc. It uses sh’s $() command substitution feature.)

Sample output:

      20 text files.
      20 unique files.                              
       6 files ignored.

http://cloc.sourceforge.net v 1.62  T=0.22 s (62.5 files/s, 2771.2 lines/s)
-------------------------------------------------------------------------------
Language                     files          blank        comment           code
-------------------------------------------------------------------------------
Javascript                       2             13            111            309
JSON                             3              0              0             58
HTML                             2              7             12             50
Handlebars                       2              0              0             37
CoffeeScript                     4              1              4             12
SASS                             1              1              1              5
-------------------------------------------------------------------------------
SUM:                            14             22            128            471
-------------------------------------------------------------------------------

You will have to install CLOC first. You can probably install cloc with your package manager – for example, brew install cloc with Homebrew.

cloc $(git ls-files) is often an improvement over cloc .. For example, the above sample output with git ls-files reports 471 lines of code. For the same project, cloc . reports a whopping 456,279 lines (and takes six minutes to run), because it searches the dependencies in the Git-ignored node_modules folder.

SQL: Two select statements in one query

You can combine data from the two tables, order by goals highest first and then choose the top two like this:

MySQL

select *
from (
  select * from tblMadrid
  union all
  select * from tblBarcelona
) alldata
order by goals desc
limit 0,2;

SQL Server

select top 2 *
from (
  select * from tblMadrid
  union all
  select * from tblBarcelona
) alldata
order by goals desc;

If you only want Messi and Ronaldo

select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'

To ensure that messi is at the top of the result, you can do something like this:

select * from (
  select * from tblBarcelona where name = 'messi'
  union all
  select * from tblMadrid where name = 'ronaldo'
) stars
order by name;

How do I assign a port mapping to an existing Docker container?

In Fujimoto Youichi's example test01 is a container, whereas test02 is an image.

Before doing docker run you can remove the original container and then assign the container the same name again:

$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01

(Using -P to expose ports to random ports rather than manually assigning).

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

When user press F5 although new request goes to web server and get a responce for the request as well. But when the responce header is Parsed it check the required information in browser cache. If the required information in cache has not expired then that information is restored from in cache itself.

When user click on CTRL-F5 even then new request goes to web server and get a responce. But this time when the responce header is Parsed it do not check any required information in cache, and bring all updated information form server only.

Resource from src/main/resources not found after building with maven

FileReader reads from files on the file system.

Perhaps you intended to use something like this to load a file from the class path

// this will look in src/main/resources before building and myjar.jar! after building.
InputStream is = MyClass.class.getClassloader()
                     .getResourceAsStream("config.txt");

Or you could extract the file from the jar before reading it.

git submodule tracking latest

Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming


Update March 2013

Git 1.8.2 added the possibility to track branches.

"git submodule" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).

# add submodule to track master branch
git submodule add -b master [URL to Git repo];

# update your submodule
git submodule update --remote 

If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".

Also see Vogella's tutorial on submodules for general information on submodules.

Note:

git submodule add -b . [URL to Git repo];
                    ^^^

See git submodule man page:

A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.


See commit b928922727d6691a3bdc28160f93f25712c565f6:

submodule add: If --branch is given, record it in .gitmodules

This allows you to easily record a submodule.<name>.branch option in .gitmodules when you add a new submodule. With this patch,

$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>

reduces to

$ git submodule add -b <branch> <repository> [<path>]

This means that future calls to

$ git submodule update --remote ...

will get updates from the same branch that you used to initialize the submodule, which is usually what you want.

Signed-off-by: W. Trevor King [email protected]


Original answer (February 2012):

A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log within that submodule.

So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:

  • cd in the submodule
  • git fetch/pull to make sure it has the latest commits on the right branch
  • cd back in the parent repo
  • add and commit in order to record the new commit of the submodule.

gitslave (that you already looked at) seems to be the best fit, including for the commit operation.

It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).

Other alternatives are detailed here.

How to insert a data table into SQL Server database table?

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

git rebase: "error: cannot stat 'file': Permission denied"

I just ran into this issue. Non of the answers here happened to solve this for me.

Ended up being nuget packages I added on a branch that, once switched back to master branch, seemed to not exist. Once I did a merge it would say newtonsoft...xml could not stat. I would go to the file in question and open it but Windows threw an error back saying it can't find the file (even though I was looking right at it)

How I solved this was right click delete the file (which worked but I couldnt open it because windows couldnt find it???) and try to merge again and it solved the problem.

Very strange.

Hope this helps someone later.

How do I determine k when using k-means clustering?

I worked on a Python package kneed (Kneedle algorithm). It finds cluster numbers dynamically as the point where the curve starts to flatten. Given a set of x and y values, kneed will return the knee point of the function. The knee joint is the point of maximum curvature. Here is the sample code.

y = [7342.1301373073857, 6881.7109460930769, 6531.1657905495022,  
6356.2255554679778, 6209.8382535595829, 6094.9052166741121, 
5980.0191582610196, 5880.1869867848218, 5779.8957906367368, 
5691.1879324562778, 5617.5153566271356, 5532.2613232619951, 
5467.352265375117, 5395.4493783888756, 5345.3459908298091, 
5290.6769823693812, 5243.5271656371888, 5207.2501206569532, 
5164.9617535255456]

x = range(1, len(y)+1)

from kneed import KneeLocator
kn = KneeLocator(x, y, curve='convex', direction='decreasing')

print(kn.knee)

Reverse colormap in matplotlib

The standard colormaps also all have reversed versions. They have the same names with _r tacked on to the end. (Documentation here.)

True and False for && logic and || Logic table

I think You ask for Boolean algebra which describes the output of various operations performed on boolean variables. Just look at the article on Wikipedia.

What is "string[] args" in Main class for?

You must have seen some application that run from the commandline and let you to pass them arguments. If you write one such app in C#, the array args serves as the collection of the said arguments.

This how you process them:

static void Main(string[] args) {
    foreach (string arg in args) {
       //Do something with each argument
    }
}

multiprocessing.Pool: When to use apply, apply_async or map?

Regarding apply vs map:

pool.apply(f, args): f is only executed in ONE of the workers of the pool. So ONE of the processes in the pool will run f(args).

pool.map(f, iterable): This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. So you take advantage of all the processes in the pool.

How do I call the base class constructor?

There is no super() in C++. You have to call the Base Constructor explicitly by name.

Getting individual colors from a color map in matplotlib

You can do this with the code below, and the code in your question was actually very close to what you needed, all you have to do is call the cmap object you have.

import matplotlib

cmap = matplotlib.cm.get_cmap('Spectral')

rgba = cmap(0.5)
print(rgba) # (0.99807766255210428, 0.99923106502084169, 0.74602077638401709, 1.0)

For values outside of the range [0.0, 1.0] it will return the under and over colour (respectively). This, by default, is the minimum and maximum colour within the range (so 0.0 and 1.0). This default can be changed with cmap.set_under() and cmap.set_over().

For "special" numbers such as np.nan and np.inf the default is to use the 0.0 value, this can be changed using cmap.set_bad() similarly to under and over as above.

Finally it may be necessary for you to normalize your data such that it conforms to the range [0.0, 1.0]. This can be done using matplotlib.colors.Normalize simply as shown in the small example below where the arguments vmin and vmax describe what numbers should be mapped to 0.0 and 1.0 respectively.

import matplotlib

norm = matplotlib.colors.Normalize(vmin=10.0, vmax=20.0)

print(norm(15.0)) # 0.5

A logarithmic normaliser (matplotlib.colors.LogNorm) is also available for data ranges with a large range of values.

(Thanks to both Joe Kington and tcaswell for suggestions on how to improve the answer.)

Determine which element the mouse pointer is on top of in JavaScript

<!-- One simple solution to your problem could be like this: -->

<div>
<input type="text" id="fname" onmousemove="javascript: alert(this.id);" />
<!-- OR -->
<input type="text" id="fname" onclick="javascript: alert(this.id);" />
</div>
<!-- Both mousemove over the field & click on the field displays "fname"-->
<!-- Works fantastic in IE, FireFox, Chrome, Opera. -->
<!-- I didn't test it for Safari. -->

How does lock work exactly?

lock is actually hidden Monitor class.

How to allow user to pick the image with Swift?

If you want to pick only normal image you can use below code,that check that the picked image is not panorama image.

let picker = UIImagePickerController()

func photoFromLibrary() {

        self.picker.allowsEditing = true
        self.picker.sourceType = .photoLibrary
        //picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        self.present(self.picker, animated: true, completion: nil)

}

func shootPhoto() {

            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.picker.allowsEditing = true
                self.picker.sourceType = UIImagePickerControllerSourceType.camera
                self.picker.cameraCaptureMode = .photo
                self.picker.modalPresentationStyle = .fullScreen
                self.present(self.picker,animated: true,completion: nil)
            }

}

//Image picker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let str = "\(info["UIImagePickerControllerOriginalImage"]!)"

    let s = str.slice(from: "{", to: "}")

    if let arr = s?.components(separatedBy: ","){
        if arr.count >= 2 {
            if Int(arr[0])! > 11000 {
                picker.dismiss(animated:true, completion: nil)
                self.makeToast("Invalid Image!!!")
                return
            }
                     }
        }
    }

    if  let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
        self.UserImageView.image = image
    }
    picker.dismiss(animated:true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
    picker.dismiss(animated: true, completion: nil)
}

ConcurrentHashMap vs Synchronized HashMap

We can achieve thread safety by using both ConcurrentHashMap and synchronisedHashmap. But there is a lot of difference if you look at their architecture.

  1. synchronisedHashmap

It will maintain the lock at the object level. So if you want to perform any operation like put/get then you have to acquire the lock first. At the same time, other threads are not allowed to perform any operation. So at a time, only one thread can operate on this. So the waiting time will increase here. We can say that performance is relatively low when you are comparing with ConcurrentHashMap.

  1. ConcurrentHashMap

It will maintain the lock at the segment level. It has 16 segments and maintains the concurrency level as 16 by default. So at a time, 16 threads can be able to operate on ConcurrentHashMap. Moreover, read operation doesn't require a lock. So any number of threads can perform a get operation on it.

If thread1 wants to perform put operation in segment 2 and thread2 wants to perform put operation on segment 4 then it is allowed here. Means, 16 threads can perform update(put/delete) operation on ConcurrentHashMap at a time.

So that the waiting time will be less here. Hence the performance is relatively better than synchronisedHashmap.

OwinStartup not firing

I am not sure if this will still help someone, but I've done all of the solutions above (and from some other posts) to no avail.

What fixed the issue on my end was to put a backslash to the end of RedirectUri value in the web.config (crazy, I know!). RedirectUri is a parameter in UseOpenIdConnectAuthentication.

So, instead of:

<add key="ida:RedirectUri" value="https://www.bogussite.com/home" />

Do this:

<add key="ida:RedirectUri" value="https://www.bogussite.com/home/" />

And updated the Reply URL on the Azure App Settings as well.

That somehow made the Startup to run as expected (probably cleared some cache), and the breakpoints are now firing.

FYI. I was modelling my code from here: https://github.com/microsoftgraph/aspnet-connect-sample

NSNotificationCenter addObserver in Swift

Swift 5 Notification Observer

override func viewDidLoad() {
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
}

@objc func batteryLevelChanged(notification : NSNotification){
    //do here code
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)

}

Correct use of flush() in JPA/Hibernate

Actually, em.flush(), do more than just sends the cached SQL commands. It tries to synchronize the persistence context to the underlying database. It can cause a lot of time consumption on your processes if your cache contains collections to be synchronized.

Caution on using it.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

Permutation of array

Here is an implementation of the Permutation in Java:

Permutation - Java

You should have a check on it!

Edit: code pasted below to protect against link-death:

// Permute.java -- A class generating all permutations

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;

public class Permute implements Iterator {

   private final int size;
   private final Object [] elements;  // copy of original 0 .. size-1
   private final Object ar;           // array for output,  0 .. size-1
   private final int [] permutation;  // perm of nums 1..size, perm[0]=0

   private boolean next = true;

   // int[], double[] array won't work :-(
   public Permute (Object [] e) {
      size = e.length;
      elements = new Object [size];    // not suitable for primitives
      System.arraycopy (e, 0, elements, 0, size);
      ar = Array.newInstance (e.getClass().getComponentType(), size);
      System.arraycopy (e, 0, ar, 0, size);
      permutation = new int [size+1];
      for (int i=0; i<size+1; i++) {
         permutation [i]=i;
      }
   }

   private void formNextPermutation () {
      for (int i=0; i<size; i++) {
         // i+1 because perm[0] always = 0
         // perm[]-1 because the numbers 1..size are being permuted
         Array.set (ar, i, elements[permutation[i+1]-1]);
      }
   }

   public boolean hasNext() {
      return next;
   }

   public void remove() throws UnsupportedOperationException {
      throw new UnsupportedOperationException();
   }

   private void swap (final int i, final int j) {
      final int x = permutation[i];
      permutation[i] = permutation [j];
      permutation[j] = x;
   }

   // does not throw NoSuchElement; it wraps around!
   public Object next() throws NoSuchElementException {

      formNextPermutation ();  // copy original elements

      int i = size-1;
      while (permutation[i]>permutation[i+1]) i--;

      if (i==0) {
         next = false;
         for (int j=0; j<size+1; j++) {
            permutation [j]=j;
         }
         return ar;
      }

      int j = size;

      while (permutation[i]>permutation[j]) j--;
      swap (i,j);
      int r = size;
      int s = i+1;
      while (r>s) { swap(r,s); r--; s++; }

      return ar;
   }

   public String toString () {
      final int n = Array.getLength(ar);
      final StringBuffer sb = new StringBuffer ("[");
      for (int j=0; j<n; j++) {
         sb.append (Array.get(ar,j).toString());
         if (j<n-1) sb.append (",");
      }
      sb.append("]");
      return new String (sb);
   }

   public static void main (String [] args) {
      for (Iterator i = new Permute(args); i.hasNext(); ) {
         final String [] a = (String []) i.next();
         System.out.println (i);
      }
   }
}

How can I bring my application window to the front?

Use Form.Activate() or Form.Focus() methods.

Console errors. Failed to load resource: net::ERR_INSECURE_RESPONSE

For me the problem was the <base href="https://domain.ext/"> tag.

After removing, it was OK. Cannot really understand why it was a problem.

Remove directory which is not empty

My modified answer from @oconnecp (https://stackoverflow.com/a/25069828/3027390)

Uses path.join for better cross-platform experience. So, don't forget to require it.

var path = require('path');

Also renamed function to rimraf ;)

/**
 * Remove directory recursively
 * @param {string} dir_path
 * @see https://stackoverflow.com/a/42505874/3027390
 */
function rimraf(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function(entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                rimraf(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

If my interface must return Task what is the best way to have a no-operation implementation?

return Task.CompletedTask; // this will make the compiler happy

How to scroll HTML page to given anchor?

The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:

JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

I fixed it by changing the selector. The full snippet is this:

$(function() {
  $("a[href*='#']:not([href='#'])").click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
    var target = $(this.hash);
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
    if (target.length) {
      $('html,body').animate({
        scrollTop: target.offset().top
      }, 1000);
      return false;
    }
  }
 });
});

What does -z mean in Bash?

-z string True if the string is null (an empty string)

How to create a file name with the current date & time in Python?

I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time, We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'

"%x" instead of "%Y%m%d-%H%M%S"

How to configure socket connect timeout

I found this. Simpler than the accepted answer, and works with .NET v2

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// Connect using a timeout (5 seconds)

IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null );

bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

if ( socket.Connected )
{
    socket.EndConnect( result );
}
else 
{
     // NOTE, MUST CLOSE THE SOCKET

     socket.Close();
     throw new ApplicationException("Failed to connect server.");
}

//... 

Is there a GUI design app for the Tkinter / grid geometry?

Apart from the options already given in other answers, there's a current more active, recent and open-source project called pygubu.

This is the first description by the author taken from the github repository:

Pygubu is a RAD tool to enable quick & easy development of user interfaces for the python tkinter module.

The user interfaces designed are saved as XML, and by using the pygubu builder these can be loaded by applications dynamically as needed. Pygubu is inspired by Glade.


Pygubu hello world program is an introductory video explaining how to create a first project using Pygubu.

The following in an image of interface of the last version of pygubu designer on a OS X Yosemite 10.10.2:

enter image description here

I would definitely give it a try, and contribute to its development.

Receiving "Attempted import error:" in react app

This is another option:

export default function Counter() {

}

jQuery - Fancybox: But I don't want scrollbars!

Edit line 197 and 198 of jquery.fancybox.css:

.fancybox-lock .fancybox-overlay {
    overflow: auto;
    overflow-y: auto;
}

jQuery get the rendered height of an element?

So is this the answer?

"If you need to calculate something but not show it, set the element to visibility:hidden and position:absolute, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."

I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.

29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.

1) clientHeight was also 0.

2) Dom actually gave me a height which was great.

3) ClientRects returns a result almost identical to the DOM technique.

Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.

I added a few snapshots to illustrate how the height is calculated differently. Menu block rendered normally Menu block added to DOM Temp element

The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!

(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.

* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!

When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.

This is illustrated in the following snapshot (taken from Chrome once working.)
enter image description here

Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.

I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

java.io.InvalidClassException: local class incompatible:

I believe this happens because you use the different versions of the same class on client and server. It can be different data fields or methods

What is a race condition?

A race condition is an undesirable situation that occurs when a device or system attempts to perform two or more operations at the same time, but because of the nature of the device or system, the operations must be done in the proper sequence in order to be done correctly.

In computer memory or storage, a race condition may occur if commands to read and write a large amount of data are received at almost the same instant, and the machine attempts to overwrite some or all of the old data while that old data is still being read. The result may be one or more of the following: a computer crash, an "illegal operation," notification and shutdown of the program, errors reading the old data, or errors writing the new data.

Is there any way to prevent input type="number" getting negative values?

This solution allows all keyboard functionality including copy paste with keyboard. It prevents pasting of negative numbers with the mouse. It works with all browsers and the demo on codepen uses bootstrap and jQuery. This should work with non english language settings and keyboards. If the browser doesn't support the paste event capture (IE), it will remove the negative sign after focus out. This solution behaves as the native browser should with min=0 type=number.

Markup:

<form>
  <input class="form-control positive-numeric-only" id="id-blah1" min="0" name="nm1" type="number" value="0" />
  <input class="form-control positive-numeric-only" id="id-blah2" min="0" name="nm2" type="number" value="0" />
</form>

Javascript

$(document).ready(function() {
  $("input.positive-numeric-only").on("keydown", function(e) {
    var char = e.originalEvent.key.replace(/[^0-9^.^,]/, "");
    if (char.length == 0 && !(e.originalEvent.ctrlKey || e.originalEvent.metaKey)) {
      e.preventDefault();
    }
  });

  $("input.positive-numeric-only").bind("paste", function(e) {
    var numbers = e.originalEvent.clipboardData
      .getData("text")
      .replace(/[^0-9^.^,]/g, "");
    e.preventDefault();
    var the_val = parseFloat(numbers);
    if (the_val > 0) {
      $(this).val(the_val.toFixed(2));
    }
  });

  $("input.positive-numeric-only").focusout(function(e) {
    if (!isNaN(this.value) && this.value.length != 0) {
      this.value = Math.abs(parseFloat(this.value)).toFixed(2);
    } else {
      this.value = 0;
    }
  });
});

Convert an ArrayList to an object array

Using these libraries:

  • gson-2.8.5.jar
  • json-20180813.jar

Using this code:

List<Object[]> testNovedads = crudService.createNativeQuery(
                "SELECT cantidad, id FROM NOVEDADES GROUP BY id ");

        Gson gson = new Gson();
        String json = gson.toJson(new TestNovedad());
        JSONObject jsonObject = new JSONObject(json);
        Collection<TestNovedad> novedads = new ArrayList<>();
        for (Object[] object : testNovedads) {
            Iterator<String> iterator = jsonObject.keys();
            int pos = 0;
            for (Iterator i = iterator; i.hasNext();) {
                jsonObject.put((String) i.next(), object[pos++]);
            }
            novedads.add(gson.fromJson(jsonObject.toString(), TestNovedad.class));
        }
        for (TestNovedad testNovedad : novedads) {
            System.out.println(testNovedad.toString());
        }

/**
 * Autores: Chalo Mejia 
 * Fecha: 01/10/2020
 */
package org.main;

import java.io.Serializable;

public class TestNovedad implements Serializable {

    private static final long serialVersionUID = -6362794385792247263L;

    private int id;

    private int cantidad;

    public TestNovedad() {
        // TODO Auto-generated constructor stub
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getCantidad() {
        return cantidad;
    }

    public void setCantidad(int cantidad) {
        this.cantidad = cantidad;
    }

    @Override
    public String toString() {
        return "TestNovedad [id=" + id + ", cantidad=" + cantidad + "]";
    }

}

Concatenation of strings in Lua

If you are asking whether there's shorthand version of operator .. - no there isn't. You cannot write a ..= b. You'll have to type it in full: filename = filename .. ".tmp"

error: This is probably not a problem with npm. There is likely additional logging output above

Check if port you want to run your app is free. For me, it was the problem.

Counting no of rows returned by a select query

Try wrapping your entire select in brackets, then running a count(*) on that

select count(*)
from
(
   select m.id
   from Monitor as m 
    inner join Monitor_Request as mr 
       on mr.Company_ID=m.Company_id   group by m.Company_id
    having COUNT(m.Monitor_id)>=5
) myNewTable

How do I find duplicate values in a table in Oracle?

In case where multiple columns identify unique row (e.g relations table ) there you can use following

Use row id e.g. emp_dept(empid, deptid, startdate, enddate) suppose empid and deptid are unique and identify row in that case

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.rowid <> ied.rowid and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);

and if such table has primary key then use primary key instead of rowid, e.g id is pk then

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.id <> ied.id and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);

Is there StartsWith or Contains in t sql with variables?

It seems like what you want is http://msdn.microsoft.com/en-us/library/ms186323.aspx.

In your example it would be (starts with):

set @isExpress = (CharIndex('Express Edition', @edition) = 1)

Or contains

set @isExpress = (CharIndex('Express Edition', @edition) >= 1)

Error 415 Unsupported Media Type: POST not reaching REST if JSON, but it does if XML

I had similar problem while using in postman. for POST request under header section add these as

key:valuepair

Content-Type:application/json Accept:application/json

i hope it will work.

C# event with custom arguments

I might be late in the game, but how about:

public event Action<MyEvent> EventTriggered = delegate { }; 

private void Trigger(MyEvent e) 
{ 
     EventTriggered(e);
} 

Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.

I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.

How to set the value for Radio Buttons When edit?

just add 'checked="checked"' in the correct radio button that you would like it to be default on. As example you could use php quick if notation to add that in:

<input type="radio" name="sex" value="Male" size="17" <?php echo($isMale?'checked="checked"':''); ?>>Male
<input type="radio" name="sex" value="Female" size="17" <?php echo($isFemale?'checked="checked"':''); ?>>Female

in this example $isMale & $isFemale is boolean values that you assign based on the value from your database.

Cordova : Requirements check failed for JDK 1.8 or greater

Today I also got this error Cordova : Requirements check failed for JDK 1.8 or greater in my Mac OS while build Ionic App when I run command ionic cordova build --release android via terminal.

Below command resolve my issue :-

export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.8.0_231.jdk/Contents/Home"

Hope it will help someone in future!

C - The %x format specifier

That specifies the how many digits you want it to show.

integer value or * that specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified. In the case when * is used, the width is specified by an additional argument of type int. If the value of the argument is negative, it results with the - flag specified and positive field width.

How to find the extension of a file in C#?

At the server you can check the MIME type, lookup flv mime type here or on google.

You should be checking that the mime type is

video/x-flv

If you were using a FileUpload in C# for instance, you could do

FileUpload.PostedFile.ContentType == "video/x-flv"

How can I extract substrings from a string in Perl?

String 1:

$input =~ /'^\S+'/;
$s1 = $&;

String 2:

$input =~ /\(.*\)/;
$s2 = $&;

String 3:

$input =~ /\*?$/;
$s3 = $&;

How can I scroll a div to be visible in ReactJS?

I'm just adding another bit of info for others searching for a Scroll-To capability in React. I had tied several libraries for doing Scroll-To for my app, and none worked from my use case until I found react-scrollchor, so I thought I'd pass it on. https://github.com/bySabi/react-scrollchor

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

Session 'app': Error Launching activity

All answers did not work for me.This error raised when I was trying to rename the app package.I have ended up creating a new project with the new package name and move my files to the new one.

Simple Vim commands you wish you'd known earlier

:b [any portion of a buffer name] to switch buffers. So if you have two buffers, "somefile1.txt", and "someotherfile2.txt", you can switch to the second with simply ":b 2.t<enter>". It also supports tab completion, although it's not required.

Speaking of tab completion, the setting :set wildmode=full wildmenu is also very helpful. It enables complete tab completion for command-mode, as well as a very helpful ncurses-style menu of all the possible matches when using it.

How can I get browser to prompt to save password?

Your site is probably already in the list where the browser is told not to prompt for saving a password. In firefox, Options -> Security -> Remember password for sites[check box] - exceptions[button]

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

Adding local .aar files to Gradle build using "flatDirs" is not working

This solution is working with Android Studio 4.0.1.

Apart from creating a new module as suggested in above solution, you can try this solution.

If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.

In your root project build.gradle

add

repositories {
flatDir {
    dirs 'libs'
}}

Then in the module where you want to add the .aar file locally. simply add below lines of code.

dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')

}

Happy Coding :)

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

Setting up PostgreSQL ODBC on Windows

Please note that you must install the driver for the version of your software client(MS access) not the version of the OS. that's mean that if your MS Access is a 32-bits version,you must install a 32-bit odbc driver. regards

PuTTY scripting to log onto host

Figured this out with the help of a friend. The -m PuTTY option will end your session immediately after it executes the shell file. What I've done instead is I've created a batch script called putty.bat with these contents on my Windows machine:

@echo off
putty -load "host" -l username -pw password

This logs me in remotely to the Linux host. On the host side, I created a shell file called sql with these contents:

#!/bin/tcsh

add oracle10g
sqlplus username password

My host's Linux build used tcsh. Other Linux builds might use bash, so simply replace tcsh with bash and you should be fine.

To summarize, automating these steps are now done in two easy steps:

  1. Double-click putty.bat. This opens PuTTY and logs me into the host.
  2. Run command tcsh sql. This adds the oracle tool to my host, and logs me into the sql database.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Make an /login url, than accept "user" and "password" parameters via GET and don't require basic auth. Here, use php, node, java, whatever and parse your passwd file and match parameters (user/pass) against it. If there is a match then redirect to http://user:[email protected]/ (this will set credential on your browser) if not, send 401 response (without WWW-Authenticate header).

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

WORDPRESS is having this error mostly:
SOLUTION:
Locate your PHP installed directory on Remote live hosting SERVER or "Local Server"
In case of Windows os
for example if you using xampp or wamp webserver. it will be in xammp directory 'c:\xammp\php'
Note: For Unix/Linux OS, locate your PHP directory in Webserver

Find & Edit PHP.INI file
Find 'allow_url_include'
replace it with value 'on'
allow_url_include=On
Save you php.ini & RESTART you web-server.

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

How can I enable or disable the GPS programmatically on Android?

This code works on ROOTED phones:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String[] cmds = {"cd /system/bin" ,"settings put secure location_providers_allowed +gps"};
        try {
            Process p = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(p.getOutputStream());
            for (String tmpCmd : cmds) {
                os.writeBytes(tmpCmd + "\n");
            }
            os.writeBytes("exit\n");
            os.flush();
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}

For turning off GPS you can use this command instead

settings put secure location_providers_allowed -gps

You can also toggle network accuracy using the following commands: for turning on use:

settings put secure location_providers_allowed +network

and for turning off you can use:

settings put secure location_providers_allowed -network

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Root element is missing

If you are loading the XML file from a remote location, I would check to see if the file is actually being downloaded correctly using a sniffer like Fiddler.

I wrote a quick console app to run your code and parse the file and it works fine for me.

How do you post to the wall on a facebook page (not profile)

Harish has the answer here - except you need to request manage_pages permission when authenticating and then using the page-id instead of me when posting....

$result = $facebook->api('page-id/feed/','post',$attachment);

Using switch statement with a range of value in each case?

Try this if you must use switch.

public static int range(int num){ 
    if ( 10 < num && num < 20)
        return 1;
    if ( 20 <= num && num < 30)
        return 2;
    return 3;
}

public static final int TEN_TWENTY = 1;
public static final int TWENTY_THIRTY = 2;

public static void main(String[]args){
    int a = 110;
    switch (range(a)){
        case TEN_TWENTY: 
            System.out.println("10-20"); 
            break;
        case TWENTY_THIRTY: 
            System.out.println("20-30"); 
            break;
        default: break;
    }
}

Openssl : error "self signed certificate in certificate chain"

You have a certificate which is self-signed, so it's non-trusted by default, that's why OpenSSL complains. This warning is actually a good thing, because this scenario might also rise due to a man-in-the-middle attack.

To solve this, you'll need to install it as a trusted server. If it's signed by a non-trusted CA, you'll have to install that CA's certificate as well.

Have a look at this link about installing self-signed certificates.

How to check for an empty struct?

Here are 3 more suggestions or techniques:

With an Additional Field

You can add an additional field to tell if the struct has been populated or it is empty. I intentionally named it ready and not empty because the zero value of a bool is false, so if you create a new struct like Session{} its ready field will be automatically false and it will tell you the truth: that the struct is not-yet ready (it's empty).

type Session struct {
    ready bool

    playerId string
    beehive string
    timestamp time.Time
}

When you initialize the struct, you have to set ready to true. Your isEmpty() method isn't needed anymore (although you can create one if you want to) because you can just test the ready field itself.

var s Session

if !s.ready {
    // do stuff (populate s)
}

Significance of this one additional bool field increases as the struct grows bigger or if it contains fields which are not comparable (e.g. slice, map and function values).

Using the Zero Value of an Existing Field

This is similar to the previous suggestion, but it uses the zero value of an existing field which is considered invalid when the struct is not empty. Usability of this is implementation dependant.

For example if in your example your playerId cannot be the empty string "", you can use it to test if your struct is empty like this:

var s Session

if s.playerId == "" {
    // do stuff (populate s, give proper value to playerId)
}

In this case it's worth incorporating this check into an isEmpty() method because this check is implementation dependant:

func (s Session) isEmpty() bool {
    return s.playerId == ""
}

And using it:

if s.isEmpty() {
    // do stuff (populate s, give proper value to playerId)
}

Use Pointer to your struct

The second suggestion is to use a Pointer to your struct: *Session. Pointers can have nil values, so you can test for it:

var s *Session

if s == nil {
    s = new(Session)
    // do stuff (populate s)
}

How to declare Return Types for Functions in TypeScript

You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.

The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.

class Greeter {
    greet() {
        return "Hello, ";  // type infered to be string
    }
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.

function foo(){
    if (true)
        return "string"; 
    else 
        return 0;
}

This, however, will work:

function foo() : any{
    if (true)
        return "string"; 
    else 
        return 0;
}

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

Set Canvas size using javascript

You can set the width like this :

function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

How do I deploy Node.js applications as a single executable file?

JXcore will allow you to turn any nodejs application into a single executable, including all dependencies, in either Windows, Linux, or Mac OS X.

Here is a link to the installer: https://github.com/jxcore/jxcore-release

And here is a link to how to set it up: http://jxcore.com/turn-node-applications-into-executables/

It is very easy to use and I have tested it in both Windows 8.1 and Ubuntu 14.04.

FYI: JXcore is a fork of NodeJS so it is 100% NodeJS compatible, with some extra features.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Open Sublime Text from Terminal in macOS

I'm using oh-my-zsh on Mac OSX Mavericks and the symbol link didn't work for me, so I added an alias in my .zshrc file instead:

alias subl="/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl"

Open a new terminal and you should be good to go, and type subl.

How to find out what character key is pressed?

**check this out** 
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(document).keypress(function(e)
        {

            var keynum;
            if(window.event)
            { // IE                 
                keynum = e.keyCode;
            }
                else if(e.which)
                    { 
                    // Netscape/Firefox/Opera                   
                    keynum = e.which;
                    }
                    alert(String.fromCharCode(keynum));
                    var unicode=e.keyCode? e.keyCode : e.charCode;
                    alert(unicode);
        });
});  

</script>
</head>
<body>

<input type="text"></input>
</body>
</html>

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

One need to update Newtonsoft.Json -Version GO to Tools => NuGet Package Manager => Package Manager Console and Type Install-Package Newtonsoft.Json -Version 12.0.2 in Package Manager Console Window.

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

How to round a number to significant figures in Python

Given a question so thoroughly answered why not add another

This suits my aesthetic a little better, though many of the above are comparable

import numpy as np

number=-456.789
significantFigures=4

roundingFactor=significantFigures - int(np.floor(np.log10(np.abs(number)))) - 1
rounded=np.round(number, roundingFactor)

string=rounded.astype(str)

print(string)

This works for individual numbers and numpy arrays, and should function fine for negative numbers.

There's one additional step we might add - np.round() returns a decimal number even if rounded is an integer (i.e. for significantFigures=2 we might expect to get back -460 but instead we get -460.0). We can add this step to correct for that:

if roundingFactor<=0:
    rounded=rounded.astype(int)

Unfortunately, this final step won't work for an array of numbers - I'll leave that to you dear reader to figure out if you need.

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

Regular expression to match a dot

In your regex you need to escape the dot "\." or use it inside a character class "[.]", as it is a meta-character in regex, which matches any character.

Also, you need \w+ instead of \w to match one or more word characters.


Now, if you want the test.this content, then split is not what you need. split will split your string around the test.this. For example:

>>> re.split(r"\b\w+\.\w+@", s)
['blah blah blah ', 'gmail.com blah blah']

You can use re.findall:

>>> re.findall(r'\w+[.]\w+(?=@)', s)   # look ahead
['test.this']
>>> re.findall(r'(\w+[.]\w+)@', s)     # capture group
['test.this']

WebAPI Multiple Put/Post parameters

If attribute routing is being used, you can use the [FromUri] and [FromBody] attributes.

Example:

[HttpPost()]
[Route("api/products/{id:int}")]
public HttpResponseMessage AddProduct([FromUri()] int id,  [FromBody()] Product product)
{
  // Add product
}

How do we determine the number of days for a given month in python

Alternative solution:

>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29

convert string to char*

First of all, you would have to allocate memory:

char * S = new char[R.length() + 1];

then you can use strcpy with S and R.c_str():

std::strcpy(S,R.c_str());

You can also use R.c_str() if the string doesn't get changed or the c string is only used once. However, if S is going to be modified, you should copy the string, as writing to R.c_str() results in undefined behavior.

Note: Instead of strcpy you can also use str::copy.

Aligning a float:left div to center?

try it like this:

  <div id="divContainer">
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <div class="divImageHolder">
    IMG HERE
    </div>
    <br class="clear" />
    </div>

    <style type="text/css">
    #divContainer { margin: 0 auto; width: 800px; }
    .divImageHolder { float:left; }
    .clear { clear:both; }
    </style>

Submit two forms with one button

A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:

var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
    postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));

document.forms.payPal.submit();

Variables declared outside function

The local names for a function are decided when the function is defined:

>>> x = 1
>>> def inc():
...     x += 5
...     
>>> inc.__code__.co_varnames
('x',)

In this case, x exists in the local namespace. Execution of x += 5 requires a pre-existing value for x (for integers, it's like x = x + 5), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError is named as such.

Compare the other version, where x is not a local variable, so it can be resolved at the global scope instead:

>>> def incg():
...    print(x)
...    
>>> incg.__code__.co_varnames
()

Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

How to insert current datetime in postgresql insert query

For current datetime, you can use now() function in postgresql insert query.

You can also refer following link.

insert statement in postgres for data type timestamp without time zone NOT NULL,.

What exactly does += do in python?

According to the documentation

x += y is equivalent to x = operator.iadd(x, y). Another way to put it is to say that z = operator.iadd(x, y) is equivalent to the compound statement z = x; z += y.

So x += 3 is the same as x = x + 3.

x = 2

x += 3

print(x)

will output 5.

Notice that there's also

Runtime vs. Compile time

Run time means something happens when you run the program.

Compile time means something happens when you compile the program.

Is Google Play Store supported in avd emulators?

Yes, you can enable/use Play Store on Android Emulator(AVD): Before that you have to set up some prerequisites:

  1. Start Android SDK Manager and select Google Play Intel x86 Atom System Image (Recomended: because it will work comparatively faster) of your required android version (For Example: Android 7.1.1 or API 25)

[Note: Please keep all other thing as it is, if you are going to install it for first time] Or Install as the image below: enter image description here

  1. After download is complete Goto Tools->Manage AVDs...->Create from your Android SDK Manager

  2. enter image description here

Check you have provided following option correctly. Not sure about internal and SD card storage. You can choose different. And Target must be your downloaded android version

  1. Also check Google Play Intel Atom (x86) in CPU/ABI is provided

  2. Click OK

  3. Then Start your Android Emulator. There you will see the Android Play Store. See --- enter image description here

jQuery onclick toggle class name

you can use toggleClass() to toggle class it is really handy.

case:1

<div id='mydiv' class="class1"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class2"></div>

case:2

<div id='mydiv' class="class2"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class1"></div>

case:3

<div id='mydiv' class="class1 class2 class3"></div>

$('#mydiv').toggleClass('class1 class2');

output: <div id='mydiv' class="class3"></div>

How to use a decimal range() step value?

import numpy as np
for i in np.arange(0, 1, 0.1): 
    print i 

Wampserver icon not going green fully, mysql services not starting up?

I was running on the same problem, wampmysqld64 did not start, so I checked the Mysql log which you should find it inside the main wamp64 folder, and I found all the details on why is not working. on my computer I found another mysql instance is running so it prevents the wampmysqld64 to start. I stopped the other instance, and everything works fine after.

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

How do I solve this "Cannot read property 'appendChild' of null" error?

Your condition id !== 0 will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null error.

Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.

window.onload = function loadContIcons() {
    var elem = document.createElement("img");
    elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
    elem.setAttribute("class", "up_icon");

    var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
    if (container !== null) {
        container.appendChild(elem);
    } else console.log("aaaaa");

    var elem1 = document.createElement("img");
    elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
    elem1.setAttribute("class", "down_icon");

    container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
    if (container !== null) {
        container.appendChild(elem1);
    } else console.log("aaaaa");
}

Regular Expression to get a string between parentheses in Javascript

You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

_x000D_
_x000D_
var regExp = /\(([^)]+)\)/;_x000D_
var matches = regExp.exec("I expect five hundred dollars ($500).");_x000D_
_x000D_
//matches[1] contains the value between the parentheses_x000D_
console.log(matches[1]);
_x000D_
_x000D_
_x000D_

Breakdown:

  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

Here is a visual explanation on RegExplained

AFNetworking Post Request

please try below answer.

+(void)callAFWSPost:(NSDictionary *)dict withURL:(NSString *)strUrl 
withBlock:(dictionary)block
{
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
[manager POST:[NSString stringWithFormat:@"%@/%@",WebserviceUrl,strUrl] parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
 {
     if (!responseObject)
     {
         NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
         [dict setObject:ServerResponceError forKey:@"error"];
         block(responseObject);
         return ;
     }
     else if ([responseObject isKindOfClass:[NSDictionary class]]) {
         block(responseObject);
         return ;
     }
 }
      failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
 {
     NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
     [dict setObject:ServerResponceError forKey:@"error"];
     block(dict);
 }];
}

Draw in Canvas by finger, Android

In addition to Ishan's answer, if you want to draw programatically without user interaction, you can edit the class just a little like this.

public class DrawingCanvas extends View {

private Paint mPaint;
private Path mPath;
private boolean isUserInteractionEnabled = false;

public DrawingCanvas(Context context, AttributeSet attrs) {
    super(context, attrs);
    mPaint = new Paint();
    mPaint.setColor(Color.RED);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(10);
    mPath = new Path();
}


@Override
protected void onDraw(Canvas canvas) {
    canvas.drawPath(mPath, mPaint);
    super.onDraw(canvas);
}


@Override
public boolean onTouchEvent(MotionEvent event) {
    if (isUserInteractionEnabled) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(), event.getY());
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                break;
        }
    }

    return true;
}

public void moveCursorTo(float x, float y) {
    mPath.moveTo(x, y);
}

public void makeLine(float toX, float toY) {
    mPath.lineTo(toX, toY);
}

public void setUserInteractionEnabled(boolean userInteractionEnabled) {
    isUserInteractionEnabled = userInteractionEnabled;
}
}

And then use it like

drawingCanvas.setUserInteractionEnabled(true) // to enable user interaction
drawingCanvas.setUserInteractionEnabled(true) // to disable user interaction

To Draw programatically

drawingCanvas.moveCursorTo(70f, 70f) // Move the cursor (Define starting point)
drawingCanvas.makeLine(200f, 200f) // End point (To where you need to draw)

Array formula on Excel for Mac

This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.

Android ImageView's onClickListener does not work

Well my solution was another one, or let's say, the bug was:

I simply had another imageview with the same id in another <included /> twice-encapsuled xml layout, which was found before the one that i wanted to react on the click. Solution: Give one of them another id...

How to set input type date's default value to today?

If you are using ruby you can use this to set the default value to today's date and time:

<input type="datetime-local" name="time" value="<%= Time.now.strftime('%Y-%m-%dT%H:%M') %>" />

Excel: Can I create a Conditional Formula based on the Color of a Cell?

Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.

On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:

=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))

Hit OK then close the "Name Manager" window.

Now, in cell A1 enter the following:

=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))

This will return FQS for red and SM for yellow. For any other color the cell will remain blank.

***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).

Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html

Cheers.

::Edit::

The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).

Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:

=GET.CELL(63,Sheet1!B2)

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

The PowerShell -and conditional operator

Another option:

if( ![string]::IsNullOrEmpty($user_sam) -and ![string]::IsNullOrEmpty($user_case) )
{
   ...
}

List of encodings that Node.js supports

If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:

npm install iconv

npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz

> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild

gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.

fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.

'' is not recognized as an internal or external command, operable program or batch file

When you want to run an executable file from the Command prompt, (cmd.exe), or a batch file, it will:

  • Search the current working directory for the executable file.
  • Search all locations specified in the %PATH% environment variable for the executable file.

If the file isn't found in either of those options you will need to either:

  1. Specify the location of your executable.
  2. Change the working directory to that which holds the executable.
  3. Add the location to %PATH% by apending it, (recommended only with extreme caution).

You can see which locations are specified in %PATH% from the Command prompt, Echo %Path%.

Because of your reported error we can assume that Mobile.exe is not in the current directory or in a location specified within the %Path% variable, so you need to use 1., 2. or 3..

Examples for 1.

C:\directory_path_without_spaces\My-App\Mobile.exe

or:

"C:\directory path with spaces\My-App\Mobile.exe"

Alternatively you may try:

Start C:\directory_path_without_spaces\My-App\Mobile.exe

or

Start "" "C:\directory path with spaces\My-App\Mobile.exe"

Where "" is an empty title, (you can optionally add a string between those doublequotes).

Examples for 2.

CD /D C:\directory_path_without_spaces\My-App
Mobile.exe

or

CD /D "C:\directory path with spaces\My-App"
Mobile.exe

You could also use the /D option with Start to change the working directory for the executable to be run by the start command

Start /D C:\directory_path_without_spaces\My-App Mobile.exe

or

Start "" /D "C:\directory path with spaces\My-App" Mobile.exe

Finding height in Binary Search Tree

For people like me who like one line solutions:

public int getHeight(Node root) {
    return Math.max(root.left != null ? getHeight(root.left) : -1, 
                    root.right != null ? getHeight(root.right) : -1) 
                    + 1;
}

Weird PHP error: 'Can't use function return value in write context'

This error is quite right and highlights a contextual syntax issue. Can be reproduced by performing any kind "non-assignable" syntax. For instance:

function Syntax($hello) { .... then attempt to call the function as though a property and assign a value.... $this->Syntax('Hello') = 'World';

The above error will be thrown because syntactially the statement is wrong. The right assignment of 'World' cannot be written in the context you have used (i.e. syntactically incorrect for this context). 'Cannot use function return value' or it could read 'Cannot assign the right-hand value to the function because its read-only'

The specific error in the OPs code is as highlighted, using brackets instead of square brackets.

Virtualenv Command Not Found

Simple answer is that if you are not a sudo user as I was not one.You need to add path of your bin folder (/home/myusername/.local/bin).So basically the command line searches in which of these path is the command which you have typed.

export PATH=/home/b18150/.local/bin:/usr/bin:/bin

here it will search in local/bin first then /usr/bin and then /bin.