Programs & Examples On #Atomicreference

When to use AtomicReference in Java?

Another simple example is to do a safe-thread modification in a session object.

public PlayerScore getHighScore() {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    return holder.get();
}

public void updateHighScore(PlayerScore newScore) {
    ServletContext ctx = getServletConfig().getServletContext();
    AtomicReference<PlayerScore> holder 
        = (AtomicReference<PlayerScore>) ctx.getAttribute("highScore");
    while (true) {
        HighScore old = holder.get();
        if (old.score >= newScore.score)
            break;
        else if (holder.compareAndSet(old, newScore))
            break;
    } 
}

Source: http://www.ibm.com/developerworks/library/j-jtp09238/index.html

Subscripts in plots in R

expression is your friend:

plot(1,1, main=expression('title'^2))  #superscript
plot(1,1, main=expression('title'[2])) #subscript

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

display html page with node.js

This did the trick for me:

var express = require('express'),
app = express(); 
app.use('/', express.static(__dirname + '/'));
app.listen(8080);

How can I get the external SD card path for Android 4.0+?

I am sure this code will surely resolve your issues...This is working fine for me...\

try {
            File mountFile = new File("/proc/mounts");
            usbFoundCount=0;
            sdcardFoundCount=0;
            if(mountFile.exists())
             {
                Scanner usbscanner = new Scanner(mountFile);
                while (usbscanner.hasNext()) {
                    String line = usbscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/usbcard1")) {
                        usbFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/usbcard1" );
                    }
            }
         }
            if(mountFile.exists()){
                Scanner sdcardscanner = new Scanner(mountFile);
                while (sdcardscanner.hasNext()) {
                    String line = sdcardscanner.nextLine();
                    if (line.startsWith("/dev/fuse /storage/sdcard1")) {
                        sdcardFoundCount=1;
                        Log.i("-----USB--------","USB Connected and properly mounted---/dev/fuse /storage/sdcard1" );
                    }
            }
         }
            if(usbFoundCount==1)
            {
                Toast.makeText(context,"USB Connected and properly mounted", 7000).show();
                Log.i("-----USB--------","USB Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"USB not found!!!!", 7000).show();
                Log.i("-----USB--------","USB not found!!!!" );

            }
            if(sdcardFoundCount==1)
            {
                Toast.makeText(context,"SDCard Connected and properly mounted", 7000).show();
                Log.i("-----SDCard--------","SDCard Connected and properly mounted" );
            }
            else
            {
                Toast.makeText(context,"SDCard not found!!!!", 7000).show();
                Log.i("-----SDCard--------","SDCard not found!!!!" );

            }
        }catch (Exception e) {
            e.printStackTrace();
        } 

How do I get the collection of Model State Errors in ASP.NET MVC?

Putting together several answers from above, this is what I ended up using:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List<string> that contains each error message. From there, it's easy to do what you want with that list.

enter image description here

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

Show SOME invisible/whitespace characters in Eclipse

I use Checkstlye plugin for such a purpose. In Checkstyle configuration, I add special regexp rules to detect lines with TABs and then mark such lines as checkstyle ERROR, which is clearly visible in Eclipse editor. Works fine.

Can't connect to Postgresql on port 5432

Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

How do I use a custom Serializer with Jackson?

If your only requirement in your custom serializer is to skip serializing the name field of User, mark it as transient. Jackson will not serialize or deserialize transient fields.

[ see also: Why does Java have transient fields? ]

SyntaxError: expected expression, got '<'

I had this same error when I migrated a Wordpress site to another server. The URL in the header for my js scripts was still pointing to the old server and domain name.

Once I updated the domain name, the error went away.

Install numpy on python3.3 - Install pip for python3

I'm on Ubuntu 15.04. This seemed to work:

$ sudo pip3 install numpy

On RHEL this worked:

$ sudo python3 -m pip install numpy

Storing sex (gender) in database

There is already an ISO standard for this; no need to invent your own scheme:

http://en.wikipedia.org/wiki/ISO_5218

Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

MySql server startup error 'The server quit without updating PID file '

The solution that worked for me was here: https://serverfault.com/questions/334284/cant-create-pid-file-on-mysql-server-permission-denied

Changing some of my permissions seemed to do the trick. I'm running a Mid-2012 Macbook Air with OS X 10.8.2 and mysql was installed with homebrew.

chmod 0755 /var
chown root:wheel /var/tmp
sudo chmod 0771 /usr/local/var/mysql/*

How to center horizontally div inside parent div

You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:

<div id='parent' style='width: 100%;'>
   <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>

How to determine when a Git branch was created?

very simple

In the address bar of your web browser, type the following URL and press the Enter key to retrieve information of a GitHub repository.

https://api.github.com/repos/{:owner}/{:repository}

Note! In the URL above, replace the {:owner} and {:repository} parts with the values that can be found in the URL of the GitHub repository for which you want to know the creation date. For example, if the URL of the repository is https://github.com/ArthurGareginyan/batch-rename/, then the URL of it’s information will be https://api.github.com/repos/ArthurGareginyan/batch-rename.

output:

image

Convert JS object to JSON string

you can use native stringify function like this

_x000D_
_x000D_
const j={ "name": "binchen" }_x000D_
_x000D_
/** convert json to string */_x000D_
const jsonString = JSON.stringify(j)_x000D_
_x000D_
console.log(jsonString) // {"name":"binchen"}
_x000D_
_x000D_
_x000D_

Remove array element based on object property

Using lodash library it is simple as this

_.remove(myArray , { field: 'money' });

Getting time and date from timestamp with php

$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];

How do you write to a folder on an SD card in Android?

File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...

Convert multidimensional array into single array

none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as @AlienWebguy already did, but with tiny difference.

function nestedToSingle(array $array)
{
    $singleDimArray = [];

    foreach ($array as $item) {

        if (is_array($item)) {
            $singleDimArray = array_merge($singleDimArray, nestedToSingle($item));

        } else {
            $singleDimArray[] = $item;
        }
    }

    return $singleDimArray;
}

test example

$array = [
        'first',
        'second',
        [
            'third',
            'fourth',
        ],
        'fifth',
        [
            'sixth',
            [
                'seventh',
                'eighth',
                [
                    'ninth',
                    [
                        [
                            'tenth'
                        ]
                    ]
                ],
                'eleventh'
            ]
        ],
        'twelfth'
    ];

    $array = nestedToSingle($array);
    print_r($array);

    //output
    array:12 [
        0 => "first"
        1 => "second"
        2 => "third"
        3 => "fourth"
        4 => "fifth"
        5 => "sixth"
        6 => "seventh"
        7 => "eighth"
        8 => "ninth"
        9 => "tenth"
        10 => "eleventh"
        11 => "twelfth"
   ]

Valid characters in a Java class name

Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

From the official Java Tutorial.

CSV with comma or semicolon?

1.> Change File format to .CSV (semicolon delimited)

To achieve the desired result we need to temporary change the delimiter setting in the Excel Options:

Move to File -> Options -> Advanced -> Editing Section

Uncheck the “Use system separators” setting and put a comma in the “Decimal Separator” field.

Now save the file in the .CSV format and it will be saved in the semicolon delimited format.

How can you undo the last git add?

You cannot undo the latest git add, but you can undo all adds since the last commit. git reset without a commit argument resets the index (unstages staged changes):

git reset

horizontal scrollbar on top and bottom of table

Without JQuery (2017)

Because you might not need JQuery, here is a working Vanilla JS version based on @StanleyH answer:

_x000D_
_x000D_
var wrapper1 = document.getElementById('wrapper1');_x000D_
var wrapper2 = document.getElementById('wrapper2');_x000D_
wrapper1.onscroll = function() {_x000D_
  wrapper2.scrollLeft = wrapper1.scrollLeft;_x000D_
};_x000D_
wrapper2.onscroll = function() {_x000D_
  wrapper1.scrollLeft = wrapper2.scrollLeft;_x000D_
};
_x000D_
#wrapper1, #wrapper2{width: 300px; border: none 0px RED;_x000D_
overflow-x: scroll; overflow-y:hidden;}_x000D_
#wrapper1{height: 20px; }_x000D_
#wrapper2{height: 100px; }_x000D_
#div1 {width:1000px; height: 20px; }_x000D_
#div2 {width:1000px; height: 100px; background-color: #88FF88;_x000D_
overflow: auto;}
_x000D_
<div id="wrapper1">_x000D_
    <div id="div1">_x000D_
    </div>_x000D_
</div>_x000D_
<div id="wrapper2">_x000D_
    <div id="div2">_x000D_
    aaaa bbbb cccc dddd aaaa bbbb cccc _x000D_
    dddd aaaa bbbb cccc dddd aaaa bbbb _x000D_
    cccc dddd aaaa bbbb cccc dddd aaaa _x000D_
    bbbb cccc dddd aaaa bbbb cccc dddd_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

Passing parameters to click() & bind() event in jquery?

From where would you get these values? If they're from the button itself, you could just do

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}

C++ templates that accept only certain types

There is no keyword for such type checks, but you can put some code in that will at least fail in an orderly fashion:

(1) If you want a function template to only accept parameters of a certain base class X, assign it to a X reference in your function. (2) If you want to accept functions but not primitives or vice versa, or you want to filter classes in other ways, call a (empty) template helper function within your function that's only defined for the classes you want to accept.

You can use (1) and (2) also in member functions of a class to force these type checks on the entire class.

You can probably put it into some smart Macro to ease your pain. :)

How do you initialise a dynamic array in C++?

Since c++11 we could use list initialization:

char* c = new char[length]{};

For an aggregate type, then aggregate initialization will be performed, which has the same effect like char c[2] = {};.

Java character array initializer

You initialized and declared your String to "Hi there", initialized your char[] array with the correct size, and you began a loop over the length of the array which prints an empty string combined with a given element being looked at in the array. At which point did you factor in the functionality to put in the characters from the String into the array?

When you attempt to print each element in the array, you print an empty String, since you're adding 'nothing' to an empty String, and since there was no functionality to add in the characters from the input String to the array. You have everything around it correctly implemented, though. This is the code that should go after you initialize the array, but before the for-loop that iterates over the array to print out the elements.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
}

It would be more efficient to just combine the for-loops to print each character out right after you put it into the array.

for (int count = 0; count < ini.length(); count++) {
  array[count] = ini.charAt(count);
  System.out.println(array[count]);
}

At this point, you're probably wondering why even put it in a char[] when I can just print them using the reference to the String object ini itself.

String ini = "Hi there";

for (int count = 0; count < ini.length(); count++) {
   System.out.println(ini.charAt(count));
}

Definitely read about Java Strings. They're fascinating and work pretty well, in my opinion. Here's a decent link: https://www.javatpoint.com/java-string

String ini = "Hi there"; // stored in String constant pool

is stored differently in memory than

String ini = new String("Hi there"); // stored in heap memory and String constant pool

, which is stored differently than

char[] inichar = new char[]{"H", "i", " ", "t", "h", "e", "r", "e"};
String ini = new String(inichar); // converts from char array to string

.

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How can I make a time delay in Python?

While everyone else has suggested the de facto time module, I thought I'd share a different method using matplotlib's pyplot function, pause.

An example

from matplotlib import pyplot as plt
plt.pause(5)    # Pauses the program for 5 seconds

Typically this is used to prevent the plot from disappearing as soon as it is plotted or to make crude animations.

This would save you an import if you already have matplotlib imported.

Center Contents of Bootstrap row container

For Bootstrap 4, use the below code:

<div class="mx-auto" style="width: 200px;">
  Centered element
</div>

Ref: https://getbootstrap.com/docs/4.0/utilities/spacing/#horizontal-centering

Bootstrap 3 - Responsive mp4-video

Tip for MULTIPLE VIDEOS on a page: I recently solved an issue with no mp4 playback in Chrome or Firefox (played fine in IE) in a page with 16 videos in modals (bootstrap 3) after discovering the frame rates of all the videos must be identical. I had 6 videos at 25fps and 12 at 29.97fps... after rendering all to 25fps versions, everything runs smooth across all browsers.

Find size of an array in Perl

To find the size of an array use the scalar keyword:

print scalar @array;

To find out the last index of an array there is $# (Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#:

print "$#array+1";

Example:

my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";

Output:

3

3

VBA error 1004 - select method of range class failed

assylias and Head of Catering have already given your the reason why the error is occurring.

Now regarding what you are doing, from what I understand, you don't need to use Select at all

I guess you are doing this from VBA PowerPoint? If yes, then your code be rewritten as

Dim sourceXL As Object, sourceBook As Object
Dim sourceSheet As Object, sourceSheetSum As Object
Dim lRow As Long
Dim measName As Variant, partName As Variant
Dim filepath As String

filepath = CStr(FileDialog)

'~~> Establish an EXCEL application object
On Error Resume Next
Set sourceXL = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set sourceXL = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

Set sourceBook = sourceXL.Workbooks.Open(filepath)
Set sourceSheet = sourceBook.Sheets("Measurements")
Set sourceSheetSum = sourceBook.Sheets("Analysis Summary")

lRow = sourceSheetSum.Range("C" & sourceSheetSum.Rows.Count).End(xlUp).Row
measName = sourceSheetSum.Range("C3:C" & lRow)

lRow = sourceSheetSum.Range("D" & sourceSheetSum.Rows.Count).End(xlUp).Row
partName = sourceSheetSum.Range("D3:D" & lRow)

Change the jquery show()/hide() animation?

You can also use a fadeIn/FadeOut Combo, too....

$('.test').bind('click', function(){
    $('.div1').fadeIn(500); 
    $('.div2').fadeOut(500);
    $('.div3').fadeOut(500);
    return false;
});

Django request.GET

msg = request.GET.get('q','default')
if (msg == default):
    message = "YOU SUBMITTED NOTHING"
else: 
    message = "you submitted = %s" %msg"
return HttpResponse(message);

Duplicate Entire MySQL Database

I sometimes do a mysqldump and pipe the output into another mysql command to import it into a different database.

mysqldump --add-drop-table -u wordpress -p wordpress | mysql -u wordpress -p wordpress_backup

what's the differences between r and rb in fopen

use "rb" to open a binary file. Then the bytes of the file won't be encoded when you read them

Apache 13 permission denied in user's home directory

selinux is cause for that problem.....

TException: Error: TSocket: Could not connect to localhost:9160 (Permission denied [13]) To resolve it, you need to change an SELinux boolean value (which will automatically persist across reboots). You may also want to restart httpd to reset the proxy worker, although this isn't strictly required.

setsebool -P httpd_can_network_connect 1

or

(13) Permission Denied

Error 13 indicates a filesystem permissions problem. That is, Apache was denied access to a file or directory due to incorrect permissions. It does not, in general, imply a problem in the Apache configuration files.

In order to serve files, Apache must have the proper permission granted by the operating system to access those files. In particular, the User or Group specified in httpd.conf must be able to read all files that will be served and search the directory containing those files, along with all parent directories up to the root of the filesystem.

Typical permissions on a unix-like system for resources not owned by the User or Group specified in httpd.conf would be 644 -rw-r--r-- for ordinary files and 755 drwxr-x-r-x for directories or CGI scripts. You may also need to check extended permissions (such as SELinux permissions) on operating systems that support them.

An Example

Lets say that you received the Permission Denied error when accessing the file /usr/local/apache2/htdocs/foo/bar.html on a unix-like system.

First check the existing permissions on the file:

cd /usr/local/apache2/htdocs/foo ls -l bar.htm

Fix them if necessary:

chmod 644 bar.html

Then do the same for the directory and each parent directory (/usr/local/apache2/htdocs/foo, /usr/local/apache2/htdocs, /usr/local/apache2, /usr/local, /usr):

ls -la chmod +x . cd ..

repeat up to the root

On some systems, the utility namei can be used to help find permissions problems by listing the permissions along each component of the path:

namei -m /usr/local/apache2/htdocs/foo/bar.html

If all the standard permissions are correct and you still get a Permission Denied error, you should check for extended-permissions. For example you can use the command setenforce 0 to turn off SELinux and check to see if the problem goes away. If so, ls -alZ can be used to view SELinux permission and chcon to fix them.

In rare cases, this can be caused by other issues, such as a file permissions problem elsewhere in your apache2.conf file. For example, a WSGIScriptAlias directive not mapping to an actual file. The error message may not be accurate about which file was unreadable.

DO NOT set files or directories to mode 777, even "just to test", even if "it's just a test server". The purpose of a test server is to get things right in a safe environment, not to get away with doing it wrong. All it will tell you is if the problem is with files that actually exist.

Select Multiple Fields from List in Linq

Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:

var cats = listObject
    .Select(i => new { i.category_id, i.category_name })
    .Distinct()
    .OrderByDescending(i => i.category_name)
    .ToArray();

Since you (apparently) need to store it for later use, you could use the GroupBy operator:

Data[] cats = listObject
    .GroupBy(i => new { i.category_id, i.category_name })
    .OrderByDescending(g => g.Key.category_name)
    .Select(g => g.First())
    .ToArray();

How to sort by Date with DataTables jquery plugin?

I got solution after working whole day on it. It is little hacky solution Added span inside td tag

<td><span><%= item.StartICDate %></span></td>. 

Date format which Im using is dd/MM/YYYY. Tested in Datatables1.9.0

How does one convert a HashMap to a List in Java?

If you wanna maintain the same order in your list, say: your Map looks like:

map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")

and you want your list looks like

["msg1", "msg2", "msg3"]   // same order as the map

you will have to iterate through the Map:

// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)

List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
    list.add(entry.getKey(), entry.getValue());
}  

Is it possible to use Visual Studio on macOS?

Yes! You can use the new Visual Studio for Mac, which Microsoft launched in November.

Read about it here: https://msdn.microsoft.com/magazine/mt790182

Download a preview version here: https://www.visualstudio.com/vs/visual-studio-mac/

Read large files in Java

Yes. I also think that using read() with arguments like read(Char[], int init, int end) is a better way to read a such a large file (Eg : read(buffer,0,buffer.length))

And I also experienced the problem of missing values of using the BufferedReader instead of BufferedInputStreamReader for a binary data input stream. So, using the BufferedInputStreamReader is a much better in this like case.

How to reset all checkboxes using jQuery or pure JS?

I used something like that

$(yourSelector).find('input:checkbox').removeAttr('checked');

How can I get the last character in a string?

You should look at charAt function and take length of the string.

var b = 'I am a JavaScript hacker.';
console.log(b.charAt(b.length-1));

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

@Silverstorm

I had Hyperv installed and virtualization enabled in my BIOS.

But SOLUTION A didn't work for me.

However, SOLUTION B worked like a charm.

SOLUTION B (If Hyper-V feature is already enabled but doesn't work)

Enable Hypervisor with

bcdedit /set hypervisorlaunchtype auto Now restart the system and try again.

Use String.split() with multiple delimiters

You can use the regex "\W".This matches any non-word character.The required line would be:

String[] tokens=pdfName.split("\\W");

How to add colored border on cardview?

As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.

Add this if you haven't already

implementation 'com.google.android.material:material:1.0.0'

Now change to Cardview to MaterialCardView

<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"

app:strokeWidth="1dp"
app:strokeColor="@color/black">

Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight">

Apache and IIS side by side (both listening to port 80) on windows2003

For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80, e.g 8080 by setting the TCP port in the properties of each of its sites (including the default one).

In Apache, enable mod_proxy and mod_proxy_http, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.

<VirtualHost *:80>
    ServerName foo.bar
    ServerAlias *
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
</VirtualHost>

Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.

Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.

Error: Unfortunately you can't have non-Gradle Java modules and > Android-Gradle modules in one project

  1. Go to File -> Invalidate Caches/Restart.
  2. Close the project.
  3. Go to project folder and delete .idea folder.
  4. Delete YourProjectName.iml in project folder.
  5. Delete app.iml in app folder.
  6. Open Android studio -> open existing project, and then select your project.
  7. The Load Settings error and Unsupported modules detected error will be gone.

How to make a HTML Page in A4 paper size page(s)?

A4 size is 210x297mm

So you can set the HTML page to fit those sizes with CSS:

html,body{
    height:297mm;
    width:210mm;
}

How do I embed PHP code in JavaScript?

This is the bit of code you need at the top of your JavaScript file:

<?php
    header('Content-Type: text/javascript; charset=UTF-8');
?>

(function() {
    alert("hello world");
}) ();

Pandas get the most frequent values of a column

To get the n most frequent values, just subset .value_counts() and grab the index:

# get top 10 most frequent names
n = 10
dataframe['name'].value_counts()[:n].index.tolist()

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

check if a std::vector contains a certain object?

Checking if v contains the element x:

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}

ASP.NET MVC Global Variables

The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:

public static class GlobalVars
{
    private const string GlobalKey = "AllMyVars";

    static GlobalVars()
    {
        Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;

        if (table == null)
        {
            table = new Hashtable();
            HttpContext.Current.Application[GlobalKey] = table;
        }
    }

    public static Hashtable Vars
    {
        get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
    }

    public static IEnumerable<SomeClass> SomeCollection
    {
        get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
        set { WriteVar("SomeCollection", value); }
    }

    internal static DateTime SomeDate
    {
        get { return (DateTime)GetVar("SomeDate"); }
        set { WriteVar("SomeDate", value); }
    }

    private static object GetVar(string varName)
    {
        if (Vars.ContainsKey(varName))
        {
            return Vars[varName];
        }

        return null;
    }

    private static void WriteVar(string varName, object value)
    {
        if (value == null)
        {
            if (Vars.ContainsKey(varName))
            {
                Vars.Remove(varName);
            }
            return;
        }

        if (Vars[varName] == null)
        {
            Vars.Add(varName, value);
        }
        else
        {
            Vars[varName] = value;
        }
    }
}

Correct way to delete cookies server-side

Setting "expires" to a past date is the standard way to delete a cookie.

Your problem is probably because the date format is not conventional. IE probably expects GMT only.

MySQL ORDER BY multiple column ASC and DESC

group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1

Why is Visual Studio 2010 not able to find/open PDB files?

I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols

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

The for attribute shows that this label stands for related input field, or check box or radio button or any other data entering field associated with it. for example

<li>
    <label>{translate:blindcopy}</label>
    <a class="" href="#" title="{translate:savetemplate}" onclick="" ><i class="fa fa-list" class="button" ></i></a> &nbsp 
            <input type="text" id="BlindCopy" name="BlindCopy" class="splitblindcopy" />

</li>

How to validate numeric values which may contain dots or commas?

\d{1,2}[\,\.]{1}\d{1,2}

EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan

^[0-9]{1,2}([,.][0-9]{1,2})?$

How to change the URI (URL) for a remote Git repository?

An alternative approach is to rename the 'old' origin (in the example below I name it simply old-origin) and adding a new one. This might be the desired approach if you still want to be able to push to the old origin every now and then:

git remote rename origin old-origin
git remote add origin [email protected]>:<username>/<projectname>.git

And in case you need to push your local state to the new origin:

git push -u origin --all
git push -u origin --tags

XSLT string replace

I keep hitting this answer. But none of them list the easiest solution for xsltproc (and probably most XSLT 1.0 processors):

  1. Add the exslt strings name to the stylesheet, i.e.:
<xsl:stylesheet
  version="1.0"
  xmlns:str="http://exslt.org/strings"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  1. Then use it like:
<xsl:value-of select="str:replace(., ' ', '')"/>

Why is my Button text forced to ALL CAPS on Lollipop?

You could add android:textAllCaps="false" to the button.

The button text might be transformed to uppercase by your app's theme that applies to all buttons. Check themes / styles files for setting the attribute android:textAllCaps.

Problems with Android Fragment back stack

First of all thanks @Arvis for an eye opening explanation.

I prefer different solution to the accepted answer here for this problem. I don't like messing with overriding back behavior any more than absolutely necessary and when I've tried adding and removing fragments on my own without default back stack poping when back button is pressed I found my self in fragment hell :) If you .add f2 over f1 when you remove it f1 won't call any of callback methods like onResume, onStart etc. and that can be very unfortunate.

Anyhow this is how I do it:

Currently on display is only fragment f1.

f1 -> f2

Fragment2 f2 = new Fragment2();
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,f2).addToBackStack(null).commit();

nothing out of the ordinary here. Than in fragment f2 this code takes you to fragment f3.

f2 -> f3

Fragment3 f3 = new Fragment3();
getActivity().getSupportFragmentManager().popBackStack();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

I'm not sure by reading docs if this should work, this poping transaction method is said to be asynchronous, and maybe a better way would be to call popBackStackImmediate(). But as far I can tell on my devices it's working flawlessly.

The said alternative would be:

final FragmentActivity activity = getActivity();
activity.getSupportFragmentManager().popBackStackImmediate();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

Here there will actually be brief going back to f1 beofre moving on to f3, so a slight glitch there.

This is actually all you have to do, no need to override back stack behavior...

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

Transparent image - background color

If I understand you right, you can do this:

<img src="image.png" style="background-color:red;" />

In fact, you can even apply a whole background-image to the image, resulting in two "layers" without the need for multi-background support in the browser ;)

How can I specify a [DllImport] path at runtime?

Contrary to the suggestions by some of the other answers, using the DllImport attribute is still the correct approach.

I honestly don't understand why you can't do just like everyone else in the world and specify a relative path to your DLL. Yes, the path in which your application will be installed differs on different people's computers, but that's basically a universal rule when it comes to deployment. The DllImport mechanism is designed with this in mind.

In fact, it isn't even DllImport that handles it. It's the native Win32 DLL loading rules that govern things, regardless of whether you're using the handy managed wrappers (the P/Invoke marshaller just calls LoadLibrary). Those rules are enumerated in great detail here, but the important ones are excerpted here:

Before the system searches for a DLL, it checks the following:

  • If a DLL with the same module name is already loaded in memory, the system uses the loaded DLL, no matter which directory it is in. The system does not search for the DLL.
  • If the DLL is on the list of known DLLs for the version of Windows on which the application is running, the system uses its copy of the known DLL (and the known DLL's dependent DLLs, if any). The system does not search for the DLL.

If SafeDllSearchMode is enabled (the default), the search order is as follows:

  1. The directory from which the application loaded.
  2. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  3. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  4. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  5. The current directory.
  6. The directories that are listed in the PATH environment variable. Note that this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search path.

So, unless you're naming your DLL the same thing as a system DLL (which you should obviously not be doing, ever, under any circumstances), the default search order will start looking in the directory from which your application was loaded. If you place the DLL there during the install, it will be found. All of the complicated problems go away if you just use relative paths.

Just write:

[DllImport("MyAppDll.dll")] // relative path; just give the DLL's name
static extern bool MyGreatFunction(int myFirstParam, int mySecondParam);

But if that doesn't work for whatever reason, and you need to force the application to look in a different directory for the DLL, you can modify the default search path using the SetDllDirectory function.
Note that, as per the documentation:

After calling SetDllDirectory, the standard DLL search path is:

  1. The directory from which the application loaded.
  2. The directory specified by the lpPathName parameter.
  3. The system directory. Use the GetSystemDirectory function to get the path of this directory.
  4. The 16-bit system directory. There is no function that obtains the path of this directory, but it is searched.
  5. The Windows directory. Use the GetWindowsDirectory function to get the path of this directory.
  6. The directories that are listed in the PATH environment variable.

So as long as you call this function before you call the function imported from the DLL for the first time, you can modify the default search path used to locate DLLs. The benefit, of course, is that you can pass a dynamic value to this function that is computed at run-time. That isn't possible with the DllImport attribute, so you will still use a relative path (the name of the DLL only) there, and rely on the new search order to find it for you.

You'll have to P/Invoke this function. The declaration looks like this:

[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool SetDllDirectory(string lpPathName);

What does "fatal: bad revision" mean?

I had a similar issue with Intellij. The issue was that someone added the file that I am trying to compare in Intellij to .gitignore, without actually deleting the file from Git.

Gradle - Could not find or load main class

In my build.gradle, I resolved this issue by creating a task and then specifying the "mainClassName" as follows:

task(runSimpleXYZProgram, group: 'algorithms', description: 'Description of what your program does', dependsOn: 'classes', type: JavaExec) {
    mainClassName = 'your.entire.package.classContainingYourMainMethod'
}

get next sequence value from database using hibernate

You can use Hibernate Dialect API for Database independence as follow

class SequenceValueGetter {
    private SessionFactory sessionFactory;

    // For Hibernate 3
    public Long getId(final String sequenceName) {
        final List<Long> ids = new ArrayList<Long>(1);

        sessionFactory.getCurrentSession().doWork(new Work() {
            public void execute(Connection connection) throws SQLException {
                DialectResolver dialectResolver = new StandardDialectResolver();
                Dialect dialect =  dialectResolver.resolveDialect(connection.getMetaData());
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {
                    preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
                    resultSet = preparedStatement.executeQuery();
                    resultSet.next();
                    ids.add(resultSet.getLong(1));
                }catch (SQLException e) {
                    throw e;
                } finally {
                    if(preparedStatement != null) {
                        preparedStatement.close();
                    }
                    if(resultSet != null) {
                        resultSet.close();
                    }
                }
            }
        });
        return ids.get(0);
    }

    // For Hibernate 4
    public Long getID(final String sequenceName) {
        ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
            @Override
            public Long execute(Connection connection) throws SQLException {
                DialectResolver dialectResolver = new StandardDialectResolver();
                Dialect dialect =  dialectResolver.resolveDialect(connection.getMetaData());
                PreparedStatement preparedStatement = null;
                ResultSet resultSet = null;
                try {
                    preparedStatement = connection.prepareStatement( dialect.getSequenceNextValString(sequenceName));
                    resultSet = preparedStatement.executeQuery();
                    resultSet.next();
                    return resultSet.getLong(1);
                }catch (SQLException e) {
                    throw e;
                } finally {
                    if(preparedStatement != null) {
                        preparedStatement.close();
                    }
                    if(resultSet != null) {
                        resultSet.close();
                    }
                }

            }
        };
        Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
        return maxRecord;
    }

}

How to open a new form from another form

You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.

It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.

Remove Null Value from String array in java

A gc-friendly piece of code:

public static<X> X[] arrayOfNotNull(X[] array) {
    for (int p=0, N=array.length; p<N; ++p) {
        if (array[p] == null) {
            int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
            X[] res = Arrays.copyOf(array, m);
            for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
            return res;
        }
    }
    return array;
}

It returns the original array if it contains no nulls. It does not modify the original array.

maxlength ignored for input type="number" in Chrome

<input type="number" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" onKeyDown="if(this.value.length==10 && event.keyCode!=8) return false;">

DEMO - JSFIDDLE

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

NVIDIA NVML Driver/library version mismatch

So I was having this problem, none of the other remedies worked. The error message was opaque, but checking dmesg was key:

[   10.118255] NVRM: API mismatch: the client has the version 410.79, but
           NVRM: this kernel module has the version 384.130.  Please
           NVRM: make sure that this kernel module and all NVIDIA driver
           NVRM: components have the same version.

However I had completely removed the 384 version, and removed any remaining kernel drivers nvidia-384*. But even after reboot, I was still getting this. Seeing this meant that the kernel was still compiled to reference 384, but was only finding 410. So I recompiled my kernel:

# uname -a # find the kernel it's using
Linux blah 4.13.0-43-generic #48~16.04.1-Ubuntu SMP Thu May 17 12:56:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
# update-initramfs -c -k 4.13.0-43-generic #recompile it
# reboot

And then it worked.

After removing 384, I still had 384 files in: /var/lib/dkms/nvidia-XXX/XXX.YY/4.13.0-43-generic/x86_64/module /lib/modules/4.13.0-43-generic/kernel/drivers

I recommend using the locate command (not installed by default) rather than searching the filesystem every time.

How to determine the Schemas inside an Oracle Data Pump Export file

If you open the DMP file with an editor that can handle big files, you might be able to locate the areas where the schema names are mentioned. Just be sure not to change anything. It would be better if you opened a copy of the original dump.

req.body empty on posts

I solved this using multer as suggested above, but they missed giving a full working example, on how to do this. Basically this can happen when you have a form group with enctype="multipart/form-data". Here's the HTML for the form I had:

<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">            
  </div>
</form>

And here's how to use multer to get the values and names of this form with Express.js and node.js:

var multer  = require('multer')
var upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
   // req.file is the name of your file in the form above, here 'uploaded_file'
   // req.body will hold the text fields, if there were any 
   console.log(req.file, req.body)
});

how to call a variable in code behind to aspx page

You can access a public/protected property using the data binding expression <%# myproperty %> as given below:

    <asp:Label ID="Label1" runat="server" Text="<%#CodeBehindVarPublic %>"></asp:Label>

you should call DataBind method, otherwise it can't be evaluated.

    public partial class WebForm1 : System.Web.UI.Page
    {
     public string CodeBehindVarPublic { get; set; }
      protected void Page_Load(object sender, EventArgs e)
        {
          CodeBehindVarPublic ="xyz";
       //you should call the next line  in case of using <%#CodeBehindVarPublic %>

          DataBind();
        }

}

SQL update trigger only when column is modified

fyi The code I ended up with:

IF UPDATE (QtyToRepair)
    begin
        INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
        SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
        INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber 
        WHERE I.QtyToRepair <> D.QtyToRepair
end

TypeError: 'dict' object is not callable

it's number_map[int(x)], you tried to actually call the map with one argument

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

Cannot edit in read-only editor VS Code

Had the same problem. Here’s what I did & it got me the results I wanted.

  1. Go to the Terminal of Visual studio code.
  2. Cd to the directory of the file that has the code you wrote and ran. Let's call the program " xx.cpp "
  3. Type g++ xx.cpp -o a.out (creates an executable)
  4. To run your program, type ./a.out

How do I break a string across more than one line of code in JavaScript?

No need of any manual break in code. Just add \n where you want to break.

alert ("Please Select file \n to delete");

This will show the alert like

Please select file 
to delete.

Rules for C++ string literals escape character

With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string literal operator.

using namespace std::string_literals;
auto const x = "\0" "0"s;

Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char> constructor approach, but it at least gets rid of the ' and , characters.

How can I render a list select box (dropdown) with bootstrap?

Another option could be using bootstrap select. On their own words:

A custom select / multiselect for Bootstrap using button dropdown, designed to behave like regular Bootstrap selects.

How do you dynamically allocate a matrix?

I have this grid class that can be used as a simple matrix if you don't need any mathematical operators.

/**
 * Represents a grid of values.
 * Indices are zero-based.
 */
template<class T>
class GenericGrid
{
    public:
        GenericGrid(size_t numRows, size_t numColumns);

        GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue);

        const T & get(size_t row, size_t col) const;

        T & get(size_t row, size_t col);

        void set(size_t row, size_t col, const T & inT);

        size_t numRows() const;

        size_t numColumns() const;

    private:
        size_t mNumRows;
        size_t mNumColumns;
        std::vector<T> mData;
};


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns);
}


template<class T>
GenericGrid<T>::GenericGrid(size_t numRows, size_t numColumns, const T & inInitialValue):
    mNumRows(numRows),
    mNumColumns(numColumns)
{
    mData.resize(numRows*numColumns, inInitialValue);
}


template<class T>
const T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx) const
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
T & GenericGrid<T>::get(size_t rowIdx, size_t colIdx)
{
    return mData[rowIdx*mNumColumns + colIdx];
}


template<class T>
void GenericGrid<T>::set(size_t rowIdx, size_t colIdx, const T & inT)
{
    mData[rowIdx*mNumColumns + colIdx] = inT;
}


template<class T>
size_t GenericGrid<T>::numRows() const
{
    return mNumRows;
}


template<class T>
size_t GenericGrid<T>::numColumns() const
{
    return mNumColumns;
}

Create a shortcut on Desktop

Without additional reference:

using System;
using System.Runtime.InteropServices;

public class Shortcut
{

private static Type m_type = Type.GetTypeFromProgID("WScript.Shell");
private static object m_shell = Activator.CreateInstance(m_type);

[ComImport, TypeLibType((short)0x1040), Guid("F935DC23-1CF0-11D0-ADB9-00C04FD58A0B")]
private interface IWshShortcut
{
    [DispId(0)]
    string FullName { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0)] get; }
    [DispId(0x3e8)]
    string Arguments { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e8)] set; }
    [DispId(0x3e9)]
    string Description { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3e9)] set; }
    [DispId(0x3ea)]
    string Hotkey { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ea)] set; }
    [DispId(0x3eb)]
    string IconLocation { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3eb)] set; }
    [DispId(0x3ec)]
    string RelativePath { [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ec)] set; }
    [DispId(0x3ed)]
    string TargetPath { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ed)] set; }
    [DispId(0x3ee)]
    int WindowStyle { [DispId(0x3ee)] get; [param: In] [DispId(0x3ee)] set; }
    [DispId(0x3ef)]
    string WorkingDirectory { [return: MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] get; [param: In, MarshalAs(UnmanagedType.BStr)] [DispId(0x3ef)] set; }
    [TypeLibFunc((short)0x40), DispId(0x7d0)]
    void Load([In, MarshalAs(UnmanagedType.BStr)] string PathLink);
    [DispId(0x7d1)]
    void Save();
}

public static void Create(string fileName, string targetPath, string arguments, string workingDirectory, string description, string hotkey, string iconPath)
{
    IWshShortcut shortcut = (IWshShortcut)m_type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, m_shell, new object[] { fileName });
    shortcut.Description = description;
    shortcut.Hotkey = hotkey;
    shortcut.TargetPath = targetPath;
    shortcut.WorkingDirectory = workingDirectory;
    shortcut.Arguments = arguments;
    if (!string.IsNullOrEmpty(iconPath))
        shortcut.IconLocation = iconPath;
    shortcut.Save();
}
}

To create Shortcut on Desktop:

    string lnkFileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Notepad.lnk");
    Shortcut.Create(lnkFileName,
        System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "notepad.exe"),
        null, null, "Open Notepad", "Ctrl+Shift+N", null);

PHP 5 disable strict standards error

In php.ini set :

error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT

How to create json by JavaScript for loop?

Your question is pretty hard to decode, but I'll try taking a stab at it.

You say:

I want to create a json object having two fields uniqueIDofSelect and optionValue in javascript.

And then you say:

I need output like

[{"selectID":2,"optionValue":"2"},
{"selectID":4,"optionvalue":"1"}]

Well, this example output doesn't have the field named uniqueIDofSelect, it only has optionValue.

Anyway, you are asking for array of objects...

Then in the comment to michaels answer you say:

It creates json object array. but I need only one json object.

So you don't want an array of objects?

What do you want then?

Please make up your mind.

In C#, how to check whether a string contains an integer?

Sorry, didn't quite get your question. So something like this?

str.ToCharArray().Any(char.IsDigit);

Or does the value have to be an integer completely, without any additional strings?

if(str.ToCharArray().All(char.IsDigit(c));

Get type of a generic parameter in Java with reflection

One construct, I once stumbled upon looked like

Class<T> persistentClass = (Class<T>)
   ((ParameterizedType)getClass().getGenericSuperclass())
      .getActualTypeArguments()[0];

So there seems to be some reflection-magic around that I unfortunetly don't fully understand... Sorry.

Storing and displaying unicode string (??????) using PHP and MySQL

For those who are looking for PHP ( >5.3.5 ) PDO statement, we can set charset as per below:

$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');

Unable to run Java GUI programs with Ubuntu

In my case

-Djava.awt.headless=true

was set (indirectly by a Maven configuration). I had to actively use

-Djava.awt.headless=false

to override this.

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.

Tomcat 7 is not running on browser(http://localhost:8080/ )

You may face two errors while testing tomcat server startup.

  1. Error in the Eclipse inbuilt browser - This page can’t be displayed Turn on TLS 1.0, TLS 1.1, and TLS 1.2 in Advanced settings and try connecting to https://localhost:8080 again. If this error persists, it is possible that this site uses an unsupported protocol. Please contact the site administrator.
  2. 404 error in the normal browsers.

Fixes -

  1. For the eclipse browser error, check whether you are using secured URL - https://localhost:8080. This should be http://localhost:8080
  2. For the 404 error: Go to Tomcat server in the console. Do a right click, select properties. In the properties window, Click "Switch location" and then click OK. Followed by that, Go to Tomcat server in the console, double click it, Under "server locations" select "Use Tomcat installation" radio button. Save it.

The reason for choosing this option is, When the default option is given as eclipse location, we will see 404 error as it changes Catalina parameters (sometimes). But if we change it to Tomcat location, it works fine.

While, Do While, For loops in Assembly Language (emu8086)

For-loops:

For-loop in C:

for(int x = 0; x<=3; x++)
{
    //Do something!
}

The same loop in 8086 assembler:

        xor cx,cx   ; cx-register is the counter, set to 0
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        inc cx      ; Increment
        cmp cx,3    ; Compare cx to the limit
        jle loop1   ; Loop while less or equal

That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:

        mov cx,4    ; 4 iterations
loop1   nop         ; Whatever you wanna do goes here, should not change cx
        loop loop1  ; loop instruction decrements cx and jumps to label if not 0

If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction

times 4 nop

Do-while-loops

Do-while-loop in C:

int x=1;
do{
    //Do something!
}
while(x==1)

The same loop in assembler:

        mov ax,1
loop1   nop         ; Whatever you wanna do goes here
        cmp ax,1    ; Check wether cx is 1
        je loop1    ; And loop if equal

While-loops

While-loop in C:

while(x==1){
    //Do something
}

The same loop in assembler:

        jmp loop1   ; Jump to condition first
cloop1  nop         ; Execute the content of the loop
loop1   cmp ax,1    ; Check the condition
        je cloop1   ; Jump to content of the loop if met

For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.

Windows Explorer "Command Prompt Here"

Inside your current folder, simply press Shift+Alt+F --then--> Enter.

The prompt will appear with your current folder's path set.

Note: That works only in Windows 7 / Vista. What it does is that drops the "File" menu down for you, because the "Shift" key is pressed the option "Open command window here" is enabled and focused as the first available option of "File" menu. Pressing enter starts the focused option therefor the command window.

Edit:

In case you are in a folder and you already selected some of its contents (file/folder) this wont work. In that case Click on the empty area inside the folder to deselect any previously selected files and repeat.

Edit2:

Another way you can open terminal in current directory is to type cmd on file browser navigation bar where the path of current folder is written.

In order to focus with your keyboard on the navigation bar Ctrl+L. Then you can type cmd and hit Enter

make html text input field grow as I type?

Here's a method that worked for me. When you type into the field, it puts that text into the hidden span, then gets its new width and applies it to the input field. It grows and shrinks with your input, with a safeguard against the input virtually disappearing when you erase all input. Tested in Chrome. (EDIT: works in Safari, Firefox and Edge at the time of this edit)

_x000D_
_x000D_
function travel_keyup(e)_x000D_
{_x000D_
    if (e.target.value.length == 0) return;_x000D_
    var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
    oSpan.textContent=e.target.value;_x000D_
    match_span(e.target, oSpan);_x000D_
}_x000D_
function travel_keydown(e)_x000D_
{_x000D_
    if (e.key.length == 1)_x000D_
    {_x000D_
        if (e.target.maxLength == e.target.value.length) return;_x000D_
        var oSpan=document.querySelector('#menu-enter-travel span');_x000D_
        oSpan.textContent=e.target.value + '' + e.key;_x000D_
        match_span(e.target, oSpan);_x000D_
    }_x000D_
}_x000D_
function match_span(oInput, oSpan)_x000D_
{_x000D_
    oInput.style.width=oSpan.getBoundingClientRect().width + 'px';_x000D_
}_x000D_
_x000D_
window.addEventListener('load', function()_x000D_
{_x000D_
    var oInput=document.querySelector('#menu-enter-travel input');_x000D_
    oInput.addEventListener('keyup', travel_keyup);_x000D_
    oInput.addEventListener('keydown', travel_keydown);_x000D_
_x000D_
    match_span(oInput, document.querySelector('#menu-enter-travel span'));_x000D_
});
_x000D_
#menu-enter-travel input_x000D_
{_x000D_
 width: 8px;_x000D_
}_x000D_
#menu-enter-travel span_x000D_
{_x000D_
 visibility: hidden;_x000D_
    position: absolute;_x000D_
    top: 0px;_x000D_
    left: 0px;_x000D_
}
_x000D_
<div id="menu-enter-travel">_x000D_
<input type="text" pattern="^[0-9]{1,4}$" maxlength="4">KM_x000D_
<span>9</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I manage conflicts with git submodules?

I struggled a bit with the answers on this question and didn't have much luck with the answers in a similar SO post either. So this is what worked for me - bearing in mind that in my case, the submodule was maintained by a different team, so the conflict came from different submodule versions in master and my local branch of the project I was working on:

  1. Run git status - make a note of the submodule folder with conflicts
  2. Reset the submodule to the version that was last committed in the current branch:

    git reset HEAD path/to/submodule

  3. At this point, you have a conflict-free version of your submodule which you can now update to the latest version in the submodule's repository:

    cd path/to/submodule
    git submodule foreach git pull origin SUBMODULE-BRANCH-NAME
  4. And now you can commit that and get back to work.

I want to align the text in a <td> to the top

https://developer.mozilla.org/en/CSS/vertical-align

<table style="height: 275px; width: 188px">
    <tr>
        <td style="width: 259px; vertical-align:top">
            main page
        </td>
    </tr>
</table>

?

Displaying splash screen for longer than default seconds

In Swift 4.2

For Delay 1 second after default launch time...

Thread.sleep(forTimeInterval: 1)

Inserting the iframe into react component

If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution

var Iframe = React.createClass({     
  render: function() {
    return(         
      <div>          
        <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>         
      </div>
    )
  }
});

ReactDOM.render(
  <Iframe src="http://plnkr.co/" height="500" width="500"/>,
  document.getElementById('example')
);

here live demo is available Demo

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.

Postgresql : syntax error at or near "-"

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; --- i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

How to Identify port number of SQL server

  1. Open Run in your system.

  2. Type %windir%\System32\cliconfg.exe

  3. Click on ok button then check that the "TCP/IP Network Protocol Default Value Setup" pop-up is open.

  4. Highlight TCP/IP under the Enabled protocols window.

  5. Click the Properties button.

  6. Enter the new port number, then click OK.

enter image description here

Practical uses for the "internal" keyword in C#

The internal keyword is heavily used when you are building a wrapper over non-managed code.

When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.

You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.

How to load a text file into a Hive table stored as sequence files

You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.

Start with a tab delimited file:

% cat /tmp/input.txt
a       b
a2      b2

create a sequence file

hive> create table test_sq(k string, v string) stored as sequencefile;

try to load; as expected, this will fail:

hive> load data local inpath '/tmp/input.txt' into table test_sq;

But with this table:

hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;

The load works just fine:

hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a       b
a2      b2

Now load into the sequence table from the text table:

insert into table test_sq select * from test_t;

Can also do load/insert with overwrite to replace all.

Laravel Soft Delete posts

In the Latest version of Laravel i.e above Laravel 5.0. It is quite simple to perform this task. In Model, inside the class just write 'use SoftDeletes'. Example

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

And In Controller, you can do deletion. Example

User::where('email', '[email protected]')->delete();

or

User::where('email', '[email protected]')->softDeletes();

Make sure that you must have 'deleted_at' column in the users Table.

Convert date to datetime in Python

If you need something quick, datetime_object.date() gives you a date of a datetime object.

Android studio doesn't list my phone under "Choose Device"

rejected master -> master (non-fast-forward)

I've just received this error.

I created a github repository after creating my local git repository so I needed to accept the changes into local before pushing to github. In this case the only change was the readme file created as optional step when creating github repository.

git pull https://github.com/*username*/*repository*.git master

repository URL is got from here on project github page :

enter image description here

I then re-initialised (this may not be needed)

git init
git add .
git commit -m "update"

Then push :

git push

How do I trim a file extension from a String in Java?

public static String removeExtension(String file) {
    if(file != null && file.length() > 0) {
        while(file.contains(".")) {
            file = file.substring(0, file.lastIndexOf('.'));
        }
    }
    return file;
}

Dynamically create checkbox with JQuery from text input

Put a global variable to generate the ids.

<script>
    $(function(){
        // Variable to get ids for the checkboxes
        var idCounter=1;
        $("#btn1").click(function(){
            var val = $("#txtAdd").val();
            $("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
            idCounter ++;
        });
    });
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" /> 
<button id="btn1">Click</button>

How do I conditionally apply CSS styles in AngularJS?

Here's how i conditionally applied gray text style on a disabled button

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  styleUrls: [ './app.component.css' ],
  template: `
  <button 
    (click)='buttonClick1()' 
    [disabled] = "btnDisabled"
    [ngStyle]="{'color': (btnDisabled)? 'gray': 'black'}">
    {{btnText}}
  </button>`
})
export class AppComponent  {
  name = 'Angular';
  btnText = 'Click me';
  btnDisabled = false;
  buttonClick1() {
    this.btnDisabled = true;
    this.btnText = 'you clicked me';
    setTimeout(() => {
      this.btnText = 'click me again';
      this.btnDisabled = false
      }, 5000);
  }
}

Here's a working example:
https://stackblitz.com/edit/example-conditional-disable-button?file=src%2Fapp%2Fapp.component.html

Docker is installed but Docker Compose is not ? why?

The above solutions didn't work for me. But I found this that worked:

sudo apt-get update -y && sudo apt-get install -y python3-pip python3-dev
sudo apt-get remove docker docker-engine docker.io
curl -fsSL get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo pip3 install docker-compose
#sudo docker-compose -f docker-compose-profess.yml pull ofw
sudo usermod -a -G docker $USER
sudo reboot

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

How to set a Header field on POST a form?

Set a cookie value on the page, and then read it back server side.

You won't be able to set a specific header, but the value will be accessible in the headers section and not the content body.

Git Clone: Just the files, please?

It sounds like you just want a copy of the source code. If so why not just copy the directory and exclude the .git directory from the copy?

How to set a bitmap from resource

just replace this line

bm = BitmapFactory.decodeResource(null, R.id.image);

with

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.YourImageName);

I mean to say just change null value with getResources() If you use this code in any button or Image view click event just append getApplicationContext() before getResources()..

Kotlin Ternary Conditional Operator

TASK:

Let's consider the following example:

if (!answer.isSuccessful()) {
    result = "wrong"
} else {
    result = answer.body().string()
}
return result

We need the following equivalent in Kotlin:

return ( !answer.isSuccessful() ) ? "wrong" : answer.body().string()


SOLUTION 1.a. You can use if-expression in Kotlin:

return if (!answer.isSuccessful()) "wrong" else answer.body().string()

SOLUTION 1.b. It can be much better if you flip this if-expression (let's do it without not):

return if (answer.isSuccessful()) answer.body().string() else "wrong"


SOLUTION 2. Kotlin’s Elvis operator ?: can do a job even better:

return answer.body()?.string() ?: "wrong"


SOLUTION 3. Or use an Extension function for the corresponding Answer class:

fun Answer.bodyOrNull(): Body? = if (isSuccessful()) body() else null


SOLUTION 4. Using the Extension function you can reduce a code thanks to Elvis operator:

return answer.bodyOrNull()?.string() ?: "wrong"


SOLUTION 5. Or just use when operator:

when (!answer.isSuccessful()) {
    parseInt(str) -> result = "wrong"
    else -> result = answer.body().string()
}

Send Post Request with params using Retrofit

Post data to backend using retrofit

 implementation 'com.squareup.retrofit2:retrofit:2.8.1'
 implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
 implementation 'com.google.code.gson:gson:2.8.6'
 implementation 'com.squareup.okhttp3:logging-interceptor:4.5.0'

public interface UserService {
  @POST("users/")
  Call<UserResponse> userRegistration(@Body UserRegistration 
    userRegistration);
}



public class ApiClient {

    private static Retrofit getRetrofit(){
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient
                .Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.larntech.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();



        return retrofit;

    }


    public static UserService getService(){
        UserService userService = getRetrofit().create(UserService.class);
        return userService;
    }

}

What does a question mark represent in SQL queries?

It normally represents a parameter to be supplied by client.

MongoDB: How to find the exact version of installed MongoDB

Sometimes you need to see version of mongodb after making a connection from your project/application/code. In this case you can follow like this:

 mongoose.connect(
    encodeURI(DB_URL), {
      keepAlive: true
    },
    (err) => {
      if (err) {
        console.log(err)
      }else{
           const con = new mongoose.mongo.Admin(mongoose.connection.db)
              con.buildInfo( (err, db) => {
              if(err){
                throw err
              }
             // see the db version
             console.log(db.version)
            })
      }
    }
  )

Hope this will be helpful for someone.

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

How to refresh activity after changing language (Locale) inside application

For Android 4.2 (API 17), you need to use android:configChanges="locale|layoutDirection" in your AndroidManifest.xml. See onConfigurationchanged is not called over jellybean(4.2.1)

Converting 'ArrayList<String> to 'String[]' in Java

Generics solution to covert any List<Type> to String []:

public static  <T> String[] listToArray(List<T> list) {
    String [] array = new String[list.size()];
    for (int i = 0; i < array.length; i++)
        array[i] = list.get(i).toString();
    return array;
}

Note You must override toString() method.

class Car {
  private String name;
  public Car(String name) {
    this.name = name;
  }
  public String toString() {
    return name;
  }
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);

File Upload in WebView

I found that I needed 3 interface definitions in order to handle various version of android.

public void openFileChooser(ValueCallback < Uri > uploadMsg) {
  mUploadMessage = uploadMsg;
  Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  i.addCategory(Intent.CATEGORY_OPENABLE);
  i.setType("image/*");
  FreeHealthTrack.this.startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);
}

public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType) {
  openFileChooser(uploadMsg);
}

public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType, String capture) {
  openFileChooser(uploadMsg);
}

Jquery Validate custom error message location

 if (e.attr("name") == "firstName" ) {
     $("#firstName__validate").text($(error).text());
     console.log($(error).html());
 }

Try this get text of error object

Django Rest Framework File Upload

def post(self,request):
        serializer = ProductSerializer(data=request.DATA, files=request.FILES)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

Get name of object or class

Get your object's constructor function and then inspect its name property.

myObj.constructor.name

Returns "myClass".

Angular 4.3 - HttpClient set params

Since HTTP Params class is immutable therefore you need to chain the set method:

const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");

Fast way of finding lines in one file that are not in another?

I found that for me using a normal if and for loop statement worked perfectly.

for i in $(cat file2);do if [ $(grep -i $i file1) ];then echo "$i found" >>Matching_lines.txt;else echo "$i missing" >>missing_lines.txt ;fi;done

Restore a postgres backup file using the command line?

I was having authentication problems running pg_dump, so I moved my dump file

mv database_dump /tmp

into the temp directory and then ran

su -u postgres
cd /tmp
pg_restore database_dump

If you have a large database dump, you may just want to create another directory where your current user and the postgres user can access and putting the database dump file into that.

How to convert datetime to integer in python

When converting datetime to integers one must keep in mind the tens, hundreds and thousands.... like "2018-11-03" must be like 20181103 in int for that you have to 2018*10000 + 100* 11 + 3

Similarly another example, "2018-11-03 10:02:05" must be like 20181103100205 in int

Explanatory Code

dt = datetime(2018,11,3,10,2,5)
print (dt)

#print (dt.timestamp()) # unix representation ... not useful when converting to int

print (dt.strftime("%Y-%m-%d"))
print (dt.year*10000 + dt.month* 100  + dt.day)
print (int(dt.strftime("%Y%m%d")))

print (dt.strftime("%Y-%m-%d %H:%M:%S"))
print (dt.year*10000000000 + dt.month* 100000000 +dt.day * 1000000 + dt.hour*10000  +  dt.minute*100 + dt.second)
print (int(dt.strftime("%Y%m%d%H%M%S")))

General Function

To avoid that doing manually use below function

def datetime_to_int(dt):
    return int(dt.strftime("%Y%m%d%H%M%S"))

Stopping Docker containers by image name - Ubuntu

If you want to prefer a simple AWK approach, here Is my take:

docker rm -f $(docker ps | awk '{ if($2 == "<your image name>") { print $NF}}')

$(docker ps | awk '{ if($2 == "<your image name>") { print $NF}}') - prints the docker container names based on input image

docker ps - list all containers

awk '{ if($2 == "<your-image-name>") { print $NF}}' - The second parsed column of docker ps gives the image name. Comparing it with your image name will execute print $NF which prints the container name.

docker rm -f removes the containers

For example, removing all running containers of ubuntu image, can be done simply as:

docker rm -f $(docker ps | awk '{ if($2 == "ubuntu:latest") { print $NF}}')

PS: Remember to include the image tag in AWK, since it's a equal comparator.

How to compare data between two table in different databases using Sql Server 2008?

Another solution (non T-SQL): you can use tablediff utility. For example if you want to compare two tables (Localitate) from two different servers (ROBUH01 & ROBUH02) you can use this shell command:

C:\Program Files\Microsoft SQL Server\100\COM>tablediff -sourceserver ROBUH01 -s
ourcedatabase SIM01 -sourceschema dbo -sourcetable Localitate -destinationserver
 ROBUH02 -destinationschema dbo -destinationdatabase SIM02 -destinationtable Lo
calitate

Results:

Microsoft (R) SQL Server Replication Diff Tool Copyright (c) 2008 Microsoft Corporation User-specified agent parameter values: 
-sourceserver ROBUH01 
-sourcedatabase SIM01 
-sourceschema dbo 
-sourcetable Localitate 
-destinationserver ROBUH02 
-destinationschema dbo 
-destinationdatabase SIM02 
-destinationtable Localitate 

Table [SIM01].[dbo].[Localitate] on ROBUH01 and Table [SIM02].[dbo].[Localitate ] on ROBUH02 have 10 differences. 

Err Id Dest. 
Only 21433 Dest. 
Only 21434 Dest. 
Only 21435 Dest. 
Only 21436 Dest. 
Only 21437 Dest. 
Only 21438 Dest. 
Only 21439 Dest. 
Only 21441 Dest. 
Only 21442 Dest. 
Only 21443 
The requested operation took 9,9472657 seconds.
------------------------------------------------------------------------

HTML not loading CSS file

I have struggled with this same problem (Ubuntu 16.04, Bluefish editor, FireFox, Google Chrome.

Solution: Clear browsing data in Chrome "Settings > Advanced Settings > Clear Browsing Data", In Firefox, "Open Menu image top right tool bar 'Preferences' > Advanced ", look for this image in the menu: Cached Web Content click the button "Clear Now". Browser's cache the .css file and if it has not changed they usually won't reload it. So when you change your .css file clear this web cache and it should work unless a problem exists in your .css file. Peace, Stan

How to go back last page

Maybe you'd like to check if the previous point of history is within your app. For example, if you enter directly to your app and do location.back() (by pressing a <- back button in a toolbar for example), you'd be back to your browser's main page, instead of going somewhere else within your app.

This is how I check for this:

import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-foo',
  template: ''
})
export class FooComponent {

  private readonly canGoBack: boolean;

  constructor(
    private readonly route: ActivatedRoute,
    private readonly router: Router,
    private readonly location: Location
  ) {
    // This is where the check is done. Make sure to do this
    // here in the constructor, otherwise `getCurrentNavigation()`
    // will return null. 
    this.canGoBack = !!(this.router.getCurrentNavigation()?.previousNavigation);
  }

  goBack(): void {
    if (this.canGoBack) {
      // We can safely go back to the previous location as
      // we know it's within our app.
      this.location.back();
    } else {
      // There's no previous navigation.
      // Here we decide where to go. For example, let's say the
      // upper level is the index page, so we go up one level.
      this.router.navigate(['..'], {relativeTo: this.route});
    }
  }

}

We check if the navigation that loaded the current route has a previous sibling. This has to be done in the constructor, while the navigation process is still active.

This doesn't come without caveats though:

  • canGoBack will be false even if the previous location is actually within our app but the page was refreshed.
  • The user might want to "go back" to the previous page (where the goBack() ocurred) by clicking the browser's back button, but since the app went back on history instead of pushing a new location, the user will be going back even further and might get confused.

Anaconda Installed but Cannot Launch Navigator

In my case; it was available in the anaconda folder in "All App" from main menu

How to embed a .mov file in HTML?

Had issues using the code in the answer provided by @haynar above (wouldn't play on Chrome), and it seems that one of the more modern ways to ensure it plays is to use the video tag

Example:

<video controls="controls" width="800" height="600" 
       name="Video Name" src="http://www.myserver.com/myvideo.mov"></video>

This worked like a champ for my .mov file (generated from Keynote) in both Safari and Chrome, and is listed as supported in most modern browsers (The video tag is supported in Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.)

Note: Will work in IE / etc.. if you use MP4 (Mov is not officially supported by those guys)

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Quickest way to convert XML to JSON in Java

I found this the quick and easy way: Used: org.json.XML class from java-json.jar

if (statusCode == 200 && inputStream != null) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = bufferedReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}

How can I time a code segment for testing performance with Pythons timeit?

Focus on one specific thing. Disk I/O is slow, so I'd take that out of the test if all you are going to tweak is the database query.

And if you need to time your database execution, look for database tools instead, like asking for the query plan, and note that performance varies not only with the exact query and what indexes you have, but also with the data load (how much data you have stored).

That said, you can simply put your code in a function and run that function with timeit.timeit():

def function_to_repeat():
    # ...

duration = timeit.timeit(function_to_repeat, number=1000)

This would disable the garbage collection, repeatedly call the function_to_repeat() function, and time the total duration of those calls using timeit.default_timer(), which is the most accurate available clock for your specific platform.

You should move setup code out of the repeated function; for example, you should connect to the database first, then time only the queries. Use the setup argument to either import or create those dependencies, and pass them into your function:

def function_to_repeat(var1, var2):
    # ...

duration = timeit.timeit(
    'function_to_repeat(var1, var2)',
    'from __main__ import function_to_repeat, var1, var2', 
    number=1000)

would grab the globals function_to_repeat, var1 and var2 from your script and pass those to the function each repetition.

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

nodeJS - How to create and read session with express

I need to point out here that you're incorrectly adding middleware to the application. The app.use calls should not be done within the app.get request handler, but outside of it. Simply call them directly after createServer, or take a look at the other examples in the docs.

The secret you pass to express.session should be a string constant, or perhaps something taken from a configuration file. Don't feed it something the client might know, that's actually dangerous. It's a secret only the server should know about.

If you want to store the email address in the session, simply do something along the lines of:

req.session.email = req.param('email');

With that out of the way...


If I understand correctly, what you're trying to do is handle one or more HTTP requests and keep track of a session, then later on open a Socket.IO connection from which you need the session data as well.

What's tricky about this problem is that Socket.IO's means of making the magic work on any http.Server is by hijacking the request event. Thus, Express' (or rather Connect's) session middleware is never called on the Socket.IO connection.

I believe you can make this work, though, with some trickery.

You can get to Connect's session data; you simply need to get a reference to the session store. The easiest way to do that is to create the store yourself before calling express.session:

// A MemoryStore is the default, but you probably want something
// more robust for production use.
var store = new express.session.MemoryStore;
app.use(express.session({ secret: 'whatever', store: store }));

Every session store has a get(sid, callback) method. The sid parameter, or session ID, is stored in a cookie on the client. The default name of that cookie is connect.sid. (But you can give it any name by specifying a key option in your express.session call.)

Then, you need to access that cookie on the Socket.IO connection. Unfortunately, Socket.IO doesn't seem to give you access to the http.ServerRequest. A simple work around would be to fetch the cookie in the browser, and send it over the Socket.IO connection.

Code on the server would then look something like the following:

var io      = require('socket.io'),
    express = require('express');

var app    = express.createServer(),
    socket = io.listen(app),
    store  = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({ secret: 'something', store: store }));

app.get('/', function(req, res) {
  var old = req.session.email;
  req.session.email = req.param('email');

  res.header('Content-Type', 'text/plain');
  res.send("Email was '" + old + "', now is '" + req.session.email + "'.");
});

socket.on('connection', function(client) {
  // We declare that the first message contains the SID.
  // This is where we handle the first message.
  client.once('message', function(sid) {
    store.get(sid, function(err, session) {
      if (err || !session) {
        // Do some error handling, bail.
        return;
      }

      // Any messages following are your chat messages.
      client.on('message', function(message) {
        if (message.email === session.email) {
          socket.broadcast(message.text);
        }
      });
    });
  });
});

app.listen(4000);

This assumes you only want to read an existing session. You cannot actually create or delete sessions, because Socket.IO connections may not have a HTTP response to send the Set-Cookie header in (think WebSockets).

If you want to edit sessions, that may work with some session stores. A CookieStore wouldn't work for example, because it also needs to send a Set-Cookie header, which it can't. But for other stores, you could try calling the set(sid, data, callback) method and see what happens.

jQuery select option elements by value

Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing

$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")

Creating runnable JAR with Gradle

You can use the SpringBoot plugin:

plugins {
  id "org.springframework.boot" version "2.2.2.RELEASE"
}

Create the jar

gradle assemble

And then run it

java -jar build/libs/*.jar

Note: your project does NOT need to be a SpringBoot project to use this plugin.

How do I get HTTP Request body content in Laravel?

You can pass data as the third argument to call(). Or, depending on your API, it's possible you may want to use the sixth parameter.

From the docs:

$this->call($method, $uri, $parameters, $files, $server, $content);

Convert string to float?

Try this:

String numberStr = "3.5";
Float number = null;
try {
   number = Float.parseFloat(numberStr);
} catch (NumberFormatException e) {
    System.out.println("numberStr is not a number");
}

Are PDO prepared statements sufficient to prevent SQL injection?

No, they are not always.

It depends on whether you allow user input to be placed within the query itself. For example:

$dbh = new PDO("blahblah");

$tableToUse = $_GET['userTable'];

$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );

would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:

$dbh = new PDO("blahblah");

$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))    
 $tableToUse = 'users';

$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );

Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:

$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');

The reason why the above does not work is because DESC and ASC are not data. PDO can only escape for data. Secondly, you can't even put ' quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC or ASC.

grep using a character vector with multiple patterns

Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))

MongoDB logging all queries

The profiler data is written to a collection in your DB, not to file. See http://docs.mongodb.org/manual/tutorial/manage-the-database-profiler/

I would recommend using 10gen's MMS service, and feed development profiler data there, where you can filter and sort it in the UI.

ES6 modules implementation, how to load a json file

This just works on React & React Native

const data = require('./data/photos.json');

console.log('[-- typeof data --]', typeof data); // object


const fotos = data.xs.map(item => {
    return { uri: item };
});

How can I open a link in a new window?

You can like:

window.open('url', 'window name', 'window settings')

jQuery:

$('a#link_id').click(function(){
  window.open('url', 'window name', 'window settings');
  return false;
});

You could also set the target to _blank actually.

Best font for coding

Funny, I was just researching this yesterday!

I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download

Dynamically allocating an array of objects

I'd recommend using std::vector: something like

typedef std::vector<int> A;
typedef std::vector<A> AS;

There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.

How to use range-based for() loop with std::map?

In C++17 this is called structured bindings, which allows for the following:

std::map< foo, bar > testing = { /*...blah...*/ };
for ( const auto& [ k, v ] : testing )
{
  std::cout << k << "=" << v << "\n";
}

Excel - extracting data based on another list

I have been hasseling with that as other folks have.

I used the criteria;

=countif(matchingList,C2)=0

where matchingList is the list that i am using as a filter.

have a look at this

http://www.youtube.com/watch?v=x47VFMhRLnM&list=PL63A7644FE57C97F4&index=30

The trick i found is that normally you would have the column heading in the criteria matching the data column heading. this will not work for criteria that is a formula.

What I found was if I left the column heading blank for only the criteria that has the countif formula in the advanced filter works. If I have the column heading i.e. the column heading for column C2 in my formula example then the filter return no output.

Hope this helps

How does one remove a Docker image?

Image:

  1. List images

    docker images

  2. Remove one image

    docker rmi image_name

  3. Force remove one image

    docker rmi -f image_name

Container:

  1. List all containers

    docker ps -a

  2. Remove one container

    docker rm container_id

  3. Force remove one container

    docker rm -f container_id

Using Default Arguments in a Function

You can't do this directly, but a little code fiddling makes it possible to emulate.

function foo($blah, $x = false, $y = false) {
  if (!$x) $x = "some value";
  if (!$y) $y = "some other value";

  // code
}

Chrome disable SSL checking for sites?

In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.

I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?

Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,

There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.

The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).

Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

How to start new activity on button click

    Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);    
    startActivity(in);

    This is an explicit intent to start secondscreen activity.

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

How to hide status bar in Android

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

    setTheme(R.style.Theme_AppCompat_Light_NoActionBar);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
    , WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity__splash_screen);
}

Detecting arrow key presses in JavaScript

Here's how I did it:

var leftKey = 37, upKey = 38, rightKey = 39, downKey = 40;
var keystate;
document.addEventListener("keydown", function (e) {
    keystate[e.keyCode] = true;
});
document.addEventListener("keyup", function (e) {
    delete keystate[e.keyCode];
});

if (keystate[leftKey]) {
//code to be executed when left arrow key is pushed.
}
if (keystate[upKey]) {
//code to be executed when up arrow key is pushed.
}
if (keystate[rightKey]) {
//code to be executed when right arrow key is pushed.
}
if (keystate[downKey]) {
//code to be executed when down arrow key is pushed.
}

How to serialize Joda DateTime with Jackson JSON processor?

This has become very easy with Jackson 2.0 and the Joda module.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

Maven dependency:

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-joda</artifactId>
  <version>2.1.1</version>
</dependency>  

Code and documentation: https://github.com/FasterXML/jackson-datatype-joda

Binaries: http://repo1.maven.org/maven2/com/fasterxml/jackson/datatype/jackson-datatype-joda/

Creating a UITableView Programmatically

vc.m

#import "ViewController.h"

import "secondViewController.h"

 @interface ViewController ()
 {

NSArray *cityArray;
NSArray *citySubTitleArray;
NSArray *cityImage;
NSInteger selectindexpath;

}
@end

 @implementation ViewController

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

cityArray = [[NSArray 
alloc]initWithObjects:@"Coimbatore",@"Salem",@"Chennai",nil];

citySubTitleArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
cityImage = [[NSArray alloc]initWithObjects:@"12-300x272.png"
 , @"380267_70d232fc33b44d4ebe7b42bbe63ee9be.png",@"apple-logo_318
 -40184.png", nil];

 }


 #pragma mark - UITableView Data Source

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;

 }

 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection 
 :(NSInteger)section
  {
return cityImage.count;
 }

- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"city";

UITableViewCell *cell =
 [tableView dequeueReusableCellWithIdentifier:cellId];

if (cell == nil)
{
    cell = [[UITableViewCell 
  alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}

cell.textLabel.text = [cityArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [citySubTitleArray objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:
 [cityImage objectAtIndex:indexPath.row]];




 //    NSData *data = [[NSData alloc]initWithContentsOfURL:
 [NSURL URLWithString:@""]];

 //    cell.imageView.image = [UIImage imageWithData:data];

return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath
:  (NSIndexPath *)indexPath
 {
 NSLog(@"---- %@",[cityArray objectAtIndex:indexPath.row]);
 NSLog(@"----- %@",[cityImage objectAtIndex:indexPath.row]);
 selectindexpath=indexPath.row;
 [self performSegueWithIdentifier:@"second" sender:self];
  }

  #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little p
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 if ([segue.identifier isEqualToString:@"second"])
 {
    secondViewController *object=segue.destinationViewController;
    object.cityName=[cityArray objectAtIndex:selectindexpath];
    object.cityImage=[cityImage objectAtIndex:selectindexpath];
       }
 }


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }

 @end

vc.m

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController<UITableViewDataSource
  , UITableViewDelegate>
 @property (strong, nonatomic) IBOutlet UITableView *cityLabelList;

@end

sv.m

 #import <UIKit/UIKit.h>

@interface secondViewController : UIViewController
@property(strong, nonatomic) NSString *cityName;
 @property(strong,nonatomic)NSString *cityImage;
@end

sv.h

#import "secondViewController.h"

 @interface secondViewController ()

 @property (strong, nonatomic) IBOutlet UILabel *lbl_desc;
 @property (strong, nonatomic) IBOutlet UIImageView *img_city;
    @end

 @implementation secondViewController

 - (void)viewDidLoad {
 [super viewDidLoad];
// Do any additional setup after loading the view.
self.title=self.cityName;


if ([self.cityName isEqualToString:@"Coimbatore"])
{


    self.lbl_desc.text=@"Coimbatore city";
    self.img_city.image=[UIImage imageNamed:
    [NSString stringWithFormat:@"%@",self.cityImage]];
}
 else if ([self.cityName isEqualToString:@"Chennai"])
 {

    self.lbl_desc.text= @"Chennai City Gangstar";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
  else
   {


    self.lbl_desc.text= @"selam City";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
 }

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

Showing which files have changed between two revisions

And if you are looking for changes only among certain file(s), then:

git diff branch1 branch2 -- myfile1.js myfile2.js

branch1 is optional and your current branch (the branch you are on) will be considered by default if branch1 is not provided. e.g:

git diff master -- controller/index.js

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

Error: macro names must be identifiers using #ifdef 0

Use the following to evaluate an expression (constant 0 evaluates to false).

#if 0
 ...
#endif

How to prevent rm from reporting that a file was not found?

As far as rm -f doing "anything else", it does force (-f is shorthand for --force) silent removal in situations where rm would otherwise ask you for confirmation. For example, when trying to remove a file not writable by you from a directory that is writable by you.

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

How to specify the download location with wget?

"-P" is the right option, please read on for more related information:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -P prefix
   --directory-prefix=prefix
       Set directory prefix to prefix.  The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree.  The default is . (the current directory).

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

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

All links to the Azure Active Directory Connection page now seem to be invalid.

I had an older version of Azure AD installed too, this is what worked for me. Install this.

Run these in an elevated PS session:

uninstall-module AzureAD  # this may or may not be needed
install-module AzureAD
install-module AzureADPreview
install-module MSOnline

I was then able to log in and run what I needed.

How can I get the executing assembly version?

Product Version may be preferred if you're using versioning via GitVersion or other versioning software.

To get this from within your class library you can call System.Diagnostics.FileVersionInfo.ProductVersion:

using System.Diagnostics;
using System.Reflection;

//...

var assemblyLocation = Assembly.GetExecutingAssembly().Location;
var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion

enter image description here

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action

You could also use the RenderView Controller extension from here (source)

and use it like this:

public ActionResult Do() {
var html = this.RenderView("index", theModel);
...
}

it works for razor and web-forms viewengines

How to update SQLAlchemy row entry?

I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model

def update_state(chat_id, state):
    try:
        value = Users.query.filter(Users.chat_id == str(chat_id)).first()
        value.state = str(state)
        db.session.flush()
        db.session.commit()
        #db.session.close()
    except:
        print('Error in def update_state')

Why use db.session.flush()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?

Storing Images in PostgreSQL

Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...

We need some distinction between "original image" and "processed image", like thumbnail.

As Jcoby's answer says, there are two options, then, I recommend:

  • use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.

  • use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".

  • use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.

NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.

NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.


EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.

Using json_encode on objects in PHP (regardless of scope)

$products=R::findAll('products');
$string = rtrim(implode(',', $products), ',');
echo $string;

Can a java file have more than one class?

If you want to implement a singleton, that is a class that runs in your program with only one instance in memory throughout the execution of the application, then one of the ways to implement a singleton is to nest a private static class inside a public class. Then the inner private class only instantiates itself when its public method to access the private instance is called.

Check out this wiki article,

https://en.wikipedia.org/wiki/Singleton_pattern

The concept takes a while to chew on.

Subtract a value from every number in a list in Python?

If are you working with numbers a lot, you might want to take a look at NumPy. It lets you perform all kinds of operation directly on numerical arrays. For example:

>>> import numpy
>>> array = numpy.array([49, 51, 53, 56])
>>> array - 13
array([36, 38, 40, 43])

How to count number of records per day?

This one is like the answer above which uses the MySql DATE_FORMAT() function. I also selected just one specific week in Jan.

SELECT 
    DatePart(day, DateAdded) AS date, 
    COUNT(entryhash) AS count 
FROM Responses 
    where DateAdded > '2020-01-25' and DateAdded < '2020-02-01' 
GROUP BY 
    DatePart(day, DateAdded )

How to find a whole word in a String in java

You can use regular expressions. Use Matcher and Pattern methods to get the desired output

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false