Programs & Examples On #Django ajax selects

django-ajax-selects is a module for Django which enables editing of ForeignKey, ManyToMany and CharField using jQuery UI Autocomplete.

How to make sure that a certain Port is not occupied by any other process

netstat -ano|find ":port_no" will give you the list.
a: Displays all connections and listening ports.
n: Displays addresses and port numbers in numerical form.
o: Displays the owning process ID associated with each connection .

example : netstat -ano | find ":1900" This gives you the result like this.

UDP   *:*                                    1324  
UDP         *:*                                    1324  
UDP    [::1]:1900             *:*                                    1324  
UDP    [fe80::8db8:d9cc:12a8:2262%13]:1900  *:*                      1324

jQuery toggle CSS?

You can do by maintaining the state as below:

    if($(this).attr('data-click-state') == 1) {
        $(this).attr('data-click-state', 0);
        $(this).css('background-color', 'red')
    else {
      $(this).attr('data-click-state', 1);
      $(this).css('background-color', 'orange')

Take a reference from hear codepen example

Adding options to select with javascript

The most concise and intuitive way would be:

var selectElement = document.getElementById('ageselect');_x000D_
for (var age = 12; age <= 100; age++) {_x000D_
  selectElement.add(new Option(age));_x000D_
Your age: <select id="ageselect"><option value="">Please select</option></select>

You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
HTMLSelect?Element?.add(item[, before]);
new Option(text, value, defaultSelected, selected);

Best way to store date/time in mongodb

One datestamp is already in the _id object, representing insert time

So if the insert time is what you need, it's already there:

Login to mongodb shell

ubuntu@ip-10-0-1-223:~$ mongo
MongoDB shell version: 2.4.9
connecting to:

Create your database by inserting items

> db.penguins.insert({"penguin": "skipper"})
> db.penguins.insert({"penguin": "kowalski"})

Lets make that database the one we are on now

> use penguins
switched to db penguins

Get the rows back:

> db.penguins.find()
{ "_id" : ObjectId("5498da1bf83a61f58ef6c6d5"), "penguin" : "skipper" }
{ "_id" : ObjectId("5498da28f83a61f58ef6c6d6"), "penguin" : "kowalski" }

Get each row in yyyy-MM-dd HH:mm:ss format:

> db.penguins.find().forEach(function (doc){ d = doc._id.getTimestamp(); print(d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds()) })
2014-12-23 3:4:41
2014-12-23 3:4:53

If that last one-liner confuses you I have a walkthrough on how that works here:

CSS - Expand float child DIV height to parent's height

I learned of this neat trick in an internship interview. The original question is how do you ensure the height of each top component in three columns have the same height that shows all the content available. Basically create a child component that is invisible that renders the maximum possible height.

<div class="parent">
    <div class="assert-height invisible">
        <!-- content -->
    <div class="shown">
        <!-- content -->

Insert some string into given string at given index in Python

I know it's malapropos, but IMHO easy way is:

def insert (source_str, insert_str, pos):
    return source_str[:pos]+insert_str+source_str[pos:]

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Some code examples for simple GET request. Maybe this helps understanding the difference. Using then:

$http.get('/someURL').then(function(response) {
    var data =,
        status = response.status,
        header = response.header,
        config = response.config;
    // success handler
}, function(response) {
    var data =,
        status = response.status,
        header = response.header,
        config = response.config;
    // error handler

Using success/error:

$http.get('/someURL').success(function(data, status, header, config) {
    // success handler
}).error(function(data, status, header, config) {
    // error handler

Import existing source code to GitHub

Add a GitHub repository as remote origin (replace [] with your URL):

git remote add origin [[email protected]:...]

Switch to your master branch and copy it to develop branch:

git checkout master
git checkout -b develop

Push your develop branch to the GitHub develop branch (-f means force):

git push -f origin develop:develop

How would I stop a while loop after n amount of time?

You do not need to use the while True: loop in this case. There is a much simpler way to use the time condition directly:

import time

# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    test = 0
    if test == 5:
    test -= 1

Multiple conditions with CASE statements

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

SELECT * FROM [Purchasing].[Vendor] WHERE  
  WHEN @url IS null OR @url = '' OR @url = 'ALL'
    THEN PurchasingWebServiceURL LIKE '%'
  WHEN @url = 'blank'
    THEN PurchasingWebServiceURL = ''
  WHEN @url = 'fail'
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%'
  ELSE PurchasingWebServiceURL = '%' + @url + '%' 

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Server unable to read htaccess file, denying access to be safe

In linux,

find project_directory_name_here -type d -exec chmod 755 {} \;
find project_directory_name_here -type f -exec chmod 644 {} \;

It will replace all files and folder permission of project_directory_name_here and its inside stuff.

Django: Display Choice Value

It looks like you were on the right track - get_FOO_display() is most certainly what you want:

In templates, you don't include () in the name of a method. Do the following:

{{ person.get_gender_display }}

Getting last day of the month in a given string date

            String givenStringDate ="07/16/2020";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        java.util.Date convertedUtillDate;
             * If your output requirement is in LocalDate format use below snippet
            LocalDate localDate =LocalDate.parse(givenStringDate, formatter);
            LocalDate localDateLastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());

             * If your output requirement is in Calendar format use below snippet
            convertedUtillDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            Calendar calendarLastDayOfMonth = Calendar.getInstance();
            int lastDate = calendarLastDayOfMonth.getActualMaximum(Calendar.DATE);
            calendarLastDayOfMonth.set(Calendar.DATE, lastDate);

Tested in Java 1.8. I hope this will help some one.

How to add leading zeros?

str_pad from the stringr package is an alternative.

anim = 25499:25504
str_pad(anim, width=6, pad="0")

Lock down Microsoft Excel macro

Just like you can password protect workbooks and worksheets, you can password protect a macro in Excel from being viewed (and executed).

Place a command button on your worksheet and add the following code lines:

  1. First, create a simple macro that you want to protect.

    Range("A1").Value = "This is secret code"

  2. Next, click Tools, Then VBAProject Properties...

enter image description here

Click Tools, VBAProject Properties...

  1. On the Protection tab, check "Lock project for viewing" and enter a password twice.

enter image description here

Enter a Password Twice

  1. Click OK.

  2. Save, close and reopen the Excel file. Try to view the code.

enter image description here

The following dialog box will appear:

Password Protected from being Viewed

You can still execute the code by clicking on the command button but you cannot view or edit the code anymore (unless you know the password). The password for the downloadable Excel file is "easy".

  1. If you want to password protect the macro from being executed, add the following code lines:
Dim password As Variant
password = Application.InputBox("Enter Password", "Password Protected")

Select Case password
    Case Is = False
        'do nothing
    Case Is = "easy"
        Range("A1").Value = "This is secret code"
    Case Else
        MsgBox "Incorrect Password"
End Select

Result when you click the command button on the sheet:

enter image description here

Password Protected from being Executed

Explanation: The macro uses the InputBox method of the Application object. If the users clicks Cancel, this method returns False and nothing happens (InputBox disappears). Only when the user knows the password ("easy" again), the secret code will be executed. If the entered password is incorrect, a MsgBox is displayed. Note that the user cannot take a look at the password in the Visual Basic Editor because the project is protected from being viewed

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

This thread has some great tips. However....

@GirishB's answer isn't correct - sorry. Jartender's is best.

Also, every post in here seems to assume you're logging in to the Linux guest as root, except for @tomoguisuru. Yuck! Don't use root, use a separate user account and "sudo" when you need root privileges. Then this user (or any other user who needs the shared folder) should have membership in the vboxsf group, and @tomoguisuru's command is perfect, even terser than what I use.

Forget running mount yourself. Set up the shared folder to auto mount and you'll find the shared folder - it's under /media in my OEL (RH and Centos probably the same). If it's not there, just run "mount" with no arguments and look for the mounted directory of type vboxsf.

Terminal showing 'mount' and where to find mounted shared folder

What's "this" in JavaScript onclick?

In JavaScript this refers to the element containing the action. For example, if you have a function called hide():

function hide(element){ = 'none';

Calling hide with this will hide the element. It returns only the element clicked, even if it is similar to other elements in the DOM.

For example, you may have this clicking a number in the HTML below will only hide the bullet point clicked.

  <li class="bullet" onclick="hide(this);">1</li>
  <li class="bullet" onclick="hide(this);">2</li>
  <li class="bullet" onclick="hide(this);">3</li>
  <li class="bullet" onclick="hide(this);">4</li>

How to ignore the certificate check when ssl

CA5386 : Vulnerability analysis tools will alert you to these codes.

Correct code :

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
   return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;

Which characters are valid in CSS class names/selectors?

You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(az), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.


In short, the previous rule translates to the following, extracted from the W3C spec.:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

1 It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).

2 Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. --indent1, is invalid. However, I'm pretty sure I've seen this in practice.

How to set cache: false in jQuery.get call

Per the JQuery documentation, .get() only takes the url, data (content), dataType, and success callback as its parameters. What you're really looking to do here is modify the jqXHR object before it gets sent. With .ajax(), this is done with the beforeSend() method. But since .get() is a shortcut, it doesn't allow it.

It should be relatively easy to switch your .ajax() calls to .get() calls though. After all, .get() is just a subset of .ajax(), so you can probably use all the default values for .ajax() (except, of course, for beforeSend()).


::Looks at Jivings' answer::

Oh yeah, forgot about the cache parameter! While beforeSend() is useful for adding other headers, the built-in cache parameter is far simpler here.

Using curl to upload POST data with files

You need to use the -F option:
-F/--form <name=content> Specify HTTP multipart POST data (H)

Try this:

curl \
  -F "userid=1" \
  -F "filecomment=This is an image file" \
  -F "image=@/home/user1/Desktop/test.jpg" \

Can I get the name of the current controller in the view?

controller_path holds the path of the controller used to serve the current view. (ie: admin/settings).


controller_name holds the name of the controller used to serve the current view. (ie: settings).

How can I include a YAML file inside another?

Standard YAML 1.2 doesn't include natively this feature. Nevertheless many implementations provides some extension to do so.

I present a way of achieving it with Java and snakeyaml:1.24 (Java library to parse/emit YAML files) that allows creating a custom YAML tag to achieve the following goal (you will see I'm using it to load test suites defined in several YAML files and that I made it work as a list of includes for a target test: node):

# ... yaml prev stuff

tests: !include
  - '1.hello-test-suite.yaml'
  - ''
  - ''

# ... more yaml document

Here is the one-class Java that allows processing the !include tag. Files are loaded from classpath (Maven resources directory):

 * Custom YAML loader. It adds support to the custom !include tag which allows splitting a YAML file across several
 * files for a better organization of YAML tests.
@Slf4j   // <-- This is a Lombok annotation to auto-generate logger
public class MyYamlLoader {

    private static final Constructor CUSTOM_CONSTRUCTOR = new MyYamlConstructor();

    private MyYamlLoader() {

     * Parse the only YAML document in a stream and produce the Java Map. It provides support for the custom !include
     * YAML tag to split YAML contents across several files.
    public static Map<String, Object> load(InputStream inputStream) {
        return new Yaml(CUSTOM_CONSTRUCTOR)

     * Custom SnakeYAML constructor that registers custom tags.
    private static class MyYamlConstructor extends Constructor {

        private static final String TAG_INCLUDE = "!include";

        MyYamlConstructor() {
            // Register custom tags
            yamlConstructors.put(new Tag(TAG_INCLUDE), new IncludeConstruct());

         * The actual include tag construct.
        private static class IncludeConstruct implements Construct {

            public Object construct(Node node) {
                List<Node> inclusions = castToSequenceNode(node);
                return parseInclusions(inclusions);

            public void construct2ndStep(Node node, Object object) {
                // do nothing

            private List<Node> castToSequenceNode(Node node) {
                try {
                    return ((SequenceNode) node).getValue();

                } catch (ClassCastException e) {
                    throw new IllegalArgumentException(String.format("The !import value must be a sequence node, but " +
                            "'%s' found.", node));

            private Object parseInclusions(List<Node> inclusions) {

                List<InputStream> inputStreams = inputStreams(inclusions);

                try (final SequenceInputStream sequencedInputStream =
                             new SequenceInputStream(Collections.enumeration(inputStreams))) {

                    return new Yaml(CUSTOM_CONSTRUCTOR)

                } catch (IOException e) {
                    log.error("Error closing the stream.", e);
                    return null;

            private List<InputStream> inputStreams(List<Node> scalarNodes) {

            private InputStream inputStream(Node scalarNode) {
                String filePath = castToScalarNode(scalarNode).getValue();
                final InputStream is = getClass().getClassLoader().getResourceAsStream(filePath);
                Assert.notNull(is, String.format("Resource file %s not found.", filePath));
                return is;

            private ScalarNode castToScalarNode(Node scalarNode) {
                try {
                    return ((ScalarNode) scalarNode);

                } catch (ClassCastException e) {
                    throw new IllegalArgumentException(String.format("The value must be a scalar node, but '%s' found" +
                            ".", scalarNode));



How can I solve the error LNK2019: unresolved external symbol - function?

In Visual Studio 2017 if you want to test public members, simply put your real project and test project in the same solution, and add a reference to your real project in the test project.

See C++ Unit Testing in Visual Studio from the MSDN blog for more details. You can also check Write unit tests for C/C++ in Visual Studio as well as Use the Microsoft Unit Testing Framework for C++ in Visual Studio, the latter being if you need to test non public members and need to put the tests in the same project as your real code.

Note that things you want to test will need to be exported using __declspec(dllexport). See Exporting from a DLL Using __declspec(dllexport) for more details.

How should I throw a divide by zero exception in Java without actually dividing by zero?

You should not throw an ArithmeticException. Since the error is in the supplied arguments, throw an IllegalArgumentException. As the documentation says:

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

Which is exactly what is going on here.

if (divisor == 0) {
    throw new IllegalArgumentException("Argument 'divisor' is 0");

Access item in a list of lists

You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17 is element 2 in list 0, which is list1[0][2]:

>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]

So, your example would be

50 - list1[0][0] + list1[0][1] - list1[0][2]

How to do a simple file search in cmd

You can search in windows by DOS and explorer GUI.


1) DIR

2) ICACLS (searches for files and folders to set ACL on them)

3) cacls ..................................................

2) example

icacls c:*ntoskrnl*.* /grant system:(f) /c /t ,then use PMON from sysinternals to monitor what folders are denied accesss. The result contains

access path contains your drive

process name is explorer.exe

those were filters youu must apply

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff


int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

make a header full screen (width) css

#header {
margin: 0;
padding: 0;
width: 100%;
background: xxxx;

#header #content {
margin: 0px auto;
width: 800px; /* or whatever */

<div id="header">
<div id="content">
stuff here

How do you add an action to a button programmatically in xcode

try this:

first write this in your .h file of viewcontroller

UIButton *btn;

Now write this in your .m file of viewcontrollers viewDidLoad.

btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];

write this outside viewDidLoad method in .m file of your view controller

- (IBAction)btnClicked:(id)sender
   //Write a code you want to execute on buttons click event

Javascript: formatting a rounded number to N decimals

I found a way. This is Christoph's code with a fix:

function toFixed(value, precision) {
    var precision = precision || 0,
        power = Math.pow(10, precision),
        absValue = Math.abs(Math.round(value * power)),
        result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));

    if (precision > 0) {
        var fraction = String(absValue % power),
            padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
        result += '.' + padding + fraction;
    return result;

Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".

Generate JSON string from NSDictionary in iOS

Now no need third party classes ios 5 introduced Nsjsonserialization

NSString *urlString=@"Your url";
NSString *urlUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[[NSURL alloc]initWithString:urlUTF8];
NSURLRequest *request=[NSURLRequest requestWithURL:url];

NSURLResponse *response;

NSData *GETReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

NSError *myError = nil;

NSDictionary *res = [NSJSONSerialization JSONObjectWithData:GETReply options:NSJSONReadingMutableLeaves|| NSJSONReadingMutableContainers error:&myError];


this code can useful for getting jsondata.

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

I agree the documentation on imageEdgeInsets and titleEdgeInsets should be better, but I figured out how to get the correct positioning without resorting to trial and error.

The general idea is here at this question, but that was if you wanted both text and image centered. We don't want the image and text to be centered individually, we want the image and the text to be centered together as a single entity. This is in fact what UIButton already does so we simply need to adjust the spacing.

CGFloat spacing = 10; // the amount of spacing to appear between image and title
tabBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
tabBtn.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);

I also turned this into a category for UIButton so it will be easy to use:


@interface UIButton(ImageTitleCentering)

-(void) centerButtonAndImageWithSpacing:(CGFloat)spacing;



@implementation UIButton(ImageTitleCentering)

-(void) centerButtonAndImageWithSpacing:(CGFloat)spacing {
    self.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, spacing);
    self.titleEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, 0);


So now all I have to do is:

[button centerButtonAndImageWithSpacing:10];

And I get what I need every time. No more messing with the edge insets manually.

EDIT: Swapping Image and Text

In response to @Javal in comments

Using this same mechanism, we can swap the image and the text. To accomplish the swap, simply use a negative spacing but also include the width of the text and the image. This will require frames to be known and layout performed already.

[self.view layoutIfNeeded];
CGFloat flippedSpacing = -(desiredSpacing + button.currentImage.size.width + button.titleLabel.frame.size.width);
[button centerButtonAndImageWithSpacing:flippedSpacing];

Of course you will probably want to make a nice method for this, potentially adding a second category method, this is left as an exercise to the reader.

How do I grep recursively?

If you are looking for a specific content in all files from a directory structure, you may use find since it is more clear what you are doing:

find -type f -exec grep -l "texthere" {} +

Note that -l (downcase of L) shows the name of the file that contains the text. Remove it if you instead want to print the match itself. Or use -H to get the file together with the match. All together, other alternatives are:

find -type f -exec grep -Hn "texthere" {} +

Where -n prints the line number.

How to define custom configuration variables in rails

I just wanted to update this for the latest cool stuff in Rails 4.2, you can now do this inside any of your config/**/*.rb files: = 42

...and this will be available in your app as:

See more here:

Is there a way to get rid of accents and convert a whole string to regular letters?

In case anyone is strugling to do this in kotlin, this code works like a charm. To avoid inconsistencies I also use .toUpperCase and Trim(). then i cast this function:

   fun stripAccents(s: String):String{

   if (s == null) {
      return "";

val chars: CharArray = s.toCharArray()

var sb = StringBuilder(s)
var cont: Int = 0

while (chars.size > cont) {
    var c: kotlin.Char
    c = chars[cont]
    var c2:String = c.toString()
   //these are my needs, in case you need to convert other accents just Add new entries aqui
    c2 = c2.replace("Ã", "A")
    c2 = c2.replace("Õ", "O")
    c2 = c2.replace("Ç", "C")
    c2 = c2.replace("Á", "A")
    c2 = c2.replace("Ó", "O")
    c2 = c2.replace("Ê", "E")
    c2 = c2.replace("É", "E")
    c2 = c2.replace("Ú", "U")

    c = c2.single()
    sb.setCharAt(cont, c)


return sb.toString()


to use these fun cast the code like this:

     var str: String
     str = editText.text.toString() //get the text from EditText
     str = str.toUpperCase().trim()

     str = stripAccents(str) //call the function

YouTube: How to present embed video with sound muted

<iframe width="560" height="315" src=";autoplay=1&controls=1&loop=1" rel=0&amp frameborder="0" allowfullscreen></iframe>

Send inline image in email

    MailMessage mail = new MailMessage();
    //set the addresses
    mail.From = new MailAddress("[email protected]");
    mail.To.Add("[email protected]");

    //set the content
    mail.Subject = "Sucessfully Sent the HTML and Content of mail";

    //first we create the Plain Text part
    string plainText = "Non-HTML Plain Text Message for Non-HTML enable mode";
    AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain");
    XmlTextReader reader = new XmlTextReader(@"E:\HTMLPage.htm");
    string[] address = new string[30];
    string finalHtml = "";
    var i = -1;
    while (reader.Read())
        if (reader.NodeType == XmlNodeType.Element)
        { // The node is an element.
            if (reader.AttributeCount <= 1)
                if (reader.Name == "img")
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                        if (reader.Name == "src")
                            address[i] = reader.Value;
                            address[i] = address[i].Remove(0, 8);
                            finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString();
                            finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                    finalHtml += ">";
                    finalHtml += "<" + reader.Name;
                    while (reader.MoveToNextAttribute())
                        finalHtml += " " + reader.Name + "='" + reader.Value + "'";
                    finalHtml += ">";

        else if (reader.NodeType == XmlNodeType.Text)
        { //Display the text in each element.
            finalHtml += reader.Value;
        else if (reader.NodeType == XmlNodeType.EndElement)
            //Display the end of the element.
            finalHtml += "</" + reader.Name;
            finalHtml += ">";


    AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html");
    LinkedResource[] logo = new LinkedResource[i + 1];
    for (int j = 0; j <= i; j++)
        logo[j] = new LinkedResource(address[j]);
        logo[j].ContentId = "chartlogo" + j;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "";
    smtp.Port = 587;
    smtp.Credentials = new NetworkCredential(
        "[email protected]", "Password");
    smtp.EnableSsl = true;

How to add a TextView to LinearLayout in Android

Here's where the exception occurs

((LinearLayout) linearLayout).addView(valueTV);

addView method takes in a parameter of type View, not TextView. Therefore, typecast the valueTv object into a View object, explicitly.

Therefore, the corrected code would be :

((LinearLayout) linearLayout).addView((TextView)valueTV);

How to do this in Laravel, subquery where in

using a variable


How to open spss data files in excel?

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

pspp-convert <input.sav> <output.csv>


How to Resize a Bitmap in Android?

While the previous answers do scale the image and take care of the aspect ratio, the resampling itself should be done so that there is no aliasing. Taking care of scale is a matter of fixing arguments correctly. There are many comments about the quality of the output images from standard scaling call. to maintain quality of the image one should use the standard call:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);

with the last argument set to true because it will do the bilinear filtering for resampling to prevent aliasing. Read more about aliasing here:

From android documentation:,%20int,%20int,%20boolean)

public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)

filter : boolean, Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.

How to get numeric position of alphabets in java?

This depends on the alphabet but for the english one, try this:

String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
   int position = input.charAt(i) - 'a' + 1;

How to get last 7 days data from current datetime to last 7 days in sql server

This worked for me!!

SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()

Android - border for button

I know its about a year late, but you can also create a 9 path image There's a tool that comes with android SDK which helps in creating such image See this link:

PS: the image can be infinitely scaled as well

Live search through table rows

I used the previous answers and combine them to create:

Search any columns by hide rows and highlighting

Css for highlight found texts:

em {
   background-color: yellow


function removeHighlighting(highlightedElements) {
   highlightedElements.each(function() {
      var element = $(this);

function addHighlighting(element, textToHighlight) {
   var text = element.text();
   var highlightedText = '<em>' + textToHighlight + '</em>';
   var newText = text.replace(textToHighlight, highlightedText);


$("#search").keyup(function() {
   var value = this.value.toLowerCase().trim();

   removeHighlighting($("table tr em"));

   $("table tr").each(function(index) {
      if (!index) return;
      $(this).find("td").each(function() {
         var id = $(this).text().toLowerCase().trim();
         var matchedIndex = id.indexOf(value);
         if (matchedIndex === 0) {
            addHighlighting($(this), value);
         var not_found = (matchedIndex == -1);
         return not_found;

Demo here

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

In DefaultConfig Add multiDexEnabled = true

    defaultConfig {
    applicationId "com.test"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    multiDexEnabled = true
    testInstrumentationRunner ""

How to check if a Constraint exists in Sql server?

IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
    DROP CONSTRAINT FK_ChannelPlayerSkins_Channels

How do I create a dynamic key to be added to a JavaScript object variable

Square brackets:

jsObj['key' + i] = 'example' + 1;

In JavaScript, all arrays are objects, but not all objects are arrays. The primary difference (and one that's pretty hard to mimic with straight JavaScript and plain objects) is that array instances maintain the length property so that it reflects one plus the numeric value of the property whose name is numeric and whose value, when converted to a number, is the largest of all such properties. That sounds really weird, but it just means that given an array instance, the properties with names like "0", "5", "207", and so on, are all treated specially in that their existence determines the value of length. And, on top of that, the value of length can be set to remove such properties. Setting the length of an array to 0 effectively removes all properties whose names look like whole numbers.

OK, so that's what makes an array special. All of that, however, has nothing at all to do with how the JavaScript [ ] operator works. That operator is an object property access mechanism which works on any object. It's important to note in that regard that numeric array property names are not special as far as simple property access goes. They're just strings that happen to look like numbers, but JavaScript object property names can be any sort of string you like.

Thus, the way the [ ] operator works in a for loop iterating through an array:

for (var i = 0; i < myArray.length; ++i) {
  var value = myArray[i]; // property access
  // ...

is really no different from the way [ ] works when accessing a property whose name is some computed string:

var value = jsObj["key" + i];

The [ ] operator there is doing precisely the same thing in both instances. The fact that in one case the object involved happens to be an array is unimportant, in other words.

When setting property values using [ ], the story is the same except for the special behavior around maintaining the length property. If you set a property with a numeric key on an array instance:

myArray[200] = 5;

then (assuming that "200" is the biggest numeric property name) the length property will be updated to 201 as a side-effect of the property assignment. If the same thing is done to a plain object, however:

myObj[200] = 5;

there's no such side-effect. The property called "200" of both the array and the object will be set to the value 5 in otherwise the exact same way.

One might think that because that length behavior is kind-of handy, you might as well make all objects instances of the Array constructor instead of plain objects. There's nothing directly wrong about that (though it can be confusing, especially for people familiar with some other languages, for some properties to be included in the length but not others). However, if you're working with JSON serialization (a fairly common thing), understand that array instances are serialized to JSON in a way that only involves the numerically-named properties. Other properties added to the array will never appear in the serialized JSON form. So for example:

var obj = [];
obj[0] = "hello world";
obj["something"] = 5000;

var objJSON = JSON.stringify(obj);

the value of "objJSON" will be a string containing just ["hello world"]; the "something" property will be lost.


If you're able to use ES6 JavaScript features, you can use Computed Property Names to handle this very easily:

var key = 'DYNAMIC_KEY',
    obj = {
        [key]: 'ES6!'

// > { 'DYNAMIC_KEY': 'ES6!' }

Get current working directory in a Qt application

Just tested and QDir::currentPath() does return the path from which I called my executable.

And a symlink does not "exist". If you are executing an exe from that path you are effectively executing it from the path the symlink points to.

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()



   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

Ansible: How to delete files and folders inside a directory?

Using shell module (idempotent too):

- shell: /bin/rm -rf /home/mydata/web/*

If there are dot/hidden files:

- shell: /bin/rm -rf /home/mydata/web/* /home/mydata/web/.*

Cleanest solution if you don't care about creation date and owner/permissions:

- file: path=/home/mydata/web state=absent
- file: path=/home/mydata/web state=directory

How to use onClick() or onSelect() on option tag in a JSP page?

In my case:

  <script type="text/javascript">

    function changeFunction(val) {

       //Show option value

   <select id="selectBox" onchange="changeFunction(this)">
     <option value="1">Option #1</option>
     <option value="2">Option #2</option>

Changing ViewPager to enable infinite page scrolling

I built a library that can make any ViewPager, pagerAdapter (or FragmentStatePagerAdapter), and optional TabLayout infinitely Scrolling.

How to get the full path of running process?

What you can do is use WMI to get the paths. This will allow you to get the path regardless it's a 32-bit or 64-bit application. Here's an example demonstrating how you can get it:

// include the namespace
using System.Management;

var wmiQueryString = "SELECT ProcessId, ExecutablePath, CommandLine FROM Win32_Process";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
    var query = from p in Process.GetProcesses()
                join mo in results.Cast<ManagementObject>()
                on p.Id equals (int)(uint)mo["ProcessId"]
                select new
                    Process = p,
                    Path = (string)mo["ExecutablePath"],
                    CommandLine = (string)mo["CommandLine"],
    foreach (var item in query)
        // Do what you want with the Process, Path, and CommandLine

Note that you'll have to reference the System.Management.dll assembly and use the System.Management namespace.

For more info on what other information you can grab out of these processes such as the command line used to start the program (CommandLine), see the Win32_Process class and WMI .NET for for more information.

How to view the list of compile errors in IntelliJ?

the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.

Check if a Python list item contains a string inside another string

If you just need to know if 'abc' is in one of the items, this is the shortest way:

if 'abc' in str(my_list):

Note: this assumes 'abc' is an alphanumeric text. Do not use it if 'abc' could be a just a special character (i.e. []', ).

Conversion failed when converting date and/or time from character string while inserting datetime

I'm Tried this and it's working with me :

SELECT CONVERT(date, yourDate ,104)

How to go from Blob to ArrayBuffer

Just to complement Mr @potatosalad answer.

You don't actually need to access the function scope to get the result on the onload callback, you can freely do the following on the event parameter:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer =;

Why this is better? Because then we may use arrow function without losing the context

var fileReader = new FileReader();
fileReader.onload = (event) => {
    this.externalScopeVariable =;

Visual Studio can't 'see' my included header files

I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.

I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.

After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.

I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.

It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.

Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project. It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

GetElementByID - Multiple IDs

Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.

<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>


  document.getElementById('click').addEventListener('click', function(){

  function doStuff() {
    for(var i=1; i<=2; i++){
        var el = document.getElementById("hello" + i); = 'none';


Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

Most of the time this happens due to less memory space. first check then try some other tricks .

Python set to list

Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):

>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']

Check that you didn't overwrite list by accident:

>>> assert list == __builtins__.list

What is the correct way to free memory in C#

  1. Yes
  2. What do you mean by the same? It will be re-executed every time the method is run.
  3. Yes, the .Net garbage collector uses an algorithm that starts with any global/in-scope variables, traverses them while following any reference it finds recursively, and deletes any object in memory deemed to be unreachable. see here for more detail on Garbage Collection
  4. Yes, the memory from all variables declared in a method is released when the method exits as they are all unreachable. In addition, any variables that are declared but never used will be optimized out by the compiler, so in reality your Foo variable will never ever take up memory.
  5. the using statement simply calls dispose on an IDisposable object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.

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

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

How to add onload event to a div element

You cannot add event onload on div, but you can add onkeydown and trigger onkeydown event on document load

$(function ()_x000D_
<script src=""></script>_x000D_
<div  onkeydown="setCss( );"> </div>`


In my case I was using a third party library (i.e. vendor) and the library comes with a sample app which I already had install on my device. So that sample app was now conflicting each time I try to install my own app implementing the library. So I just uninstalled the vendor's sample app and it works afterwards.

How to calculate a Mod b in Casio fx-991ES calculator

type normal division first and then type shift + S->d

Wpf control size to content?

If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:

        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>

Java Try Catch Finally blocks without Catch

The finally block is always run after the try block ends, whether try ends normally or abnormally due to an exception, er, throwable.

If an exception is thrown by any of the code within the try block, then the current method simply re-throws (or continues to throw) the same exception (after running the finally block).

If the finally block throws an exception / error / throwable, and there is already a pending throwable, it gets ugly. Quite frankly, I forget exactly what happens (so much for my certification years ago). I think both throwables get linked together, but there is some special voodoo you have to do (i.e. - a method call I would have to look up) to get the original problem before the "finally" barfed, er, threw up.

Incidentally, try/finally is a pretty common thing to do for resource management, since java has no destructors.

E.g. -

r = new LeakyThing();
try { useResource( r); }
finally { r.release(); }  // close, destroy, etc

"Finally", one more tip: if you do bother to put in a catch, either catch specific (expected) throwable subclasses, or just catch "Throwable", not "Exception", for a general catch-all error trap. Too many problems, such as reflection goofs, throw "Errors", rather than "Exceptions", and those will slip right by any "catch all" coded as:

catch ( Exception e) ...  // doesn't really catch *all*, eh?

do this instead:

catch ( Throwable t) ...

Remove all padding and margin table HTML and CSS

I find the most perfectly working answer is this

.noBorder {
    border: 0px;
    border-collapse: collapse;

Use of def, val, and var in scala


def person = new Person("Kumar", 12) 

you are defining a function/lazy variable which always returns a new Person instance with name "Kumar" and age 12. This is totally valid and the compiler has no reason to complain. Calling person.age will return the age of this newly created Person instance, which is always 12.

When writing

person.age = 45

you assign a new value to the age property in class Person, which is valid since age is declared as var. The compiler will complain if you try to reassign person with a new Person object like

person = new Person("Steve", 13)  // Error

How can the default node version be set using NVM?

You can also like this:

$ nvm alias default lts/fermium

align images side by side in html

Try using this format

   <img src="img" alt="The Pulpit Rock" width="304" height="228">
   <figcaption>Fig1. - A view of the pulpit rock in Norway.</figcaption>

This will give you a real caption (just add the 2nd and 3rd imgs using Float:left like others suggested)

How to set enum to null

You can either use the "?" operator for a nullable type.

public Color? myColor = null;

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

public Color myColor = Color.None;

Disable Drag and Drop on HTML elements?

This might work: You can disable selecting with css3 for text, image and basically everything.

.unselectable {
   -moz-user-select: -moz-none;
   -khtml-user-select: none;
   -webkit-user-select: none;

     Introduced in IE 10.
   -ms-user-select: none;
   user-select: none;

Of course only for the newer browsers. For more details check:

How to disable text selection highlighting using CSS?

How do I center text horizontally and vertically in a TextView?

Here is solution.

       android:text="**Your String Value**" />

Position absolute but relative to parent

If you don't give any position to parent then by default it takes static. If you want to understand that difference refer to this example

Example 1::



Here parent class has no position so element is placed according to body.

Example 2::


In this example parent has relative position hence element are positioned absolute inside relative parent. examples?

You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.

My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.

How do I get PHP errors to display?

Some web hosting providers allow you to change PHP parameters in the .htaccess file.

You can add the following line:

php_value display_errors 1

I had the same issue as yours and this solution fixed it.

Padding a table row

Option 1

You could also solve it by adding a transparent border to the row (tr), like this




tr {
    border-top: 12px solid transparent;
    border-bottom: 12px solid transparent;

Works like a charm, although if you need regular borders, then this method will sadly not work.

Option 2

Since rows act as a way to group cells, the correct way to do this, would be to use

table {
    border-collapse: inherit;
    border-spacing: 0 10px;

Vue.js toggle class on click

new Vue({_x000D_
  el: '#fsbar',_x000D_
    isActive: false_x000D_
  methods: {_x000D_
    toggle: function(){_x000D_
      this.isActive = !this.isActive;_x000D_
    DEMO STYLE_x000D_
@import ",400,500,600,700";_x000D_
body {_x000D_
    font-family: 'Poppins', sans-serif;_x000D_
    background: #fafafa;_x000D_
p {_x000D_
    font-family: 'Poppins', sans-serif;_x000D_
    font-size: 1.1em;_x000D_
    font-weight: 300;_x000D_
    line-height: 1.7em;_x000D_
    color: #999;_x000D_
a, a:hover, a:focus {_x000D_
    color: inherit;_x000D_
    text-decoration: none;_x000D_
    transition: all 0.3s;_x000D_
.navbar {_x000D_
    padding: 15px 10px;_x000D_
    background: #fff;_x000D_
    border: none;_x000D_
    border-radius: 0;_x000D_
    margin-bottom: 40px;_x000D_
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
.navbar-btn {_x000D_
    box-shadow: none;_x000D_
    outline: none !important;_x000D_
    border: none;_x000D_
.line {_x000D_
    width: 100%;_x000D_
    height: 1px;_x000D_
    border-bottom: 1px dashed #ddd;_x000D_
    margin: 40px 0;_x000D_
i, span {_x000D_
    display: inline-block;_x000D_
/* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
.wrapper {_x000D_
    display: flex;_x000D_
    align-items: stretch;_x000D_
#sidebar {_x000D_
    min-width: 250px;_x000D_
    max-width: 250px;_x000D_
    background: #7386D5;_x000D_
    color: #fff;_x000D_
    transition: all 0.3s;_x000D_
_x000D_ {_x000D_
    min-width: 80px;_x000D_
    max-width: 80px;_x000D_
    text-align: center;_x000D_
_x000D_ .sidebar-header h3, .CTAs {_x000D_
    display: none;_x000D_
_x000D_ .sidebar-header strong {_x000D_
    display: block;_x000D_
#sidebar ul li a {_x000D_
    text-align: left;_x000D_
_x000D_ ul li a {_x000D_
    padding: 20px 10px;_x000D_
    text-align: center;_x000D_
    font-size: 0.85em;_x000D_
_x000D_ ul li a i {_x000D_
    margin-right:  0;_x000D_
    display: block;_x000D_
    font-size: 1.8em;_x000D_
    margin-bottom: 5px;_x000D_
_x000D_ ul ul a {_x000D_
    padding: 10px !important;_x000D_
_x000D_ a[aria-expanded="false"]::before, a[aria-expanded="true"]::before {_x000D_
    top: auto;_x000D_
    bottom: 5px;_x000D_
    right: 50%;_x000D_
    -webkit-transform: translateX(50%);_x000D_
    -ms-transform: translateX(50%);_x000D_
    transform: translateX(50%);_x000D_
#sidebar .sidebar-header {_x000D_
    padding: 20px;_x000D_
    background: #6d7fcc;_x000D_
#sidebar .sidebar-header strong {_x000D_
    display: none;_x000D_
    font-size: 1.8em;_x000D_
#sidebar ul.components {_x000D_
    padding: 20px 0;_x000D_
    border-bottom: 1px solid #47748b;_x000D_
#sidebar ul li a {_x000D_
    padding: 10px;_x000D_
    font-size: 1.1em;_x000D_
    display: block;_x000D_
#sidebar ul li a:hover {_x000D_
    color: #7386D5;_x000D_
    background: #fff;_x000D_
#sidebar ul li a i {_x000D_
    margin-right: 10px;_x000D_
#sidebar ul > a, a[aria-expanded="true"] {_x000D_
    color: #fff;_x000D_
    background: #6d7fcc;_x000D_
a[data-toggle="collapse"] {_x000D_
    position: relative;_x000D_
a[aria-expanded="false"]::before, a[aria-expanded="true"]::before {_x000D_
    content: '\e259';_x000D_
    display: block;_x000D_
    position: absolute;_x000D_
    right: 20px;_x000D_
    font-family: 'Glyphicons Halflings';_x000D_
    font-size: 0.6em;_x000D_
a[aria-expanded="true"]::before {_x000D_
    content: '\e260';_x000D_
ul ul a {_x000D_
    font-size: 0.9em !important;_x000D_
    padding-left: 30px !important;_x000D_
    background: #6d7fcc;_x000D_
ul.CTAs {_x000D_
    padding: 20px;_x000D_
ul.CTAs a {_x000D_
    text-align: center;_x000D_
    font-size: 0.9em !important;_x000D_
    display: block;_x000D_
    border-radius: 5px;_x000D_
    margin-bottom: 5px;_x000D_
_x000D_ {_x000D_
    background: #fff;_x000D_
    color: #7386D5;_x000D_
a.article, a.article:hover {_x000D_
    background: #6d7fcc !important;_x000D_
    color: #fff !important;_x000D_
/* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
#content {_x000D_
    padding: 20px;_x000D_
    min-height: 100vh;_x000D_
    transition: all 0.3s;_x000D_
/* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
@media (max-width: 768px) {_x000D_
    #sidebar {_x000D_
        min-width: 80px;_x000D_
        max-width: 80px;_x000D_
        text-align: center;_x000D_
        margin-left: -80px !important ;_x000D_
    a[aria-expanded="false"]::before, a[aria-expanded="true"]::before {_x000D_
        top: auto;_x000D_
        bottom: 5px;_x000D_
        right: 50%;_x000D_
        -webkit-transform: translateX(50%);_x000D_
        -ms-transform: translateX(50%);_x000D_
        transform: translateX(50%);_x000D_
    }_x000D_ {_x000D_
        margin-left: 0 !important;_x000D_
    #sidebar .sidebar-header h3, #sidebar .CTAs {_x000D_
        display: none;_x000D_
    #sidebar .sidebar-header strong {_x000D_
        display: block;_x000D_
    #sidebar ul li a {_x000D_
        padding: 20px 10px;_x000D_
    #sidebar ul li a span {_x000D_
        font-size: 0.85em;_x000D_
    #sidebar ul li a i {_x000D_
        margin-right:  0;_x000D_
        display: block;_x000D_
    #sidebar ul ul a {_x000D_
        padding: 10px !important;_x000D_
    #sidebar ul li a i {_x000D_
        font-size: 1.3em;_x000D_
    #sidebar {_x000D_
        margin-left: 0;_x000D_
    #sidebarCollapse span {_x000D_
        display: none;_x000D_
<script src=""></script>_x000D_
<!DOCTYPE html>_x000D_
        <meta charset="utf-8">_x000D_
        <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
        <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
        <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
         <!-- Bootstrap CSS CDN -->_x000D_
        <link rel="stylesheet" href="">_x000D_
        <!-- Our Custom CSS -->_x000D_
        <link rel="stylesheet" href="style4.css">_x000D_
        <div class="wrapper" id="fsbar">_x000D_
            <!-- Sidebar Holder -->_x000D_
            <nav id="sidebar" :class="{ active: isActive }">_x000D_
                <div class="sidebar-header">_x000D_
                    <h3>Bootstrap Sidebar</h3>_x000D_
                <ul class="list-unstyled components">_x000D_
                    <li class="active">_x000D_
                        <a href="#homeSubmenu" data-toggle="collapse" aria-expanded="false">_x000D_
                            <i class="glyphicon glyphicon-home"></i>_x000D_
                        <ul class="collapse list-unstyled" id="homeSubmenu">_x000D_
                            <li><a href="#">Home 1</a></li>_x000D_
                            <li><a href="#">Home 2</a></li>_x000D_
                            <li><a href="#">Home 3</a></li>_x000D_
                        <a href="#">_x000D_
                            <i class="glyphicon glyphicon-briefcase"></i>_x000D_
                        <a href="#pageSubmenu" data-toggle="collapse" aria-expanded="false">_x000D_
                            <i class="glyphicon glyphicon-duplicate"></i>_x000D_
                        <ul class="collapse list-unstyled" id="pageSubmenu">_x000D_
                            <li><a href="#">Page 1</a></li>_x000D_
                            <li><a href="#">Page 2</a></li>_x000D_
                            <li><a href="#">Page 3</a></li>_x000D_
                        <a href="#">_x000D_
                            <i class="glyphicon glyphicon-link"></i>_x000D_
                        <a href="#">_x000D_
                            <i class="glyphicon glyphicon-paperclip"></i>_x000D_
                       isActive: false, </a>_x000D_
                        <a href="#">_x000D_
                            <i class="glyphicon glyphicon-send"></i>_x000D_
                <ul class="list-unstyled CTAs">_x000D_
                    <li><a href="" class="download">Download source</a></li>_x000D_
                    <li><a href="" class="article">Back to article</a></li>_x000D_
            <!-- Page Content Holder -->_x000D_
            <div id="content">_x000D_
                <nav class="navbar navbar-default">_x000D_
                    <div class="container-fluid">_x000D_
                        <div class="navbar-header">_x000D_
                            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn" @click="toggle()">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
                            <ul class="nav navbar-nav navbar-right">_x000D_
                                <li><a href="#">Page</a></li>_x000D_
                                <li><a href="#">Page</a></li>_x000D_
                                <li><a href="#">Page</a></li>_x000D_
                                <li><a href="#">Page</a></li>_x000D_
                <h2>Collapsible Sidebar Using Bootstrap 3</h2>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                <div class="line"></div>_x000D_
                <h2>Lorem Ipsum Dolor</h2>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                <div class="line"></div>_x000D_
                <h2>Lorem Ipsum Dolor</h2>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                <div class="line"></div>_x000D_
                <h3>Lorem Ipsum Dolor</h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
        <!-- jQuery CDN -->_x000D_
         <script src=""></script>_x000D_
         <!-- Bootstrap Js CDN -->_x000D_
         <script src=""></script>_x000D_
        /<script type="text/javascript">_x000D_
         //    $(document).ready(function () {_x000D_
          //       $('#sidebarCollapse').on('click', function () {_x000D_
           //          $('#sidebar').toggleClass('active');_x000D_
            //     });_x000D_
            // }); jquery equivalent to vue_x000D_

Why should we typedef a struct so often in C?

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

Stuff like

typedef struct {
  int x, y;
} Point;

Point point_new(int x, int y)
  Point a;
  a.x = x;
  a.y = y;
  return a;

becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef, is the case I guess.

Also note that while your example (and mine) omitted naming the struct itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:

typedef struct Point Point;

Point * point_new(int x, int y);

and then provide the struct definition in the implementation file:

struct Point
  int x, y;

Point * point_new(int x, int y)
  Point *p;
  if((p = malloc(sizeof *p)) != NULL)
    p->x = x;
    p->y = y;
  return p;

In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

Can I use multiple versions of jQuery on the same page?

After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.

    <script src="" type="text/javascript"></script>
    <script src="" type="text/javascript"></script>
    <script>var $j = jQuery.noConflict(true);</script>
       console.log($().jquery); // This prints v1.4.2
       console.log($j().jquery); // This prints v1.9.1

So then adding the "j" after the "$" was all I needed to do.

$j(function () {
        $j('.button-pro').on('click', function () {
            var el = $('#cnt' +'btn', ''));
            $j('#contentnew > div').not(el).animate({
                height: "toggle",
                opacity: "toggle"
            }, 100).hide();

Argparse optional positional arguments?

Use nargs='?' (or nargs='*' if you need more than one dir)

parser.add_argument('dir', nargs='?', default=os.getcwd())

extended example:

>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]

positional arguments:

optional arguments:
  -h, --help  show this help message and exit

Tricks to manage the available memory in an R session

With only 4GB of RAM (running Windows 10, so make that about 2 or more realistically 1GB) I've had to be real careful with the allocation.

I use data.table almost exclusively.

The 'fread' function allows you to subset information by field names on import; only import the fields that are actually needed to begin with. If you're using base R read, null the spurious columns immediately after import.

As 42- suggests, where ever possible I will then subset within the columns immediately after importing the information.

I frequently rm() objects from the environment as soon as they're no longer needed, e.g. on the next line after using them to subset something else, and call gc().

'fread' and 'fwrite' from data.table can be very fast by comparison with base R reads and writes.

As kpierce8 suggests, I almost always fwrite everything out of the environment and fread it back in, even with thousand / hundreds of thousands of tiny files to get through. This not only keeps the environment 'clean' and keeps the memory allocation low but, possibly due to the severe lack of RAM available, R has a propensity for frequently crashing on my computer; really frequently. Having the information backed up on the drive itself as the code progresses through various stages means I don't have to start right from the beginning if it crashes.

As of 2017, I think the fastest SSDs are running around a few GB per second through the M2 port. I have a really basic 50GB Kingston V300 (550MB/s) SSD that I use as my primary disk (has Windows and R on it). I keep all the bulk information on a cheap 500GB WD platter. I move the data sets to the SSD when I start working on them. This, combined with 'fread'ing and 'fwrite'ing everything has been working out great. I've tried using 'ff' but prefer the former. 4K read/write speeds can create issues with this though; backing up a quarter of a million 1k files (250MBs worth) from the SSD to the platter can take hours. As far as I'm aware, there isn't any R package available yet that can automatically optimise the 'chunkification' process; e.g. look at how much RAM a user has, test the read/write speeds of the RAM / all the drives connected and then suggest an optimal 'chunkification' protocol. This could produce some significant workflow improvements / resource optimisations; e.g. split it to ... MB for the ram -> split it to ... MB for the SSD -> split it to ... MB on the platter -> split it to ... MB on the tape. It could sample data sets beforehand to give it a more realistic gauge stick to work from.

A lot of the problems I've worked on in R involve forming combination and permutation pairs, triples etc, which only makes having limited RAM more of a limitation as they will often at least exponentially expand at some point. This has made me focus a lot of attention on the quality as opposed to quantity of information going into them to begin with, rather than trying to clean it up afterwards, and on the sequence of operations in preparing the information to begin with (starting with the simplest operation and increasing the complexity); e.g. subset, then merge / join, then form combinations / permutations etc.

There do seem to be some benefits to using base R read and write in some instances. For instance, the error detection within 'fread' is so good it can be difficult trying to get really messy information into R to begin with to clean it up. Base R also seems to be a lot easier if you're using Linux. Base R seems to work fine in Linux, Windows 10 uses ~20GB of disc space whereas Ubuntu only needs a few GB, the RAM needed with Ubuntu is slightly lower. But I've noticed large quantities of warnings and errors when installing third party packages in (L)Ubuntu. I wouldn't recommend drifting too far away from (L)Ubuntu or other stock distributions with Linux as you can loose so much overall compatibility it renders the process almost pointless (I think 'unity' is due to be cancelled in Ubuntu as of 2017). I realise this won't go down well with some Linux users but some of the custom distributions are borderline pointless beyond novelty (I've spent years using Linux alone).

Hopefully some of that might help others out.

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

check boxlist selected values with seperator

 string items = string.Empty;
        foreach (ListItem i in CheckBoxList1.Items)
            if (i.Selected == true)
                items += i.Text + ",";
        Response.Write("selected items"+ items);

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

The oracle limit is 1000 parameters. The issue has been resolved by hibernate in version 4.1.7 although by splitting the passed parameter list in sets of 500 see JIRA HHH-1123

Pythonic way to return list of every nth item in a larger list

From manual: s[i:j:k] slice of s from i to j with step k

li = range(100)
sub = li[0::10]

>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]

Keeping ASP.NET Session Open / Alive

[Late to the party...]

Another way to do this without the overhead of an Ajax call or WebService handler is to load a special ASPX page after a given amount of time (i.e., prior to the session state time-out, which is typically 20 minutes):

// Client-side JavaScript
function pingServer() {
    // Force the loading of a keep-alive ASPX page
    var img = new Image(1, 1);
    img.src = '/KeepAlive.aspx';

The KeepAlive.aspx page is simply an empty page which does nothing but touch/refresh the Session state:

// KeepAlive.aspx.cs
public partial class KeepSessionAlive: System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        // Refresh the current user session
        Session["refreshTime"] = DateTime.UtcNow;

This works by creating an img (image) element and forcing the browser to load its contents from the KeepAlive.aspx page. Loading that page causes the server to touch (update) the Session object, extending the session's expiration sliding time window (typically by another 20 minutes). The actual web page contents are discarded by the browser.

An alternative, and perhaps cleaner, way to do this is to create a new iframe element and load the KeepAlive.aspx page into it. The iframe element is hidden, such as by making it a child element of a hidden div element somewhere on the page.

Activity on the page itself can be detected by intercepting mouse and keyboard actions for the entire page body:

// Called when activity is detected
function activityDetected(evt) {

// Watch for mouse or keyboard activity
function watchForActivity() {
    var opts = { passive: true };
    document.body.addEventListener('mousemove', activityDetected, opts);
    document.body.addEventListener('keydown', activityDetected, opts);

I cannot take credit for this idea; see:

Creating a simple login form

edited @Asraful Haque answer with a bit of js to show and hide the box

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Login Page</title>
    /* Basics */
    html, body {
        width: 100%;
        height: 100%;
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        color: #444;
        -webkit-font-smoothing: antialiased;
        background: #f0f0f0;
    #container {
        position: fixed;
        width: 340px;
        height: 280px;
        top: 50%;
        left: 50%;
        margin-top: -140px;
        margin-left: -170px;
        background: #fff;
        border-radius: 3px;
        border: 1px solid #ccc;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .1);
        display: none;
    form {
        margin: 0 auto;
        margin-top: 20px;
    label {
        color: #555;
        display: inline-block;
        margin-left: 18px;
        padding-top: 10px;
        font-size: 14px;
    p a {
        font-size: 11px;
        color: #aaa;
        float: right;
        margin-top: -13px;
        margin-right: 20px;
     -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
    p a:hover {
        color: #555;
    input {
        font-family: "Helvetica Neue", Helvetica, sans-serif;
        font-size: 12px;
        outline: none;
    input[type=password] ,input[type=time]{
        color: #777;
        padding-left: 10px;
        margin: 10px;
        margin-top: 12px;
        margin-left: 18px;
        width: 290px;
        height: 35px;
        border: 1px solid #c7d0d2;
        border-radius: 2px;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #f5f7f8;
        -webkit-transition: all .4s ease;
        -moz-transition: all .4s ease;
        transition: all .4s ease;
    input[type=password]:hover,input[type=time]:hover {
        border: 1px solid #b6bfc0;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .7), 0 0 0 5px #f5f7f8;
    input[type=password]:focus,input[type=time]:focus {
        border: 1px solid #a8c9e4;
        box-shadow: inset 0 1.5px 3px rgba(190, 190, 190, .4), 0 0 0 5px #e6f2f9;
    #lower {
        background: #ecf2f5;
        width: 100%;
        height: 69px;
        margin-top: 20px;
          box-shadow: inset 0 1px 1px #fff;
        border-top: 1px solid #ccc;
        border-bottom-right-radius: 3px;
        border-bottom-left-radius: 3px;
    input[type=checkbox] {
        margin-left: 20px;
        margin-top: 30px;
    .check {
        margin-left: 3px;
        font-size: 11px;
        color: #444;
        text-shadow: 0 1px 0 #fff;
    input[type=submit] {
        float: right;
        margin-right: 20px;
        margin-top: 20px;
        width: 80px;
        height: 30px;
        font-size: 14px;
        font-weight: bold;
        color: #fff;
        background-color: #acd6ef; /*IE fallback*/
        background-image: -webkit-gradient(linear, left top, left bottom, from(#acd6ef), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #acd6ef 0%, #6ec2e8 100%);
        border-radius: 30px;
        border: 1px solid #66add6;
        box-shadow: 0 1px 2px rgba(0, 0, 0, .3), inset 0 1px 0 rgba(255, 255, 255, .5);
        cursor: pointer;
    input[type=submit]:hover {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#b6e2ff), to(#6ec2e8));
        background-image: -moz-linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
        background-image: linear-gradient(top left 90deg, #b6e2ff 0%, #6ec2e8 100%);
    input[type=submit]:active {
        background-image: -webkit-gradient(linear, left top, left bottom, from(#6ec2e8), to(#b6e2ff));
        background-image: -moz-linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
        background-image: linear-gradient(top left 90deg, #6ec2e8 0%, #b6e2ff 100%);
    function clicker () {
        var login = document.getElementById("container");"block";

    <a href="#" id="link" onClick="clicker();">login</a>
    <!-- Begin Page Content -->
    <div id="container">
        <form action="login_process.php" method="post">
            <label for="loginmsg" style="color:hsla(0,100%,50%,0.5); font-family:"Helvetica Neue",Helvetica,sans-serif;"><?php  echo @$_GET['msg'];?></label>
            <label for="username">Username:</label>
            <input type="text" id="username" name="username">
            <label for="password">Password:</label>
            <input type="password" id="password" name="password">
            <div id="lower">
                <input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
                <input type="submit" value="Login">
            </div><!--/ lower-->
    </div><!--/ container-->
    <!-- End Page Content -->

mysqldump data only

If you just want the INSERT queries, use the following:

mysqldump --skip-triggers --compact --no-create-info

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

C++ passing an array pointer as a function argument

You're over-complicating it - it just needs to be:

void generateArray(int *a, int si)
    for (int j = 0; j < si; j++)
        a[j] = rand() % 9;

int main()
    const int size=5;
    int a[size];

    generateArray(a, size);

    return 0;

When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.

How to switch between frames in Selenium WebDriver using Java

You can also use:


(0) being the first iframe on the html.

to switch back to the default content:


Cell spacing in UICollectionView

Swift 3 Version

Simply create a UICollectionViewFlowLayout subclass and paste this method.

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let answer = super.layoutAttributesForElements(in: rect) else { return nil }

        for i in 1..<answer.count {
            let currentAttributes = answer[i]
            let previousAttributes = answer[i - 1]

            let maximumSpacing: CGFloat = 8
            let origin = previousAttributes.frame.maxX

            if (origin + maximumSpacing + currentAttributes.frame.size.width < self.collectionViewContentSize.width && currentAttributes.frame.origin.x > previousAttributes.frame.origin.x) {
                var frame = currentAttributes.frame
                frame.origin.x = origin + maximumSpacing
                currentAttributes.frame = frame

        return answer

How to execute a shell script in PHP?

If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling

exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");

and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo and adding the following line to the very end of it

www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2

All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.

Embed Youtube video inside an Android app

although I suggest to use youtube api or call new intent and make the system handle it (i.e. youtube app), here some code that can help you, it has a call to an hidden method because you can't pause and resume webview

import java.lang.reflect.Method;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;


public class MultimediaPlayer extends Activity
    private WebView mWebView;
    private boolean mIsPaused = false;

    protected void onCreate(Bundle savedInstanceState)

        String media_url = VIDEO_URL;

        mWebView = (WebView) findViewById(;
        mWebView.setWebChromeClient(new WebChromeClient());

        WebSettings ws = mWebView.getSettings();

        mIsPaused = true;

    protected void onPause()

    protected void onResume()

    private void pauseBrowser()
        if (!mIsPaused)
            // pause flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onPause");
            mIsPaused = true;

    private void resumeBrowser()
        if (mIsPaused)
            // resume flash and javascript etc
            callHiddenWebViewMethod(mWebView, "onResume");
            mIsPaused = false;

    private void callHiddenWebViewMethod(final WebView wv, final String name)
            final Method method = WebView.class.getMethod(name);
        } catch (final Exception e)

How to count down in for loop?

The range function in python has the syntax:

range(start, end, step)

It has the same syntax as python lists where the start is inclusive but the end is exclusive.

So if you want to count from 5 to 1, you would use range(5,0,-1) and if you wanted to count from last to posn you would use range(last, posn - 1, -1).

How to avoid "RuntimeError: dictionary changed size during iteration" error?

I would try to avoid inserting empty lists in the first place, but, would generally use:

d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty

If prior to 2.7:

d = dict( (k, v) for k,v in d.iteritems() if v )

or just:

empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:

MySQL: What's the difference between float and double?

Perhaps this example could explain.

CREATE TABLE `test`(`fla` FLOAT,`flb` FLOAT,`dba` DOUBLE(10,2),`dbb` DOUBLE(10,2)); 

We have a table like this:

| Field | Type        |
| fla   | float       |
| flb   | float       |
| dba   | double(10,2)|
| dbb   | double(10,2)|

For first difference, we try to insert a record with '1.2' to each field:

INSERT INTO `test` values (1.2,1.2,1.2,1.2);

The table showing like this:

SELECT * FROM `test`;

| fla  | flb  | dba  | dbb  |
|  1.2 |  1.2 | 1.20 | 1.20 |

See the difference?

We try to next example:

SELECT fla+flb, dba+dbb FROM `test`;

Hola! We can find the difference like this:

| fla+flb            | dba+dbb |
| 2.4000000953674316 |    2.40 |

Check if textbox has empty value

if ( $("#txt").val().length == 0 )
  // do something

I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.

How to run .NET Core console app from the command line

With dotnetcore3.0 you can package entire solution into a single-file executable using PublishSingleFile property


Source Single-file executables

An example of Self Contained, Release OSX executable:

dotnet publish -c Release -r osx-x64 -p:PublishSingleFile=True --self-contained True

An example of Self Contained, Debug Linux 64bit executable:

dotnet publish -c Debug -r linux-x64 -p:PublishSingleFile=True --self-contained True

Linux build is independed of distribution and I have found them working on Ubuntu 18.10, CentOS 7.7, and Amazon Linux 2.

A Self Contained executable includes Dotnet Runtime and Runtime does not require to be installed on a target machine. The published executables are saved under:

<ProjectDir>/bin/<Release or Debug>/netcoreapp3.0/<target-os>/publish/ on Linux, OSX and

<ProjectDir>\bin\<Release or Debug>\netcoreapp3.0\<target-os>\publish\ on Windows.

How to break nested loops in JavaScript?

You return to "break" you nested for loop.

function foo ()
    for(var k = 0; k < 4; k++){
        for(var m = 0; m < 4; m++){
            if(m == 2){
                //break dance;

Android - Pulling SQlite database android device

 > is it possible to pull in any way a database of an Android device without having to root it? 

yes if your android app creates a file copy of the database that is accessable by everyone.

android protects apps private data so it is not visible/accessable by other apps. a database is private data. your app can of course read the database-file so it can do a file-copy to some public visible file.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Have had the same problem happen to me twice now, the only fix sofa has been to restart the tomcat server and restart the build.

How do I subtract minutes from a date in javascript?

Try as below:

var dt = new Date();
dt.setMinutes( dt.getMinutes() - 20 );

how to clear localstorage,sessionStorage and cookies in javascript? and then retrieve?

The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.

Custom date format with jQuery validation plugin

Here is an example for a new validation method that will validate almost any date format, including:

  • dd/mm/yy or dd/mm/yyyy
  • or
  • dd,mm,yy or dd,mm,yyyy
  • dd mm yy or dd mm yyyy
  • dd-mm-yy or dd-mm-yyyy

Then, when you pass the value to the php you can convert it with strtotime

Here is how to add the method:

    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-1])[/., -](0?[1-9]|1[0-2])[/., -](19|20)?\d{2}$/);
    "Please enter a date in the format!"

Then you add the new filter with:

    rules : {
        field: {
            anyDate: true


Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

I removed C:\ProgramData\Oracle\Java\javapath from my path, and it worked for me.

But make sure you include x64 JDK and JRE addresses in your path.

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

Multiple axis line chart in excel

Taking the answer above as guidance;

I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.

Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.

The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.

Thanks to the guy above for the idea!

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

    <script type="text/javascript" src="/jquery.js"></script>
    <iframe id="my_frame" src="/wherev"></iframe>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

.rar, .zip files MIME Type

In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:

import Foundation
import MobileCoreServices

extension URL {
    var mimeType: String? {
        guard self.pathExtension.count != 0 else {
            return nil

        let pathExtension = self.pathExtension as CFString
        if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
            guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
                return nil
            return mimeType.takeRetainedValue() as String

        return nil

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

How to convert a pymongo.cursor.Cursor into a dict?

The MongoDB find method does not return a single result, but a list of results in the form of a Cursor. This latter is an iterator, so you can go through it with a for loop.

For your case, just use the findOne method instead of find. This will returns you a single document as a dictionary.

Apply function to pandas groupby

As of Pandas version 0.22, there exists also an alternative to apply: pipe, which can be considerably faster than using apply (you can also check this question for more differences between the two functionalities).

For your example:

df = pd.DataFrame({"my_label": ['A','B','A','C','D','D','E']})

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

The apply version

df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])


A         0.285714
B         0.142857
C         0.142857
D         0.285714
E         0.142857

and the pipe version

df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())


A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

So the values are identical, however, the timings differ quite a lot (at least for this small dataframe):

%timeit df.groupby('my_label').apply(lambda grp: grp.count() / df.shape[0])
100 loops, best of 3: 5.52 ms per loop


%timeit df.groupby('my_label').pipe(lambda grp: grp.size() / grp.size().sum())
1000 loops, best of 3: 843 µs per loop

Wrapping it into a function is then also straightforward:

def get_perc(grp_obj):
    gr_size = grp_obj.size()
    return gr_size / gr_size.sum()

Now you can call



A    0.285714
B    0.142857
C    0.142857
D    0.285714
E    0.142857

However, for this particular case, you do not even need a groupby, but you can just use value_counts like this:

df['my_label'].value_counts(sort=False) / df.shape[0]


A    0.285714
C    0.142857
B    0.142857
E    0.142857
D    0.285714
Name: my_label, dtype: float64

For this small dataframe it is quite fast

%timeit df['my_label'].value_counts(sort=False) / df.shape[0]
1000 loops, best of 3: 770 µs per loop

As pointed out by @anmol, the last statement can also be simplified to

df['my_label'].value_counts(sort=False, normalize=True)

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup

Here's a jsfiddle for you to play around.

Combining two sorted lists in Python

Well, the naive approach (combine 2 lists into large one and sort) will be O(N*log(N)) complexity. On the other hand, if you implement the merge manually (i do not know about any ready code in python libs for this, but i'm no expert) the complexity will be O(N), which is clearly faster. The idea is described wery well in post by Barry Kelly.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

You could rather do a upsert, this operation in MongoDB is utilized to save document into collection. If document matches query criteria then it will perform update operation otherwise it will insert a new document into collection.

something similar as below

    {upsert : true}

C# Break out of foreach loop after X number of items

int count = 0;
foreach (ListViewItem lvi in listView.Items)
    if(++count > 50) break;

How do I check if a string is valid JSON in Python?

Example Python script returns a boolean if a string is valid json:

import json

def is_json(myjson):
    json_object = json.loads(myjson)
  except ValueError as e:
    return False
  return True

Which prints:

print is_json("{}")                          #prints True
print is_json("{asdf}")                      #prints False
print is_json('{ "age":100}')                #prints True
print is_json("{'age':100 }")                #prints False
print is_json("{\"age\":100 }")              #prints True
print is_json('{"age":100 }')                #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True

Convert a JSON string to a Python dictionary:

import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo'])    #prints bar

mylist = json.loads("[5,6,7]")
[5, 6, 7]

Convert a python object to JSON string:

foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo))           #prints {"gummy": "bear"}

If you want access to low-level parsing, don't roll your own, use an existing library:

Great tutorial on python JSON module:

Is String JSON and show syntax errors and error messages:

sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json


, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.

json_xs is capable of syntax checking, parsing, prittifying, encoding, decoding and more:

How to tell which row number is clicked in a table?

A better approach would be to delegate the event, which means catching it as it bubbles to the parent node.

delegation - overview

This solution is both more robust and efficient.

It allows the event to be handled even if more rows are dynamically added to the table later, and also results in attaching a single event handler to the parent node (table element), instead of one for each child node (tr element).

Assuming that the OP's example is a simplified one, the table's structure can be more complex, for example:

<table id="indexedTable">

Therefore, a simplistic approach such as getting will not work, as clicking the internal <p> and clicking the center <td> will produce different results.

Using delegation normalizes the event handling, only assuming that there are no nested tables.


Both of the following snippets are equivalent:

$("#indexedTable").delegate("tr", "click", function(e) {
    console.log($(e.currentTarget).index() + 1);

$("#indexedTable").on("click", "tr", function(e) {
    console.log($(e.currentTarget).index() + 1);

They attach a listener to table element and handle any event that bubbles from the table rows. The current API is the on method and the delegate method is legacy API (and actually calls on behind the scenes).

Note that the order of parameters to both functions is different.


A comparison between direct handler attachment and delegation is available below or on jsFiddle:

$("#table-delegate").on("click", "tr", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  $("#delegation-idx").text(idx);  _x000D_
  console.log('delegated', idx);_x000D_
$("#table-direct tr").on("click", function(e) {_x000D_
  var idx = $(e.currentTarget).index() + 1;_x000D_
  console.log('direct', idx);_x000D_
$('[data-action=add-row]').click(function(e) {_x000D_
  var id =;_x000D_
  $('#' + id + ' tbody')_x000D_
button.add-row {_x000D_
    margin-bottom: 5px;_x000D_
<script src=""></script>_x000D_
<script src=""></script>_x000D_
<link href="" rel="stylesheet"/>_x000D_
<h1>Event handling test</h1>_x000D_
<p>Add rows to both tables and see the difference in handling.</p>_x000D_
<p>Event delegation attaches a single event listener and events related to newly added children are caught.</p>_x000D_
<p>Direct event handling attaches an event handler to each child, where children added after the inital handler attachment don't have a handler attached to them, and therefore their indices won't be logged to console.</p>_x000D_
<p><span>row index: </span><span id="delegation-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-delegate">Add row to delegation</button>_x000D_
<table id="table-delegate" class="table">_x000D_
<h2>Direct attachment</h2>_x000D_
<p><span>row index: </span><span id="direct-idx">unknown</span></p>_x000D_
<button class="add-row" data-action="add-row" data-table="table-direct">Add row to direct</button>_x000D_
<table id="table-direct" class="table">_x000D_

Here's the demo on jsFiddle.


If you do have nested tables (or, in the general case, wish to delegate to elements with specific depth), you can use this suggestion from the jQuery bug report.

Replace invalid values with None in Pandas DataFrame

df.replace('-', np.nan).astype("object")

This will ensure that you can use isnull() later on your dataframe

How do I find the current machine's full hostname in C (hostname and domain information)?

The easy way, try uname()

If that does not work, use gethostname() then gethostbyname() and finally gethostbyaddr()

The h_name of hostent{} should be your FQDN

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)


df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
0  4806105017087
1  4806105017087
2            NaN

Python MySQLdb TypeError: not all arguments converted during string formatting

I don't understand the first two answers. I think they must be version-dependent. I cannot reproduce them on MySQLdb 1.2.3, which comes with Ubuntu 14.04LTS. Let's try them. First, we verify that MySQL doesn't accept double-apostrophes:

mysql> select * from methods limit 1;
| MethodID | MethodDescription  | MethodLink |
|       32 | Autonomous Sensing | NULL       |
1 row in set (0.01 sec)

mysql> select * from methods where MethodID = ''32'';
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '9999'' ' at line 1

Nope. Let's try the example that Mandatory posted using the query constructor inside /usr/lib/python2.7/dist-packages/MySQLdb/ where I opened "con" as a connection to my database.

>>> search = "test"
>>> "SELECT * FROM records WHERE email LIKE '%s'" % con.literal(search)
"SELECT * FROM records WHERE email LIKE ''test''"

Nope, the double apostrophes cause it to fail. Let's try Mike Graham's first comment, where he suggests leaving off the apostrophes quoting the %s:

>>> "SELECT * FROM records WHERE email LIKE %s" % con.literal(search)
"SELECT * FROM records WHERE email LIKE 'test'"

Yep, that will work, but Mike's second comment and the documentation says that the argument to execute (processed by con.literal) must be a tuple (search,) or a list [search]. You can try them, but you'll find no difference from the output above.

The best answer is ksg97031's.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...


How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

Why can't I reference my class library?

Since they are both in the same solution, instead of adding a reference to the DLL, add a reference to the class library project itself (the Add Reference dialog will have a tab for this).

Ahh, it's a different solution. Missed that. How about you try instead of adding a reference to the project addding a reference to the compiled DLL of your class library. The Add Reference dialog has a Browse tab which does this.

How can I concatenate a string and a number in Python?

Since Python is a strongly typed language, concatenating a string and an integer as you may do in Perl makes no sense, because there's no defined way to "add" strings and numbers to each other.

Explicit is better than implicit.

...says "The Zen of Python", so you have to concatenate two string objects. You can do this by creating a string from the integer using the built-in str() function:

>>> "abc" + str(9)

Alternatively use Python's string formatting operations:

>>> 'abc%d' % 9

Perhaps better still, use str.format():

>>> 'abc{0}'.format(9)

The Zen also says:

There should be one-- and preferably only one --obvious way to do it.

Which is why I've given three options. It goes on to say...

Although that way may not be obvious at first unless you're Dutch.

VBA shorthand for x=x+1?

If you want to call the incremented number directly in a function, this solution works bettter:

Function inc(ByRef data As Integer)
    data = data + 1
    inc = data
End Function

for example:

Wb.Worksheets(mySheet).Cells(myRow, inc(myCol))

If the function inc() returns no value, the above line will generate an error.

Removing unwanted table cell borders with CSS

Try assigning the style of border: 0px; border-collapse: collapse; to the table element.

Calling Python in PHP

is so easy You can use [phpy - library for php][1] php file

  require_once "vendor/autoload.php";

  use app\core\App;

  $app = new App();
  $python = $app->python;
  $output = $python->set(your python path)->send(data..)->gen();

python file:

import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))

you can see also example in github page [1]:

T-SQL: Deleting all duplicate rows but keeping one

Example query:

FROM Table
GROUP BY Field1, Field2, Field3, ...

Here fields are column on which you want to group the duplicate rows.

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

Python "TypeError: unhashable type: 'slice'" for encoding categorical data

I was getting same error (TypeError: unhashable type: 'slice') with below code:

included_cols = [2,4,10]
dataset = dataset[:,included_cols]  #Columns 2,4 and 10 are included.

Resolved with below code by putting iloc after dataset:

included_cols = [2,4,10]
dataset = dataset.iloc[:,included_cols]  #Columns 2,4 and 10 are included.

Is there a "theirs" version of "git merge -s ours"?

This answer was given by Paul Pladijs. I just took his commands and made a git alias for convenience.

Edit your .gitconfig and add the following:

    mergetheirs = "!git merge -s ours \"$1\" && git branch temp_THEIRS && git reset --hard \"$1\" && git reset --soft temp_THEIRS && git commit --amend && git branch -D temp_THEIRS"

Then you can "git merge -s theirs A" by running:

git checkout B (optional, just making sure we're on branch B)
git mergetheirs A

How to see what privileges are granted to schema of another user

Use example with from the post of Szilágyi Donát.

I use two querys, one to know what roles I have, excluding connect grant:

SELECT * FROM USER_ROLE_PRIVS WHERE GRANTED_ROLE != 'CONNECT'; -- Roles of the actual Oracle Schema

Know I like to find what privileges/roles my schema/user have; examples of my roles ROLE_VIEW_PAYMENTS & ROLE_OPS_CUSTOMERS. But to find the tables/objecst of an specific role I used:


The owner schema for this example could be PRD_CUSTOMERS_OWNER (or the role/schema inself).


rmagick gem install "Can't find Magick-config"

The new correct way is to install libmagickwand-dev:

sudo apt-get install libmagickwand-dev

Then you should be able to install rmagick no problem.

Alter column in SQL Server

Try this one.

ALTER TABLE tb_TableName

ALTER TABLE tb_TableName

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.

Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

How can I pass arguments to a batch file?

Inspired by an answer elsewhere by @Jon, I have crafted a more general algorithm for extracting named parameters, optional values, and switches.

Let us say that we want to implement a utility foobar. It requires an initial command. It has an optional parameter --foo which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default. It also has an optional parameter --bar which takes a required value. Lastly it can take a flag --baz with no value allowed. Oh, and these parameters can come in any order.

In other words, it looks like this:

foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]

Here is a solution:

REM FooBar parameter demo
REM By Garret Wilson


IF "%CMD%" == "" (
  GOTO usage

IF "%PARAM%" == "--foo" (
  IF NOT "%ARG%" == "" (
    IF NOT "%ARG:~0,2%" == "--" (
      SET FOO=%ARG%
    ) ELSE (
  ) ELSE (
) ELSE IF "%PARAM%" == "--bar" (
  IF NOT "%ARG%" == "" (
  ) ELSE (
    ECHO Missing bar value. 1>&2
    GOTO usage
) ELSE IF "%PARAM%" == "--baz" (
  SET BAZ=true
) ELSE IF "%PARAM%" == "" (
  GOTO endargs
) ELSE (
  ECHO Unrecognized option %1. 1>&2
  GOTO usage
GOTO args

ECHO Command: %CMD%
IF NOT "%FOO%" == "" (
  ECHO Foo: %FOO%
IF NOT "%BAR%" == "" (
  ECHO Bar: %BAR%
IF "%BAZ%" == "true" (
  ECHO Baz

REM TODO do something with FOO, BAR, and/or BAZ
GOTO :eof

ECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]
  • Use SETLOCAL so that the variables don't escape into the calling environment.
  • Don't forget to initialize the variables SET FOO=, etc. in case someone defined them in the calling environment.
  • Use %~1 to remove quotes.
  • Use IF "%ARG%" == "" and not IF [%ARG%] == [] because [ and ] don't play will at all with values ending in a space.
  • Even if you SHIFT inside an IF block, the current args such as %~1 don't get updated because they are determined when the IF is parsed. You could use %~1 and %~2 inside the IF block, but it would be confusing because you had a SHIFT. You could put the SHIFT at the end of the block for clarity, but that might get lost and/or confuse people as well. So "capturing" %~1 and %~1 outside the block seems best.
  • You don't want to use a parameter in place of another parameter's optional value, so you have to check IF NOT "%ARG:~0,2%" == "--".
  • Be careful only to SHIFT when you use one of the parameters.
  • The duplicate code SET FOO=%DEFAULT_FOO% is regrettable, but the alternative would be to add an IF "%FOO%" == "" SET FOO=%DEFAULT_FOO% outside the IF NOT "%ARG%" == "" block. However because this is still inside the IF "%PARAM%" == "--foo" block, the %FOO% value would have been evaluated and set before you ever entered the block, so you would never detect that both the --foo parameter was present and also that the %FOO% value was missing.
  • Note that ECHO Missing bar value. 1>&2 sends the error message to stderr.
  • Want a blank line in a Windows batch file? You gotta use ECHO: or one of the variations.

Load CSV data into MySQL in Python

If it is a pandas data frame you could do:

Sending the data

csv_data.to_sql=(con=mydb, name='<the name of your table>',
  if_exists='replace', flavor='mysql')

to avoid the use of the for.

Linq select object from list depending on objects attribute

I think you are looking for this?

var correctAnswer = Answers.First(a => a.Correct);

You can use single by typing :

var correctAnswer = Answers.Single(a => a.Correct);

How to encrypt String in Java

How about this:

private static byte[] xor(final byte[] input, final byte[] secret) {
    final byte[] output = new byte[input.length];
    if (secret.length == 0) {
        throw new IllegalArgumentException("empty security key");
    int spos = 0;
    for (int pos = 0; pos < input.length; ++pos) {
        output[pos] = (byte) (input[pos] ^ secret[spos]);
        if (spos >= secret.length) {
            spos = 0;
    return output;

Works fine for me and is rather compact.

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

What's the best mock framework for Java?

We are heavily using EasyMock and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.

How to execute a query in ms-access in VBA code?

Take a look at this tutorial for how to use SQL inside VBA:

For a query that won't return results, use (reference here):


For one that will, use (reference here):

Dim dBase As Database

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

        combo1.DisplayMember = "Text";
        combo1.ValueMember = "Value";   
        combo1.Items.Add(new { Text = "someText"), Value = "someValue") });
        dynamic item = combo1.Items[combo1.SelectedIndex];
        var itemValue = item.Value;
        var itemText = item.Text;

Unfortunatly "combo1.SelectedValue" does not work, i did not want to bind my combobox with any source, so i came up with this solution. Maybe it will help someone.

Invoke-customs are only supported starting with android 0 --min-api 26

After hours of struggling, I solved it by including the following within app/build.gradle:

android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8

Invoke-WebRequest, POST with parameters

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri -Method POST -Body $postParams

MySQL convert date string to Unix timestamp

For current date just use UNIX_TIMESTAMP() in your MySQL query.

What is the difference between a strongly typed language and a statically typed language?

Both are poles on two different axis:

  • strongly typed vs. weakly typed
  • statically typed vs. dynamically typed

Strongly typed means, a will not be automatically converted from one type to another. Weakly typed is the opposite: Perl can use a string like "123" in a numeric context, by automatically converting it into the int 123. A strongly typed language like python will not do this.

Statically typed means, the compiler figures out the type of each variable at compile time. Dynamically typed languages only figure out the types of variables at runtime.

how to change any data type into a string in python

Use formatting:

"%s" % (x)


x = time.ctime(); str = "%s" % (x); print str

Output: Thu Jan 11 20:40:05 2018

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  Using dad As New SqlDataAdapter(strSql, cnn)
  End Using
End Using

Is there a way to do repetitive tasks at intervals?

Check out this library:

Example as below:

c := cron.New()
c.AddFunc("0 30 * * * *", func() { fmt.Println("Every hour on the half hour") })
c.AddFunc("@hourly",      func() { fmt.Println("Every hour") })
c.AddFunc("@every 1h30m", func() { fmt.Println("Every hour thirty") })

How to display request headers with command line curl

I believe the command line switch you are looking for to pass to curl is -I.

Example usage:

$ curl -I  
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:05 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

Additionally, if you encounter a response HTTP status code of 301, you might like to also pass a -L argument switch to tell curl to follow URL redirects, and, in this case, print the headers of all pages (including the URL redirects), illustrated below:

$ curl -I -L
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 302 Found
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Set-Cookie: UID=b8c37e33defde51cf91e1e03e51657da
Location: noaccess.php
Content-Type: text/html

HTTP/1.1 200 OK
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*


"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;

String formatting in Python 3

Here are the docs about the "new" format syntax. An example would be:

"({:d} goals, ${:d})".format(self.goals, self.penalties)

If both goals and penalties are integers (i.e. their default format is ok), it could be shortened to:

"({} goals, ${})".format(self.goals, self.penalties)

And since the parameters are fields of self, there's also a way of doing it using a single argument twice (as @Burhan Khalid noted in the comments):

"({0.goals} goals, ${0.penalties})".format(self)


  • {} means just the next positional argument, with default format;
  • {0} means the argument with index 0, with default format;
  • {:d} is the next positional argument, with decimal integer format;
  • {0:d} is the argument with index 0, with decimal integer format.

There are many others things you can do when selecting an argument (using named arguments instead of positional ones, accessing fields, etc) and many format options as well (padding the number, using thousands separators, showing sign or not, etc). Some other examples:

"({goals} goals, ${penalties})".format(goals=2, penalties=4)
"({goals} goals, ${penalties})".format(**self.__dict__)

"first goal: {0.goal_list[0]}".format(self)
"second goal: {.goal_list[1]}".format(self)

"conversion rate: {:.2f}".format(self.goals / self.shots) # '0.20'
"conversion rate: {:.2%}".format(self.goals / self.shots) # '20.45%'
"conversion rate: {:.0%}".format(self.goals / self.shots) # '20%'

"self: {!s}".format(self) # 'Player: Bob'
"self: {!r}".format(self) # '<__main__.Player instance at 0x00BF7260>'

"games: {:>3}".format(  # 'games: 123'
"games: {:>3}".format(  # 'games:   4'
"games: {:0>3}".format( # 'games: 004'

Note: As others pointed out, the new format does not supersede the former, both are available both in Python 3 and the newer versions of Python 2 as well. Some may say it's a matter of preference, but IMHO the newer is much more expressive than the older, and should be used whenever writing new code (unless it's targeting older environments, of course).

jQuery Refresh/Reload Page if Ajax Success after time


You can use the reload function in your if condition for success and the page will reload after the condition is successful.

Do you recommend using semicolons after every statement in JavaScript?

I'd say consistency is more important than saving a few bytes. I always include semicolons.

On the other hand, I'd like to point out there are many places where the semicolon is not syntactically required, even if a compressor is nuking all available whitespace. e.g. at then end of a block.

if (a) { b() }

Error: request entity too large

I don't think this is the express global size limit, but specifically the connect.json middleware limit. This is 100kb by default when you use express.bodyParser() and don't provide a limit option.

Try:'/api/0.1/people', express.bodyParser({limit: '5mb'}), yourHandler);

Use Mockito to mock some methods but not others

Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.

I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.

Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.

increase legend font size ggplot2

You can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg, col=as.factor(cyl))) +
  geom_point() +
  theme_bw() +

Programmatically Add CenterX/CenterY Constraints

In Swift 5 it looks like this:

label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: vc.view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: vc.view.centerYAnchor).isActive = true

Convert a Map<String, String> to a POJO

@Hamedz if use many data, use Jackson to convert light data, use apache... TestCase:

import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; public class TestPerf { public static final int LOOP_MAX_COUNT = 1000; public static void main(String[] args) { Map<String, Object> map = new HashMap<>(); map.put("success", true); map.put("number", 1000); map.put("longer", 1000L); map.put("doubler", 1000D); map.put("data1", "testString"); map.put("data2", "testString"); map.put("data3", "testString"); map.put("data4", "testString"); map.put("data5", "testString"); map.put("data6", "testString"); map.put("data7", "testString"); map.put("data8", "testString"); map.put("data9", "testString"); map.put("data10", "testString"); runBeanUtilsPopulate(map); runJacksonMapper(map); } private static void runBeanUtilsPopulate(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { try { TestClass bean = new TestClass(); BeanUtils.populate(bean, map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } long t2 = System.currentTimeMillis(); System.out.println("BeanUtils t2-t1 = " + String.valueOf(t2 - t1)); } private static void runJacksonMapper(Map<String, Object> map) { long t1 = System.currentTimeMillis(); for (int i = 0; i < LOOP_MAX_COUNT; i++) { ObjectMapper mapper = new ObjectMapper(); TestClass testClass = mapper.convertValue(map, TestClass.class); } long t2 = System.currentTimeMillis(); System.out.println("Jackson t2-t1 = " + String.valueOf(t2 - t1)); } @Data @AllArgsConstructor @NoArgsConstructor public static class TestClass { private Boolean success; private Integer number; private Long longer; private Double doubler; private String data1; private String data2; private String data3; private String data4; private String data5; private String data6; private String data7; private String data8; private String data9; private String data10; } }

Actual meaning of 'shell=True' in subprocess

The other answers here adequately explain the security caveats which are also mentioned in the subprocess documentation. But in addition to that, the overhead of starting a shell to start the program you want to run is often unnecessary and definitely silly for situations where you don't actually use any of the shell's functionality. Moreover, the additional hidden complexity should scare you, especially if you are not very familiar with the shell or the services it provides.

Where the interactions with the shell are nontrivial, you now require the reader and maintainer of the Python script (which may or may not be your future self) to understand both Python and shell script. Remember the Python motto "explicit is better than implicit"; even when the Python code is going to be somewhat more complex than the equivalent (and often very terse) shell script, you might be better off removing the shell and replacing the functionality with native Python constructs. Minimizing the work done in an external process and keeping control within your own code as far as possible is often a good idea simply because it improves visibility and reduces the risks of -- wanted or unwanted -- side effects.

Wildcard expansion, variable interpolation, and redirection are all simple to replace with native Python constructs. A complex shell pipeline where parts or all cannot be reasonably rewritten in Python would be the one situation where perhaps you could consider using the shell. You should still make sure you understand the performance and security implications.

In the trivial case, to avoid shell=True, simply replace

subprocess.Popen("command -with -options 'like this' and\\ an\\ argument", shell=True)


subprocess.Popen(['command', '-with','-options', 'like this', 'and an argument'])

Notice how the first argument is a list of strings to pass to execvp(), and how quoting strings and backslash-escaping shell metacharacters is generally not necessary (or useful, or correct). Maybe see also When to wrap quotes around a shell variable?

If you don't want to figure this out yourself, the shlex.split() function can do this for you. It's part of the Python standard library, but of course, if your shell command string is static, you can just run it once, during development, and paste the result into your script.

As an aside, you very often want to avoid Popen if one of the simpler wrappers in the subprocess package does what you want. If you have a recent enough Python, you should probably use

  • With check=True it will fail if the command you ran failed.
  • With stdout=subprocess.PIPE it will capture the command's output.
  • With text=True (or somewhat obscurely, with the synonym universal_newlines=True) it will decode output into a proper Unicode string (it's just bytes in the system encoding otherwise, on Python 3).

If not, for many tasks, you want check_output to obtain the output from a command, whilst checking that it succeeded, or check_call if there is no output to collect.

I'll close with a quote from David Korn: "It's easier to write a portable shell than a portable shell script." Even'echo "$HOME"', shell=True) is not portable to Windows.

How to implement a Map with multiple keys?

I recommend something like this:

    public class MyMap {

      Map<Object, V> map = new HashMap<Object, V>();

      public V put(K1 key,V value){
        return map.put(key, value);

      public V put(K2 key,V value){
        return map.put(key, value);

      public V get(K1 key){    
        return map.get(key);

      public V get(K2 key){    
        return map.get(key);

      //Same for conatains


Then you can use it like:
myMap.put(k1,value) or myMap.put(k2,value)

Advantages: It is simple, enforces type safety, and doesn't store repeated data (as the two maps solutions do, though still store duplicate values).
Drawbacks: Not generic.

Send message to specific client with and node.js

In 1.0 you should use:


What are 'get' and 'set' in Swift?

A simple question should be followed by a short, simple and clear answer.

  • When we are getting a value of the property it fires its get{} part.

  • When we are setting a value to the property it fires its set{} part.

PS. When setting a value to the property, SWIFT automatically creates a constant named "newValue" = a value we are setting. After a constant "newValue" becomes accessible in the property's set{} part.


var A:Int = 0
var B:Int = 0

var C:Int {
get {return 1}
set {print("Recived new value", newValue, " and stored into 'B' ")
     B = newValue

//When we are getting a value of C it fires get{} part of C property
A = C 
A            //Now A = 1

//When we are setting a value to C it fires set{} part of C property
C = 2
B            //Now B = 2

MVC3 EditorFor readOnly

For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.

I have this in my Model.

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
    public DateTime issueDate { get; set; }

and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.

To make it work the way I want I put this in the View...

     @Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})

and this in my ready function...

     $('#issueDate').prop('readOnly', true);

I hope this would be helpful for someone out there. Sorry for my English

How to check if a process is in hang state (Linux)

What do you mean by ‘hang state’? Typically, a process that is unresponsive and using 100% of a CPU is stuck in an endless loop. But there's no way to determine whether that has happened or whether the process might not eventually reach a loop exit state and carry on.

Desktop hang detectors just work by sending a message to the application's event loop and seeing if there's any response. If there's not for a certain amount of time they decide the app has ‘hung’... but it's entirely possible it was just doing something complicated and will come back to life in a moment once it's done. Anyhow, that's not something you can use for any arbitrary process.

Convert Rows to columns using 'Pivot' in SQL Server

Here is a revision of @Tayrn answer above that might help you understand pivoting a little easier:

This may not be the best way to do this, but this is what helped me wrap my head around how to pivot tables.

ID = rows you want to pivot

MY_KEY = the column you are selecting from your original table that contains the column names you want to pivot.

VAL = the value you want returning under each column.

MAX(VAL) => Can be replaced with other aggregiate functions. SUM(VAL), MIN(VAL), ETC...

select @cols = STUFF((SELECT ',' + QUOTENAME(MY_KEY) 
                from yt
                group by MY_KEY
                order by MY_KEY ASC
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
set @query = 'SELECT ID,' + @cols + ' from 
            select ID, MY_KEY, VAL 
            from yt
        ) x
            for MY_KEY in (' + @cols + ')
        ) p '


How to deep merge instead of shallow merge?

My use case for this was to merge default values into a configuration. If my component accepts a configuration object that has a deeply nested structure, and my component defines a default configuration, I wanted to set default values in my configuration for all configuration options that were not supplied.

Example usage:

export default MyComponent = ({config}) => {
  const mergedConfig = mergeDefaults(config, {header:{margins:{left:10, top: 10}}});
  // Component code here

This allows me to pass an empty or null config, or a partial config and have all of the values that are not configured fall back to their default values.

My implementation of mergeDefaults looks like this:

export default function mergeDefaults(config, defaults) {
  if (config === null || config === undefined) return defaults;
  for (var attrname in defaults) {
    if (defaults[attrname].constructor === Object) config[attrname] = mergeDefaults(config[attrname], defaults[attrname]);
    else if (config[attrname] === undefined) config[attrname] = defaults[attrname];
  return config;

And these are my unit tests

import '@testing-library/jest-dom/extend-expect';
import mergeDefaults from './mergeDefaults';

describe('mergeDefaults', () => {
  it('should create configuration', () => {
    const config = mergeDefaults(null, { a: 10, b: { c: 'default1', d: 'default2' } });
  it('should fill configuration', () => {
    const config = mergeDefaults({}, { a: 10, b: { c: 'default1', d: 'default2' } });
  it('should not overwrite configuration', () => {
    const config = mergeDefaults({ a: 12, b: { c: 'config1', d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' } });
  it('should merge configuration', () => {
    const config = mergeDefaults({ a: 12, b: { d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' }, e: 15 });

What port is used by Java RMI connection?

All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.

If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.

  • In the case where your remote object extends UnicastRemoteObject, have its constructor call super(port) with some non-zero port number.

  • In the case where it doesn't extend UnicastRemoteObject, provide a non-zero port number to UnicastRemoteObject.exportObject().

There are several wrinkles to this.

  • If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry(). So if you create a Registry on port 1099, all other objects exported from that JVM can share port 1099.

  • If you are using socket factories, your RMIServerSocketFactory must have a sensible implementation of equals() for port sharing to work, i.e. one that doesn't just rely on object identity via == or Object.equals().

  • If either you don't provide a server socket factory, or you do provide one with a sensible equals() method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099) followed by any number of super(1099) or exportObject(..., 1099) calls.

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

Yes, LINQ to Objects supports this with Enumerable.Concat:

var together = first.Concat(second);

NB: Should first or second be null you would receive a ArgumentNullException. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:

var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type

How to concatenate two strings in C++?

There is a strcat() function from the ported C library that will do "C style string" concatenation for you.

BTW even though C++ has a bunch of functions to deal with C-style strings, it could be beneficial for you do try and come up with your own function that does that, something like:

char * con(const char * first, const char * second) {
    int l1 = 0, l2 = 0;
    const char * f = first, * l = second;

    // step 1 - find lengths (you can also use strlen)
    while (*f++) ++l1;
    while (*l++) ++l2;

    char *result = new char[l1 + l2];

    // then concatenate
    for (int i = 0; i < l1; i++) result[i] = first[i];
    for (int i = l1; i < l1 + l2; i++) result[i] = second[i - l1];

    // finally, "cap" result with terminating null char
    result[l1+l2] = '\0';
    return result;

...and then...

char s1[] = "file_name";
char *c = con(s1, ".txt");

... the result of which is file_name.txt.

You might also be tempted to write your own operator + however IIRC operator overloads with only pointers as arguments is not allowed.

Also, don't forget the result in this case is dynamically allocated, so you might want to call delete on it to avoid memory leaks, or you could modify the function to use stack allocated character array, provided of course it has sufficient length.

How to disable Google asking permission to regularly check installed apps on my phone?

On Android 5.0+

Settings > More > Developer Options > Uncheck "Verify apps via USB"!

enter image description here

Push Notifications in Android Platform

C2DM: your app-users must have the gmail account.

MQTT: when your connection reached to 1024, it will stop work because of it used "select model " of linux.

There is a free push service and api for android, you can try it:

What is the difference between venv, pyvenv, pyenv, virtualenv, virtualenvwrapper, pipenv, etc?

I would just avoid the use of virtualenv after Python3.3+ and instead use the standard shipped library venv. To create a new virtual environment you would type:

$ python3 -m venv <MYVENV>  

virtualenv tries to copy the Python binary into the virtual environment's bin directory. However it does not update library file links embedded into that binary, so if you build Python from source into a non-system directory with relative path names, the Python binary breaks. Since this is how you make a copy distributable Python, it is a big flaw. BTW to inspect embedded library file links on OS X, use otool. For example from within your virtual environment, type:

$ otool -L bin/python
    @executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)

Consequently I would avoid virtualenvwrapper and pipenv. pyvenv is deprecated. pyenv seems to be used often where virtualenv is used but I would stay away from it also since I think venv also does what pyenv is built for.

venv creates virtual environments in the shell that are fresh and sandboxed, with user-installable libraries, and it's multi-python safe. Fresh because virtual environments only start with the standard libraries that ship with python, you have to install any other libraries all over again with pip install while the virtual environment is active. Sandboxed because none of these new library installs are visible outside the virtual environment, so you can delete the whole environment and start again without worrying about impacting your base python install. User-installable libraries because the virtual environment's target folder is created without sudo in some directory you already own, so you won't need sudo permissions to install libraries into it. Finally it is multi-python safe, since when virtual environments activate, the shell only sees the python version (3.4, 3.5 etc.) that was used to build that virtual environment.

pyenv is similar to venv in that it lets you manage multiple python environments. However with pyenv you can't conveniently rollback library installs to some start state and you will likely need admin privileges at some point to update libraries. So I think it is also best to use venv.

In the last couple of years I have found many problems in build systems (emacs packages, python standalone application builders, installers...) that ultimately come down to issues with virtualenv. I think python will be a better platform when we eliminate this additional option and only use venv.

EDIT: Tweet of the BDFL,

I use venv (in the stdlib) and a bunch of shell aliases to quickly switch.

— Guido van Rossum (@gvanrossum) October 22, 2020

How do I create a MessageBox in C#?

MessageBox.Show also returns a DialogResult, which if you put some buttons on there, means you can have it returned what the user clicked. Most of the time I write something like

if (MessageBox.Show("Do you want to continue?", "Question", MessageBoxButtons.YesNo) == MessageBoxResult.Yes) {
     //some interesting behaviour here

which I guess is a bit unwieldy but it gets the job done.

See for additional enum options you can use here.

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

I think this represents a good answer.

APK Signature Scheme v2 verification

  1. Locate the APK Signing Block and verify that:
    1. Two size fields of APK Signing Block contain the same value.
    2. ZIP Central Directory is immediately followed by ZIP End of Central Directory record.
    3. ZIP End of Central Directory is not followed by more data.
  2. Locate the first APK Signature Scheme v2 Block inside the APK Signing Block. If the v2 Block if present, proceed to step 3. Otherwise, fall back to verifying the APK using v1 scheme.
  3. For each signer in the APK Signature Scheme v2 Block:
    1. Choose the strongest supported signature algorithm ID from signatures. The strength ordering is up to each implementation/platform version.
    2. Verify the corresponding signature from signatures against signed data using public key. (It is now safe to parse signed data.)
    3. Verify that the ordered list of signature algorithm IDs in digests and signatures is identical. (This is to prevent signature stripping/addition.)
    4. Compute the digest of APK contents using the same digest algorithm as the digest algorithm used by the signature algorithm.
    5. Verify that the computed digest is identical to the corresponding digest from digests.
    6. Verify that SubjectPublicKeyInfo of the first certificate of certificates is identical to public key.
  4. Verification succeeds if at least one signer was found and step 3 succeeded for each found signer.

Note: APK must not be verified using the v1 scheme if a failure occurs in step 3 or 4.

JAR-signed APK verification (v1 scheme)

The JAR-signed APK is a standard signed JAR, which must contain exactly the entries listed in META-INF/MANIFEST.MF and where all entries must be signed by the same set of signers. Its integrity is verified as follows:

  1. Each signer is represented by a META-INF/<signer>.SF and META-INF/<signer>.(RSA|DSA|EC) JAR entry.
  2. <signer>.(RSA|DSA|EC) is a PKCS #7 CMS ContentInfo with SignedData structure whose signature is verified over the <signer>.SF file.
  3. <signer>.SF file contains a whole-file digest of the META-INF/MANIFEST.MF and digests of each section of META-INF/MANIFEST.MF. The whole-file digest of the MANIFEST.MF is verified. If that fails, the digest of each MANIFEST.MF section is verified instead.
  4. META-INF/MANIFEST.MF contains, for each integrity-protected JAR entry, a correspondingly named section containing the digest of the entry’s uncompressed contents. All these digests are verified.
  5. APK verification fails if the APK contains JAR entries which are not listed in the MANIFEST.MF and are not part of JAR signature. The protection chain is thus <signer>.(RSA|DSA|EC) ? <signer>.SF ? MANIFEST.MF ? contents of each integrity-protected JAR entry.

Track a new remote branch created on GitHub

git fetch
git branch --track branch-name origin/branch-name

First command makes sure you have remote branch in local repository. Second command creates local branch which tracks remote branch. It assumes that your remote name is origin and branch name is branch-name.

--track option is enabled by default for remote branches and you can omit it.

'Connect-MsolService' is not recognized as the name of a cmdlet

I had to do this in that order:

Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD

Take a screenshot via a Python script on Linux

There is a python package for this Autopy

The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

HTML Canvas Full Screen

it's simple, set canvas width and height to screen.width and screen.height. then press F11! think F11 should make full screen in most browsers does in FFox and IE.

How to redirect stderr to null in cmd.exe

Your DOS command 2> nul

Read page Using command redirection operators. Besides the "2>" construct mentioned by Tanuki Software, it lists some other useful combinations.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.