Programs & Examples On #Android contentprovider

Content providers are one of the primary building blocks of Android applications, providing content to applications.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

i had this problem :

Installation did not succeed.
The application could not be installed: INSTALL_FAILED_CONFLICTING_PROVIDER

but it was not from provider of manifest the below library in my app has conflict with other app and the others can not be install:

implementation 'com.iceteck.silicompressorr:silicompressor:2.2.1'

How to use support FileProvider for sharing content to other apps?

Here is my blog post about why we need to use FileProvider and how to use it correctly. Fully updated to the latest versions of Android.

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

Identifying Exception Type in a handler Catch Block

Alternatively:

var exception = err as Web2PDFException; 

if ( excecption != null ) 
{ 
     Web2PDFException wex = exception; 
     .... 
}

How to remove all callbacks from a Handler?

As josh527 said, handler.removeCallbacksAndMessages(null); can work.
But why?
If you have a look at the source code, you can understand it more clearly. There are 3 type of method to remove callbacks/messages from handler(the MessageQueue):

  1. remove by callback (and token)
  2. remove by message.what (and token)
  3. remove by token

Handler.java (leave some overload method)

/**
 * Remove any pending posts of Runnable <var>r</var> with Object
 * <var>token</var> that are in the message queue.  If <var>token</var> is null,
 * all callbacks will be removed.
 */
public final void removeCallbacks(Runnable r, Object token)
{
    mQueue.removeMessages(this, r, token);
}

/**
 * Remove any pending posts of messages with code 'what' and whose obj is
 * 'object' that are in the message queue.  If <var>object</var> is null,
 * all messages will be removed.
 */
public final void removeMessages(int what, Object object) {
    mQueue.removeMessages(this, what, object);
}

/**
 * Remove any pending posts of callbacks and sent messages whose
 * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
 * all callbacks and messages will be removed.
 */
public final void removeCallbacksAndMessages(Object token) {
    mQueue.removeCallbacksAndMessages(this, token);
}

MessageQueue.java do the real work:

void removeMessages(Handler h, int what, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.what == what
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.what == what
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeMessages(Handler h, Runnable r, Object object) {
    if (h == null || r == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h && p.callback == r
               && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && n.callback == r
                    && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

void removeCallbacksAndMessages(Handler h, Object object) {
    if (h == null) {
        return;
    }

    synchronized (this) {
        Message p = mMessages;

        // Remove all messages at front.
        while (p != null && p.target == h
                && (object == null || p.obj == object)) {
            Message n = p.next;
            mMessages = n;
            p.recycleUnchecked();
            p = n;
        }

        // Remove all messages after front.
        while (p != null) {
            Message n = p.next;
            if (n != null) {
                if (n.target == h && (object == null || n.obj == object)) {
                    Message nn = n.next;
                    n.recycleUnchecked();
                    p.next = nn;
                    continue;
                }
            }
            p = n;
        }
    }
}

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to identify the domain ..this name will only be identified by hql queries ..ie ..name of the domain object

@Table(name = "someThing") => this name will be used to which table referred by domain object..ie ..name of the table

How do you change the document font in LaTeX?

As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).

Try \usepackage{times}.

Getting the length of two-dimensional array

nir[0].length

Note 0: You have to have minimum one array in your array.
Note 1: Not all sub-arrays are not necessary the same length.

What is the correct way to check for string equality in JavaScript?

String Objects can be checked using JSON.stringify() trick.

_x000D_
_x000D_
var me = new String("me");
var you = new String("me");
var isEquel = JSON.stringify(me) === JSON.stringify(you);
console.log(isEquel);
_x000D_
_x000D_
_x000D_

Reload activity in Android

Start with an intent your same activity and close the activity.

Intent refresh = new Intent(this, Main.class);
startActivity(refresh);//Start the same Activity
finish(); //finish Activity.

React Error: Target Container is not a DOM Element

Just to give an alternative solution, because it isn't mentioned.

It's perfectly fine to use the HTML attribute defer here. So when loading the DOM, a regular <script> will load when the DOM hits the script. But if we use defer, then the DOM and the script will load in parallel. The cool thing is the script gets evaluated in the end - when the DOM has loaded (source).

<script src="{% static "build/react.js" %}" defer></script>

R plot: size and resolution

If you'd like to use base graphics, you may have a look at this. An extract:

You can correct this with the res= argument to png, which specifies the number of pixels per inch. The smaller this number, the larger the plot area in inches, and the smaller the text relative to the graph itself.

Create html documentation for C# code

The above method for Visual Studio didn't seem to apply to Visual Studio 2013, but I was able to find the described checkbox using the Project Menu and selecting my project (probably the last item on the submenu) to get to the dialog with the checkbox (on the Build tab).

Android YouTube app Play Video Intent

EDIT: The below implementation proved to have problems on at least some HTC devices (they crashed). For that reason I don't use setclassname and stick with the action chooser menu. I strongly discourage using my old implementation.

Following is the old implementation:

Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(youtubelink));
if(Utility.isAppInstalled("com.google.android.youtube", getActivity())) {
    intent.setClassName("com.google.android.youtube", "com.google.android.youtube.WatchActivity");
}
startActivity(intent);

Where Utility is my own personal utility class with following methode:

public static boolean isAppInstalled(String uri, Context context) {
    PackageManager pm = context.getPackageManager();
    boolean installed = false;
    try {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        installed = true;
    } catch (PackageManager.NameNotFoundException e) {
        installed = false;
    }
    return installed;
}

First I check if youtube is installed, if it is installed, I tell android which package I prefer to open my intent.

How to have a default option in Angular.js select box

In my case, I was need to insert a initial value only to tell to user to select an option, so, I do like the code below:

<select ...
    <option value="" ng-selected="selected">Select one option</option>
</select>

When I tryed an option with the value != of an empty string (null) the option was substituted by angular, but, when put an option like that (with null value), the select apear with this option.

Sorry by my bad english and I hope that I help in something with this.

Prevent jQuery UI dialog from setting focus to first textbox

I'd the same issue and solved it by inserting an empty input before the datepicker, that steals the focus every time the dialog is opened. This input is hidden on every opening of the dialog and shown again on closing.

How to Add Incremental Numbers to a New Column Using Pandas

Here:

df = df.reset_index()
df.columns[0] = 'New_ID'
df['New_ID'] = df.index + 880

How to Apply global font to whole HTML document

Use the following css:

* {
    font: Verdana, Arial, 'sans-serif' !important;/* <-- fonts */
}

The *-selector means any/all elements, but will obviously be on the bottom of the food chain when it comes to overriding more specific selectors.

Note that the !important-flag will render the font-style for * to be absolute, even if other selectors have been used to set the text (for example, the body or maybe a p).

How To: Execute command line in C#, get STD OUT results

You will need to use ProcessStartInfo with RedirectStandardOutput enabled - then you can read the output stream. You might find it easier to use ">" to redirect the output to a file (via the OS), and then simply read the file.

[edit: like what Ray did: +1]

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

so that the entry is UNchecked then the software keyboard will be displayed once again.

jQuery get an element by its data-id

Yes, you can find out element by data attribute.

element = $('a[data-item-id="stand-out"]');

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

install cx_oracle for python

Thanks Burhan Khalid. Your advice to make a a soft link make my installation finally work.

To recap:

  1. You need both the basic version and the SDK version of instant client

  2. You need to set both LD_LIBRARY_PATH and ORACLE_HOME

  3. You need to create a soft link (ln -s libclntsh.so.12.1 libclntsh.so in my case)

None of this is documented anywhere, which is quite unbelievable and quite frustrating. I spent over 3 hours yesterday with failed builds because I didn't know to create a soft link.

WMI "installed" query different from add/remove programs list?

You can get it in one line with powershell and batch file :

@echo off
Powershell /command "Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-List"
Pause

How do I call a Django function on button click?

here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).

<html>
    <head>
        <title>An example</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script>
            function call_counter(url, pk) {
                window.open(url);
                $.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
                    alert("counter updated!");
                });
            }
        </script>
    </head>
    <body>
        <button onclick="call_counter('http://www.google.com', 12345);">
            I update object 12345
        </button>
        <button onclick="call_counter('http://www.yahoo.com', 999);">
            I update object 999
        </button>
    </body>
</html>

Alternative approach

Instead of placing the JavaScript code, you can change your link in this way:

<a target="_blank" 
    class="btn btn-info pull-right" 
    href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
    Check It Out
</a>

and in your views.py:

def YOUR_VIEW_DEF(request, pk):
    YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
    return HttpResponseRedirect(request.GET.get('next')))

How to add multiple font files for the same font?

nowadays,2017-12-17. I don't find any description about Font-property-order‘s necessity in spec. And I test in chrome always works whatever the order is.

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 900;
  src: url('#{$fa-font-path}/fa-solid-900.eot');
  src: url('#{$fa-font-path}/fa-solid-900.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-solid-900.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-solid-900.woff') format('woff'),
  url('#{$fa-font-path}/fa-solid-900.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-solid-900.svg#fontawesome') format('svg');
}

@font-face {
  font-family: 'Font Awesome 5 Free';
  font-weight: 400;
  src: url('#{$fa-font-path}/fa-regular-400.eot');
  src: url('#{$fa-font-path}/fa-regular-400.eot?#iefix') format('embedded-opentype'),
  url('#{$fa-font-path}/fa-regular-400.woff2') format('woff2'),
  url('#{$fa-font-path}/fa-regular-400.woff') format('woff'),
  url('#{$fa-font-path}/fa-regular-400.ttf') format('truetype'),
  url('#{$fa-font-path}/fa-regular-400.svg#fontawesome') format('svg');
}

Kotlin's List missing "add", "remove", Map missing "put", etc?

Agree with all above answers of using MutableList but you can also add/remove from List and get a new list as below.

val newListWithElement = existingList + listOf(element)
val newListMinusElement = existingList - listOf(element)

Or

val newListWithElement = existingList.plus(element)
val newListMinusElement = existingList.minus(element)

How to select a specific node with LINQ-to-XML

Assuming the ID is unique:

var result = xmldoc.Element("Customers")
                   .Elements("Customer")
                   .Single(x => (int?)x.Attribute("ID") == 2);

You could also use First, FirstOrDefault, SingleOrDefault or Where, instead of Single for different circumstances.

What is the difference between BIT and TINYINT in MySQL?

From my experience I'm telling you that BIT has problems on linux OS types(Ubuntu for ex). I developped my db on windows and after I deployed everything on linux, I had problems with queries that inserted or selected from tables that had BIT DATA TYPE.

Bit is not safe for now. I changed to tinyint(1) and worked perfectly. I mean that you only need a value to diferentiate if it's 1 or 0 and tinyint(1) it's ok for that

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

This certificate has an invalid issuer Apple Push Services

If you are facing the "This certificate has an invalid issuer" error for all your certificates then do the following steps.

Steps:

  • Open Keychain and Click on Login -> All Items from the left panel.
  • Now, Click on View -> Show Expired Certificates from the top navigation menu.
  • Now search for "Apple Worldwide Developer Relations Certification Authority" and delete expired certificates.
  • After deleting expired certificates, visit the following URL and download the new certificate, https://developer.apple.com/certificationauthority/AppleWWDRCA.cer.
  • Double click on the newly downloaded certificate, and install it in your keychain.
  • Double check: List expired certificates by following step number 3.
  • Now you have a valid "Apple Worldwide Developer Relations Certification Authority" having expiry date 2023-02-07.

Reference:

Loop Through All Subfolders Using VBA

Just a simple folder drill down.

sub sample()
    Dim FileSystem As Object
    Dim HostFolder As String

    HostFolder = "C:\"

    Set FileSystem = CreateObject("Scripting.FileSystemObject")
    DoFolder FileSystem.GetFolder(HostFolder)
end  sub

Sub DoFolder(Folder)
    Dim SubFolder
    For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder
    Next
    Dim File
    For Each File In Folder.Files
        ' Operate on each file
    Next
End Sub

How to extract a substring using regex

In Scala,

val ticks = "'([^']*)'".r

ticks findFirstIn mydata match {
    case Some(ticks(inside)) => println(inside)
    case _ => println("nothing")
}

for (ticks(inside) <- ticks findAllIn mydata) println(inside) // multiple matches

val Some(ticks(inside)) = ticks findFirstIn mydata // may throw exception

val ticks = ".*'([^']*)'.*".r    
val ticks(inside) = mydata // safe, shorter, only gets the first set of ticks

What's the default password of mariadb on fedora?

Lucups, Floris is right, but you comment that this didn't solve your problem. I ran into the same symptoms, where mysql (mariadb) will not accept the blank password it should accept, and '/var/lib/mysql' does not exist.

I found that this Moonpoint.com page was on-point. Perhaps, like me, you tried to start the mysqld service instead of the mariadb service. Try:

systemctl start mariadb.service
systemctl status mysqld service

Followed by the usual:

mysql_secure_installation

Java - Convert image to Base64

 byte[] byteArray = new byte[102400];
 base64String = Base64.encode(byteArray);

That code will encode 102400 bytes, no matter how much data you actually use in the array.

while ((bytesRead = fis.read(byteArray)) != -1)

You need to use the value of bytesRead somewhere.

Also, this may not read the whole file into the array in one go (it only reads as much as is in the I/O buffer), so your loop will probably not work, you may end up with half an image in your array.

I'd use Apache Commons IOUtils here:

 Base64.encode(FileUtils.readFileToByteArray(file));

Remove a string from the beginning of a string

Plain form, without regex:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';

if (substr($str, 0, strlen($prefix)) == $prefix) {
    $str = substr($str, strlen($prefix));
} 

Takes: 0.0369 ms (0.000,036,954 seconds)

And with:

$prefix = 'bla_';
$str = 'bla_string_bla_bla_bla';
$str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str);

Takes: 0.1749 ms (0.000,174,999 seconds) the 1st run (compiling), and 0.0510 ms (0.000,051,021 seconds) after.

Profiled on my server, obviously.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Cause for the error according to the Java [8] Platform, Standard Edition Troubleshooting Guide: (emphasis and line breaks added)

[...] "GC overhead limit exceeded" indicates that the garbage collector is running all the time and Java program is making very slow progress.

After a garbage collection, if the Java process is spending more than approximately 98% of its time doing garbage collection and if it is recovering less than 2% of the heap and has been doing so far the last 5 (compile time constant) consecutive garbage collections, then a java.lang.OutOfMemoryError is thrown. [...]

  1. Increase the heap size if current heap is not enough.
  2. If you still get this error after increasing heap memory, use memory profiling tools like MAT ( Memory analyzer tool), Visual VM etc and fix memory leaks.
  3. Upgrade JDK version to latest version ( 1.8.x) or at least 1.7.x and use G1GC algorithm. . The throughput goal for the G1 GC is 90 percent application time and 10 percent garbage collection time
  4. Apart from setting heap memory with -Xms1g -Xmx2g , try

    -XX:+UseG1GC -XX:G1HeapRegionSize=n -XX:MaxGCPauseMillis=m  
    -XX:ParallelGCThreads=n -XX:ConcGCThreads=n
    

Have a look at some more related questions regarding G1GC

SQL Server: use CASE with LIKE

SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname, 
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE 
Lname END AS LnameTrue FROM dbo.____Fname_Lname

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);

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

How do I kill the process currently using a port on localhost in Windows?

If you are using GitBash

Step one:

netstat -ano | findstr :8080

Step two:

taskkill /PID typeyourPIDhere /F 

(/F forcefully terminates the process)

Install gitk on Mac

If you happen to already have Fink installed, this worked for me on Yosemite / OS X 10.10.5:

fink install git

Note that as a side effect, other git commands are also using the newer git version (2.5.1) installed by Fink, rather than the version from Apple (2.3.2), which is still there but preempted by my $PATH.

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

PHP Date Time Current Time Add Minutes

$ck=2016-09-13 14:12:33;
$endtime = date('H-i-s', strtotime("+05 minutes", strtotime($ck)));  

LEFT OUTER JOIN in LINQ

Now as an extension method:

public static class LinqExt
{
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(this IEnumerable<TLeft> left, IEnumerable<TRight> right, Func<TLeft, TKey> leftKey, Func<TRight, TKey> rightKey,
        Func<TLeft, TRight, TResult> result)
    {
        return left.GroupJoin(right, leftKey, rightKey, (l, r) => new { l, r })
             .SelectMany(
                 o => o.r.DefaultIfEmpty(),
                 (l, r) => new { lft= l.l, rght = r })
             .Select(o => result.Invoke(o.lft, o.rght));
    }
}

Use like you would normally use join:

var contents = list.LeftOuterJoin(list2, 
             l => l.country, 
             r => r.name,
            (l, r) => new { count = l.Count(), l.country, l.reason, r.people })

Hope this saves you some time.

How do I debug error ECONNRESET in Node.js?

I also get ECONNRESET error during my development, the way I solve it is by not using nodemon to start my server, just use "node server.js" to start my server fixed my problem.

It's weird, but it worked for me, now I never see the ECONNRESET error again.

How do you create a REST client for Java?

I use Apache HTTPClient to handle all the HTTP side of things.

I write XML SAX parsers for the XML content that parses the XML into your object model. I believe that Axis2 also exposes XML -> Model methods (Axis 1 hid this part, annoyingly). XML generators are trivially simple.

It doesn't take long to code, and is quite efficient, in my opinion.

Redirect to a page/URL after alert button is pressed

if (window.confirm('Really go to another page?'))
{
    alert('message');
    window.location = '/some/url';
}
else
{
    die();
}

What is the difference between String and StringBuffer in Java?

A String is immutable, i.e. when it's created, it can never change.

A StringBuffer (or its non-synchronized cousin StringBuilder) is used when you need to construct a string piece by piece without the performance overhead of constructing lots of little Strings along the way.

The maximum length for both is Integer.MAX_VALUE, because they are stored internally as arrays, and Java arrays only have an int for their length pseudo-field.

The performance improvement between Strings and StringBuffers for multiple concatenation is quite significant. If you run the following test code, you will see the difference. On my ancient laptop with Java 6, I get these results:

Concat with String took: 1781ms
Concat with StringBuffer took: 0ms
public class Concat
{
    public static String concatWithString()
    {
        String t = "Cat";
        for (int i=0; i<10000; i++)
        {
            t = t + "Dog";
        }
        return t;
    }
    public static String concatWithStringBuffer()
    {
        StringBuffer sb = new StringBuffer("Cat");
        for (int i=0; i<10000; i++)
        {
            sb.append("Dog");
        }
        return sb.toString();
    }
    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        concatWithString();
        System.out.println("Concat with String took: " + (System.currentTimeMillis() - start) + "ms");
        start = System.currentTimeMillis();
        concatWithStringBuffer();
        System.out.println("Concat with StringBuffer took: " + (System.currentTimeMillis() - start) + "ms");
    }
}

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

Convert JSON to Map

Use JSON lib E.g. http://www.json.org/java/

// Assume you have a Map<String, String> in JSONObject jdata
@SuppressWarnings("unchecked")
Iterator<String> nameItr = jdata.keys();
Map<String, String> outMap = new HashMap<String, String>();
while(nameItr.hasNext()) {
    String name = nameItr.next();
    outMap.put(name, jdata.getString(name));

}

Rename multiple files by replacing a particular pattern in the filenames using a shell script

An example to help you get off the ground.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

The shell automatically evaluates *.jpg to all the matching files.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.

Is there an easy way to strike through text in an app widget?

I tried few options but, this works best for me:

String text = "<strike><font color=\'#757575\'>Some text</font></strike>";
textview.setText(Html.fromHtml(text));

cheers

How can I select all rows with sqlalchemy?

I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class MyTable(Base):
    __tablename__ = 'MyTable'
    id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
    some_col = Column(String(500))

    def __init__(self, some_col):
        self.some_col = some_col

engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()

for class_instance in session.query(MyTable).all():
    print(vars(class_instance))

session.close()

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

Leave menu bar fixed on top when scrolled

In this example, you may show your menu centered.

HTML

<div id="main-menu-container">
    <div id="main-menu">
        //your menu
    </div>
</div>

CSS

.f-nav{  /* To fix main menu container */
    z-index: 9999;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
}
#main-menu-container {
    text-align: center; /* Assuming your main layout is centered */
}
#main-menu {
    display: inline-block;
    width: 1024px; /* Your menu's width */
}

JS

$("document").ready(function($){
    var nav = $('#main-menu-container');

    $(window).scroll(function () {
        if ($(this).scrollTop() > 125) {
            nav.addClass("f-nav");
        } else {
            nav.removeClass("f-nav");
        }
    });
});

How to search for a part of a word with ElasticSearch

Try the solution with is described here: Exact Substring Searches in ElasticSearch

{
    "mappings": {
        "my_type": {
            "index_analyzer":"index_ngram",
            "search_analyzer":"search_ngram"
        }
    },
    "settings": {
        "analysis": {
            "filter": {
                "ngram_filter": {
                    "type": "ngram",
                    "min_gram": 3,
                    "max_gram": 8
                }
            },
            "analyzer": {
                "index_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": [ "ngram_filter", "lowercase" ]
                },
                "search_ngram": {
                    "type": "custom",
                    "tokenizer": "keyword",
                    "filter": "lowercase"
                }
            }
        }
    }
}

To solve the disk usage problem and the too-long search term problem short 8 characters long ngrams are used (configured with: "max_gram": 8). To search for terms with more than 8 characters, turn your search into a boolean AND query looking for every distinct 8-character substring in that string. For example, if a user searched for large yard (a 10-character string), the search would be:

"arge ya AND arge yar AND rge yard.

How to run a specific Android app using Terminal?

You can Start the android Service by this command.

adb shell am startservice -n packageName/.ServiceClass

How can I validate google reCAPTCHA v2 using javascript/jQuery?

You cannot validate alone with JS only. But if you want to check in the submit button that reCAPTCHA is validated or not that is user has clicked on reCAPTCHA then you can do that using below code.

 let recaptchVerified = false;
firebase.initializeApp(firebaseConfig);
firebase.auth().languageCode = 'en';
window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container',{
    'callback': function(response) {
        recaptchVerified = true;
        // reCAPTCHA solved, allow signInWithPhoneNumber.
        // ...
    },
    'expired-callback': function() {
        // Response expired. Ask user to solve reCAPTCHA again.
        // ...
    }
});

Here I have used a variable recaptchVerified where I make it initially false and when Recaptcha is validated then I make it true.

So I can use recaptchVerified variable when the user click on the submit button and check if he had verified the captcha or not.

Could not load type 'XXX.Global'

In my case, a AfterBuild target in the project to compile the web application was the reason for this error.

See here for more info

Accessing inventory host variable in Ansible playbook

Thanks a lot this note was very useful for me! Was able to send the variable defined under /group_var/vars in the ansible playbook as indicated below.

tasks:
- name: check service account password expiry
- command:

sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}

Angular 2 change event on every keypress

In my case, the solution is:

[ngModel]="X?.Y" (ngModelChange)="X.Y=$event"

How to pass prepareForSegue: an object

I came across this question when I was trying to learn how to pass data from one View Controller to another. I need something visual to help me learn though, so this answer is a supplement to the others already here. It is a little more general than the original question but it can be adapted to work.

This basic example works like this:

enter image description here

The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

First View Controller

import UIKit

class FirstViewController: UIViewController {

    @IBOutlet weak var textField: UITextField!

    // This function is called before the segue
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        // get a reference to the second view controller
        let secondViewController = segue.destinationViewController as! SecondViewController

        // set a variable in the second view controller with the String to pass
        secondViewController.receivedString = textField.text!
    }

}

Second View Controller

import UIKit

class SecondViewController: UIViewController {

    @IBOutlet weak var label: UILabel!

    // This variable will hold the data being passed from the First View Controller
    var receivedString = ""

    override func viewDidLoad() {
        super.viewDidLoad()

        // Used the text from the First View Controller to set the label
        label.text = receivedString
    }

}

Remember to

  • Make the segue by control clicking on the button and draging it over to the Second View Controller.
  • Hook up the outlets for the UITextField and the UILabel.
  • Set the first and second View Controllers to the appropriate Swift files in IB.

Source

How to send data through segue (swift) (YouTube tutorial)

See also

View Controllers: Passing data forward and passing data back (fuller answer)

Git, fatal: The remote end hung up unexpectedly

You probably did clone the repository within an existing one, to solve the problem can simply clone of the repository in another directory and replicate the changes to this new directory and then run the push.

how to insert value into DataGridView Cell?

You can use this function if you want to add the data into database, with a button. I hope it will help.

// dgvBill is name of DataGridView

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnectingString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for (int i = 0; i < dgvBill.Rows.Count; i++) 
            {
                StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price,  total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();         
             }
         }
     }
 }
 catch (Exception err)
 {
     MessageBox.Show(err.Message  , "Error !");
 }

Assign variable value inside if-statement

Because I know it's possible in while conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.

HINT: what type while and if condition should be ??

If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.

How to load URL in UIWebView in Swift?

Swift 3 - Xcode 8.1

 @IBOutlet weak var myWebView: UIWebView!

    override func viewDidLoad() {
            super.viewDidLoad()

            let url = URL (string: "https://ir.linkedin.com/in/razipour1993")
            let requestObj = URLRequest(url: url!)
            myWebView.loadRequest(requestObj)

        }

python int( ) function

import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

"Object doesn't support this property or method" error in IE11

What fixed this for me was that I had a React component being rendered prior to my core.js shim being loaded.

import ReactComponent from '.'
import 'core-js/es6'

Loading the core-js prior to the ReactComponent fixed my issue

import 'core-js/es6'
import ReactComponent from '.'

Checking if output of a command contains a certain string in a shell script

Testing $? is an anti-pattern.

if ./somecommand | grep -q 'string'; then
  echo "matched"
fi

SQL Server query to find all permissions/access for all users in a database

From SQL Server 2005 on, you can use system views for that. For example, this query lists all users in a database, with their rights:

select  princ.name
,       princ.type_desc
,       perm.permission_name
,       perm.state_desc
,       perm.class_desc
,       object_name(perm.major_id)
from    sys.database_principals princ
left join
        sys.database_permissions perm
on      perm.grantee_principal_id = princ.principal_id

Be aware that a user can have rights through a role as well. For example, the db_data_reader role grants select rights on most objects.

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

git gc --prune=now is not what you want.

git remote prune public

or git remote prune origin # if thats the the remote source

is what you want

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

The solution is pretty easy... Searched for it for a while and it turns out that you just have to edit 2 config-files:

  • /usr/my.cnf
  • /etc/mysql/my.cnf

in both files you'll have to add:

[mysqld]
...
sql_mode=NO_ENGINE_SUBSTITUTION

At least, that's what's working for 5.6.24-2+deb.sury.org~precise+2

React ignores 'for' attribute of the label element

That is htmlFor in JSX and class is className in JSX

Fast ceiling of an integer division in C / C++

There's a solution for both positive and negative x but only for positive y with just 1 division and without branches:

int ceil(int x, int y) {
    return x / y + (x % y > 0);
}

Note, if x is positive then division is towards zero, and we should add 1 if reminder is not zero.

If x is negative then division is towards zero, that's what we need, and we will not add anything because x % y is not positive

Android dependency has different version for the compile and runtime

If anyone getting this dependency issue in 2019, update Android Studio to 3.4 or later

How to debug when Kubernetes nodes are in 'Not Ready' state

Steps to debug:-

In case you face any issue in kubernetes, first step is to check if kubernetes self applications are running fine or not.

Command to check:- kubectl get pods -n kube-system

If you see any pod is crashing, check it's logs

if getting NotReady state error, verify network pod logs.

if not able to resolve with above, follow below steps:-

  1. kubectl get nodes # Check which node is not in ready state

  2. kubectl describe node nodename #nodename which is not in readystate

  3. ssh to that node

  4. execute systemctl status kubelet # Make sure kubelet is running

  5. systemctl status docker # Make sure docker service is running

  6. journalctl -u kubelet # To Check logs in depth

Most probably you will get to know about error here, After fixing it reset kubelet with below commands:-

  1. systemctl daemon-reload
  2. systemctl restart kubelet

In case you still didn't get the root cause, check below things:-

  1. Make sure your node has enough space and memory. Check for /var directory space especially. command to check: -df -kh, free -m

  2. Verify cpu utilization with top command. and make sure any process is not taking an unexpected memory.

How to Empty Caches and Clean All Targets Xcode 4 and later

Command-Option-Shift-K to clean out the build folder. Even better, quit Xcode and clean out ~/Library/Developer/Xcode/DerivedData manually. Remove all its contents because there's a bug where Xcode will run an old version of your project that's in there somewhere. (Xcode 4.2 will show you the Derived Data folder: choose Window > Organizer and switch to the Projects tab. Click the right-arrow to the right of the Derived Data folder name.)

In the simulator, choose iOS Simulator > Reset Content and Settings.

Finally, for completeness, you can delete the contents of /var/folders; some caching happens there too.

WARNING: Deleting /var/folders can cause issues, and you may need to repair or reinstall your operating system after doing so.

EDIT: I have just learned that if you are afraid to grapple with /var/folders/ you can use the following command in the Terminal to delete in a more targeted way:

rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache"

EDIT: For certain Swift-related problems I have found it useful to delete ~/Library/Caches/com.apple.dt.Xcode. You lose a lot when you do this, like your spare copies of the downloaded documentation doc sets, but it can be worth it.

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();
        }

}

Efficient way to do batch INSERTS with JDBC

SQLite: The above answers are all correct. For SQLite, it is a little bit different. Nothing really helps, even to put it in a batch is (sometimes) not improving performance. In that case, try to disable auto-commit and commit by hand after you are done (Warning! When multiple connections write at the same time, you can clash with these operations)

// connect(), yourList and compiledQuery you have to implement/define beforehand
try (Connection conn = connect()) {
     conn.setAutoCommit(false);
     preparedStatement pstmt = conn.prepareStatement(compiledQuery);
     for(Object o : yourList){
        pstmt.setString(o.toString());
        pstmt.executeUpdate();
        pstmt.getGeneratedKeys(); //if you need the generated keys
     }
     pstmt.close();
     conn.commit();

}

Java URLConnection Timeout

I have used similar code for downloading logs from servers. I debug my code and discovered that implementation of URLConnection which is returned is sun.net.www.protocol.http.HttpURLConnection.

Abstract class java.net.URLConnection have two attributes connectTimeout and readTimeout and setters are in abstract class. Believe or not implementation sun.net.www.protocol.http.HttpURLConnection have same attributes connectTimeout and readTimeout without setters and attributes from implementation class are used in getInputStream method. So there is no use of setting connectTimeout and readTimeout because they are never used in getInputStream method. In my opinion this is bug in sun.net.www.protocol.http.HttpURLConnection implementation.

My solution for this was to use HttpClient and Get request.

node and Error: EMFILE, too many open files

Here's my two cents: Considering a CSV file is just lines of text I've streamed the data (strings) to avoid this problem.

Easiest solution for me that worked in my usecase.

It can be used with graceful fs or standard fs. Just note that there won't be headers in the file when creating.

// import graceful-fs or normal fs
const fs = require("graceful-fs"); // or use: const fs = require("fs") 

// Create output file and set it up to receive streamed data
// Flag is to say "append" so that data can be recursively added to the same file 
let fakeCSV = fs.createWriteStream("./output/document.csv", {
  flags: "a",
});

and the data that needs to be streamed to the file i've done like this

// create custom streamer that can be invoked when needed
const customStreamer = (dataToWrite) => {
  fakeCSV.write(dataToWrite + "\n");
};

Note that the dataToWrite is simply a string with a custom seperator like ";" or ",". i.e.

const dataToWrite = "batman" + ";" + "superman"
customStreamer(dataToWrite);

This writes "batman;superman" to the file.


Convert Set to List without creating new List

You can use the List.addAll() method. It accepts a Collection as an argument, and your set is a Collection.

List<String> mainList = new ArrayList<String>();
mainList.addAll(set);

EDIT: as respond to the edit of the question.
It is easy to see that if you want to have a Map with Lists as values, in order to have k different values, you need to create k different lists.
Thus: You cannot avoid creating these lists at all, the lists will have to be created.

Possible work around:
Declare your Map as a Map<String,Set> or Map<String,Collection> instead, and just insert your set.

Generating a random hex color code with PHP

An RGB hex string is just a number from 0x0 through 0xFFFFFF, so simply generate a number in that range and convert it to hexadecimal:

function rand_color() {
    return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}

or:

function rand_color() {
    return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}

What's in an Eclipse .classpath/.project file?

Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.

The .project file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)

The .classpath file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings directory inside the project); the .classpath file is just one of them. Specifically, the .classpath file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).

Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath file portability.

How to add default value for html <textarea>?

You can also add the "value" attribute and set that so something like so:


<textarea value="your value"> </textarea>

Is there a way to remove unused imports and declarations from Angular 2+?

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

Convert js Array() to JSon object for use with JQuery .ajax

Don't make it an Array if it is not an Array, make it an object:

var saveData = {};
saveData.a = 2;
saveData.c = 1;

// equivalent to...
var saveData = {a: 2, c: 1}

// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;

Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

Is there a way to view past mysql queries with phpmyadmin?

You just need to click on console at the bottom of the screen in phpMyAdmin and you will get the Executed history:

enter image description here

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

Convert a PHP script into a stand-alone windows executable

I tried most of solution given in the 1st answer, the only one that worked for me and is non-commercial is php-desktop.

I simply put my php files in the www/ folder, changed the name of .exe and was able to run my php as an exe !!

Also there is a complete documentation, up to date support, windows and linux (and soon mac) compatibility and options can easily be changed.

Codeigniter's `where` and `or_where`

You can modify just the two lines:

->where('(library.available_until >=', date("Y-m-d H:i:s"), FALSE)
->or_where("library.available_until = '00-00-00 00:00:00')", NULL, FALSE)

EDIT:

Omitting the FALSE parameter would have placed the backticks before the brackets and make them a part of the table name/value, making the query unusable.

The NULL parameter is there just because the function requires the second parameter to be a value, and since we don't have one, we send NULL.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).

ClusterIp exposure < NodePort exposure < LoadBalancer exposure

  • ClusterIp
    Expose service through k8s cluster with ip/name:port
  • NodePort
    Expose service through Internal network VM's also external to k8s ip/name:port
  • LoadBalancer
    Expose service through External world or whatever you defined in your LB.

git with development, staging and production branches

one of the best things about git is that you can change the work flow that works best for you.. I do use http://nvie.com/posts/a-successful-git-branching-model/ most of the time but you can use any workflow that fits your needs

"Repository does not have a release file" error

#For Unable to 'apt update' my Ubuntu 19.04

The repositories for older releases that are not supported (like 11.04, 11.10 and 13.04) get moved to an archive server. There are repositories available at http://old-releases.ubuntu.com.

first break up this file

cp /etc/apt/sources.list /etc/apt/sources.list.bak sudo sed -i -re 's/([a-z]{2}.)?archive.ubuntu.com|security.ubuntu.com/old-releases.ubuntu.com/g' /etc/apt/sources.list

then

sudo apt-get update && sudo apt-get dist-upgrade

Should I always use a parallel stream when possible?

Other answers have already covered profiling to avoid premature optimization and overhead cost in parallel processing. This answer explains the ideal choice of data structures for parallel streaming.

As a rule, performance gains from parallelism are best on streams over ArrayList , HashMap , HashSet , and ConcurrentHashMap instances; arrays; int ranges; and long ranges. What these data structures have in common is that they can all be accurately and cheaply split into subranges of any desired sizes, which makes it easy to divide work among parallel threads. The abstraction used by the streams library to perform this task is the spliterator , which is returned by the spliterator method on Stream and Iterable.

Another important factor that all of these data structures have in common is that they provide good-to-excellent locality of reference when processed sequentially: sequential element references are stored together in memory. The objects referred to by those references may not be close to one another in memory, which reduces locality-of-reference. Locality-of-reference turns out to be critically important for parallelizing bulk operations: without it, threads spend much of their time idle, waiting for data to be transferred from memory into the processor’s cache. The data structures with the best locality of reference are primitive arrays because the data itself is stored contiguously in memory.

Source: Item #48 Use Caution When Making Streams Parallel, Effective Java 3e by Joshua Bloch

org.hibernate.PersistentObjectException: detached entity passed to persist

This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

Solution:

@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

How to create a regex for accepting only alphanumeric characters?

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";

Manually highlight selected text in Notepad++

To highlight a block of code in Notepad++, please do the following steps

  1. Select the required text.
  2. Right click to display the context menu
  3. Choose Style token and select any of the five choices available ( styles from Using 1st style to using 5th style). Each is of different colors.If you want yellow color choose using 3rd style.

If you want to create your own style you can use Style Configurator under Settings menu.

Detect Browser Language in PHP

The official way to handle this is using the PECL HTTP library. Unlike some answers here, this correctly handles the language priorities (q-values), partial language matches and will return the closest match, or when there are no matches it falls back to the first language in your array.

PECL HTTP:
http://pecl.php.net/package/pecl_http

How to use:
http://php.net/manual/fa/function.http-negotiate-language.php

$supportedLanguages = [
    'en-US', // first one is the default/fallback
    'fr',
    'fr-FR',
    'de',
    'de-DE',
    'de-AT',
    'de-CH',
];

// Returns the negotiated language 
// or the default language (i.e. first array entry) if none match.
$language = http_negotiate_language($supportedLanguages, $result);

Replacing backslashes with forward slashes with str_replace() in php

No regex, so no need for //.

this should work:

$str = str_replace("\\", '/', $str);

You need to escape "\" as well.

How to change fontFamily of TextView in Android

It's the same as android:typeface.

built-in fonts are:

  • normal
  • sans
  • serif
  • monospace

See android:typeface.

Altering a column to be nullable

In PostgresQL it is:

ALTER TABLE tableName ALTER COLUMN columnName DROP NOT NULL;

React - Preventing Form Submission

You have prevent the default action of the event and return false from the function.

function onTestClick(e) {
    e.preventDefault();
    return false;
}

Eclipse IDE for Java - Full Dark Theme

  • Help ? Install New Software.
  • Enter Eclipse Color Theme Plugin URL: http://eclipse-color-theme.github.com/update
  • Install Eclipse Color Theme Plugin.
  • Restart Eclipse.
  • Goto Window ? Preferences ? General ? Appearance ? Color Theme
  • I like the Havenjark default Color Theme. Eclipse Color Theme Plugin comes loaded with 24 default Color Themes and option to Import a theme. enter image description here

How to save SELECT sql query results in an array in C# Asp.net

Use a SQL DATA READER:

In this example i use a List instead an array.

try
{
    SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
    connection.Open();

    SqlDataReader reader = comm.ExecuteReader();
    List<string> str = new List<string>();
    int i=0;
    while (reader.Read())
    {
        str.Add( reader.GetValue(i).ToString() );
        i++;
    }
    reader.Close();
}
catch (Exception)
{
    throw;
}
finally
{
    connection.Close();
}

Convert String To date in PHP

If it's a string that you trust meaning that you have checked it before hand then the following would also work.

$date = new DateTime('2015-03-27');

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

In my case I simply remove

implementation "com.google.android.gms:play-services-ads:16.0.0

and add firebase ads dependencies

implementation 'com.google.firebase:firebase-ads:17.1.2'

Environment variables in Jenkins

What ultimately worked for me was the following steps:

  1. Configure the Environment Injector Plugin: https://wiki.jenkins-ci.org/display/JENKINS/EnvInject+Plugin
  2. Goto to the /job//configure screen
  3. In Build Environment section check "Inject environment variables to the build process"
  4. In "Properties Content" specified: TZ=America/New_York

How can I create a "Please Wait, Loading..." animation using jQuery?

It is very simple.

HTML

<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

<body>

  <div id="cover"> <span class="glyphicon glyphicon-refresh w3-spin preloader-Icon"></span>Please Wait, Loading…</div>

  <h1>Dom Loaded</h1>
</body>

CSS

#cover {
  position: fixed;
  height: 100%;
  width: 100%;
  top: 0;
  left: 0;
  background: #141526;
  z-index: 9999;
  font-size: 65px;
  text-align: center;
  padding-top: 200px;
  color: #fff;
  font-family:tahoma;
}

JS - JQuery

$(window).on('load', function () {
  $("#cover").fadeOut(1750);
});

What is the difference between Google App Engine and Google Compute Engine?

App Engine gives developers the ability to control Google Compute Engine cores, as well as provide a web-facing front end for Google Compute Engine data processing applications.

On the other hand, Compute Engine offers direct and complete operating system management of your virtual machines. To present your App, you're going to need resources, and Google Cloud Storage is ideal for storing your assets and data, whatever they're used for. You get fast data access with hosting around the globe. Reliability is guaranteed at a 99.95% up-time, and Google also provides the ability to back up and restore your data, and believe it or not, storage is unlimited.

You can manage your assets with Google Cloud Storage, storing, retrieving, displaying, and deleting them. You can also quickly read and write to flat datasheets that are kept in Cloud Storage. Next in the Google Cloud lineup is BigQuery. With BigQuery, you can analyze massive amounts of data, we're talking millions of records, within seconds. Access is handled via a straightforward UI, or a Representational State Transfer, or REST interface.

Data storage is, as you might suspect, not a problem, and scales to hundreds of TB. BigQuery is accessible via a host of client libraries, including those for Java, .NET, Python, Go, Ruby, PHP, and Javascript. A SQL-like syntax called NoSQL is available which can be accessed through these client libraries, or through a web user interface. Finally, let's talk about the Google Cloud platform database options, Cloud SQL and Cloud Datastore.

There is a major difference. Cloud SQL is for relational databases, primarily MySQL, whereas Cloud Datastore is for non-relational databases using noSQL. With Cloud SQL, you have the choice of either hosting in the US, Europe, or Asia, with 100 GB of storage, and 16 GB of RAM per database instance.

Cloud Datastore is available at no charge for up to 50 K read/write instructions per month and 1 GB of data stored also per month. There is a fee if you exceed these quotas, however. App Engine can also work with other lesser known, more targeted members of the Google Cloud platform, including the Cloud Endpoints for creating API backends, Google Prediction API for data analysis and trend forecasting, or the Google Translate API, for multilingual output.

While you can do a fair amount with App Engine on its own, It's potential skyrockets when you factor in its ability to work easily and efficiently with its fellow Google Cloud platform services.

pandas groupby sort within groups

Here's other example of taking top 3 on sorted order, and sorting within the groups:

In [43]: import pandas as pd                                                                                                                                                       

In [44]:  df = pd.DataFrame({"name":["Foo", "Foo", "Baar", "Foo", "Baar", "Foo", "Baar", "Baar"], "count_1":[5,10,12,15,20,25,30,35], "count_2" :[100,150,100,25,250,300,400,500]})

In [45]: df                                                                                                                                                                        
Out[45]: 
   count_1  count_2  name
0        5      100   Foo
1       10      150   Foo
2       12      100  Baar
3       15       25   Foo
4       20      250  Baar
5       25      300   Foo
6       30      400  Baar
7       35      500  Baar


### Top 3 on sorted order:
In [46]: df.groupby(["name"])["count_1"].nlargest(3)                                                                                                                               
Out[46]: 
name   
Baar  7    35
      6    30
      4    20
Foo   5    25
      3    15
      1    10
dtype: int64


### Sorting within groups based on column "count_1":
In [48]: df.groupby(["name"]).apply(lambda x: x.sort_values(["count_1"], ascending = False)).reset_index(drop=True)
Out[48]: 
   count_1  count_2  name
0       35      500  Baar
1       30      400  Baar
2       20      250  Baar
3       12      100  Baar
4       25      300   Foo
5       15       25   Foo
6       10      150   Foo
7        5      100   Foo

Font-awesome, input type 'submit'

With multiple submits, when you need the value of the submit selected, this can be done quite easily. Just create a hidden field in your form and change its value depending on what button is clicked. For example, in the form, say you have:

<input type="hidden" id="Clicked" name="Clicked" value="" />
<button type="submit" class="btn btn-success ClickCheck" id="Create"> <i class="fa fa-file-pdf-o"> Create Bill</i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Reset"> <i class="fa fa-times"> Reset</i></button>
<button type="submit" class="btn btn-success ClickCheck" id="StoreData"> <i class="fa fa-archive"> Save</i></button>

Using jQuery:

<script type="text/javascript">
    $(document).ready(function()
    {
        $('.ClickCheck').click(function()
        {
            var ButtonID = $(this).attr('id');
            $('#Clicked').val(ButtonID);
        });
    });
</script>

Then you can retrieve the value of the button clicked in the "Clicked" post variable

What are the integrity and crossorigin attributes?

Both attributes have been added to Bootstrap CDN to implement Subresource Integrity.

Subresource Integrity defines a mechanism by which user agents may verify that a fetched resource has been delivered without unexpected manipulation Reference

Integrity attribute is to allow the browser to check the file source to ensure that the code is never loaded if the source has been manipulated.

Crossorigin attribute is present when a request is loaded using 'CORS' which is now a requirement of SRI checking when not loaded from the 'same-origin'. More info on crossorigin

More detail on Bootstrap CDNs implementation

How to get ip address of a server on Centos 7 in bash

Ref: https://garbagevalue.com/blog/4-simle-ways-to-check-ip-adress-in-centos-7


I'm using CentOS 7 and command

ip a

is enough to do the job.

enter image description here

Edit

Just slice out the IP address part from that test.

ip a | grep 192

REST / SOAP endpoints for a WCF service

MSDN seems to have an article for this now:

https://msdn.microsoft.com/en-us/library/bb412196(v=vs.110).aspx

Intro:

By default, Windows Communication Foundation (WCF) makes endpoints available only to SOAP clients. In How to: Create a Basic WCF Web HTTP Service, an endpoint is made available to non-SOAP clients. There may be times when you want to make the same contract available both ways, as a Web endpoint and as a SOAP endpoint. This topic shows an example of how to do this.

How do you Encrypt and Decrypt a PHP String?

Before you do anything further, seek to understand the difference between encryption and authentication, and why you probably want authenticated encryption rather than just encryption.

To implement authenticated encryption, you want to Encrypt then MAC. The order of encryption and authentication is very important! One of the existing answers to this question made this mistake; as do many cryptography libraries written in PHP.

You should avoid implementing your own cryptography, and instead use a secure library written by and reviewed by cryptography experts.

Update: PHP 7.2 now provides libsodium! For best security, update your systems to use PHP 7.2 or higher and only follow the libsodium advice in this answer.

Use libsodium if you have PECL access (or sodium_compat if you want libsodium without PECL); otherwise...
Use defuse/php-encryption; don't roll your own cryptography!

Both of the libraries linked above make it easy and painless to implement authenticated encryption into your own libraries.

If you still want to write and deploy your own cryptography library, against the conventional wisdom of every cryptography expert on the Internet, these are the steps you would have to take.

Encryption:

  1. Encrypt using AES in CTR mode. You may also use GCM (which removes the need for a separate MAC). Additionally, ChaCha20 and Salsa20 (provided by libsodium) are stream ciphers and do not need special modes.
  2. Unless you chose GCM above, you should authenticate the ciphertext with HMAC-SHA-256 (or, for the stream ciphers, Poly1305 -- most libsodium APIs do this for you). The MAC should cover the IV as well as the ciphertext!

Decryption:

  1. Unless Poly1305 or GCM is used, recalculate the MAC of the ciphertext and compare it with the MAC that was sent using hash_equals(). If it fails, abort.
  2. Decrypt the message.

Other Design Considerations:

  1. Do not compress anything ever. Ciphertext is not compressible; compressing plaintext before encryption can lead to information leaks (e.g. CRIME and BREACH on TLS).
  2. Make sure you use mb_strlen() and mb_substr(), using the '8bit' character set mode to prevent mbstring.func_overload issues.
  3. IVs should be generating using a CSPRNG; If you're using mcrypt_create_iv(), DO NOT USE MCRYPT_RAND!
  4. Unless you're using an AEAD construct, ALWAYS encrypt then MAC!
  5. bin2hex(), base64_encode(), etc. may leak information about your encryption keys via cache timing. Avoid them if possible.

Even if you follow the advice given here, a lot can go wrong with cryptography. Always have a cryptography expert review your implementation. If you are not fortunate enough to be personal friends with a cryptography student at your local university, you can always try the Cryptography Stack Exchange forum for advice.

If you need a professional analysis of your implementation, you can always hire a reputable team of security consultants to review your PHP cryptography code (disclosure: my employer).

Important: When to Not Use Encryption

Don't encrypt passwords. You want to hash them instead, using one of these password-hashing algorithms:

Never use a general-purpose hash function (MD5, SHA256) for password storage.

Don't encrypt URL Parameters. It's the wrong tool for the job.

PHP String Encryption Example with Libsodium

If you are on PHP < 7.2 or otherwise do not have libsodium installed, you can use sodium_compat to accomplish the same result (albeit slower).

<?php
declare(strict_types=1);

/**
 * Encrypt a message
 * 
 * @param string $message - message to encrypt
 * @param string $key - encryption key
 * @return string
 * @throws RangeException
 */
function safeEncrypt(string $message, string $key): string
{
    if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new RangeException('Key is not the correct size (must be 32 bytes).');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
    
    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

/**
 * Decrypt a message
 * 
 * @param string $encrypted - message encrypted with safeEncrypt()
 * @param string $key - encryption key
 * @return string
 * @throws Exception
 */
function safeDecrypt(string $encrypted, string $key): string
{   
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
    
    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if (!is_string($plain)) {
        throw new Exception('Invalid MAC');
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}

Then to test it out:

<?php
// This refers to the previous code block.
require "safeCrypto.php"; 

// Do this once then store it somehow:
$key = random_bytes(SODIUM_CRYPTO_SECRETBOX_KEYBYTES);
$message = 'We are all living in a yellow submarine';

$ciphertext = safeEncrypt($message, $key);
$plaintext = safeDecrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

Halite - Libsodium Made Easier

One of the projects I've been working on is an encryption library called Halite, which aims to make libsodium easier and more intuitive.

<?php
use \ParagonIE\Halite\KeyFactory;
use \ParagonIE\Halite\Symmetric\Crypto as SymmetricCrypto;

// Generate a new random symmetric-key encryption key. You're going to want to store this:
$key = new KeyFactory::generateEncryptionKey();
// To save your encryption key:
KeyFactory::save($key, '/path/to/secret.key');
// To load it again:
$loadedkey = KeyFactory::loadEncryptionKey('/path/to/secret.key');

$message = 'We are all living in a yellow submarine';
$ciphertext = SymmetricCrypto::encrypt($message, $key);
$plaintext = SymmetricCrypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

All of the underlying cryptography is handled by libsodium.

Example with defuse/php-encryption

<?php
/**
 * This requires https://github.com/defuse/php-encryption
 * php composer.phar require defuse/php-encryption
 */

use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;

require "vendor/autoload.php";

// Do this once then store it somehow:
$key = Key::createNewRandomKey();

$message = 'We are all living in a yellow submarine';

$ciphertext = Crypto::encrypt($message, $key);
$plaintext = Crypto::decrypt($ciphertext, $key);

var_dump($ciphertext);
var_dump($plaintext);

Note: Crypto::encrypt() returns hex-encoded output.

Encryption Key Management

If you're tempted to use a "password", stop right now. You need a random 128-bit encryption key, not a human memorable password.

You can store an encryption key for long-term use like so:

$storeMe = bin2hex($key);

And, on demand, you can retrieve it like so:

$key = hex2bin($storeMe);

I strongly recommend just storing a randomly generated key for long-term use instead of any sort of password as the key (or to derive the key).

If you're using Defuse's library:

"But I really want to use a password."

That's a bad idea, but okay, here's how to do it safely.

First, generate a random key and store it in a constant.

/**
 * Replace this with your own salt! 
 * Use bin2hex() then add \x before every 2 hex characters, like so:
 */
define('MY_PBKDF2_SALT', "\x2d\xb7\x68\x1a\x28\x15\xbe\x06\x33\xa0\x7e\x0e\x8f\x79\xd5\xdf");

Note that you're adding extra work and could just use this constant as the key and save yourself a lot of heartache!

Then use PBKDF2 (like so) to derive a suitable encryption key from your password rather than encrypting with your password directly.

/**
 * Get an AES key from a static password and a secret salt
 * 
 * @param string $password Your weak password here
 * @param int $keysize Number of bytes in encryption key
 */
function getKeyFromPassword($password, $keysize = 16)
{
    return hash_pbkdf2(
        'sha256',
        $password,
        MY_PBKDF2_SALT,
        100000, // Number of iterations
        $keysize,
        true
    );
}

Don't just use a 16-character password. Your encryption key will be comically broken.

How to find the location of the Scheduled Tasks folder

I want to extend @Jan answer:

It's seems, that Task Scheduler 1.0 API uses C:\Windows\Tasks folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API uses C:\Windows\System32\Tasks to create and enumerate tasks (this example).

It's also seems, that windows console utility schtasks and GUI utility taskschd.msc uses Task Scheduler 2.0 API.

P.S. I found, that if task placed in C:\Windows\Tasks and have not set AccountInformation, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation (even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON - task will be displayed in all standard applications.

Solution found here

How can I enable CORS on Django REST Framework

In case anyone is getting back to this question and deciding to write their own middleware, this is a code sample for Django's new style middleware -

class CORSMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"

        return response

How to convert string to date to string in Swift iOS?

Swift 2 and below

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)

And in Swift 3 and higher this would now be written as:

let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)

SQL SERVER, SELECT statement with auto generate row id

This will work in SQL Server 2008.

select  top 100 ROW_NUMBER() OVER (ORDER BY tmp.FirstName) ,* from tmp

Cheers

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

get one item from an array of name,value JSON

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
_x000D_
_x000D_

You can see a list of supported browsers here.

In the future with ES6, you'll be able to use array.find.

Storage permission error in Marshmallow

   Try this



int permission = ContextCompat.checkSelfPermission(MainActivity.this,
                    android.Manifest.permission.WRITE_EXTERNAL_STORAGE);

     if (permission != PackageManager.PERMISSION_GRANTED) {
                Log.i("grant", "Permission to record denied");

                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setMessage(getString(R.string.permsg))
                            .setTitle(getString(R.string.permtitle));

                    builder.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                            Log.i("grant", "Clicked");
                            makeRequest();
                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();

                } else {

                    //makeRequest1();
                    makeRequest();
                }
            }


     protected void makeRequest() {
            ActivityCompat.requestPermissions(this,
                    new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    500);
        }



     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case 500: {

                    if (grantResults.length == 0
                            || grantResults[0] !=
                            PackageManager.PERMISSION_GRANTED) {

                        Log.i("1", "Permission has been denied by user");

                    } else {

                        Log.i("1", "Permission has been granted by user");

                    }
                    return;
                }

            }
        }

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

NotificationCenter issue on Swift 3

I think it has changed again.

For posting this works in Xcode 8.2.

NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)

Add new line in text file with Windows batch file

Suppose you want to insert a particular line of text (not an empty line):

@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1

@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
  SETLOCAL EnableDelayedExpansion
  SET /p L=
  IF %%i==%insertat% ECHO(!TL!
  ECHO(!L!
  ENDLOCAL
)
) >%tempfile%

COPY /Y %tempfile% %origfile% >NUL

DEL %tempfile%

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

parsing JSONP $http.jsonp() response in angular.js

I'm using angular 1.6.4 and answer provided by subhaze didn't work for me. I modified it a bit and then it worked - you have to use value returned by $sce.trustAsResourceUrl. Full code:

var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts"
url = $sce.trustAsResourceUrl(url);

$http.jsonp(url, {jsonpCallbackParam: 'callback'})
    .then(function(data){
        console.log(data.found);
    });

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

ngFor with index as value in attribute

I would use this syntax to set the index value into an attribute of the HTML element:

Angular >= 2

You have to use let to declare the value rather than #.

<ul>
    <li *ngFor="let item of items; let i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Angular = 1

<ul>
    <li *ngFor="#item of items; #i = index" [attr.data-index]="i">
        {{item}}
    </li>
</ul>

Here is the updated plunkr: http://plnkr.co/edit/LiCeyKGUapS5JKkRWnUJ?p=preview.

How can I get the browser's scrollbar sizes?

This life-hack decision will give you opportunity to find browser scrollY width (vanilla JavaScript). Using this example you can get scrollY width on any element including those elements that shouldn't have to have scroll according to your current design conception,:

getComputedScrollYWidth     (el)  {

  let displayCSSValue  ; // CSS value
  let overflowYCSSValue; // CSS value

  // SAVE current original STYLES values
  {
    displayCSSValue   = el.style.display;
    overflowYCSSValue = el.style.overflowY;
  }

  // SET TEMPORALLY styles values
  {
    el.style.display   = 'block';
    el.style.overflowY = 'scroll';
  }

  // SAVE SCROLL WIDTH of the current browser.
  const scrollWidth = el.offsetWidth - el.clientWidth;

  // REPLACE temporally STYLES values by original
  {
    el.style.display   = displayCSSValue;
    el.style.overflowY = overflowYCSSValue;
  }

  return scrollWidth;
}

Convert list of dictionaries to a pandas DataFrame

How do I convert a list of dictionaries to a pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.


DataFrame(), DataFrame.from_records(), and .from_dict()

Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.

Consider a very contrived example.

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

This list consists of "records" with every keys present. This is the simplest case you could encounter.

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Word on Dictionary Orientations: orient='index'/'columns'

Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".

orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.

For example, data above is in the "columns" orient.

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Note: If you are using pd.DataFrame.from_records, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.

orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict.

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

This case is not considered in the OP, but is still useful to know.

Setting Custom Index

If you need a custom index on the resultant DataFrame, you can set it using the index=... argument.

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

This is not supported by pd.DataFrame.from_dict.

Dealing with Missing Keys/Columns

All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

Reading Subset of Columns

"What if I don't want to read in every single column"? You can easily specify this using the columns=... parameter.

For example, from the example dictionary of data2 above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

This is not supported by pd.DataFrame.from_dict with the default orient "columns".

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'

Reading Subset of Rows

Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2 above, you can use:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

The Panacea: json_normalize for Nested Data

A strong, robust alternative to the methods outlined above is the json_normalize function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
pd.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

Again, keep in mind that the data passed to json_normalize needs to be in the list-of-dictionaries (records) format.

As mentioned, json_normalize can also handle nested dictionaries. Here's an example taken from the documentation.

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]
pd.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

For more information on the meta and record_path arguments, check out the documentation.


Summarising

Here's a table of all the methods discussed above, along with supported features/functionality.

enter image description here

* Use orient='columns' and then transpose to get the same effect as orient='index'.

How do I draw a shadow under a UIView?

For fellow Xamarians, the Xamarin.iOS/C# version of the answer would look like the following:

public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
    CGContext currentContext = UIGraphics.GetCurrentContext();
    currentContext.SaveState();
    currentContext.SetShadow(new CGSize(-15, 20), 5);
    base.DrawRect(area, formatter);
    currentContext.RestoreState();                
}

The main difference is that you acquire an instance of CGContext on which you directly call the appropriate methods.

XSL xsl:template match="/"

The match attribute indicates on which parts the template transformation is going to be applied. In that particular case the "/" means the root of the xml document. The value you have to provide into the match attribute should be XPath expression. XPath is the language you have to use to refer specific parts of the target xml file.

To gain a meaningful understanding of what else you can put into match attribute you need to understand what xpath is and how to use it. I suggest yo look at links I've provided for youat the bottom of the answer.

Could I write "table" or any other html tag instead of "/" ?

Yes you can. But this depends what exactly you are trying to do. if your target xml file contains HMTL elements and you are triyng to apply this xsl:template on them it makes sense to use table, div or anithing else.

Here a few links:

How to config routeProvider and locationProvider in angularJS?

you could try:

<a href="#/controllerone">Controller One</a>||
<a href="#/controllerTwo">Controller Two</a>||
<a href="#/controllerThree">Controller Three</a>

<div>
    <div ng-view=""></div>
</div>

SQL subquery with COUNT help

Assuming there is a column named business:

SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business

Identify duplicate values in a list in Python

These answers are O(n), so a little more code than using mylist.count() but much more efficient as mylist gets longer

If you just want to know the duplicates, use collections.Counter

from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]

If you need to know the indices,

from collections import defaultdict
D = defaultdict(list)
for i,item in enumerate(mylist):
    D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

How to subtract/add days from/to a date?

There is of course a lubridate solution for this:

library(lubridate)
date <- "2009-10-01"

ymd(date) - 5
# [1] "2009-09-26"

is the same as

ymd(date) - days(5)
# [1] "2009-09-26"

Other time formats could be:

ymd(date) - months(5)
# [1] "2009-05-01"

ymd(date) - years(5)
# [1] "2004-10-01"

ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

I have Mojave 10.14.6 and the only thing that did work for me was:

  • setting JAVA_HOME to the following:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  • source .bash_profile (or wherever you keep your vars, in my case .zshrc)

Hope it helps! You can now type java --version and it should work

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

Rank function in MySQL

A tweak of Daniel's version to calculate percentile along with rank. Also two people with same marks will get the same rank.

set @totalStudents = 0;
select count(*) into @totalStudents from marksheets;
SELECT id, score, @curRank := IF(@prevVal=score, @curRank, @studentNumber) AS rank, 
@percentile := IF(@prevVal=score, @percentile, (@totalStudents - @studentNumber + 1)/(@totalStudents)*100),
@studentNumber := @studentNumber + 1 as studentNumber, 
@prevVal:=score
FROM marksheets, (
SELECT @curRank :=0, @prevVal:=null, @studentNumber:=1, @percentile:=100
) r
ORDER BY score DESC

Results of the query for a sample data -

+----+-------+------+---------------+---------------+-----------------+
| id | score | rank | percentile    | studentNumber | @prevVal:=score |
+----+-------+------+---------------+---------------+-----------------+
| 10 |    98 |    1 | 100.000000000 |             2 |              98 |
|  5 |    95 |    2 |  90.000000000 |             3 |              95 |
|  6 |    91 |    3 |  80.000000000 |             4 |              91 |
|  2 |    91 |    3 |  80.000000000 |             5 |              91 |
|  8 |    90 |    5 |  60.000000000 |             6 |              90 |
|  1 |    90 |    5 |  60.000000000 |             7 |              90 |
|  9 |    84 |    7 |  40.000000000 |             8 |              84 |
|  3 |    83 |    8 |  30.000000000 |             9 |              83 |
|  4 |    72 |    9 |  20.000000000 |            10 |              72 |
|  7 |    60 |   10 |  10.000000000 |            11 |              60 |
+----+-------+------+---------------+---------------+-----------------+

Replace contents of factor column in R dataframe

For the things that you are suggesting you can just change the levels using the levels:

levels(iris$Species)[3] <- 'new'

Easy way to prevent Heroku idling?

I have an app that only needs to run from monday to friday around lunchtime. I just added the following script to the crontab at work:

#!/bin/sh
# script to unidle heroku installation for the use with cronjob
# usage in crontab:
# */5 11-15 * * 1-5 /usr/local/bin/uptimer.sh http://www.example.com
# The command /usr/local/bin/uptimer.sh http://www.example.com will execute every 5th minute of 11am through 3pm Mondays through Fridays in every month.
# resources: http://www.cronchecker.net
echo url to unidle: $1
echo [UPTIMER]: waking up at:
date
curl $1
echo [UPTIMER]: awake at:
date

So for any app just drop another line in your crontab like:

*/5 11-15 * * 1-5 /usr/local/bin/uptimer.sh http://www.example.com

How to import the class within the same directory or sub directory?

I'm not sure why this work but using Pycharm build from file_in_same_dir import class_name

The IDE complained about it but it seems it still worked. I'm using Python 3.7

SQL Server 2005 How Create a Unique Constraint?

ALTER TABLE [TableName] ADD CONSTRAINT  [constraintName] UNIQUE ([columns])

What is the correct wget command syntax for HTTPS with username and password?

I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:

curl -o <filename-to-save-as> -u <username>:<password> <url>

XmlSerializer giving FileNotFoundException at constructor

I ran into this exact issue and couldn't get around it by any of the solutions mentioned.

Then I finally found a solution. It appears that the serializer needs not only the type, but the nested types as well. Changing this:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

To this:

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T).GetNestedTypes());

Fixed the issue for me. No more exceptions or anything.

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII: http://en.wikipedia.org/wiki/RAII

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 
{ 
  G[i]->Run(); 
} 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 
{ 
   G[i]->Run(); 
} 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

How to get html to print return value of javascript function?

It depends what you're going for. I believe the closest thing JS has to print is:

document.write( produceMessage() );

However, it may be more prudent to place the value inside a span or a div of your choosing like:

document.getElementById("mySpanId").innerHTML = produceMessage();

How to call a shell script from python code?

I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.

The new way to execute external scripts is with the run function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.

import subprocess

subprocess.run(['./test.sh'])

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

Where do I find the Instagram media ID of a image

Your media ID is: 448979387270691659_45818965 This is how to get it.

  1. Go to instgram.com/username.
  2. Click the photo you want the id of.
  3. (Chrome instructions) right click on the photo (should be a popup image)
  4. Inspect element
  5. Search through the selected text, you should see something like this photo448979387270691659_45818965

There should be your photo ID.

For some reason, this only seems to work with the popup, and not the actual image URL.

Undefined index error PHP

TRY

<?php

  $rowID=$productid=$name=$price=$description="";  

   if (isset($_POST['submit'])) {
      $rowID = $_POST['rowID'];
      $productid = $_POST['productid']; //this is line 32 and so on...
      $name = $_POST['name'];
      $price = $_POST['price'];
      $description = $_POST['description'];

}

How to get images in Bootstrap's card to be the same height/width?

Each of the images need to be the exact dimensions before you put them up otherwise bootstrap 4 will try to place them in a funky shape. Bootstrap also has something like Masonry on their documents that you can use if need be, you can see that here, http://v4-alpha.getbootstrap.com/components/card/#columns.

C#: How to access an Excel cell?

Simple.

To open a workbook. Use xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

Should I use window.navigate or document.location in JavaScript?

I'd go with window.location = "http://...";. I've been coding cross-browser JavaScript for a few years, and I've never experienced problems using this approach.

window.navigate and window.location.href seems a bit odd to me.

How can I connect to MySQL in Python 3 on Windows?

There are currently a few options for using Python 3 with mysql:

https://pypi.python.org/pypi/mysql-connector-python

  • Officially supported by Oracle
  • Pure python
  • A little slow
  • Not compatible with MySQLdb

https://pypi.python.org/pypi/pymysql

  • Pure python
  • Faster than mysql-connector
  • Almost completely compatible with MySQLdb, after calling pymysql.install_as_MySQLdb()

https://pypi.python.org/pypi/cymysql

  • fork of pymysql with optional C speedups

https://pypi.python.org/pypi/mysqlclient

  • Django's recommended library.
  • Friendly fork of the original MySQLdb, hopes to merge back some day
  • The fastest implementation, as it is C based.
  • The most compatible with MySQLdb, as it is a fork
  • Debian and Ubuntu use it to provide both python-mysqldb andpython3-mysqldb packages.

benchmarks here: https://github.com/methane/mysql-driver-benchmarks

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I had this same issue when working on an Ubuntu server.

I was getting the following error:

deploy@my-comp:~$ docker login -u my-username -p my-password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
Error response from daemon: Get https://registry-1.docker.io/v2/: dial tcp 35.175.83.85:443: connect: connection refused

Here are the things I tried that did not work:

  • Restarting the docker service using sudo docker systemctl restart docker
  • Powering off and restarting the Ubuntu server.
  • Changing the name server to 8.8.8.8 in the /etc/resolv.conf file

Here's what worked for me:

I tried checking if the server has access to the internet using the following netcat command:

nc -vz google.com 443

And it returned this output:

nc: connect to google.com port 443 (tcp) failed: Connection refused
nc: connect to google.com port 443 (tcp) failed: Network is unreachable

Instead of something like this:

Ncat: Version 7.70 ( https://nmap.org/ncat )
Ncat: Connected to 172.217.166.110:443.
Ncat: 0 bytes sent, 0 bytes received in 0.07 seconds.

I tried checking again if the server has access to the internet using the following wget command:

wget -q --spider http://google.com ; echo $?

And it returned:

4

Instead of:

0

Note: Anything other than 0 in the output means your system is not connected to the internet

I then tried the last time if the server has access to the internet using the following Nmap command:

nmap -p 443 google.com

And it returned:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp closed https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Instead something like this:

Starting Nmap 7.01 ( https://nmap.org ) at 2021-02-16 11:50 WAT
Nmap scan report for google.com (216.58.223.238)
Host is up (0.00052s latency).
Other addresses for google.com (not scanned): 2c0f:fb50:4003:802::200e
rDNS record for 216.58.223.238: los02s04-in-f14.1e100.net
PORT    STATE  SERVICE
443/tcp open https

Nmap done: 1 IP address (1 host up) scanned in 1.21 seconds

Note: The state of port 443/tcp is closed instead of open

All this was enough to make me realize that connections to the internet were not allowed on the server.

All I had to do was speak with the team in charge of infrastructure to fix the network connectivity issue to the internet on the server. And once that was fixed my docker command started working fine.

Resources: 9 commands to check if connected to internet with shell script examples

That's all.

I hope this helps

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

In addition to the above:

  1. The default scope for @Autowired beans is Singleton whereas using JSR 330 @Inject annotation it is like Spring's prototype.
  2. There is no equivalent of @Lazy in JSR 330 using @Inject.
  3. There is no equivalent of @Value in JSR 330 using @Inject.

Combining "LIKE" and "IN" for SQL Server

One other option would be to use something like this

SELECT  * 
FROM    table t INNER JOIN
        (
            SELECT  'Text%' Col
            UNION SELECT 'Link%'
            UNION SELECT 'Hello%'
            UNION SELECT '%World%'
        ) List ON t.COLUMN LIKE List.Col

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

Best way to create enum of strings?

Use its name() method:

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Strings.ONE.name());
    }
}

enum Strings {
    ONE, TWO, THREE
}

yields ONE.

Clear and reset form input fields

/* See newState and use of it in eventSubmit() for resetting all the state. I have tested it is working for me. Please let me know for mistakes */

import React from 'react';
    
    const newState = {
        fullname: '',
        email: ''
    }
    
    class Form extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                fullname: ' ',
                email: ' '
            }
    
            this.eventChange = this
                .eventChange
                .bind(this);
            this.eventSubmit = this
                .eventSubmit
                .bind(this);
        }
        eventChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox'
                ? target.type
                : target.value;
            const name = target.name;
    
            this.setState({[name]: value})
        }
    
        eventSubmit(event) {
            alert(JSON.stringify(this.state))
            event.preventDefault();
            this.setState({...newState});
        }
    
        render() {
            return (
                <div className="container">
                    <form className="row mt-5" onSubmit={this.eventSubmit}>
                        <label className="col-md-12">
                            Full Name
                            <input
                                type="text"
                                name="fullname"
                                id="fullname"
                                value={this.state.fullname}
                                onChange={this.eventChange}/>
                        </label>
                        <label className="col-md-12">
                            email
                            <input
                                type="text"
                                name="email"
                                id="email"
                                value={this.state.value}
                                onChange={this.eventChange}/>
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            )
        }
    }
    
    export default Form;
    

Factorial in numpy and scipy

enter image description here

after running different aforementioned functions for factorial, by different people, turns out that math.factorial is the fastest to calculate the factorial.

find running times for different functions in the attached image

Is it possible to create a File object from InputStream

Create a temp file first.

File tempFile = File.createTempFile(prefix, suffix);
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(in, out);
return tempFile;

Youtube autoplay not working on mobile devices with embedded HTML5 player

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

unique object identifier in javascript

If you came here because you deal with class instances like me you can use static vars/methods to reference instances by a custom unique id:

_x000D_
_x000D_
class Person { 
    constructor( name ) {
        this.name = name;
        this.id = Person.ix++;
        Person.stack[ this.id ] = this;
    }
}
Person.ix = 0;
Person.stack = {};
Person.byId = id => Person.stack[ id ];

let store = {};
store[ new Person( "joe" ).id ] = true;
store[ new Person( "tim" ).id ] = true;

for( let id in store ) {
    console.log( Person.byId( id ).name );
}
_x000D_
_x000D_
_x000D_

How to play a sound in C#, .NET

For Windows Forms one way is to use the SoundPlayer

private void Button_Click(object sender, EventArgs e)
{
    using (var soundPlayer = new SoundPlayer(@"c:\Windows\Media\chimes.wav")) {
        soundPlayer.Play(); // can also use soundPlayer.PlaySync()
    }
}

MSDN page

This will also work with WPF, but you have other options like using MediaPlayer MSDN page

How to disable Google Chrome auto update?

On Windows OS:

1) open following file for edit (as an admin): C:\Windows\System32\drivers\etc\hosts (this file has no extension)

2) on the bottom, add one line: 127.0.0.1 tools.google.com

3) save the file

4) enjoy old Chrome

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

NEVER DELETE apply plugin: 'com.google.gms.google-services' from the gradle. Sometimes you are using com.google.gms:google-services:3.1.0 , without apply plugin: 'com.google.gms.google-services' your gradle build successfully. BUT IT IS COMPLETELY WRONG !!!! This error comes due to google-service.json file is not at the correct location. Go to your PROJECT TAB at left side above. If you display it as ANDROID make it PROJECT then check your google-service.json file is at this location. EXPAND app then see google-service.json file below the build.gradle. IF NOT PLACE IT THERE BY RIGHT CLICK ON THE app .

TypeError: Missing 1 required positional argument: 'self'

You can call the method like pump.getPumps(). By adding @classmethod decorator on the method. A class method receives the class as the implicit first argument, just like an instance method receives the instance.

class Pump:

def __init__(self):
    print ("init") # never prints

@classmethod
def getPumps(cls):
            # Open database connection
            # some stuff here that never gets executed because of error

So, simply call Pump.getPumps() .

In java, it is termed as static method.

Detect rotation of Android phone in the browser with JavaScript

I had the same problem. I am using Phonegap and Jquery mobile, for Adroid devices. To resize properly I had to set a timeout:

$(window).bind('orientationchange',function(e) {
  fixOrientation();
});

$(window).bind('resize',function(e) {
  fixOrientation();
});

function fixOrientation() {

    setTimeout(function() {

        var windowWidth = window.innerWidth;

        $('div[data-role="page"]').width(windowWidth);
        $('div[data-role="header"]').width(windowWidth);
        $('div[data-role="content"]').width(windowWidth-30);
        $('div[data-role="footer"]').width(windowWidth);

    },500);
}

While loop to test if a file exists in bash

I ran into a similar issue and it lead me here so I just wanted to leave my solution for anyone who experiences the same.

I found that if I ran cat /tmp/list.txt the file would be empty, even though I was certain that there were contents being placed immediately in the file. Turns out if I put a sleep 1; just before the cat /tmp/list.txt it worked as expected. There must have been a delay between the time the file was created and the time it was written, or something along those lines.

My final code:

while [ ! -f /tmp/list.txt ];
do
    sleep 1;
done;
sleep 1;
cat /tmp/list.txt;

Hope this helps save someone a frustrating half hour!

How to parse a CSV file in Bash?

We can parse csv files with quoted strings and delimited by say | with following code

while read -r line
do
    field1=$(echo "$line" | awk -F'|' '{printf "%s", $1}' | tr -d '"')
    field2=$(echo "$line" | awk -F'|' '{printf "%s", $2}' | tr -d '"')

    echo "$field1 $field2"
done < "$csvFile"

awk parses the string fields to variables and tr removes the quote.

Slightly slower as awk is executed for each field.

Set default host and port for ng serve in config file

As of right now that feature is not supported, however if this is something that bothers you an alternative would be in your package.json...

"scripts": {
  "start": "ng serve --host foo.bar --port 80"
}

This way you can simply run npm start

Another option if you want to do this across multiple projects is to create an alias, which you can potentially name ngserve which will execute your above command.

Using reCAPTCHA on localhost

This worked for me:

"With the following test keys, you will always get No CAPTCHA and all verification requests will pass.

Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI

Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe

The reCAPTCHA widget will show a warning message to claim that it's only for testing purpose. Please do not use these keys for your production traffic."

Extracted from here: https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha.-what-should-i-do

BR!

event Action<> vs event EventHandler<>

I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).

First to address the 800 lb elephant/gorilla in the room, when to choose event vs Action<T>/Func<T>:

  • Use a lambda to execute one statement or method. Use event when you want more of a pub/sub model with multiple statements/lambdas/functions that will execute (this is a major difference right off the bat).
  • Use a lambda when you want to compile statements/functions to expression trees. Use delegates/events when you want to participate in more traditional late binding such as used in reflection and COM interop.

As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:

public delegate void FireEvent(int num);

public delegate void FireNiceEvent(object sender, SomeStandardArgs args);

public class SomeStandardArgs : EventArgs
{
    public SomeStandardArgs(string id)
    {
        ID = id;
    }

    public string ID { get; set; }
}

class Program
{
    public static event FireEvent OnFireEvent;

    public static event FireNiceEvent OnFireNiceEvent;


    static void Main(string[] args)
    {
        OnFireEvent += SomeSimpleEvent1;
        OnFireEvent += SomeSimpleEvent2;

        OnFireNiceEvent += SomeStandardEvent1;
        OnFireNiceEvent += SomeStandardEvent2;


        Console.WriteLine("Firing events.....");
        OnFireEvent?.Invoke(3);
        OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));

        //Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
        Console.ReadLine();
    }

    private static void SomeSimpleEvent1(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
    }
    private static void SomeSimpleEvent2(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
    }

    private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
    {

        Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
    }
    private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
    {
        Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
    }
}

The output will look as follows:

enter image description here

If you did the same with Action<int> or Action<object, SomeStandardArgs>, you would only see SomeSimpleEvent2 and SomeStandardEvent2.

So whats going on inside of event?

If we expand out FireNiceEvent, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):

   private EventHandler<SomeStandardArgs> _OnFireNiceEvent;

    public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Combine(_OnFireNiceEvent, handler);
    }

    public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Remove(_OnFireNiceEvent, handler);
    }

    public event EventHandler<SomeStandardArgs> OnFireNiceEvent
    {
        add
        {
            add_OnFireNiceEvent(value)
        }
        remove
        {
            remove_OnFireNiceEvent(value)

        }
    }

The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar += and -= operators we have all come to know and love : )

You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).

To address a couple of points from some of the responses here:

  • There really is no difference in the 'brittleness' between changing the args list in Action<T> and changing the properties in a class derived from EventArgs. Either will not only require a compile change, they will both change a public interface and will require versioning. No difference.

  • With respect to which is an industry standard, that depends on where this is being used and why. Action<T> and such is often used in IoC and DI, and event is often used in message routing such as GUI and MQ type frameworks. Note that I said often, not always.

  • Delegates have different lifetimes than lambdas. One also has to be aware of capture... not just with closure, but also with the notion of 'look what the cat dragged in'. This does affect memory footprint/lifetime as well as management a.k.a. leaks.

One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.

Choose folders to be ignored during search in VS Code

Forget aboves for vscode exclude search pattern, try to below pattern it is working for any folder in vscode last version!

!../../../locales/*

for example i have searched like below vscode example clude settings

files to include: *.js

files to exclude: **/node_modules,!../../../locales/,!../../../theme/,!../../admin/client/*

Difference between two dates in years, months, days in JavaScript

You should try using date-fns. Here's how I did it using intervalToDuration and formatDuration functions from date-fns.

let startDate = Date.parse("2010-10-01 00:00:00 UTC");
let endDate = Date.parse("2020-11-01 00:00:00 UTC");

let duration = intervalToDuration({start: startDate, end: endDate});

let durationInWords = formatDuration(duration, {format: ["years", "months", "days"]}); //output: 10 years 1 month

How to "scan" a website (or page) for info, and bring it into my program?

JSoup solution is great, but if you need to extract just something really simple it may be easier to use regex or String.indexOf

As others have already mentioned the process is called scraping

List<T> OrderBy Alphabetical Order

If you mean an in-place sort (i.e. the list is updated):

people.Sort((x, y) => string.Compare(x.LastName, y.LastName));

If you mean a new list:

var newList = people.OrderBy(x=>x.LastName).ToList(); // ToList optional

PHP Redirect with POST data

Try this:

Send data and request with http header in page B to redirect to Gateway

<?php
$host = "www.example.com";
$path = "/path/to/script.php";
$data = "data1=value1&data2=value2";
$data = urlencode($data);

header("POST $path HTTP/1.1\\r\
" );
header("Host: $host\\r\
" );
header("Content-type: application/x-www-form-urlencoded\\r\
" );
header("Content-length: " . strlen($data) . "\\r\
" );
header("Connection: close\\r\
\\r\
" );
header($data);
?>

Additional Headers :

Accept: \*/\*
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like 
Gecko) Chrome/74.0.3729.169 Safari/537.36

How to create a directory and give permission in single command

Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.

Multiple bluetooth connection

You can take a look here ( this is not a solution but the idea is here)

sample multi client with the google chat example

what you have to change/do :

  • separate server and client logique in different classes

  • for the client you need an object to manage one connect thread and on connected thread

  • for the server you need an object to manage one listening thread per client, and one connected thread per client

  • the server open a listening thread on each UUID (one per client)

  • each client try to connect to each uuid (the uuid already taken will fail the connection => first come first served)

Any question ?

printing a value of a variable in postgresql

You can raise a notice in Postgres as follows:

raise notice 'Value: %', deletedContactId;

Read here

Python Prime number checker

def isprime(n):
    '''check if integer n is a prime'''

    # make sure n is a positive integer
    n = abs(int(n))

    # 0 and 1 are not primes
    if n < 2:
        return False

    # 2 is the only even prime number
    if n == 2: 
        return True    

    # all other even numbers are not primes
    if not n & 1: 
        return False

    # range starts with 3 and only needs to go up 
    # the square root of n for all odd numbers
    for x in range(3, int(n**0.5) + 1, 2):
        if n % x == 0:
            return False

    return True

Taken from:

http://www.daniweb.com/software-development/python/code/216880/check-if-a-number-is-a-prime-number-python

JSON: why are forward slashes escaped?

The JSON spec says you CAN escape forward slash, but you don't have to.

How to get the index of an element in an IEnumerable?

I think the best option is to implement like this:

public static int IndexOf<T>(this IEnumerable<T> enumerable, T element, IEqualityComparer<T> comparer = null)
{
    int i = 0;
    comparer = comparer ?? EqualityComparer<T>.Default;
    foreach (var currentElement in enumerable)
    {
        if (comparer.Equals(currentElement, element))
        {
            return i;
        }

        i++;
    }

    return -1;
}

It will also not create the anonymous object

How to convert a time string to seconds?

It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with %I

>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>

jQuery: how to get which button was clicked upon form submission?

A simple way to distinguish which <button> or <input type="button"...> is pressed, is by checking their 'id':

$("button").click(function() {
  var id = $(this).attr('id');
  ... 
});

How do I count unique values inside a list

In addition, use collections.Counter to refactor your code:

from collections import Counter

words = ['a', 'b', 'c', 'a']

Counter(words).keys() # equals to list(set(words))
Counter(words).values() # counts the elements' frequency

Output:

['a', 'c', 'b']
[2, 1, 1]

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}