Programs & Examples On #Rmi

Remote Method Invocation (RMI) is Java's object-oriented remote procedure call (RPC) mechanism.

Rmi connection refused with localhost

had a simliar problem with that connection exception. it is thrown either when the registry is not started yet (like in your case) or when the registry is already unexported (like in my case).

but a short comment to the difference between the 2 ways to start the registry:

Runtime.getRuntime().exec("rmiregistry 2020");

runs the rmiregistry.exe in javas bin-directory in a new process and continues parallel with your java code.

LocateRegistry.createRegistry(2020);

the rmi method call starts the registry, returns the reference to that registry remote object and then continues with the next statement.

in your case the registry is not started in time when you try to bind your object

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

What port is used by Java RMI connection?

With reference to other answers above, here is my view -

there are ports involved on both client and server side.

  • for server/remote side, if you export the object without providing a port , remote object would use a random port to listen.

  • a client, when looks up the remote object, it would always use a random port on its side and will connect to the remote object port as listed above.

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

It works for me after getting rid of "::1" in /etc/hosts.

What is the difference between Java RMI and RPC?

RPC is C based, and as such it has structured programming semantics, on the other side, RMI is a Java based technology and it's object oriented.

With RPC you can just call remote functions exported into a server, in RMI you can have references to remote objects and invoke their methods, and also pass and return more remote object references that can be distributed among many JVM instances, so it's much more powerful.

RMI stands out when the need to develop something more complex than a pure client-server architecture arises. It's very easy to spread out objects over a network enabling all the clients to communicate without having to stablish individual connections explicitly.

momentJS date string add 5 days

  1. add https://momentjs.com/downloads/moment-with-locales.js to your html page
  2. var todayDate = moment().format('DD-MM-YYYY');//to get today date 06/03/2018 if you want to add extra day to your current date then
  3. var dueDate = moment().add(15,'days').format('DD-MM-YYYY')// to add 15 days to current date..

point 2 and 3 are using in your jquery code...

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

How to do a SQL NOT NULL with a DateTime?

SELECT * FROM Table where codtable not in (Select codtable from Table where fecha is null)

What is the difference between docker-compose ports vs expose

According to the docker-compose reference,

Ports is defined as:

Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).

  • Ports mentioned in docker-compose.yml will be shared among different services started by the docker-compose.
  • Ports will be exposed to the host machine to a random port or a given port.

My docker-compose.yml looks like:

mysql:
  image: mysql:5.7
  ports:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                     Command               State            Ports
-------------------------------------------------------------------------------------
  mysql_1       docker-entrypoint.sh mysqld      Up      0.0.0.0:32769->3306/tcp

Expose is defined as:

Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.

Ports are not exposed to host machines, only exposed to other services.

mysql:
  image: mysql:5.7
  expose:
    - "3306"

If I do docker-compose ps, it will look like:

  Name                  Command             State    Ports
---------------------------------------------------------------
 mysql_1      docker-entrypoint.sh mysqld   Up      3306/tcp

Edit

In recent versions of Docker, expose doesn't have any operational impact anymore, it is just informative. (see also)

How to create a bash script to check the SSH connection?

Just in case someone only wishes to check if port 22 is open on a remote machine, this simple netcat command is useful. I used it because nmap and telnet were not available for me. Moreover, my ssh configuration uses keyboard password auth.

It is a variant of the solution proposed by GUESSWHOz.

nc -q 0 -w 1 "${remote_ip}" 22 < /dev/null &> /dev/null && echo "Port is reachable" || echo "Port is unreachable"

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

Force decimal point instead of comma in HTML5 number input (client-side)

According to the spec, You can use any as the value of step attribute:

<input type="number" step="any">

Different color for each bar in a bar chart; ChartJS

You can call this function which generates random colors for each bars

var randomColorGenerator = function () { 
    return '#' + (Math.random().toString(16) + '0000000').slice(2, 8); 
};

var barChartData = {
        labels: ["001", "002", "003", "004", "005", "006", "007"],
        datasets: [
            {
                label: "My First dataset",
                fillColor: randomColorGenerator(), 
                strokeColor: randomColorGenerator(), 
                highlightFill: randomColorGenerator(),
                highlightStroke: randomColorGenerator(),
                data: [20, 59, 80, 81, 56, 55, 40]
            }
        ]
    };

MongoDB: How to update multiple documents with a single command?

Thanks for sharing this, I used with 2.6.7 and following query just worked,

for all docs:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:true})

for single doc:

db.screen.update({stat:"PRO"} , {$set : {stat:"pro"}}, {multi:false})

PHP Echo a large block of text

To expand on @hookedonwinter's answer, here's an alternate (cleaner, in my opinion) syntax:

<?php if (is_single()): ?>
    <p>This will be shown if "is_single()" is true.</p>
<?php else: ?>
    <p>This will be shown otherwise.</p>
<?php endif; ?>

How to get current timestamp in milliseconds since 1970 just the way Java gets

use <sys/time.h>

struct timeval tp;
gettimeofday(&tp, NULL);
long int ms = tp.tv_sec * 1000 + tp.tv_usec / 1000;

refer this.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

Understanding inplace=True

inplace=True makes the function impure. It changes the original dataframe and returns None. In that case, You breaks the DSL chain. Because most of dataframe functions return a new dataframe, you can use the DSL conveniently. Like

df.sort_values().rename().to_csv()

Function call with inplace=True returns None and DSL chain is broken. For example

df.sort_values(inplace=True).rename().to_csv()

will throw NoneType object has no attribute 'rename'

Something similar with python’s build-in sort and sorted. lst.sort() returns None and sorted(lst) returns a new list.

Generally, do not use inplace=True unless you have specific reason of doing so. When you have to write reassignment code like df = df.sort_values(), try attaching the function call in the DSL chain, e.g.

df = pd.read_csv().sort_values()...

Update UI from Thread in Android

Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).

Full width image with fixed height

This can done several ways. I usually do it from my class.

From class

.image
{
    width:100%;


}

and for this your html would be:

<img class="image" src="images/image_name">

or if you want to style it using inline styling then you would just have:

<img style="width:100%; height:60px" id="image" src="images/image_name">

I however recommend doing it from your external style-sheet because as your project grows you will realize that the entire thing is easier managed with separate files for your html and your css.

Read line by line in bash script

The correct version of your script is as follows;

FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done

However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.

How to format numbers?

 function formatNumber1(number) {
  var comma = ',',
      string = Math.max(0, number).toFixed(0),
      length = string.length,
      end = /^\d{4,}$/.test(string) ? length % 3 : 0;
  return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
 }

 function formatNumber2(number) {
  return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
 }

Source: http://jsperf.com/number-format

Git Cherry-Pick and Conflicts

Before proceeding:

  • Install a proper mergetool. On Linux, I strongly suggest you to use meld:

    sudo apt-get install meld
    
  • Configure your mergetool:

    git config --global merge.tool meld
    

Then, iterate in the following way:

git cherry-pick ....
git mergetool
git cherry-pick --continue

Creating a new directory in C

I want to write a program that (...) creates the directory and a (...) file inside of it

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}

List<Object> and List<?>

package com.test;

import java.util.ArrayList;
import java.util.List;

public class TEst {

    public static void main(String[] args) {

        List<Integer> ls=new ArrayList<>();
        ls.add(1);
        ls.add(2);
        List<Integer> ls1=new ArrayList<>();
        ls1.add(3);
        ls1.add(4);
        List<List<Integer>> ls2=new ArrayList<>();
        ls2.add(ls);
        ls2.add(ls1);

        List<List<List<Integer>>> ls3=new ArrayList<>();
        ls3.add(ls2);


        m1(ls3);
    }

    private static void m1(List ls3) {
        for(Object ls4:ls3)
        {
             if(ls4 instanceof List)    
             {
                m1((List)ls4);
             }else {
                 System.out.print(ls4);
             }

        }
    }

}

How do I put variable values into a text string in MATLAB?

I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.

    >> a=['matlab','is','fun']

a =

matlabisfun

>> size(a)

ans =

     1    11

In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.

To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.

>> a={'matlab','is','fun'}

a = 

    'matlab'    'is'    'fun'

>> size(a)

ans =

     1     3

How to set some xlim and ylim in Seaborn lmplot facetgrid

The lmplot function returns a FacetGrid instance. This object has a method called set, to which you can pass key=value pairs and they will be set on each Axes object in the grid.

Secondly, you can set only one side of an Axes limit in matplotlib by passing None for the value you want to remain as the default.

Putting these together, we have:

g = sns.lmplot('X', 'Y', df, col='Z', sharex=False, sharey=False)
g.set(ylim=(0, None))

enter image description here

How to sort an array in Bash

If you can compute a unique integer for each element in the array, like this:

tab='0123456789abcdefghijklmnopqrstuvwxyz'

# build the reversed ordinal map
for ((i = 0; i < ${#tab}; i++)); do
    declare -g ord_${tab:i:1}=$i
done

function sexy_int() {
    local sum=0
    local i ch ref
    for ((i = 0; i < ${#1}; i++)); do
        ch="${1:i:1}"
        ref="ord_$ch"
        (( sum += ${!ref} ))
    done
    return $sum
}

sexy_int hello
echo "hello -> $?"
sexy_int world
echo "world -> $?"

then, you can use these integers as array indexes, because Bash always use sparse array, so no need to worry about unused indexes:

array=(a c b f 3 5)
for el in "${array[@]}"; do
    sexy_int "$el"
    sorted[$?]="$el"
done

echo "${sorted[@]}"
  • Pros. Fast.
  • Cons. Duplicated elements are merged, and it can be impossible to map contents to 32-bit unique integers.

Create an array with random values

function shuffle(maxElements) {
    //create ordered array : 0,1,2,3..maxElements
    for (var temArr = [], i = 0; i < maxElements; i++) {
        temArr[i] = i;
    }

    for (var finalArr = [maxElements], i = 0; i < maxElements; i++) {
        //remove rundom element form the temArr and push it into finalArrr
        finalArr[i] = temArr.splice(Math.floor(Math.random() * (maxElements - i)), 1)[0];
    }

    return finalArr
}

I guess this method will solve the issue with the probabilities, only limited by random numbers generator.

How to install Java SDK on CentOS?

yum install java-1.8.0

and then:

alternatives --config java

and check:

java -version

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to remove the arrow from a select element in Firefox

The appearance property from CSS3 does not allow none value. Take a look at the W3C reference. So, what you is trying to do isn't valid (indeed Chrome shouldn't accept too).

Then unfortunatelly we really don't have any cross-browser solution to hide that arrow using pure CSS. As pointed, you will need JavaScript.

I suggest you to consider using selectBox jQuery plugin. It's very lightweight and nicely done.

How to determine whether a substring is in a different string

In [7]: substring = "please help me out"

In [8]: string = "please help me out so that I could solve this"

In [9]: substring in string
Out[9]: True

Add border-bottom to table row <tr>

There are lot of incomplete answers here. Since you cannot apply a border to tr tag, you need to apply it to the td or th tags like so:

td {
  border-bottom: 1pt solid black;
}

Doing this will leave a small space between each td, which is likely not desirable if you want the border to appear as though it is the tr tag. In order to "fill in the gaps" so to speak, you need to utilize the border-collapse property on the table element and set its value to collapse, like so:

table {
  border-collapse: collapse;
}

How to save CSS changes of Styles panel of Chrome Developer Tools?

I know it is an old post, but I save it this way :

  1. Go to Sources pane.
  2. Click Show Navigator (to show the navigator pane on left).enter image description here
  3. Click the CSS file you want. (It will open in the editor, with all changes you made)
  4. Right click on editor and Save your changes.

You can also see Local Modifications to see your revisions, very interesting feature. Also work with scripts.

How to make a edittext box in a dialog

You can also create custom alert dialog by creating an xml file.

dialoglayout.xml

   <EditText
    android:id="@+id/dialog_txt_name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    android:hint="Name"
    android:singleLine="true" >

    <requestFocus />
  </EditText>
   <Button
        android:id="@+id/btn_login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="60dp"
        android:background="@drawable/red"
        android:padding="5dp"
        android:textColor="#ffffff"
        android:text="Submit" />

    <Button
        android:id="@+id/btn_cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@+id/btn_login"
        android:background="@drawable/grey"
        android:padding="5dp"
        android:text="Cancel" />

The Java Code:

@Override//to popup alert dialog
public void onClick(View arg0) {
    // TODO Auto-generated method stub
    showDialog(DIALOG_LOGIN);
});


@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog dialogDetails = null;

    switch (id) {
        case DIALOG_LOGIN:
            LayoutInflater inflater = LayoutInflater.from(this);
            View dialogview = inflater.inflate(R.layout.dialoglayout, null);
            AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
            dialogbuilder.setTitle("Title");
            dialogbuilder.setView(dialogview);
            dialogDetails = dialogbuilder.create();
            break;
    }
    return dialogDetails;
}

@Override
protected void onPrepareDialog(int id, Dialog dialog) {
    switch (id) {
        case DIALOG_LOGIN:
             final AlertDialog alertDialog = (AlertDialog) dialog;
             Button loginbutton = (Button) alertDialog
                .findViewById(R.id.btn_login);
             Button cancelbutton = (Button) alertDialog
                .findViewById(R.id.btn_cancel);
             userName = (EditText) alertDialog
                .findViewById(R.id.dialog_txt_name);
             loginbutton.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View v) {
                      String name = userName.getText().toString();
                      Toast.makeText(Activity.this, name,Toast.LENGTH_SHORT).show();
             });
             cancelbutton.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                           alertDialog.dismiss();
                      }
             });
             break;
   }
}

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

how to deal with google map inside of a hidden div (Updated picture)

Add this code before the div or pass it to a js file:

<script>
    $(document).on("pageshow","#div_name",function(){
       initialize();
    });

   function initialize() {
   // create the map

      var myOptions = {
         zoom: 14,
         center: new google.maps.LatLng(0.0, 0.0),
         mapTypeId: google.maps.MapTypeId.ROADMAP
      }
      map = new google.maps.Map(document.getElementById("div_name"), myOptions);
   }


</script>

This event will be triggered after the div loads so it will refresh the map content without having to press F5

MVC ajax json post to controller action method

Below is how I got this working.

The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

[I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

[HttpPost]  
  public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
  {            
     var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
     return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
  }

The JQuery script used to call this action method:

var requestData = {
         InvoiceNumber: $.trim(this.value),
         SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
      };


      $.ajax({
         url: '/en/myController/GetDataForInvoiceNumber',
         type: 'POST',
         data: JSON.stringify(requestData),
         dataType: 'json',
         contentType: 'application/json; charset=utf-8',
         error: function (xhr) {
            alert('Error: ' + xhr.statusText);
         },
         success: function (result) {
            CheckIfInvoiceFound(result);
         },
         async: true,
         processData: false
      });

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Recyclerview and handling different type of row inflation

You can use this library:
https://github.com/kmfish/MultiTypeListViewAdapter (written by me)

  • Better reuse the code of one cell
  • Better expansion
  • Better decoupling

Setup adapter:

adapter = new BaseRecyclerAdapter();
adapter.registerDataAndItem(TextModel.class, LineListItem1.class);
adapter.registerDataAndItem(ImageModel.class, LineListItem2.class);
adapter.registerDataAndItem(AbsModel.class, AbsLineItem.class);

For each line item:

public class LineListItem1 extends BaseListItem<TextModel, LineListItem1.OnItem1ClickListener> {

    TextView tvName;
    TextView tvDesc;


    @Override
    public int onGetLayoutRes() {
        return R.layout.list_item1;
    }

    @Override
    public void bindViews(View convertView) {
        Log.d("item1", "bindViews:" + convertView);
        tvName = (TextView) convertView.findViewById(R.id.text_name);
        tvDesc = (TextView) convertView.findViewById(R.id.text_desc);

        tvName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != attachInfo) {
                    attachInfo.onNameClick(getData());
                }
            }
        });
        tvDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != attachInfo) {
                    attachInfo.onDescClick(getData());
                }
            }
        });

    }

    @Override
    public void updateView(TextModel model, int pos) {
        if (null != model) {
            Log.d("item1", "updateView model:" + model + "pos:" + pos);
            tvName.setText(model.getName());
            tvDesc.setText(model.getDesc());
        }
    }

    public interface OnItem1ClickListener {
        void onNameClick(TextModel model);
        void onDescClick(TextModel model);
    }
}

How can I fill a div with an image while keeping it proportional?

You can achieve this using css flex properties. Please see the code below

_x000D_
_x000D_
.img-container {_x000D_
  border: 2px solid red;_x000D_
  justify-content: center;_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  overflow: hidden;_x000D_
  _x000D_
}_x000D_
.img-container .img-to-fit {_x000D_
  flex: 1;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div class="img-container">_x000D_
  <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Run a command over SSH with JSch

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

How to use jQuery Plugin with Angular 4?

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

How to save a BufferedImage as a File

File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

If you are using the TestCaseSource attribute, ensure the source exists and respects the documentation, otherwise your tests will not be discovered.

How to pass multiple checkboxes using jQuery ajax post

This would be better and easy

var arr = $('input[name="user_ids[]"]').map(function(){
  return $(this).val();
}).get();

console.log(arr);

how to run vibrate continuously in iphone?

Read the Apple Human Interaction Guidelines for iPhone. I believe this is not approved behavior in an app.

How to make a countdown timer in Android?

Revers CountDown timer with hours minutes and seconds

public void reverseTimer(int Seconds, final TextView tv) {

    new CountDownTimer(Seconds * 1000 + 1000, 1000) {

        public void onTick(long millisUntilFinished) {
            int seconds = (int) (millisUntilFinished / 1000);

            int hours = seconds / (60 * 60);
            int tempMint = (seconds - (hours * 60 * 60));
            int minutes = tempMint / 60;
            seconds = tempMint - (minutes * 60);

            tv.setText("TIME : " + String.format("%02d", hours)
                    + ":" + String.format("%02d", minutes)
                    + ":" + String.format("%02d", seconds));
        }

        public void onFinish() {
            tv.setText("Completed");
        }
    }.start();
}

Removing index column in pandas when reading a csv

you can specify which column is an index in your csv file by using index_col parameter of from_csv function if this doesn't solve you problem please provide example of your data

IIS 7, HttpHandler and HTTP Error 500.21

I had the same problem and was solved by running the following in run

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Converting VS2012 Solution to VS2010

Open the project file and not the solution. The project will be converted by the Wizard, and after converted, when you build the project, a new Solution will be generated as a VS2010 one.

How to use environment variables in docker compose

You cannot ... yet. But this is an alternative, think like a docker-composer.yml generator:

https://gist.github.com/Vad1mo/9ab63f28239515d4dafd

Basically a shell script that will replace your variables. Also you can use Grunt task to build your docker compose file at the end of your CI process.

.gitignore file for java eclipse project

put .gitignore in your main catalog

git status (you will see which files you can commit)
git add -A
git commit -m "message"
git push

make: *** [ ] Error 1 error

Sometimes you will get lots of compiler outputs with many warnings and no line of output that says "error: you did something wrong here" but there was still an error. An example of this is a missing header file - the compiler says something like "no such file" but not "error: no such file", then it exits with non-zero exit code some time later (perhaps after many more warnings). Make will bomb out with an error message in these cases!

GitHub README.md center image

For left alignment

 <img align="left" width="600" height="200" src="https://www.python.org/python-.png">

For right alignment

<img align="right" width="600" height="200" src="https://www.python.org/python-.png">

And for center alignment

<p align="center">
  <img width="600" height="200" src="https://www.python.org/python-.png">
</p>

Fork it here for future references, if you find this useful.

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

Changing Background Image with CSS3 Animations

You can use animated background-position property and sprite image.

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

How to use su command over adb shell?

1. adb shell su

win cmd

C:\>adb shell id
uid=2000(shell) gid=2000(shell)

C:\>adb shell 'su -c id'
/system/bin/sh: su -c id: inaccessible or not found

C:\>adb shell "su -c id"
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0

C:\>adb shell su -c id   
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0

win msys bash

msys2@bash:~$ adb shell 'su -c id'
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
msys2@bash:~$ adb shell "su -c id"
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
msys2@bash:~$ adb shell su -c id
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0

2. adb shell -t

if want run am cmd, -t option maybe required:

C:\>adb shell su -c am stack list
cmd: Failure calling service activity: Failed transaction (2147483646)

C:\>adb shell -t su -c am stack list
Stack id=0 bounds=[0,0][1200,1920] displayId=0 userId=0
...

shell options:

 shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
     run remote shell command (interactive shell if no command given)
     -e: choose escape character, or "none"; default '~'
     -n: don't read from stdin
     -T: disable pty allocation
     -t: allocate a pty if on a tty (-tt: force pty allocation)
     -x: disable remote exit codes and stdout/stderr separation

Android Debug Bridge version 1.0.41
Version 30.0.5-6877874

Rendering React Components from Array of Objects

This is quite likely the simplest way to achieve what you are looking for.

In order to use this map function in this instance, we will have to pass a currentValue (always-required) parameter, as well an index (optional) parameter. In the below example, station is our currentValue, and x is our index.

station represents the current value of the object within the array as it is iterated over. x automatically increments; increasing by one each time a new object is mapped.

render () {
    return (
        <div>
            {stations.map((station, x) => (
                <div key={x}> {station} </div>
            ))}
        </div>
    );
}

What Thomas Valadez had answered, while it had provided the best/simplest method to render a component from an array of objects, it had failed to properly address the way in which you would assign a key during this process.

Generic type conversion FROM string

I am not sure whether I understood your intentions correctly, but let's see if this one helps.

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
        set { base.Value = value.ToString();}
    }
}

Network tools that simulate slow network connection

On Linux, see netem: the kernel already contains support for traffic shaping, and can simulate high latency, low bandwidth, packet losses, and all sort of other adverse conditions, even on a loopback device (so you don't need a real, physical network to test across).

Converting <br /> into a new line for use in a text area

Try this one

<?php
    $text = "Hello <br /> Hello again <br> Hello again again <br/> Goodbye <BR>";
    $breaks = array("<br />","<br>","<br/>");  
    $text = str_ireplace($breaks, "\r\n", $text);  
?>  
<textarea><?php echo $text; ?></textarea>

callback to handle completion of pipe

I found an a bit different solution of my problem regarding this context. Thought worth sharing.

Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
                    callback();
                });
// message.value --> value/text to write in write.txt 
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );
    sftp.end();
    }
);

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"
        sftp.end();
        }
);

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString = Object.prototype.toString.call(data);
    console.log('type of data:', toString);
    console.log( "- file transferred" );
});

jsonStream.pipe( writeStream );

JSON formatter in C#?

Just use JsonDocument and Utf8JsonWriter. No third-party library required. No target object for deserialization for jsonString required.

using System.IO;
using System.Text;
using System.Text.Json;

// other code ...

public string Prettify(string jsonString)
{
    using var stream = new MemoryStream();
    var document = JsonDocument.Parse(jsonString);
    var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true });
    document.WriteTo(writer);
    writer.Flush();
    return Encoding.UTF8.GetString(stream.ToArray());
}

Permission denied error on Github Push

See the github help on cloning URL. With HTTPS, if you are not authorized to push, you would basically have a read-only access. So yes, you need to ask the author to give you permission.

If the author doesn't give you permission, you can always fork (clone) his repository and work on your own. Once you made a nice and tested feature, you can then send a pull request to the original author.

Java check if boolean is null

boolean can only be true or false because it's a primitive datatype (+ a boolean variables default value is false). You can use the class Boolean instead if you want to use null values. Boolean is a reference type, that's the reason you can assign null to a Boolean "variable". Example:

Boolean testvar = null;
if (testvar == null) { ...}

How to sort an array of integers correctly

I agree with aks, however instead of using

return a - b;

You should use

return a > b ? 1 : a < b ? -1 : 0;

Invoke JSF managed bean action on page load

JSF 1.0 / 1.1

Just put the desired logic in the constructor of the request scoped bean associated with the JSF page.

public Bean() {
    // Do your stuff here.
}

JSF 1.2 / 2.x

Use @PostConstruct annotated method on a request or view scoped bean. It will be executed after construction and initialization/setting of all managed properties and injected dependencies.

@PostConstruct
public void init() {
    // Do your stuff here.
}

This is strongly recommended over constructor in case you're using a bean management framework which uses proxies, such as CDI, because the constructor may not be called at the times you'd expect it.

JSF 2.0 / 2.1

Alternatively, use <f:event type="preRenderView"> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:event type="preRenderView" listener="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

JSF 2.2+

Alternatively, use <f:viewAction> in case you intend to initialize based on <f:viewParam> too, or when the bean is put in a broader scope than the view scope (which in turn indicates a design problem, but that aside). Otherwise, a @PostConstruct is perfectly fine too.

<f:metadata>
    <f:viewParam name="foo" value="#{bean.foo}" />
    <f:viewAction action="#{bean.onload}" />
</f:metadata>
public void onload() { 
    // Do your stuff here.
}

Note that this can return a String navigation case if necessary. It will be interpreted as a redirect (so you do not need a ?faces-redirect=true here).

public String onload() { 
    // Do your stuff here.
    // ...
    return "some.xhtml";
}

See also:

How to make flexbox items the same size?

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

flex: 1 1 0px

Your IDE or linter might mention that the unit of measure 'px' is redundant. If you leave it out (like: flex: 1 1 0), IE will not render this correctly. So the px is required to support Internet Explorer, as mentioned in the comments by @fabb;

How to JOIN three tables in Codeigniter

Use this code in model

public function funcname($id)
{
    $this->db->select('*');
    $this->db->from('Album a'); 
    $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
    $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
    $this->db->where('c.album_id',$id);
    $this->db->order_by('c.track_title','asc');         
    $query = $this->db->get(); 
    if($query->num_rows() != 0)
    {
        return $query->result_array();
    }
    else
    {
        return false;
    }
}

How do I customize Facebook's sharer.php

It appears the following answer no longer works, and Facebook no longer accepts parameters on the Feed Dialog links

You can use the Feed Dialog via URL to emulate the behavior of Sharer.php, but it's a little more complicated. You need a Facebook App setup with the Base URL of the URL you plan to share configured. Then you can do the following:

1) Create a link like:

   http://www.facebook.com/dialog/feed?app_id=[FACEBOOK_APP_ID]' +
        '&link=[FULLY_QUALIFIED_LINK_TO_SHARE_CONTENT]' +
        '&picture=[LINK_TO_IMAGE]' +
        '&name=' + encodeURIComponent('[CONTENT_TITLE]') +
        '&caption=' + encodeURIComponent('[CONTENT_CAPTION]) +
        '&description=' + encodeURIComponent('[CONTENT_DESCRIPTION]') +
        '&redirect_uri=' + FBVars.baseURL + '[URL_TO_REDIRECT_TO_AFTER_SHARE]' +
        '&display=popup';

(obviously replace the [CONTENT] with the appropriate content. Documentation here: https://developers.facebook.com/docs/reference/dialogs/feed)

2) Open that link in a popup window with JavaScript on click of the share link

3) I like to create file (i.e. popupclose.html) to redirect users back to when they finish sharing, this file will contain <script>window.close();</script> to close the popup window

The only downside of using the Feed Dialog (besides setup) is that, if you manage Pages as well, you don't have the ability to choose to share via a Page, only a regular user account can share. And it can give you some really cryptic error messages, most of them are related to the setup of your Facebook app or problems with either the content or URL you are sharing.

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

addEventListener in Internet Explorer

I'm using this solution and works in IE8 or greater.

if (typeof Element.prototype.addEventListener === 'undefined') {
    Element.prototype.addEventListener = function (e, callback) {
      e = 'on' + e;
      return this.attachEvent(e, callback);
    };
  }

And then:

<button class="click-me">Say Hello</button>

<script>
  document.querySelectorAll('.click-me')[0].addEventListener('click', function () {
    console.log('Hello');
  });
</script>

This will work both IE8 and Chrome, Firefox, etc.

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

Which MySQL data type to use for storing boolean values

Referring to this link Boolean datatype in Mysql, according to the application usage, if one wants only 0 or 1 to be stored, bit(1) is the better choice.

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to concatenate two numbers in javascript?

I'd prefer the concat way :

const numVar1 = 5;
const numVar2 = 6;
const value = "".concat(numVar1, numVar2);
// or directly with values
const value2 = "".concat(5, 6);

You can also use an array which can help in some use cases :

const value3 = [5, 6, numVar1].join('');

filtering NSArray into a new NSArray in Objective-C

There are loads of ways to do this, but by far the neatest is surely using [NSPredicate predicateWithBlock:]:

NSArray *filteredArray = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id object, NSDictionary *bindings) {
    return [object shouldIKeepYou];  // Return YES for each object you want in filteredArray.
}]];

I think that's about as concise as it gets.


Swift:

For those working with NSArrays in Swift, you may prefer this even more concise version:

let filteredArray = array.filter { $0.shouldIKeepYou() }

filter is just a method on Array (NSArray is implicitly bridged to Swift’s Array). It takes one argument: a closure that takes one object in the array and returns a Bool. In your closure, just return true for any objects you want in the filtered array.

Convert Set to List without creating new List

the simplest solution

I wanted a very quick way to convert my set to List and return it, so in one line I did

 return new ArrayList<Long>(mySetVariable);

Fully custom validation error message with Rails

Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.

Assuming it's Rails 3 (I don't know if it's different in previous versions),

keep this in your model:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

and in the view, instead of leaving

@instance.errors.full_messages

as it would be when we use the scaffold generator, put:

@instance.errors.first[1]

And you will get just the message you specified in the model, without the attribute name.

Explanation:

#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors  # => {:song_rep_xyz=>"can't be empty"}

#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]

#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]

So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.

Hope that helped.

how to add a jpg image in Latex

You need to use a graphics library. Put this in your preamble:

\usepackage{graphicx}

You can then add images like this:

\begin{figure}[ht!]
\centering
\includegraphics[width=90mm]{fixed_dome1.jpg}
\caption{A simple caption \label{overflow}}
\end{figure}

This is the basic template I use in my documents. The position and size should be tweaked for your needs. Refer to the guide below for more information on what parameters to use in \figure and \includegraphics. You can then refer to the image in your text using the label you gave in the figure:

And here we see figure \ref{overflow}.

Read this guide here for a more detailed instruction: http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions

Update query PHP MySQL

Without knowing what the actual error you are getting is I would guess it is missing quotes. try the following:

mysql_query("UPDATE blogEntry SET content = '$udcontent', title = '$udtitle' WHERE id = '$id'")

Max length UITextField

You can use in swift 5 or swift 4 like image look like bellow enter image description here

  1. Add textField in View Controller
  2. Connect to text to ViewController
  3. add the code in view ViewController

     class ViewController: UIViewController , UITextFieldDelegate {
    
      @IBOutlet weak var txtName: UITextField!
    
      var maxLen:Int = 8;
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
        txtName.delegate = self
       }
    
     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    
         if(textField == txtName){
            let currentText = textField.text! + string
            return currentText.count <= maxLen
         }
    
         return true;
       }
    }
    

You can download Full Source form GitHub: https://github.com/enamul95/TextFieldMaxLen

Laravel back button

The following is a complete Blade (the templating engine Laravel uses) solution:

{!! link_to(URL::previous(), 'Cancel', ['class' => 'btn btn-default']) !!}

The options array with the class is optional, in this case it specifies the styling for a Bootstrap 3 button.

JUnit tests pass in Eclipse but fail in Maven Surefire

I had the same problem (JUnit tests failed in Maven Surefire but passed in Eclipse) and managed to solve it by setting forkMode to always in the maven surefire configuration in pom.xml:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12</version>
    <configuration>
        <forkMode>always</forkMode>
    </configuration>
</plugin>

Surefire parameters: http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html

Edit (January 2014):

As Peter Perhác pointed out, the forkMode parameter is deprecated since Surefire 2.14. Beginning from Surefire 2.14 use this instead:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.16</version>
    <configuration>
        <reuseForks>false</reuseForks>
        <forkCount>1</forkCount>
    </configuration>
</plugin>

For more information see Fork Options and Parallel Test Execution

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

I had the same problem once. Calling invalidate after changing visibility almost always works, but in some cases it doesn't. I had to cheat and set the background to a transparent image and set the text to "".

Undoing a 'git push'

If you want to ignore the last commit that you have just pushed in the remote branch: this will not remove the commit but just ignoring it by moving the git pointer to the commit one earlier, refered by HEAD^ or HEAD^1

git push origin +HEAD^:branch

But if you have already pushed this commit, and others have pulled the branch. In this case, rewriting your branch's history is undesirable and you should instead revert this commit:

git revert <SHA-1>
git push origin branch

How to convert Excel values into buckets?

You're looking for the LOOKUP function. please see the following page for more info:

Data Buckets (in a range)

Where does Git store files?

To be a bit more complete, Git works with:

  • the working tree (the root of which being where you made a git init)
  • "path to the Git repository" (where there is a .git, which will store the revisions of all your files)

GIT_DIR is an environment variable, which can be an absolute path or relative path to current working directory.

If it is not defined, the "path to the git repository" is by default at the root directory of your working tree (again, where you made a git init).

You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:

git command --git-dir=<path> --work-tree=<path>

But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git, assume this it also the root directory of your working tree, and use that .git as the only container for all the revisions of your files.

Note: .git is also hidden in Windows (msysgit).
You would have to do a dir /AH to see it.
git 2.9 (June 2016) allows to configure that.


Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible to open multiple repositories, work with and then close them.

See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit cf0b179, 11 Apr 2018)

repository: introduce raw object store field

The raw object store field will contain any objects needed for access to objects in a given repository.

This patch introduces the raw object store and populates it with the objectdir, which used to be part of the repository struct.

As the struct gains members, we'll also populate the function to clear the memory for these members.

In a later step, we'll introduce a struct object_parser, that will complement the object parsing in a repository struct:

  • The raw object parser is the layer that will provide access to raw object content,
  • while the higher level object parser code will parse raw objects and keeps track of parenthood and other object relationships using 'struct object'.

    For now only add the lower level to the repository struct.

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

Prevent textbox autofill with previously entered values

This is the answer.

_x000D_
_x000D_
<asp:TextBox id="yourtextBoxname" runat="server" AutoCompleteType="Disabled"></asp:TextBox>
_x000D_
_x000D_
_x000D_

AutoCompleteType="Disabled"

If you still get the pre-filled boxes for example in the Firefox browser then its the browser's fault. You have to go

'Options' --> 'Security'(tab) --> Untick

'Remember password for sites and click on Saved Passwords button to delete any details that the browser has saved.

This should solve the problem

How to add a custom Ribbon tab using VBA?

AFAIK you cannot use VBA Excel to create custom tab in the Excel ribbon. You can however hide/make visible a ribbon component using VBA. Additionally, the link that you mentioned above is for MS Project and not MS Excel.

I create tabs for my Excel Applications/Add-Ins using this free utility called Custom UI Editor.


Edit: To accommodate new request by OP

Tutorial

Here is a short tutorial as promised:

  1. After you have installed the Custom UI Editor (CUIE), open it and then click on File | Open and select the relevant Excel File. Please ensure that the Excel File is closed before you open it via CUIE. I am using a brand new worksheet as an example.

    enter image description here

  2. Right click as shown in the image below and click on "Office 2007 Custom UI Part". It will insert the "customUI.xml"

    enter image description here

  3. Next Click on menu Insert | Sample XML | Custom Tab. You will notice that the basic code is automatically generated. Now you are all set to edit it as per your requirements.

    enter image description here

  4. Let's inspect the code

    enter image description here

    label="Custom Tab": Replace "Custom Tab" with the name which you want to give your tab. For the time being let's call it "Jerome".

    The below part adds a custom button.

    <button id="customButton" label="Custom Button" imageMso="HappyFace" size="large" onAction="Callback" />
    

    imageMso: This is the image that will display on the button. "HappyFace" is what you will see at the moment. You can download more image ID's here.

    onAction="Callback": "Callback" is the name of the procedure which runs when you click on the button.

Demo

With that, let's create 2 buttons and call them "JG Button 1" and "JG Button 2". Let's keep happy face as the image of the first one and let's keep the "Sun" for the second. The amended code now looks like this:

<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="MyCustomTab" label="Jerome" insertAfterMso="TabView">
<group id="customGroup1" label="First Tab">
<button id="customButton1" label="JG Button 1" imageMso="HappyFace" size="large" onAction="Callback1" />
<button id="customButton2" label="JG Button 2" imageMso="PictureBrightnessGallery" size="large" onAction="Callback2" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>

Delete all the code which was generated in CUIE and then paste the above code in lieu of that. Save and close CUIE. Now when you open the Excel File it will look like this:

enter image description here

Now the code part. Open VBA Editor, insert a module, and paste this code:

Public Sub Callback1(control As IRibbonControl)

    MsgBox "You pressed Happy Face"

End Sub

Public Sub Callback2(control As IRibbonControl)

    MsgBox "You pressed the Sun"

End Sub

Save the Excel file as a macro enabled file. Now when you click on the Smiley or the Sun you will see the relevant message box:

enter image description here

Hope this helps!

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

fetch in git doesn't get all branches

We had the same problem and you have to use

git fetch

git push origin branch_name

git branch -r

Hope this help someone facing the same problem

T-SQL datetime rounded to nearest minute and nearest hours with using functions

Select convert(char(8), DATEADD(MINUTE, DATEDIFF(MINUTE, 0, getdate), 0), 108) as Time

will round down seconds to 00

setState() inside of componentDidUpdate()

I had a similar problem where i have to center the toolTip. React setState in componentDidUpdate did put me in infinite loop, i tried condition it worked. But i found using in ref callback gave me simpler and clean solution, if you use inline function for ref callback you will face the null problem for every component update. So use function reference in ref callback and set the state there, which will initiate the re-render

Is mathematics necessary for programming?

It depends on what you do: Web developement, business software, etc. I think for this kind of stuff, you don't need math.

If you want to do computer graphics, audio/video processing, AI, cryptography, etc. then you need a math background, otherwise you can simply not do it.

Use of #pragma in C

what i feel is #pragma is a directive where if you want the code to be location specific .say a situation where you want the program counter to read from the specific address where the ISR is written then you can specify ISR at that location using #pragma vector=ADC12_VECTOR and followd by interrupt rotines name and its description

SQL Server : fetching records between two dates?

try to use following query

select * 
from xxx 
where convert(date,dates) >= '2012-10-26' and convert(date,dates) <= '2012-10-27'

How to force an entire layout View refresh?

This is how i used to Refresh my layout

Intent intent = getIntent();
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
startActivity(intent);

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Line Break in HTML Select Option?

Does not work fully (the hr line part) on all browsers, but here is the solution:

_x000D_
_x000D_
<select name="selector">_x000D_
  <option value="1">Option 1</option>_x000D_
  <option value="2">Option 2</option>_x000D_
  <option value="3">Option 3</option>_x000D_
  <option disabled><hr></option>_x000D_
  <option value="4">Option 4</option>_x000D_
  <option value="5">Option 5</option>_x000D_
  <option value="6">Option 6</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

sudo: npm: command not found

In case could be useful for anyone that uses rh-* packages this worked for me:

sudo ln -s /opt/rh/rh-nodejs8/root/usr/bin/npm /usr/local/bin/npm

How can I delete a user in linux when the system says its currently used in a process

It worked i used userdell --force USERNAME Some times eventhough -f and --force is same -f is not working sometimes After i removed the account i exit back to that removed username which i removed from root then what happened is this

image description here

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

After hours of analysis reading tons of logs and internet, finally found problem.

If you use docker and php 7.4 (my case) you probably get error because default security level in OpenSSL it too high for wsdl cert. Even if you disable verify and allow self-signed in SoapClient options.

You need lower seclevel in /etc/ssl/openssl.cnf from DEFAULT@SECLEVEL=2 to

DEFAULT@SECLEVEL=1

Or just add into Dockerfile

RUN sed -i "s|DEFAULT@SECLEVEL=2|DEFAULT@SECLEVEL=1|g" /etc/ssl/openssl.cnf

Source: https://github.com/dotnet/runtime/issues/30667#issuecomment-566482876


You can verify it by run on container

curl -A 'cURL User Agent' -4 https://ewus.nfz.gov.pl/ws-broker-server-ewus/services/Auth?wsdl

Before that change I got error:

SSL routines:tls_process_ske_dhe:dh key too small

Increment variable value by 1 ( shell programming)

These are the methods I know:

ichramm@NOTPARALLEL ~$ i=10; echo $i;
10
ichramm@NOTPARALLEL ~$ ((i+=1)); echo $i;
11
ichramm@NOTPARALLEL ~$ ((i=i+1)); echo $i;
12
ichramm@NOTPARALLEL ~$ i=`expr $i + 1`; echo $i;
13

Note the spaces in the last example, also note that's the only one that uses $i.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I created copy of my inet folder, to make a duplicate of the site. It showed 'access denied .../App_Data/viewstate/1/6/6/0 ... '. On checking it showed that app_data folder is having IIS_IUSER addes but does not have modify or write acess checked. Just check those boxes and the instance begin to run.

find path of current folder - cmd

Use This Code

@echo off
:: Get the current directory

for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A

echo CURRENT_DIR%%A 

(echo this To confirm this code works fine)

docker entrypoint running bash script gets "permission denied"

  1. "Permission denied" prevents your script from being invoked at all. Thus, the only syntax that could be possibly pertinent is that of the first line (the "shebang"), which should look like #!/usr/bin/env bash, or #!/bin/bash, or similar depending on your target's filesystem layout.

  2. Most likely the filesystem permissions not being set to allow execute. It's also possible that the shebang references something that isn't executable, but this is far less likely.

  3. Mooted by the ease of repairing the prior issues.


The simple reading of

docker: Error response from daemon: oci runtime error: exec: "/usr/src/app/docker-entrypoint.sh": permission denied.

...is that the script isn't marked executable.

RUN ["chmod", "+x", "/usr/src/app/docker-entrypoint.sh"]

will address this within the container. Alternately, you can ensure that the local copy referenced by the Dockerfile is executable, and then use COPY (which is explicitly documented to retain metadata).

How to add a touch event to a UIView?

Swift 3 & Swift 4

import UIKit

extension UIView {
  func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true
  }
}

Use

yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

Can Linux apps be run in Android?

Yes, they can. If you do not have a rooted phone/tablet, then you could download c4droid here to compile your apps. Then, you could download Kevin Boone's KBOX here to run the program.

Get product id and product type in magento?

you can get all product information from following code

$product_id=6//Suppose
$_product=Mage::getModel('catalog/product')->load($product_id);


    $product_data["id"]=$_product->getId();
    $product_data["name"]=$_product->getName();
    $product_data["short_description"]=$_product->getShortDescription();
    $product_data["description"]=$_product->getDescription();
    $product_data["price"]=$_product->getPrice();
    $product_data["special price"]=$_product->getFinalPrice();
    $product_data["image"]=$_product->getThumbnailUrl();
    $product_data["model"]=$_product->getSku();
    $product_data["color"]=$_product->getAttributeText('color'); //get cusom attribute value


    $storeId = Mage::app()->getStore()->getId();
    $summaryData = Mage::getModel('review/review_summary')->setStoreId($storeId)  ->load($_product->getId());
    $product_data["rating"]=($summaryData['rating_summary']*5)/100;

    $product_data["shipping"]=Mage::getStoreConfig('carriers/flatrate/price');

    if($_product->isSalable() ==1)
        $product_data["in_stock"]=1;
    else
        $product_data["in_stock"]=0;


    echo "<pre>";
    print_r($product_data);
    //echo "</pre>";

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

How can I create a dynamically sized array of structs?

For the test code: if you want to modify a pointer in a function, you should pass a "pointer to pointer" to the function. Corrected code is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct
{
    char *str1;
    char *str2;
} words;

void LoadData(words**, int*);

main()
{
    words **x;
    int num;

    LoadData(x, &num);

    printf("%s %s\n", (*x[0]).str1, (*x[0]).str2);
    printf("%s %s\n", (*x[1]).str1, (*x[1]).str2);
}

void LoadData(words **x, int *num)
{
    *x = (words*) malloc(sizeof(words));

    (*x[0]).str1 = "johnnie\0";
    (*x[0]).str2 = "krapson\0";

    *x = (words*) realloc(*x, sizeof(words) * 2);
    (*x[1]).str1 = "bob\0";
    (*x[1]).str2 = "marley\0";

    *num = *num + 1;
}

Sorting rows in a data table

try this:

DataTable DT = new DataTable();
DataTable sortedDT = DT;
sortedDT.Clear();
foreach (DataRow row in DT.Select("", "DiffTotal desc"))
{
    sortedDT.NewRow();
    sortedDT.Rows.Add(row);
}
DT = sortedDT;

Spring MVC @PathVariable with dot (.) is getting truncated

Here's an approach that relies purely on java configuration:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Configuration
public class MvcConfig extends WebMvcConfigurationSupport{

    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = super.requestMappingHandlerMapping();
        handlerMapping.setUseSuffixPatternMatch(false);
        handlerMapping.setUseTrailingSlashMatch(false);
        return handlerMapping;
    }
}

c++ exception : throwing std::string

All these work:

#include <iostream>
using namespace std;

//Good, because manual memory management isn't needed and this uses
//less heap memory (or no heap memory) so this is safer if
//used in a low memory situation
void f() { throw string("foo"); }

//Valid, but avoid manual memory management if there's no reason to use it
void g() { throw new string("foo"); }

//Best.  Just a pointer to a string literal, so no allocation is needed,
//saving on cleanup, and removing a chance for an allocation to fail.
void h() { throw "foo"; }

int main() {
  try { f(); } catch (string s) { cout << s << endl; }
  try { g(); } catch (string* s) { cout << *s << endl; delete s; }
  try { h(); } catch (const char* s) { cout << s << endl; }
  return 0;
}

You should prefer h to f to g. Note that in the least preferable option you need to free the memory explicitly.

Set background image according to screen resolution

Set body css to :

body { 
background: url(../img/background.jpg) no-repeat center center fixed #000; 
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

}

Count Vowels in String Python

if A or a in stri means if A or (a in stri) which is if True or (a in stri) which is always True, and same for each of your if statements.

What you wanted to say is if A in stri or a in stri.

This is your mistake. Not the only one - you are not really counting vowels, since you only check if string contains them once.

The other issue is that your code is far from being the best way of doing it, please see, for example, this: Count vowels from raw input. You'll find a few nice solutions there, which can easily be adopted for your particular case. I think if you go in detail through the first answer, you'll be able to rewrite your code in a correct way.

Are PostgreSQL column names case-sensitive?

if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:

select
    psat.schemaname,
    psat.relname,
    pa.attname,
    psat.relid
from
    pg_catalog.pg_stat_all_tables psat,
    pg_catalog.pg_attribute pa
where
    psat.relid = pa.attrelid

change schema name:

ALTER SCHEMA "XXXXX" RENAME TO xxxxx;

change table names:

ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;

change column names:

ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

Calculate business days

Brute attempt to detect working time - Monday to Friday 8am-4pm:

if (date('N')<6 && date('G')>8 && date('G')<16) {
   // we have a working time (or check for holidays)
}

How to install mongoDB on windows?

1. Download MongoDB

2. Install MongoDB

3. Create the required folders:

"C:\MongoDB_2_6_Standard\bin\data\db"
"C:\MongoDB_2_6_Standard\logs"
"C:\MongoDB_2_6_Standard\etc"

NOTE: If the directories do not exist, mongod.exe will not start.

4. Create a simple configuration file:

systemLog:
    destination: file
    path: C:\MongoDB_2_6_Standard\logs\mongo.log
    logAppend: true
net:
    bindIp: 127.0.0.1
    port: 27017

More info about how to create a configuration file: http://docs.mongodb.org/manual/reference/configuration-options/

5. Install MongoDB as a Windows Service (this way it will start automatically when you reboot your computer)

Run cmd with administrator privilegies, and enter the following commands:

"C:\MongoDB_2_6_Standard\bin\mongod.exe" --config "C:\MongoDB_2_6_Standard\etc\mongodb.conf" --dbpath c:\MongoDB_2_6_Standard\bin\data\db --directoryperdb --install

6. Start the MongoDB Windows Service

net start MongoDB

7. Connect to MongoDB via shell/cmd for testing

C:\MongoDB_2_6_Standard\bin\mongo.exe

NOTE: http://docs.mongodb.org/manual/tutorial/getting-started-with-the-mongo-shell/

8. That's it! You are done. :)

9. Uninstall/remove the MongoDB Windows Service (if you messed up something)

"C:\MongoDB_2_6_Standard\bin\mongod.exe" --remove

jQuery: checking if the value of a field is null (empty)

jquery provides val() function and not value(). You can check empty string using jquery

if($('#person_data[document_type]').val() != ''){}

How to get calendar Quarter from a date in TSQL

Assuming field data type INT and field name "mydate". In the OP question, the INT date values when converted to string are ISO date literals.

select DatePart(QUARTER, cast(cast(mydate as char(8)) as date))

You can use datetime if using older server version.

ng-change not working on a text input

Maybe you can try something like this:

Using a directive

directive('watchChange', function() {
    return {
        scope: {
            onchange: '&watchChange'
        },
        link: function(scope, element, attrs) {
            element.on('input', function() {
                scope.onchange();
            });
        }
    };
});

http://jsfiddle.net/H2EAB/

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

Is there a way to return a list of all the image file names from a folder using only Javascript?

Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:

The file name is okay to go into the href attribute, but the $(this).attr("href") use the text of the <a href='full/file/name' > Split file name </a>

So the $(data).find("a:contains(.jpg)") is not able to detect the extension.

I hope this is useful

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

jQuery: find element by text

The following jQuery selects div nodes that contain text but have no children, which are the leaf nodes of the DOM tree.

_x000D_
_x000D_
$('div:contains("test"):not(:has(*))').css('background-color', 'red');
_x000D_
<div>div1_x000D_
<div>This is a test, nested in div1</div>_x000D_
<div>Nested in div1<div>_x000D_
</div>_x000D_
<div>div2 test_x000D_
<div>This is another test, nested in div2</div>_x000D_
<div>Nested in div2</div>_x000D_
</div>_x000D_
<div>_x000D_
div3_x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Select 2 columns in one and combine them

select column1 || ' ' || column2 as whole_name FROM tablename;

Here || is the concat operator used for concatenating them to single column and ('') inside || used for space between two columns.

How to call a View Controller programmatically?

Import the view controller class which you want to show and use the following code

KartViewController *viewKart = [[KartViewController alloc]initWithNibName:@"KartViewController" bundle:nil];
[self presentViewController:viewKart animated:YES completion:nil];

Calling a user defined function in jQuery

_x000D_
_x000D_
function hello(){_x000D_
    console.log("hello")_x000D_
}_x000D_
$('#event-on-keyup').keyup(function(){_x000D_
    hello()_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>_x000D_
<input type="text" id="event-on-keyup">
_x000D_
_x000D_
_x000D_

How to set a default value with Html.TextBoxFor?

Try this also, that is remove new { } and replace it with string.

<%: Html.TextBoxFor(x => x.Age,"0") %>

Connecting to SQL Server Express - What is my server name?

Sometimes none of these would work for me. So I used to create a new web project in VS and select Authorization as "Individual User Accounts". I believe this work with some higher version of .NET Framework or something. But when you do this it will have your connection details. Mostly something like this

(LocalDb)\MSSQLLocalDB

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

Your error is because you have:

     JOIN user ON article.author_id = user.id
LEFT JOIN user ON article.modified_by = user.id

You have two instances of the same table, but the database can't determine which is which. To fix this, you need to use table aliases:

     JOIN USER u ON article.author_id = u.id
LEFT JOIN USER u2 ON article.modified_by = u2.id

It's good habit to always alias your tables, unless you like writing the full table name all the time when you don't have situations like these.

The next issues to address will be:

SELECT article.* , section.title, category.title, user.name, user.name

1) Never use SELECT * - always spell out the columns you want, even if it is the entire table. Read this SO Question to understand why.

2) You'll get ambiguous column errors relating to the user.name columns because again, the database can't tell which table instance to pull data from. Using table aliases fixes the issue:

SELECT article.* , section.title, category.title, u.name, u2.name

Adding dictionaries together, Python

dic0.update(dic1)

Note this doesn't actually return the combined dictionary, it just mutates dic0.

Is it possible to create static classes in PHP (like in C#)?

you can have those "static"-like classes. but i suppose, that something really important is missing: in php you don't have an app-cycle, so you won't get a real static (or singleton) in your whole application...

see Singleton in PHP

Setting Timeout Value For .NET Web Service

Try setting the timeout value in your web service proxy class:

WebReference.ProxyClass myProxy = new WebReference.ProxyClass();
myProxy.Timeout = 100000; //in milliseconds, e.g. 100 seconds

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

Is there a way to access the "previous row" value in a SELECT statement?

The selected answer will only work if there are no gaps in the sequence. However if you are using an autogenerated id, there are likely to be gaps in the sequence due to inserts that were rolled back.

This method should work if you have gaps

declare @temp (value int, primaryKey int, tempid int identity)
insert value, primarykey from mytable order by  primarykey

select t1.value - t2.value from @temp  t1
join @temp  t2 
on t1.tempid = t2.tempid - 1

Renaming part of a filename

Something like this will do it. The for loop may need to be modified depending on which filenames you wish to capture.

for fspec1 in DET01-ABC-5_50-*.dat ; do
    fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
    mv ${fspec1} ${fspec2}
done

You should always test these scripts on copies of your data, by the way, and in totally different directories.

How to visualize an XML schema?

Grid-ML Schema Viewer is great for searching and visualizing XML Schemas: https://gridml.com/xml-schema-viewer. I find it better than other tools when it comes to large schemas or when browsing through a diagram is not feasible. The tool also allows you to copy the XPath or JSON path of the selection item.

Grid-ML Schema Search Screen

Difference between a View's Padding and Margin

Sometimes you can achieve the same result by playing only with padding OR margin. Example :

Say View X contains view Y (aka : View Y is inside View X).

-View Y with Margin=30 OR View X with Padding=30 will achieve the same result: View Y will have an offset of 30.

Python Checking a string's first and last character

You are testing against the string minus the last character:

>>> '"xxx"'[:-1]
'"xxx'

Note how the last character, the ", is not part of the output of the slice.

I think you wanted just to test against the last character; use [-1:] to slice for just the last element.

However, there is no need to slice here; just use str.startswith() and str.endswith() directly.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

Matplotlib: ValueError: x and y must have same first dimension

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

The Best way is to create a user for your application and assign the permissions that are suitable for that user. Dont use 'NT AUTHORITY\NETWORK SERVICE' as your user it has its own vulnerability and it is a user that has permissions to so many things on the OS level. Stay away from this built in user.

Hibernate: best practice to pull all lazy collections

Use Hibernate.initialize() within @Transactional to initialize lazy objects.

 start Transaction 
      Hibernate.initialize(entity.getAddresses());
      Hibernate.initialize(entity.getPersons());
 end Transaction 

Now out side of the Transaction you are able to get lazy objects.

entity.getAddresses().size();
entity.getPersons().size();

How do I test if a string is empty in Objective-C?

It is working as charm for me

If the NSString is s

if ([s isKindOfClass:[NSNull class]] || s == nil || [s isEqualToString:@""]) {

    NSLog(@"s is empty");

} else {

    NSLog(@"s containing %@", s);

}

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

Order of execution of tests in TestNG

Piggy backing off of user1927494's answer, In case you want to run a single test before all others, you can do this:

@Test()
public void testOrderDoesntMatter_1() {
}

@Test(priority=-1)
public void testToRunFirst() {
}

@Test()
public void testOrderDoesntMatter_2() {
}

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


In Chrome or Opera, open a new tab and navigate to chrome://view-http-cache/

Click on whichever file you want to view. You should then see a page with a bunch of text and numbers. Copy all the text on that page. Paste it in the text box below.

Press "Go". The cached data will appear in the Results section below.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

Just add this line of code in your build.gradle file and it will work.

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

Also add these below line if above did not work at all.

compile 'com.google.android.gms:play-services:+'
compile ('org.apache.httpcomponents:httpmime:4.2.6'){
    exclude module: 'httpclient'
}
compile 'org.apache.httpcomponents:httpclient:4.2.6'

compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'

how to kill the tty in unix

The simplest way is with the pkill command. In your case:

pkill -9 -t pts/6
pkill -9 -t pts/9
pkill -9 -t pts/10

Regarding tty sessions, the commands below are always useful:

w - shows active terminal sessions

tty - shows your current terminal session (so you won't close it by accident)

last | grep logged - shows currently logged users

Sometimes we want to close all sessions of an idle user (ie. when connections are lost abruptly).

pkill -u username - kills all sessions of 'username' user.

And sometimes when we want to kill all our own sessions except the current one, so I made a script for it. There are some cosmetics and some interactivity (to avoid accidental running on the script).

#!/bin/bash
MYUSER=`whoami`
MYSESSION=`tty | cut -d"/" -f3-`
OTHERSESSIONS=`w $MYUSER | grep "^$MYUSER" | grep -v "$MYSESSION" | cut -d" " -f2`
printf "\e[33mCurrent session\e[0m: $MYUSER[$MYSESSION]\n"

if [[ ! -z $OTHERSESSIONS ]]; then
  printf "\e[33mOther sessions:\e[0m\n"
  w $MYUSER | egrep "LOGIN@|^$MYUSER" | grep -v "$MYSESSION" | column -t
  echo ----------
  read -p "Do you want to force close all your other sessions? [Y]Yes/[N]No: " answer
  answer=`echo $answer | tr A-Z a-z`
  confirm=("y" "yes")

  if [[ "${confirm[@]}" =~ "$answer" ]]; then
  for SESSION in $OTHERSESSIONS
    do
         pkill -9 -t $SESSION
         echo Session $SESSION closed.
    done
  fi
else
        echo "There are no other sessions for the user '$MYUSER'".
fi

Get client IP address via third party web service

    $.ajax({
        url: '//freegeoip.net/json/',
        type: 'POST',
        dataType: 'jsonp',
        success: function(location) {
            alert(location.ip);
        }
    });

This will work https too

Remove composer

curl -sS https://getcomposer.org/installer | sudo php
sudo mv composer.phar /usr/local/bin/composer
export PATH="$HOME/.composer/vendor/bin:$PATH"

If you have installed by this way simply

Delete composer.phar from where you've putted it.

In this case path will be /usr/local/bin/composer

Note: There is no need to delete the exported path.

How to reset Django admin password?

python manage.py changepassword username

Cannot set content-type to 'application/json' in jQuery.ajax

I found the solution for this problem here. Don't forget to allow verb OPTIONS on IIS app service handler.

Works fine. Thank you André Pedroso. :-)

Programmatically register a broadcast receiver

It is best practice to always supply the permission when registering the receiver, otherwise you will receive for any application that sends a matching intent. This can allow malicious apps to broadcast to your receiver.

Regex to validate password strength

Another solution:

import re

passwordRegex = re.compile(r'''(
    ^(?=.*[A-Z].*[A-Z])                # at least two capital letters
    (?=.*[!@#$&*])                     # at least one of these special c-er
    (?=.*[0-9].*[0-9])                 # at least two numeric digits
    (?=.*[a-z].*[a-z].*[a-z])          # at least three lower case letters
    .{8,}                              # at least 8 total digits
    $
    )''', re.VERBOSE)

def userInputPasswordCheck():
    print('Enter a potential password:')
    while True:
        m = input()
        mo = passwordRegex.search(m) 
        if (not mo):
           print('''
Your password should have at least one special charachter,
two digits, two uppercase and three lowercase charachter. Length: 8+ ch-ers.

Enter another password:''')          
        else:
           print('Password is strong')
           return
userInputPasswordCheck()

Convert Data URI to File then append to FormData

My preferred way is canvas.toBlob()

But anyhow here is yet another way to convert base64 to a blob using fetch ^^,

_x000D_
_x000D_
var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="_x000D_
_x000D_
fetch(url)_x000D_
.then(res => res.blob())_x000D_
.then(blob => {_x000D_
  var fd = new FormData()_x000D_
  fd.append('image', blob, 'filename')_x000D_
  _x000D_
  console.log(blob)_x000D_
_x000D_
  // Upload_x000D_
  // fetch('upload', {method: 'POST', body: fd})_x000D_
})
_x000D_
_x000D_
_x000D_

How to convert milliseconds to "hh:mm:ss" format?

For Kotlin

val hours = String.format("%02d", TimeUnit.MILLISECONDS.toHours(milSecs))
val minutes = String.format("%02d",
                        TimeUnit.MILLISECONDS.toMinutes(milSecs) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(milSecs)))
val seconds = String.format("%02d",
                        TimeUnit.MILLISECONDS.toSeconds(milSecs) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milSecs)))

where, milSecs is milliseconds

Set Date in a single line

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…or…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.

The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.

LocalDate

This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId) is necessary to determine a date.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

Or use the enum, Month.

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

Convert

Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.

In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0.

We also need to specify a time zone, as the date varies by time zone.

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

An Instant is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant to static method on Date to convert.

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

UIButton: set image for selected-highlighted state

In Swift 3.x, you can set highlighted image when button is selected in the following way:

// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal) 

// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)

// Selected state
button.setImage(UIImage(named: "selectedImage"), for:  .selected)

// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"), 
                for:  UIControlState.selected.union(.highlighted))

How to install php-curl in Ubuntu 16.04

This worked for me.

sudo apt-get install php-curl

How do you create nested dict in Python?

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

LINQ Inner-Join vs Left-Join

Here's a good blog post that's just been posted by Fabrice (author of LINQ in Action) which covers the material in the question that I asked. I'm putting it here for reference as readers of the question will find this useful.

Converting LINQ queries from query syntax to method/operator syntax

X-Frame-Options Allow-From multiple domains

As per the MDN Specifications, X-Frame-Options: ALLOW-FROM is not supported in Chrome and support is unknown in Edge and Opera.

Content-Security-Policy: frame-ancestors overrides X-Frame-Options (as per this W3 spec), but frame-ancestors has limited compatibility. As per these MDN Specs, it's not supported in IE or Edge.

MVC [HttpPost/HttpGet] for Action

You cant combine this to attributes.

But you can put both on one action method but you can encapsulate your logic into a other method and call this method from both actions.

The ActionName Attribute allows to have 2 ActionMethods with the same name.

[HttpGet]
public ActionResult MyMethod()
{
    return MyMethodHandler();
}

[HttpPost]
[ActionName("MyMethod")]
public ActionResult MyMethodPost()
{
    return MyMethodHandler();
}

private ActionResult MyMethodHandler()
{
    // handle the get or post request
    return View("MyMethod");
}

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

How to restart counting from 1 after erasing table in MS Access?

You can use:

CurrentDb.Execute "ALTER TABLE yourTable ALTER COLUMN myID COUNTER(1,1)"

I hope you have no relationships that use this table, I hope it is empty, and I hope you understand that all you can (mostly) rely on an autonumber to be is unique. You can get gaps, jumps, very large or even negative numbers, depending on the circumstances. If your autonumber means something, you have a major problem waiting to happen.

Deleting an object in java?

//Just use a List
//create the list
public final List<Object> myObjects;

//instantiate the list
myObjects = new ArrayList<Object>();

//add objects to the list
Object object = myObject;
myObjects.add(object);

//remove the object calling this method if you have more than 1 objects still works with 1
//object too.

private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

Getting started with Haskell

To add on others' answers - there is one useful that will help you when coding (for example when solving project Euler problems): Hoogle. You can use either the command line interface or the web interface.

Command Line

After you installed the Haskell platform be sure to cabal install hoogle

Hoogle usage example:

You have a function f x = 3 * x + 1 and you want to apply it on (5 :: Int), then apply it on the result and on that result and so on and get an infinite list of those values. You suspect there might already exist a function to assist you (not specifically for your f though).

That function would be of type (a -> a) -> a -> [a] if it takes f 5 or a -> (a -> a) -> [a] if it takes 5 f (we assume the function is for general types and not just Ints)

$ hoogle "a -> (a -> a) -> [a]"
Prelude iterate :: (a -> a) -> a -> [a]

yep, the function you need already exists and it's called iterate. you use it by iterate func 5!

Web interface

The result for the same example can be found here.

Why do Twitter Bootstrap tables always have 100% width?

Bootstrap 3:

Why fight it? Why not simply control your table width using the bootstrap grid?

<div class="row">
    <div class="col-sm-6">
        <table></table>
    </div>
</div>

This will create a table that is half (6 out of 12) of the width of the containing element.

I sometimes use inline styles as per the other answers, but it is discouraged.

Bootstrap 4:

Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

<table class="w-50"></table>

Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

How would I check a string for a certain letter in Python?

in keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.

In this case string is nothing but a list of characters:

dog = "xdasds"
if "x" in dog:
     print "Yes!"

You can check a substring too:

>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>> 
>>> 
>>> 'xa' in "xdasds"
False

Think collection:

>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>> 

You can also test the set membership over user defined classes.

For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.

Parsing JSON string in Java

Firstly there is an extra } after every array object.

Secondly "geodata" is a JSONArray. So instead of JSONObject geoObject = jObject.getJSONObject("geodata"); you have to get it as JSONArray geoObject = jObject.getJSONArray("geodata");

Once you have the JSONArray you can fetch each entry in the JSONArray using geoObject.get(<index>).

I am using org.codehaus.jettison.json.

How do I run Google Chrome as root?

Just replace following line

exec -a "$0" "$HERE/chrome" "$@"

with

exec -a "$0" "$HERE/chrome" "$@" --user-data-dir 

all things will be right.

Regex empty string or email

I prefer /^\s+$|^$/gi to match empty and empty spaces.

_x000D_
_x000D_
console.log("  ".match(/^\s+$|^$/gi));_x000D_
console.log("".match(/^\s+$|^$/gi));
_x000D_
_x000D_
_x000D_

How to close form

You need the actual instance of the WindowSettings that's open, not a new one.

Currently, you are creating a new instance of WindowSettings and calling Close on that. That doesn't do anything because that new instance never has been shown.

Instead, when showing DialogSettingsCancel set the current instance of WindowSettings as the parent.

Something like this:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel();
    dialogSettingsCancel.OwningWindowSettings = this;
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

public WindowSettings OwningWindowSettings { get; set; }

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    if(OwningWindowSettings != null)
        OwningWindowSettings.Close();
}

This approach takes into account, that a DialogSettingsCancel could potentially be opened without a WindowsSettings as parent.

If the two are always connected, you should instead use a constructor parameter:

In WindowSettings:

private void showDialogSettings_Click(object sender, EventArgs e)
{
    var dialogSettingsCancel = new DialogSettingsCancel(this);
    dialogSettingsCancel.Show();
}

In DialogSettingsCancel:

WindowSettings _owningWindowSettings;

public DialogSettingsCancel(WindowSettings owningWindowSettings)
{
    if(owningWindowSettings == null)
        throw new ArgumentNullException("owningWindowSettings");

    _owningWindowSettings = owningWindowSettings;
}

private void button1_Click(object sender, EventArgs e)
{
    this.Close();
    _owningWindowSettings.Close();
}

How to navigate to a directory in C:\ with Cygwin?

You already accepted an answer, but I just thought I'd mention that the following also works in Cygwin:

cd "C:\Foo"

I think the cd /cygdrive/c method is better, but sometimes it's useful to know that you can do this too.

MySql Error: Can't update table in stored function/trigger because it is already used by statement which invoked this stored function/trigger

You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.

However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.

If you had a row named full_brand_name and you wanted to use the first two letters as a short name in the field small_name you could use:

CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
  SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END

How to get the current plugin directory in WordPress?

$full_path = WP_PLUGIN_URL . '/'. str_replace( basename( __FILE__ ), "", plugin_basename(__FILE__) );
  • WP_PLUGIN_URL – the url of the plugins directory
  • WP_PLUGIN_DIR – the server path to the plugins directory

This link may help: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories.

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    <head>_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    _x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
    </head>_x000D_
    _x000D_
    _x000D_
    <body>_x000D_
    _x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    _x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How can I programmatically get the MAC address of an iphone

A lot of these questions only address the Mac address. If you also require the IP address I just wrote this, may need some work but seems to work well on my machine...

- (NSString *)getLocalIPAddress
{
    NSArray *ipAddresses = [[NSHost currentHost] addresses];
    NSArray *sortedIPAddresses = [ipAddresses sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.allowsFloats = NO;

    for (NSString *potentialIPAddress in sortedIPAddresses)
    {
        if ([potentialIPAddress isEqualToString:@"127.0.0.1"]) {
            continue;
        }

        NSArray *ipParts = [potentialIPAddress componentsSeparatedByString:@"."];

        BOOL isMatch = YES;

        for (NSString *ipPart in ipParts) {
            if (![numberFormatter numberFromString:ipPart]) {
                isMatch = NO;
                break;
            }
        }
        if (isMatch) {
            return potentialIPAddress;
        }
    }

    // No IP found
    return @"?.?.?.?";
}

HTML how to clear input using javascript?

You could use a placeholder because it does it for you, but for old browsers that don't support placeholder, try this:

<script>
function clearThis(target) {
    if (target.value == "[email protected]") {
        target.value = "";
    }
}
function replace(target) {
    if (target.value == "" || target.value == null) {
        target.value == "[email protected]";
    }
}
</script>
<input type="text" name="email" value="[email protected]" size="x" onfocus="clearThis(this)" onblur="replace(this)" />

CODE EXPLAINED: When the text box has focus, clear the value. When text box is not focused AND when the box is blank, replace the value.

I hope that works, I have been having the same issue, but then I tried this and it worked for me.

Git commit -a "untracked files"?

If you are having problems with untracked files, this 3-line script will help you.

git rm -r --cached .
git add -A
git commit -am 'fix'

Then just git push

How can I list the contents of a directory in Python?

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

How to compare if two structs, slices or maps are equal?

Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb

func compare(a, b T) bool {
  if &a == &b {
    return true
  }
  if a.X != b.X || a.Y != b.Y {
    return false
  }
  if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
    return false
  }
  for i, v := range a.Z {
    if b.Z[i] != v {
      return false
    }
  }
  for k, v := range a.M {
    if b.M[k] != v {
      return false
    }
  }
  return true
}

what is the difference between GROUP BY and ORDER BY in sql

They have totally different meaning and aren't really related at all.

ORDER BY allows you to sort the result set according to different criteria, such as first sort by name from a-z, then sort by the price highest to lowest.

(ORDER BY name, price DESC)

GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on those groups. You could for instance select all employees, group them by their workplace location and calculate the average salary of all employees of each workplace location.

MVC 3: How to render a view without its layout page when loaded via ajax?

I prefer, and use, your #1 option. I don't like #2 because to me View() implies you are returning an entire page. It should be a fully fleshed out and valid HTML page once the view engine is done with it. PartialView() was created to return arbitrary chunks of HTML.

I don't think it's a big deal to have a view that just calls a partial. It's still DRY, and allows you to use the logic of the partial in two scenarios.

Many people dislike fragmenting their action's call paths with Request.IsAjaxRequest(), and I can appreciate that. But IMO, if all you are doing is deciding whether to call View() or PartialView() then the branch is not a big deal and is easy to maintain (and test). If you find yourself using IsAjaxRequest() to determine large portions of how your action plays out, then making a separate AJAX action is probably better.

What is the __del__ method, How to call it?

The __del__ method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:

del obj

The reason being that del just decrements the reference count by one. If something else has a reference to the object, __del__ won't get called.

There are a few caveats to using __del__ though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.

See the python documentation on __del__ methods.

One other thing to note: __del__ methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__ method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.

How to change the interval time on bootstrap carousel?

You can use the options when initializing the carousel, like this:

// interval is in milliseconds. 1000 = 1 second -> so 1000 * 10 = 10 seconds
$('.carousel').carousel({
  interval: 1000 * 10
});

or you can use the interval attribute directly on the HTML tag, like this:

<div class="carousel" data-interval="10000">

The advantage of the latter approach is that you do not have to write any JS for it - while the advantage of the former is that you can compute the interval and initialize it with a variable value at run time.