Programs & Examples On #Unzip

Unzipping is uncompressing ZIP archives, the opposite of zipping.

Simple way to unzip a .zip file using zlib

zlib handles the deflate compression/decompression algorithm, but there is more than that in a ZIP file.

You can try libzip. It is free, portable and easy to use.

UPDATE: Here I attach quick'n'dirty example of libzip, with all the error controls ommited:

#include <zip.h>

int main()
{
    //Open the ZIP archive
    int err = 0;
    zip *z = zip_open("foo.zip", 0, &err);

    //Search for the file of given name
    const char *name = "file.txt";
    struct zip_stat st;
    zip_stat_init(&st);
    zip_stat(z, name, 0, &st);

    //Alloc memory for its uncompressed contents
    char *contents = new char[st.size];

    //Read the compressed file
    zip_file *f = zip_fopen(z, name, 0);
    zip_fread(f, contents, st.size);
    zip_fclose(f);

    //And close the archive
    zip_close(z);

    //Do something with the contents
    //delete allocated memory
    delete[] contents;
}

How do you recursively unzip archives in a directory and its subdirectories from the Unix command-line?

If you want to extract the files to the respective folder you can try this

find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;

A multi-processed version for systems that can handle high I/O:

find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'

Unzipping files

If you need to support other formats as well or just need good performance, you can use this WebAssembly library

it's promised based, it uses WebWorkers for threading and API is actually simple ES module

Unzipping files in Python

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

java.util.zip.ZipException: error in opening zip file

I was getting exception

java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0xdeadface)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:221)
    at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:140)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:118)
...

when unzipping an archive in Java. The archive itself didn't seem corrupted as 7zip (and others) opened it without any problems or complaints about invalid CRC.

I switched to Apache Commons Compress for reading the zip-entries and that resolved the problem.

How to unzip files programmatically in Android?

public class MainActivity extends Activity {

private String LOG_TAG = MainActivity.class.getSimpleName();

private File zipFile;
private File destination;

private TextView status;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    status = (TextView) findViewById(R.id.main_status);
    status.setGravity(Gravity.CENTER);

    if ( initialize() ) {
        zipFile = new File(destination, "BlueBoxnew.zip");
        try {
            Unzipper.unzip(zipFile, destination);
            status.setText("Extracted to \n"+destination.getAbsolutePath());
        } catch (ZipException e) {
            Log.e(LOG_TAG, e.getMessage());
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }
    } else {
        status.setText("Unable to initialize sd card.");
    }
}

public boolean initialize() {
    boolean result = false;
     File sdCard = new File(Environment.getExternalStorageDirectory()+"/zip/");
    //File sdCard = Environment.getExternalStorageDirectory();
    if ( sdCard != null ) {
        destination = sdCard;
        if ( !destination.exists() ) {
            if ( destination.mkdir() ) {
                result = true;
            }
        } else {
            result = true;
        }
    }

    return result;
}

 }

->Helper Class(Unzipper.java)

    import java.io.File;
    import java.io.FileInputStream;
   import java.io.FileOutputStream;
    import java.io.IOException;
       import java.util.zip.ZipEntry;
    import java.util.zip.ZipException;
    import java.util.zip.ZipInputStream;
     import android.util.Log;

   public class Unzipper {

private static String LOG_TAG = Unzipper.class.getSimpleName();

public static void unzip(final File file, final File destination) throws ZipException, IOException {
    new Thread() {
        public void run() {
            long START_TIME = System.currentTimeMillis();
            long FINISH_TIME = 0;
            long ELAPSED_TIME = 0;
            try {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(file));
                String workingDir = destination.getAbsolutePath()+"/";

                byte buffer[] = new byte[4096];
                int bytesRead;
                ZipEntry entry = null;
                while ((entry = zin.getNextEntry()) != null) {
                    if (entry.isDirectory()) {
                        File dir = new File(workingDir, entry.getName());
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        Log.i(LOG_TAG, "[DIR] "+entry.getName());
                    } else {
                        FileOutputStream fos = new FileOutputStream(workingDir + entry.getName());
                        while ((bytesRead = zin.read(buffer)) != -1) {
                            fos.write(buffer, 0, bytesRead);
                        }
                        fos.close();
                        Log.i(LOG_TAG, "[FILE] "+entry.getName());
                    }
                }
                zin.close();

                FINISH_TIME = System.currentTimeMillis();
                ELAPSED_TIME = FINISH_TIME - START_TIME;
                Log.i(LOG_TAG, "COMPLETED in "+(ELAPSED_TIME/1000)+" seconds.");
            } catch (Exception e) {
                Log.e(LOG_TAG, "FAILED");
            }
        };
    }.start();
}

   }

->xml layout(activity_main.xml):

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >

<TextView
    android:id="@+id/main_status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

</RelativeLayout>

->permission in Menifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Downloading and unzipping a .zip file without writing to disk

I'd like to add my Python3 answer for completeness:

from io import BytesIO
from zipfile import ZipFile
import requests

def get_zip(file_url):
    url = requests.get(file_url)
    zipfile = ZipFile(BytesIO(url.content))
    zip_names = zipfile.namelist()
    if len(zip_names) == 1:
        file_name = zip_names.pop()
        extracted_file = zipfile.open(file_name)
        return extracted_file
    return [zipfile.open(file_name) for file_name in zip_names]

Unzip a file with php

Just change

system('unzip $master.zip');

To this one

system('unzip ' . $master . '.zip');

or this one

system("unzip {$master}.zip");

Unzip All Files In A Directory

If by 'current directory' you mean the directory in which the zip file is, then I would use this command:

find . -name '*.zip' -execdir unzip {} \; 

excerpt from find's man page

-execdir command ;
-execdir command {} +

Like -exec, but the specified command is run from the subdirectory containing the matched file, which is not normally the directory in which you started find. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec option, the '+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your $PATH environment variable does not reference the current directory; otherwise, an attacker can run any commands they like by leaving an appropriately-named file in a directory in which you will run -execdir.

Unzip files programmatically in .net

you can use Info-unzip command line cod.you only need to download unzip.exe from Info-unzip official website.

 internal static void Unzip(string sorcefile)
    {
        try
        {
            AFolderFiles.AFolderFilesDelete.DeleteFolder(TempBackupFolder); // delete old folder   
            AFolderFiles.AFolderFilesCreate.CreateIfNotExist(TempBackupFolder); // delete old folder   
           //need to Command command also to export attributes to a excel file
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
            startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; // window type
            startInfo.FileName = UnzipExe;
            startInfo.Arguments = sorcefile + " -d " + TempBackupFolder;
            process.StartInfo = startInfo;
            process.Start();
            //string result = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            process.Dispose();
            process.Close();
        }
        catch (Exception ex){ throw ex; }
    }        

How do I put the image on the right side of the text in a UIButton?

Building on Piotr Tomasik's elegant solution: if you want to have a bit of spacing between the button label and image as well, then include that in your edge insets as follows (copying my code here that works perfectly for me):

    CGFloat spacing          = 3;
    CGFloat insetAmount      = 0.5 * spacing;

    // First set overall size of the button:
    button.contentEdgeInsets = UIEdgeInsetsMake(0, insetAmount, 0, insetAmount);
    [button sizeToFit];

    // Then adjust title and image insets so image is flipped to the right and there is spacing between title and image:
    button.titleEdgeInsets   = UIEdgeInsetsMake(0, -button.imageView.frame.size.width - insetAmount, 0,  button.imageView.frame.size.width  + insetAmount);
    button.imageEdgeInsets   = UIEdgeInsetsMake(0, button.titleLabel.frame.size.width + insetAmount, 0, -button.titleLabel.frame.size.width - insetAmount);

Thanks Piotr for your solution!

Erik

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

1 = 1 expression is commonly used in generated sql code. This expression can simplify sql generating code reducing number of conditional statements.

How to restore SQL Server 2014 backup in SQL Server 2008

No I guess you cannot restore the databases from higher version to lower version , you can make data flow b/w them i,e you can scriptout. http://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

Closing database connections in Java

It is always better to close the database/resource objects after usage. Better close the connection, resultset and statement objects in the finally block.

Until Java 7, all these resources need to be closed using a finally block. If you are using Java 7, then for closing the resources, you can do as follows.

try(Connection con = getConnection(url, username, password, "org.postgresql.Driver");
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery(sql);
) {

    // Statements
}
catch(....){}

Now, the con, stmt and rs objects become part of try block and Java automatically closes these resources after use.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

The getPosts() function seems to be expecting $con to be global, but you're not declaring it as such.

A lot of programmers regard bald global variables as a "code smell". The alternative at the other end of the scale is to always pass around the connection resource. Partway between the two is a singleton call that always returns the same resource handle.

Anonymous method in Invoke call

Actually you do not need to use delegate keyword. Just pass lambda as parameter:

control.Invoke((MethodInvoker)(() => {this.Text = "Hi"; }));

Joining two lists together

As long as they are of the same type, it's very simple with AddRange:

list2.AddRange(list1);

Change CSS properties on click

    <script>
        function change_css(){
            document.getElementById('result').style.cssText = 'padding:20px; background-color:#b2b2ff; color:#0c0800; border:1px solid #0c0800; font-size:22px;';
        }
    </script>

</head>

<body>
    <center>
        <div id="error"></div>
        <center>
            <div id="result"><h2> Javascript Example On click Change Css style</h2></div>
            <button onclick="change_css();">Check</button><br />
        </center>
    </center>
</body>

How can I select the record with the 2nd highest salary in database Oracle?

select Max(Salary) as SecondHighestSalary from Employee where Salary not in (select max(Salary) from Employee)

How to go back to previous page if back button is pressed in WebView?

here is a code with confirm exit:

@Override
    public void onBackPressed()
    {
        if(webView.canGoBack()){
            webView.goBack();
        }else{
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Exit!")
            .setMessage("Are you sure you want to close?")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();    
                }

            })
            .setNegativeButton("No", null)
            .show();    
        }   
    }

How to place object files in separate subdirectory

For all those working with implicit rules (and GNU MAKE). Here is a simple makefile which supports different directories:

#Start of the makefile

VPATH = ./src:./header:./objects

OUTPUT_OPTION = -o objects/$@

CXXFLAGS += -Wall -g -I./header

Target = $(notdir $(CURDIR)).exe

Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))



all: $(Target)

$(Target): $(Objects)
     $(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))


#Beware of -f. It skips any confirmation/errors (e.g. file does not exist)

.PHONY: clean
clean:
     rm -f $(addprefix objects/,$(Objects)) $(Target)

Lets have a closer look (I will refer to the current Directory with curdir):

This line is used to get a list of the used .o files which are in curdir/src.

Objects := $(notdir $(patsubst %.cpp,%.o,$(wildcard src/*.cpp)))
#expands to "foo.o myfoo.o otherfoo.o"

Via variable the output is set to a different directory (curdir/objects).

OUTPUT_OPTION = -o objects/$@
#OUTPUT_OPTION will insert the -o flag into the implicit rules

To make sure the compiler finds the objects in the new objects folder, the path is added to the filename.

$(Target): $(Objects)
     $(CXX) $(CXXFLAGS) -o $(Target) $(addprefix objects/,$(Objects))
#                                    ^^^^^^^^^^^^^^^^^^^^    

This is meant as an example and there is definitly room for improvement.

For additional Information consult: Make documetation. See chapter 10.2

Or: Oracle: Programming Utilities Guide

Java get last element of a collection

Iterables.getLast from Google Guava. It has some optimization for Lists and SortedSets too.

Java 6 Unsupported major.minor version 51.0

I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more

Step to Do this

1-sudo vim /etc/environment

2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)

3-Run echo $JAVA_HOME will give the JAVA_HOME set value

4-Now mvn -version will give the desired output

Apache Maven 3.3.9

Maven home: /usr/share/maven

Java version: 1.7.0_45, vendor: Oracle Corporation

Java home: /opt/dev/jdk1.7.0_45/jre

Default locale: en_US, platform encoding: UTF-8

OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"

Increasing the timeout value in a WCF service

Are you referring to the server side or the client side?

For a client, you would want to adjust the sendTimeout attribute of a binding element. For a service, you would want to adjust the receiveTimeout attribute of a binding elemnent.

<system.serviceModel>
  <bindings>
    <netTcpBinding>
      <binding name="longTimeoutBinding"
        receiveTimeout="00:10:00" sendTimeout="00:10:00">
        <security mode="None"/>
      </binding>
    </netTcpBinding>
  </bindings>

  <services>
    <service name="longTimeoutService"
      behaviorConfiguration="longTimeoutBehavior">
      <endpoint address="net.tcp://localhost/longtimeout/"
        binding="netTcpBinding" bindingConfiguration="longTimeoutBinding" />
    </service>
....

Of course, you have to map your desired endpoint to that particular binding.

How to access URL segment(s) in blade in Laravel 5?

Here is how one can do it via the global request helper function.

{{ request()->segment(1) }}

Note: request() returns the object of the Request class.

Removing page title and date when printing web page (with CSS?)

A possible workaround for the page title:

  • Provide a print button,
  • catch the onclick event,
  • use javascript to change the page title,
  • then execute the print command via javascript as well.

document.title = "Print page title"; window.print();

This should work in every browser.

C# - What does the Assert() method do? Is it still useful?

Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!

Running Python in PowerShell?

Using CMD you can run your python scripts as long as the installed python is added to the path with the following line:

C: \ Python27;

The (27) is example referring to version 2.7, add as per your version.

Path to system path:

Control Panel => System and Security => System => Advanced Settings => Advanced => Environment Variables.

Under "User Variables," append the PATH variable to the path of the Python installation directory (As above).

Once this is done, you can open a CMD where your scripts are saved, or manually navigate through the CMD.

To run the script enter:

C: \ User \ X \ MyScripts> python ScriptName.py

Drop Down Menu/Text Field in one

I'd like to add a jQuery autocomplete based solution that does the job.

Step 1: Make the list fixed height and scrollable

Get the code from https://jqueryui.com/autocomplete/ "Scrollable" example, setting max height to the list of results so it behaves as a select box.

Step 2: Open the list on focus:

Display jquery ui auto-complete list on focus event

Step 3: Set minimum chars to 0 so it opens no matter how many chars are in the input

Final result:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Scrollable results</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .ui-autocomplete {
    max-height: 100px;
    overflow-y: auto;
    /* prevent horizontal scrollbar */
    overflow-x: hidden;
  }
  /* IE 6 doesn't support max-height
   * we use height instead, but this forces the menu to always be this tall
   */
  * html .ui-autocomplete {
    height: 100px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
//      source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
      source: function (request, response) {
          response( availableTags);
      },
      minLength: 0
    }).focus(function(){
//        $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
        $(this).data("uiAutocomplete").search('');
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>


</body>
</html>

Check jsfiddle here:

https://jsfiddle.net/bao7fhm3/1/

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

I could do this with a custom attribute as follows.

[AuthorizeUser(AccessLevel = "Create")]
public ActionResult CreateNewInvoice()
{
    //...
    return View();
}

Custom Attribute class as follows.

public class AuthorizeUserAttribute : AuthorizeAttribute
{
    // Custom property
    public string AccessLevel { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = base.AuthorizeCore(httpContext);
        if (!isAuthorized)
        {                
            return false;
        }

        string privilegeLevels = string.Join("", GetUserRights(httpContext.User.Identity.Name.ToString())); // Call another method to get rights of the user from DB

        return privilegeLevels.Contains(this.AccessLevel);           
    }
}

You can redirect an unauthorised user in your custom AuthorisationAttribute by overriding the HandleUnauthorizedRequest method:

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(
                new RouteValueDictionary(
                    new
                        { 
                            controller = "Error", 
                            action = "Unauthorised" 
                        })
                );
}

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

I had same issue, I resolved from below steps:

  1. Right click on project->maven->Update project
  2. Here I selected "force update for snapshot/release"
  3. After that I compiled again my project and issue got fixed

Cannot find module '@angular/compiler'

I just run npm install and then ok.

Center an element with "absolute" position and undefined width in CSS?

None of the solutions worked for me since I didn't want to change the styling of the container/wrapper element. This code worked for me:

position: absolute;
left: 50%;
margin-left: -50px;
top: 50%;
margin-top: -50px;

How to manage local vs production settings in Django?

I use a variation of what jpartogi mentioned above, that I find a little shorter:

import platform
from django.core.management import execute_manager 

computername = platform.node()

try:
  settings = __import__(computername + '_settings')
except ImportError: 
  import sys
  sys.stderr.write("Error: Can't find the file '%r_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file local_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % (computername, __file__))
  sys.exit(1)

if __name__ == "__main__":
  execute_manager(settings)

Basically on each computer (development or production) I have the appropriate hostname_settings.py file that gets dynamically loaded.

How to activate virtualenv?

Cd to the environment path, go to the bin folder. At this point when you use ls command, you should see the "activate" file.

now type

source activate

how to add value to combobox item

I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:

Public Class MyListItem
    Private mText As String
    Private mValue As String

    Public Sub New(ByVal pText As String, ByVal pValue As String)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

Now when you want to add the items to your ComboBox you can do it like this:

myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))

Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:

Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)

One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.


Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.

Here's the new and improved GenericListItem class:

Public Class GenericListItem(Of T)
    Private mText As String
    Private mValue As T

    Public Sub New(ByVal pText As String, ByVal pValue As T)
        mText = pText
        mValue = pValue
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return mText
        End Get
    End Property

    Public ReadOnly Property Value() As T
        Get
            Return mValue
        End Get
    End Property

    Public Overrides Function ToString() As String
        Return mText
    End Function
End Class

And here is how you would now add Generic items to your ComboBox. In this case an Integer:

Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))

And now the retrieval of the item:

Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())

Keep in mind that the type Integer can be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.

PostgreSQL IF statement

Just to help if anyone stumble on this question like me, if you want to use if in PostgreSQL, you use "CASE"

select 
    case
        when stage = 1 then 'running'
        when stage = 2 then 'done'
        when stage = 3 then 'stopped'
    else 
        'not running'
    end as run_status from processes

Java serialization - java.io.InvalidClassException local class incompatible

This worked for me:

If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.

So, write the necessary objects to file again if a class is modified and recompiled.

PS: This is NOT a solution; was meant to be a workaround.

Convert serial.read() into a useable string using Arduino?

If you're using concatenate method then don't forget to trim the string if you're working with if else method.

Creating a left-arrow button (like UINavigationBar's "back" style) on a UIToolbar

I had a similar problem, and come out one library PButton. And the sample is the back navigation button like button, which can be used anywhere just like a customized button.

Something like this: enter image description here

how to generate public key from windows command prompt

ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key

Writing a list to a file with Python

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

Implement specialization in ER diagram

So I assume your permissions table has a foreign key reference to admin_accounts table. If so because of referential integrity you will only be able to add permissions for account ids exsiting in the admin accounts table. Which also means that you wont be able to enter a user_account_id [assuming there are no duplicates!]

Setting Django up to use MySQL

If you are using python3.x then Run below command

pip install mysqlclient

Then change setting.py like

DATABASES = {
'default': {
    'ENGINE': 'django.db.backends.mysql',
    'NAME': 'DB',
     'USER': 'username',
    'PASSWORD': 'passwd',
  }
  }

Why can't decimal numbers be represented exactly in binary?

As we have been discussing, in floating point arithmetic, the decimal 0.1 cannot be perfectly represented in binary.

Floating point and integer representations provide grids or lattices for the numbers represented. As arithmetic is done, the results fall off the grid and have to be put back onto the grid by rounding. Example is 1/10 on a binary grid.

If we use binary coded decimal representation as one gentleman suggested, would we be able to keep numbers on the grid?

Getting JSONObject from JSONArray

JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");

for(int i = 0; deletedtrs_array.length(); i++){

            JSONObject myObj = deletedtrs_array.getJSONObject(i);
}

Angular 2 router no base href set

it is just that add below code in the index.html head tag

   <html>
    <head>
     <base href="/">
      ...

that worked like a charm for me.

Android studio Gradle build speed up

With Android Studio 2.1 you can enable "Dex In Process" for faster app builds.

enter image description here

You can get more info about it here: https://medium.com/google-developers/faster-android-studio-builds-with-dex-in-process-5988ed8aa37e#.vijksflyn

Convert java.util.Date to java.time.LocalDate

Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();

The Date instance does contain time too along with the date while LocalDate doesn't. So you can firstly convert it into LocalDateTime using its method ofInstant() then if you want it without time then convert the instance into LocalDate.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

What is a constant reference? (not a reference to a constant)

First I think int&const icr=i; is just int& icr = i, Modifier 'const' makes no sense(It just means you cannot make the reference refer to other variable).

const int x = 10;
// int& const y = x; // Compiler error here

Second, constant reference just means you cannot change the value of variable through reference.

const int x = 10;
const int& y = x;
//y = 20; // Compiler error here

Third, Constant references can bind right-value. Compiler will create a temp variable to bind the reference.

float x = 10;
const int& y = x;
const int& z = y + 10;
cout << (long long)&x << endl; //print 348791766212
cout << (long long)&y << endl; //print 348791766276
cout << (long long)&z << endl; //print 348791766340

Kotlin - How to correctly concatenate a String

I agree with the accepted answer above but it is only good for known string values. For dynamic string values here is my suggestion.

// A list may come from an API JSON like
{
   "names": [
      "Person 1",
      "Person 2",
      "Person 3",
         ...
      "Person N"
   ]
}
var listOfNames = mutableListOf<String>() 

val stringOfNames = listOfNames.joinToString(", ") 
// ", " <- a separator for the strings, could be any string that you want

// Posible result
// Person 1, Person 2, Person 3, ..., Person N

This is useful for concatenating list of strings with separator.

How can I find last row that contains data in a specific column?

You should use the .End(xlup) but instead of using 65536 you might want to use:

sheetvar.Rows.Count

That way it works for Excel 2007 which I believe has more than 65536 rows

Random string generation with upper case letters and digits

Use Numpy's random.choice() function

import numpy as np
import string        

if __name__ == '__main__':
    length = 16
    a = np.random.choice(list(string.ascii_uppercase + string.digits), length)                
    print(''.join(a))

Documentation is here http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.random.choice.html

Installing R on Mac - Warning messages: Setting LC_CTYPE failed, using "C"

Just open the R(software) and copy and paste

system("defaults write org.R-project.R force.LANG en_US.UTF-8")

Hope this will work fine or use the other method

open(on mac): Utilities/Terminal copy and paste

defaults write org.R-project.R force.LANG en_US.UTF-8

and close both terminal and R and reopen R.

How to remove all the punctuation in a string? (Python)

Strip won't work. It only removes leading and trailing instances, not everything in between: http://docs.python.org/2/library/stdtypes.html#str.strip

Having fun with filter:

import string
asking = "hello! what's your name?"
predicate = lambda x:x not in string.punctuation
filter(predicate, asking)

CSS to keep element at "fixed" position on screen

In order to keep floating text in the same location over an image when changing browser zoom, I used this CSS:

position: absolute;
margin-top: -18%

I think the % instead of fixed pixels is what does it. Cheers!

JavaScript code to stop form submission

Just use a simple button instead of a submit button. And call a JavaScript function to handle form submit:

<input type="button" name="submit" value="submit" onclick="submit_form();"/>

Function within a script tag:

function submit_form() {
    if (conditions) {
        document.forms['myform'].submit();
    }
    else {
        returnToPreviousPage();
    }
}

You can also try window.history.forward(-1);

How to enable CORS in ASP.net Core WebAPI

Here is my code : )

  app.Use((ctx, next) =>
        {
            ctx.Response.Headers.Add("Access-Control-Allow-Origin", ctx.Request.Headers["Origin"]);
            ctx.Response.Headers.Add("Access-Control-Allow-Methods", "*");
            ctx.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
            ctx.Response.Headers.Add("Access-Control-Allow-Headers", "AccessToken,Content-Type");
            ctx.Response.Headers.Add("Access-Control-Expose-Headers", "*");
            if (ctx.Request.Method.ToLower() == "options")
            {
                ctx.Response.StatusCode = 204;

                return Task.CompletedTask;
            }
            return next();
        });

How to add a new line of text to an existing file in Java?

you have to open the file in append mode, which can be achieved by using the FileWriter(String fileName, boolean append) constructor.

output = new BufferedWriter(new FileWriter(my_file_name, true));

should do the trick

Content Security Policy: The page's settings blocked the loading of a resource

I had a similar error type. First, I tried to add the meta tags in the code, but it didn't work.

I found out that on the nginx web server you may have a security setting that may block external code to run:

# Security directives
server_tokens off;
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'  https://ajax.googleapis.com  https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://assets.zendesk.com; font-src 'self' https://fonts.gstatic.com  https://themes.googleusercontent.com; frame-src https://player.vimeo.com https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

Check the Content-Security-Policy. You may need to add the source reference.

How do you update a DateTime field in T-SQL?

UPDATE TABLE
   SET EndDate = CAST('2017-12-31' AS DATE)
 WHERE Id = '123'

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Correct way to write loops for promise.

If you really want a general promiseWhen() function for this and other purposes, then by all means do so, using Bergi's simplifications. However, because of the way promises work, passing callbacks in this way is generally unnecessary and forces you to jump through complex little hoops.

As far as I can tell you're trying :

  • to asynchronously fetch a series of user details for a collection of email addresses (at least, that's the only scenario that makes sense).
  • to do so by building a .then() chain via recursion.
  • to maintain the original order when handling the returned results.

Defined thus, the problem is actually the one discussed under "The Collection Kerfuffle" in Promise Anti-patterns, which offers two simple solutions :

  • parallel asynchronous calls using Array.prototype.map()
  • serial asynchronous calls using Array.prototype.reduce().

The parallel approach will (straightforwardly) give the issue that you are trying to avoid - that the order of the responses is uncertain. The serial approach will build the required .then() chain - flat - no recursion.

function fetchUserDetails(arr) {
    return arr.reduce(function(promise, email) {
        return promise.then(function() {
            return db.getUser(email).done(function(res) {
                logger.log(res);
            });
        });
    }, Promise.resolve());
}

Call as follows :

//Compose here, by whatever means, an array of email addresses.
var arrayOfEmailAddys = [...];

fetchUserDetails(arrayOfEmailAddys).then(function() {
    console.log('all done');
});

As you can see, there's no need for the ugly outer var count or it's associated condition function. The limit (of 10 in the question) is determined entirely by the length of the array arrayOfEmailAddys.

Invalid self signed SSL cert - "Subject Alternative Name Missing"

Following solution worked for me on chrome 65 (ref) -

Create an OpenSSL config file (example: req.cnf)

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = VA
L = SomeCity
O = MyCompany
OU = MyDivision
CN = www.company.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.company.com
DNS.2 = company.com
DNS.3 = company.net

Create the certificate referencing this config file

openssl req -x509 -nodes -days 730 -newkey rsa:2048 \
 -keyout cert.key -out cert.pem -config req.cnf -sha256

How can I change the color of a Google Maps marker?

Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.

See my answer on Google Maps API 3 - Custom marker color for default (dot) marker

How do I use the includes method in lodash to check if an object is in the collection?

You could use find to solve your problem

https://lodash.com/docs/#find

const data = [{"a": 1}, {"b": 2}]
const item = {"b": 2}


find(data, item)
// > true

Renaming the current file in Vim

Short, secure, without plugin:

:sav new_name
:!rm <C-R>#  // or !del <C-R># for windows

control + R, # will instantly expand to an alternate-file (previously edited path in current window) before pressing Enter. That allows us to review what exactly we're going to delete. Using pipe | in such a case is not secure, because if sav fails for any reason, # will still point to another place (or to nothing). That means !rm # or delete(expand(#)) may delete completely different file! So do it by hand carefully or use good script (they are mentioned in many answers here).

Educational

...or try build a function/command/script yourself. Start from sth simple like:

command! -nargs=1 Rename saveas <args> | call delete(expand('#')) | bd #

after vimrc reload, just type :Rename new_filename. What is the problem with this command?

Security test 1: What does:Rename without argument?

Yes, it deletes file hidden in '#' !

Solution: you can use eg. conditions or try statement like that:

command! -nargs=1 Rename try | saveas <args> | call delete(expand('#')) | bd # | endtry

Security test 1: :Rename (without argument) will throw an error:

E471: Argument required

Security test 2: What if the name will be the same like previous one?

Security test 3: What if the file will be in different location than your actual?

Fix it yourself. For readability you can write it in this manner:

function! s:localscript_name(name):
  try
    execute 'saveas ' . a:name
    ...
  endtry
endfunction
command! -nargs=1 Rename call s:localscript_name(<f-args>)

notes

  • !rm # is better than !rm old_name -> you don't need remember the old name

  • !rm <C-R># is better than !rm # when do it by hand -> you will see what you actually remove (safety reason)

  • !rm is generally not very secure... mv to a trash location is better

  • call delete(expand('#')) is better than shell command (OS agnostic) but longer to type and impossible to use control + R

  • try | code1 | code2 | tryend -> when error occurs while code1, don't run code2

  • :sav (or :saveas) is equivalent to :f new_name | w - see file_f - and preserves undo history

  • expand('%:p') gives whole path of your location (%) or location of alternate file (#)

How to toggle font awesome icon on click?

Simply call jQuery's toggleClass() on the i element contained within your a element(s) to toggle either the plus and minus icons:

...click(function() {
    $(this).find('i').toggleClass('fa-minus-circle fa-plus-circle');
});

Note that this assumes that a class of fa-plus-circle is added to your i element by default.

JSFiddle demo.

Datetime equal or greater than today in MySQL

SELECT * FROM table_name WHERE CONCAT( SUBSTRING(json_date, 11, 4 ) ,  '-', SUBSTRING( json_date, 7, 2 ) ,  '-', SUBSTRING(json_date, 3, 2 ) ) >= NOW();

json_date ["05/11/2011"]

How to install cron

Do you have a Windows machine or a Linux machine?

Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.

Under Linux you can create a crontab for your current user by typing:

crontab -e [username]

If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:

sudo apt-get update
sudo apt-get install cron

If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:

*/5 * * * *  /home/user/test.pl

The syntax is basically this:

.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed

Read more about it on the following pages: Wikipedia: crontab

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

EXC_BAD_ACCESS signal received

The 2010 WWDC videos are available to any participants in the apple developer program. There's a great video: "Session 311 - Advanced Memory Analysis with Instruments" that shows some examples of using zombies in instruments and debugging other memory problems.

For a link to the login page click HERE.

Compare given date with today

Few years later, I second Bobby Jack's observation that last 24 hrs is not today!!! And I am surprised that the answer was so much upvoted...

To compare if a certain date is less, equal or greater than another, first you need to turn them "down" to beginning of the day. In other words, make sure that you're talking about same 00:00:00 time in both dates. This can be simply and elegantly done as:

strtotime("today") <=> strtotime($var)

if $var has the time part on 00:00:00 like the OP specified.

Replace <=> with whatever you need (or keep it like this in php 7)

Also, obviously, we're talking about same timezone for both. For list of supported TimeZones

Completely removing phpMyAdmin

I had same problem. Try the following command. This solved my problem.

sudo apt-get install libapache2-mod-php5

What are the benefits of learning Vim?

Learning something new is always worth the effort, IMHO. I suggest you print out a cheat sheet and force yourself to use it day-in and day-out.

How to select rows with no matching entry in another table?

You can do something like this

   SELECT IFNULL(`price`.`fPrice`,100) as fPrice,product.ProductId,ProductName 
          FROM `products` left join `price` ON 
          price.ProductId=product.ProductId AND (GeoFancingId=1 OR GeoFancingId 
          IS NULL) WHERE Status="Active" AND Delete="No"

Spark specify multiple column conditions for dataframe join

Scala:

Leaddetails.join(
    Utm_Master, 
    Leaddetails("LeadSource") <=> Utm_Master("LeadSource")
        && Leaddetails("Utm_Source") <=> Utm_Master("Utm_Source")
        && Leaddetails("Utm_Medium") <=> Utm_Master("Utm_Medium")
        && Leaddetails("Utm_Campaign") <=> Utm_Master("Utm_Campaign"),
    "left"
)

To make it case insensitive,

import org.apache.spark.sql.functions.{lower, upper}

then just use lower(value) in the condition of the join method.

Eg: dataFrame.filter(lower(dataFrame.col("vendor")).equalTo("fortinet"))

Get img src with PHP

You would be better off using a DOM parser for this kind of HTML parsing. Consider this code:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//img"); // find your image
$node = $nodelist->item(0); // gets the 1st image
$value = $node->attributes->getNamedItem('src')->nodeValue;
echo "src=$value\n"; // prints src of image

OUTPUT:

src=/images/image.jpg

How do I check whether input string contains any spaces?

If you will use Regex, it already has a predefined character class "\S" for any non-whitespace character.

!str.matches("\\S+")

tells you if this is a string of at least one character where all characters are non-whitespace

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

Here you are some other version:

public class Palindrom {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a word to check: ");
    String checkWord = sc.nextLine();
    System.out.println(isPalindrome(checkWord));
    sc.close();

}

public static boolean isPalindrome(String str) {        
    StringBuilder secondSB = new StringBuilder();
    StringBuilder sb = new StringBuilder();
    sb.append(str);
    for(int i = 0; i<sb.length();i++){
        char c = sb.charAt(i);
        if(Character.isUpperCase(c)){
            sb.setCharAt(i, Character.toLowerCase(c));
        }
    }
    secondSB.append(sb);
    return sb.toString().equals(secondSB.reverse().toString());
}

}

Numpy matrix to array

A, = np.array(M.T)

depends what you mean by elegance i suppose but thats what i would do

How to determine the screen width in terms of dp or dip at runtime in Android?

If you just want to know about your screen width, you can just search for "smallest screen width" in your developer options. You can even edit it.

See last changes in svn

svn log -r {2009-09-17}:HEAD

where 2009-09-17 is the date you went on holiday. To see the changed files as well as the summary, add a -v option:

svn log -r {2009-09-17}:HEAD -v

I haven't used WebSVN but there will be a log viewer somewhere that does the equivalent of these commands under the hood.

Add primary key to existing table

Please try this-

ALTER TABLE TABLE_NAME DROP INDEX `PRIMARY`, ADD PRIMARY KEY (COLUMN1, COLUMN2,..);

Make element fixed on scroll

There are some problems implementing this which the original accepted answer does not answer:

  1. The onscroll event of the window is firing very often. This implies that you either have to use a very performant listener, or you have to delay the listener somehow. jQuery Creator John Resig states here how a delayed mechanism can be implemented, and the reasons why you should do it. In my opinion, given todays browsers and environments, a performant listener will do as well. Here is an implementation of the pattern suggested by John Resig
  2. The way position:fixed works in css, if you scroll down the page and move an element from position:static to position: fixed, the page will "jump" a little because the document "looses" the height of the element. You can get rid of that by adding the height to the scrollTop and replace the lost height in the document body with another object. You can also use that object to determine if the sticky item has already been moved to position: fixed and reduce the calls to the code reverting position: fixed to the original state: Look at the fiddle here
  3. Now, the only expensive thing in terms of performance the handler is really doing is calling scrollTop on every call. Since the interval bound handler has also its drawbacks, I'll go as far as to argue here that you can reattach the event listener to the original scroll Event to make it feel snappier without many worries. You'll have to profile it though, on every browser you target / support. See it working here

Here's the code:

JS

/* Initialize sticky outside the event listener as a cached selector.
 * Also, initialize any needed variables outside the listener for 
 * performance reasons - no variable instantiation is happening inside the listener.
 */
var sticky = $('#sticky'),
    stickyClone,
    stickyTop = sticky.offset().top,
    scrollTop,
    scrolled = false,
    $window = $(window);

/* Bind the scroll Event */
$window.on('scroll', function (e) {
    scrollTop = $window.scrollTop();

    if (scrollTop >= stickyTop && !stickyClone) {
        /* Attach a clone to replace the "missing" body height */
        stickyClone = sticky.clone().prop('id', sticky.prop('id') + '-clone')
        stickyClone = stickyClone.insertBefore(sticky);
        sticky.addClass('fixed');
    } else if (scrollTop < stickyTop && stickyClone) {
        /* Since sticky is in the viewport again, we can remove the clone and the class */
        stickyClone.remove();
        stickyClone = null;
        sticky.removeClass('fixed');
    }
});

CSS

body {
    margin: 0
}
.sticky {
    padding: 1em;
    background: black;
    color: white;
    width: 100%
}
.sticky.fixed {
    position: fixed;
    top: 0;
    left: 0;
}
.content {
    padding: 1em
}

HTML

<div class="container">
  <div id="page-above" class="content">
    <h2>Some Content above sticky</h2>
    ...some long text...
  </div>
  <div id="sticky" class="sticky">This is sticky</div>
  <div id="page-content" class="content">
    <h2>Some Random Page Content</h2>...some really long text...
  </div>
</div>

How can I make PHP display the error instead of giving me 500 Internal Server Error

Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):

error_reporting(E_ALL);
ini_set('display_errors', 'On');

After that, restart server.

Difference between text and varchar (character varying)

character varying(n), varchar(n) - (Both the same). value will be truncated to n characters without raising an error.

character(n), char(n) - (Both the same). fixed-length and will pad with blanks till the end of the length.

text - Unlimited length.

Example:

Table test:
   a character(7)
   b varchar(7)

insert "ok    " to a
insert "ok    " to b

We get the results:

a        | (a)char_length | b     | (b)char_length
----------+----------------+-------+----------------
"ok     "| 7              | "ok"  | 2

How to delete an item in a list if it exists?

try:
    s.remove("")
except ValueError:
    print "new_tag_list has no empty string"

Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?

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

Swift answer:

myButton.addTarget(self, action: "click:", for: .touchUpInside)

func click(sender: UIButton) {
    print("click")
}

Documentation: https://developer.apple.com/documentation/uikit/uicontrol/1618259-addtarget

PivotTable's Report Filter using "greater than"

Use a value filter. Click the dropdown arrow next to your Row Labels and you'll see a choice between Sort A to Z, Label Filters, and Value Filters. Selecting a Greater Than value filter will let you choose which column to use to filter out rows, even if that column has no dropdown arrow itself.

How to pass parameters to maven build using pom.xml?

If we have parameter like below in our POM XML

<version>${project.version}.${svn.version}</version>
  <packaging>war</packaging>

I run maven command line as follows :

mvn clean install package -Dproject.version=10 -Dsvn.version=1

How do I make a Git commit in the past?

The following is what I use to commit changes on foo to N=1 days in the past:

git add foo
git commit -m "Update foo"
git commit --amend --date="$(date -v-1d)"

If you want to commit to a even older date, say 3 days back, just change the date argument: date -v-3d.

That's really useful when you forget to commit something yesterday, for instance.

UPDATE: --date also accepts expressions like --date "3 days ago" or even --date "yesterday". So we can reduce it to one line command:

git add foo ; git commit --date "yesterday" -m "Update"

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

JQuery Datatables : Cannot read property 'aDataSort' of undefined

I had this problem and it was because another script was deleting all of the tables and recreating them, but my table wasn't being recreated. I spent ages on this issue before I noticed that my table wasn't even visible on the page. Can you see your table before you initialize DataTables?

Essentially, the other script was doing:

let tables = $("table");
for (let i = 0; i < tables.length; i++) {
  const table = tables[i];
  if ($.fn.DataTable.isDataTable(table)) {
    $(table).DataTable().destroy(remove);
    $(table).empty();
  }
}

And it should have been doing:

let tables = $("table.some-class-only");
... the rest ...

Difference between e.target and e.currentTarget

It's worth noting that event.target can be useful, for example, for using a single listener to trigger different actions. Let's say you have the typical "menu" sprite with 10 buttons inside, so instead of doing:

menu.button1.addEventListener(MouseEvent.CLICK, doAction1);
menu.button2.addEventListener(MouseEvent.CLICK, doAction2);
etc...

You can simply do:

menu.addEventListener(MouseEvent.CLICK, doAction);

And trigger a different action within doAction(event) depending on the event.target (using it's name property, etc...)

How to enable CORS in ASP.NET Core

Some troubleshooting tips, after I managed to waste two hours on the most trivial CORS issue:

  1. If you see CORS policy execution failed logged... Don't assume that your CORS policy is not executing properly. In fact, the CORS middleware works, and your policy is executing properly. The only thing this badly worded message means is that the request's origin doesn't match any of the allowed origins (see source), i.e. the request is disallowed.

  2. The origin check (as of ASP.NET Core 5.0) happens in a very simple way... i.e. case-sensitive ordinal string comparison (see source) between the strings you provided via WithOrigins() and what exists in HttpContext.Request.Headers[Origin].

  3. CORS can fail if you set an allowed origin with a trailing slash /, or if it contains uppercase letters. (In my case I did in fact accidentally copy the host with a trailing slash.)

'git status' shows changed files, but 'git diff' doesn't

I suspect there is something wrong either with your Git installation or your repository.

Try running:

GIT_TRACE=2 git <command>

See if you get anything useful. If that doesn't help, just use strace and see what's going wrong:

strace git <command>

How can I select from list of values in Oracle

Hi it is also possible for Strings with XML-Table

SELECT trim(COLUMN_VALUE) str FROM xmltable(('"'||REPLACE('a1, b2, a2, c1', ',', '","')||'"'));

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Best shown by example. String. 192.168.1.1 and a greedy regex \b.+\b You might think this would give you the 1st octet but is actually matches against the whole string. Why? Because the.+ is greedy and a greedy match matches every character in 192.168.1.1 until it reaches the end of the string. This is the important bit! Now it starts to backtrack one character at a time until it finds a match for the 3rd token (\b).

If the string a 4GB text file and 192.168.1.1 was at the start you could easily see how this backtracking would cause an issue.

To make a regex non greedy (lazy) put a question mark after your greedy search e.g

*?
??
+?

What happens now is token 2 (+?) finds a match, regex moves along a character and then tries the next token (\b) rather than token 2 (+?). So it creeps along gingerly.

Execute Insert command and return inserted Id in Sql

using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) " +
    "VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
    cmd.Parameters.AddWithValue("@na", Mem_NA);
    cmd.Parameters.AddWithValue("@occ", Mem_Occ);
    con.Open();

    int modified = cmd.ExecuteNonQuery();

    if (con.State == System.Data.ConnectionState.Open) con.Close();
        return modified;
}

SCOPE_IDENTITY : Returns the last identity value inserted into an identity column in the same scope. for more details http://technet.microsoft.com/en-us/library/ms190315.aspx

Bash array with spaces in elements

If you had your array like this: #!/bin/bash

Unix[0]='Debian'
Unix[1]="Red Hat"
Unix[2]='Ubuntu'
Unix[3]='Suse'

for i in $(echo ${Unix[@]});
    do echo $i;
done

You would get:

Debian
Red
Hat
Ubuntu
Suse

I don't know why but the loop breaks down the spaces and puts them as an individual item, even you surround it with quotes.

To get around this, instead of calling the elements in the array, you call the indexes, which takes the full string thats wrapped in quotes. It must be wrapped in quotes!

#!/bin/bash

Unix[0]='Debian'
Unix[1]='Red Hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'

for i in $(echo ${!Unix[@]});
    do echo ${Unix[$i]};
done

Then you'll get:

Debian
Red Hat
Ubuntu
Suse

Accessing members of items in a JSONArray with Java

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

How to see the CREATE VIEW code for a view in PostgreSQL?

These is a little thing to point out.
Using the function pg_get_viewdef or pg_views or information_schema.views you will always get a rewrited version of your original DDL.
The rewited version may or not be the same as your originl DDL script.

If the Rule Manager rewrite your view definition your original DLL will be lost and you will able to read the only the rewrited version of your view definition.
Not all views are rewrited but if you use sub-select or joins probably your views will be rewrited.

What is an efficient way to implement a singleton pattern in Java?

I use the Spring Framework to manage my singletons.

It doesn't enforce the "singleton-ness" of the class (which you can't really do anyway if there are multiple class loaders involved), but it provides a really easy way to build and configure different factories for creating different types of objects.

WampServer: php-win.exe The program can't start because MSVCR110.dll is missing

During the download of wamp server from wampserver website you get a warning..

WARNING : Vous devez avoir installé Visual Studio 2012 : VC 11 vcredist_x64/86.exe Visual Studio 2012 VC 11 vcredist_x64/86.exe : http://www.microsoft.com/en-us/download/details.aspx?id=30679

So if you install the vcredist_xxx.exe it will be ok

Creating a JSON Array in node js

Build up a JavaScript data structure with the required information, then turn it into the json string at the end.

Based on what I think you're doing, try something like this:

var result = [];
for (var name in goals) {
  if (goals.hasOwnProperty(name)) {
    result.push({name: name, goals: goals[name]});
  }
}

res.contentType('application/json');
res.send(JSON.stringify(result));

or something along those lines.

Converting datetime.date to UTC timestamp in Python

For unix systems only:

>>> import datetime
>>> d = datetime.date(2011,01,01)
>>> d.strftime("%s")  # <-- THIS IS THE CODE YOU WANT
'1293832800'

Note 1: dizzyf observed that this applies localized timezones. Don't use in production.

Note 2: Jakub Narebski noted that this ignores timezone information even for offset-aware datetime (tested for Python 2.7).

Request redirect to /Account/Login?ReturnUrl=%2f since MVC 3 install on server

Updated answer for MVC 4, heavily borrowed from this page and ASP.NET MVC issue with configuration of forms authentication section (and answered on both pages)

<appSettings>
   ...
   <add key="PreserveLoginUrl" value="true" />
</appSettings>

...

<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="43200" /> <!--43,200 in minutes - 30 days-->
</authentication>

JQuery: dynamic height() with window resize()

I feel like there should be a no javascript solution, but how is this?

http://jsfiddle.net/NfmX3/2/

$(window).resize(function() {
    $('#content').height($(window).height() - 46);
});

$(window).trigger('resize');

Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object

I was having the same issue and realized that I was providing an Undefined React component in the JSX markup. The thing is that the react component to render was dynamically calculated and it ended up being undefined!

The error stated:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in. Check the render method of C.,

The example producing this error:

_x000D_
_x000D_
var componentA = require('./components/A');_x000D_
var componentB = require('./components/B');_x000D_
_x000D_
const templates = {_x000D_
  a_type: componentA,_x000D_
  b_type: componentB_x000D_
}_x000D_
_x000D_
class C extends React.Component {_x000D_
  constructor(props) {_x000D_
    super(props);_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
  _x000D_
  render() {_x000D_
    //Let´s say that depending on the uiType coming in a data field you end up rendering a component A or B (as part of C)_x000D_
    const ComponentTemplate = templates[this.props.data.uiType];_x000D_
    return <ComponentTemplate></ComponentTemplate>_x000D_
  }_x000D_
  _x000D_
  // ..._x000D_
}
_x000D_
_x000D_
_x000D_

The problem was that an invalid "uiType" was provided and therefore this was producing undefined as result:

_x000D_
_x000D_
templates['InvalidString']
_x000D_
_x000D_
_x000D_

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

I was having issues with

Caused by: org.xml.sax.SAXParseException: cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'security:http'

and for me I had to add the spring-security-config jar to the classpath

http://docs.spring.io/spring-security/site/docs/3.1.x/reference/ns-config.html

EDIT:

It might be that you have the correct dependency in your pom.

But...

If you are using multiple spring dependencies and assembling into a single jar then the META-INF/spring.schemas is probably being overwritten by the spring.schemas of another of your spring dependencies.

(Extract that file from your assembled jar and you'll understand)

Spring schemas is just a bunch of lines that look like this:

http\://www.springframework.org/schema/p=org.springframework.beans.factory.xml.SimplePropertyNamespaceHandler
http\://www.springframework.org/schema/beans/spring-beans-3.0.xsd=org/springframework/beans/factory/xml/spring-beans-3.0.xsd

But if another dependency overwrites that file, then the definition will be retrieved from http, and if you have a firewall/proxy it will fail to get it.

One solution is to append spring.schemas and spring.handlers into a single file.

Check:

Idea to avoid that spring.handlers/spring.schemas get overwritten when merging multiple spring dependencies in a single jar

Best way to change font colour halfway through paragraph?

<span style="color:orange;">orange text</span>

Is the only way I know of barring the font tag.

Load and execution sequence of a web page?

1) HTML is downloaded.

2) HTML is parsed progressively. When a request for an asset is reached the browser will attempt to download the asset. A default configuration for most HTTP servers and most browsers is to process only two requests in parallel. IE can be reconfigured to downloaded an unlimited number of assets in parallel. Steve Souders has been able to download over 100 requests in parallel on IE. The exception is that script requests block parallel asset requests in IE. This is why it is highly suggested to put all JavaScript in external JavaScript files and put the request just prior to the closing body tag in the HTML.

3) Once the HTML is parsed the DOM is rendered. CSS is rendered in parallel to the rendering of the DOM in nearly all user agents. As a result it is strongly recommended to put all CSS code into external CSS files that are requested as high as possible in the <head></head> section of the document. Otherwise the page is rendered up to the occurance of the CSS request position in the DOM and then rendering starts over from the top.

4) Only after the DOM is completely rendered and requests for all assets in the page are either resolved or time out does JavaScript execute from the onload event. IE7, and I am not sure about IE8, does not time out assets quickly if an HTTP response is not received from the asset request. This means an asset requested by JavaScript inline to the page, that is JavaScript written into HTML tags that is not contained in a function, can prevent the execution of the onload event for hours. This problem can be triggered if such inline code exists in the page and fails to execute due to a namespace collision that causes a code crash.

Of the above steps the one that is most CPU intensive is the parsing of the DOM/CSS. If you want your page to be processed faster then write efficient CSS by eliminating redundent instructions and consolidating CSS instructions into the fewest possible element referrences. Reducing the number of nodes in your DOM tree will also produce faster rendering.

Keep in mind that each asset you request from your HTML or even from your CSS/JavaScript assets is requested with a separate HTTP header. This consumes bandwidth and requires processing per request. If you want to make your page load as fast as possible then reduce the number of HTTP requests and reduce the size of your HTML. You are not doing your user experience any favors by averaging page weight at 180k from HTML alone. Many developers subscribe to some fallacy that a user makes up their mind about the quality of content on the page in 6 nanoseconds and then purges the DNS query from his server and burns his computer if displeased, so instead they provide the most beautiful possible page at 250k of HTML. Keep your HTML short and sweet so that a user can load your pages faster. Nothing improves the user experience like a fast and responsive web page.

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

Java: how do I initialize an array size if it's unknown?

int i,largest = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of numbers in the list");
i = scan.nextInt();
int arr[] = new int[i];
System.out.println("Enter the list of numbers:");
for(int j=0;j<i;j++){
    arr[j] = scan.nextInt();
}

The above code works well. I have taken the input of the number of elements in the list and initialized the array accordingly.

Check object empty

You can't do it directly, you should provide your own way to check this. Eg.

class MyClass {
  Object attr1, attr2, attr3;

  public boolean isValid() {
    return attr1 != null && attr2 != null && attr3 != null;
  }
}

Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.

Redraw datatables after using ajax to refresh the table content?

Try destroying the datatable with bDestroy:true like this:

$("#ajaxchange").click(function(){
    var campaign_id = $("#campaigns_id").val();
    var fromDate = $("#from").val();
    var toDate = $("#to").val();

    var url = 'http://domain.com/account/campaign/ajaxrefreshgrid?format=html';
    $.post(url, { campaignId: campaign_id, fromdate: fromDate, todate: toDate},
            function( data ) { 

                $("#ajaxresponse").html(data);

                oTable6 = $('#rankings').dataTable( {"bDestroy":true,
                    "sDom":'t<"bottom"filp><"clear">',
                    "bAutoWidth": false,
                    "sPaginationType": "full_numbers",
"aoColumns": [ 
        { "bSortable": false, "sWidth": "10px" },
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null,
        null
        ]

} 
);
            });

});

bDestroy: true will first destroy and datatable instance associated with that selector before reinitializing a new one.

Quicksort: Choosing the pivot

It is entirely dependent on how your data is sorted to begin with. If you think it will be pseudo-random then your best bet is to either pick a random selection or choose the middle.

Controller not a function, got undefined, while defining controllers globally

This error might also occur when you have a large project with many modules. Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".

app.js

angular
.module('thisApp', [])
    .controller('ContactController', ['$scope', function ContactController($scope) {
        $scope.contacts = ["[email protected]", "[email protected]"];

        $scope.add = function() {
            $scope.contacts.push($scope.newcontact);
            $scope.newcontact = "";

        };
    }]);

index.html

  <html>
    <body ng-app='thisApp' ng-controller='ContactController>
         ...
        <script type="text/javascript" src="assets/js/angular.js"></script>
        <script src="app.js"></script>
    </body>
    </html>

Difference between array_map, array_walk and array_filter

The other answers demonstrate the difference between array_walk (in-place modification) and array_map (return modified copy) quite well. However, they don't really mention array_reduce, which is an illuminating way to understand array_map and array_filter.

The array_reduce function takes an array, a two-argument function and an 'accumulator', like this:

array_reduce(array('a', 'b', 'c', 'd'),
             'my_function',
             $accumulator)

The array's elements are combined with the accumulator one at a time, using the given function. The result of the above call is the same as doing this:

my_function(
  my_function(
    my_function(
      my_function(
        $accumulator,
        'a'),
      'b'),
    'c'),
  'd')

If you prefer to think in terms of loops, it's like doing the following (I've actually used this as a fallback when array_reduce wasn't available):

function array_reduce($array, $function, $accumulator) {
  foreach ($array as $element) {
    $accumulator = $function($accumulator, $element);
  }
  return $accumulator;
}

This looping version makes it clear why I've called the third argument an 'accumulator': we can use it to accumulate results through each iteration.

So what does this have to do with array_map and array_filter? It turns out that they're both a particular kind of array_reduce. We can implement them like this:

array_map($function, $array)    === array_reduce($array, $MAP,    array())
array_filter($array, $function) === array_reduce($array, $FILTER, array())

Ignore the fact that array_map and array_filter take their arguments in a different order; that's just another quirk of PHP. The important point is that the right-hand-side is identical except for the functions I've called $MAP and $FILTER. So, what do they look like?

$MAP = function($accumulator, $element) {
  $accumulator[] = $function($element);
  return $accumulator;
};

$FILTER = function($accumulator, $element) {
  if ($function($element)) $accumulator[] = $element;
  return $accumulator;
};

As you can see, both functions take in the $accumulator and return it again. There are two differences in these functions:

  • $MAP will always append to $accumulator, but $FILTER will only do so if $function($element) is TRUE.
  • $FILTER appends the original element, but $MAP appends $function($element).

Note that this is far from useless trivia; we can use it to make our algorithms more efficient!

We can often see code like these two examples:

// Transform the valid inputs
array_map('transform', array_filter($inputs, 'valid'))

// Get all numeric IDs
array_filter(array_map('get_id', $inputs), 'is_numeric')

Using array_map and array_filter instead of loops makes these examples look quite nice. However, it can be very inefficient if $inputs is large, since the first call (map or filter) will traverse $inputs and build an intermediate array. This intermediate array is passed straight into the second call, which will traverse the whole thing again, then the intermediate array will need to be garbage collected.

We can get rid of this intermediate array by exploiting the fact that array_map and array_filter are both examples of array_reduce. By combining them, we only have to traverse $inputs once in each example:

// Transform valid inputs
array_reduce($inputs,
             function($accumulator, $element) {
               if (valid($element)) $accumulator[] = transform($element);
               return $accumulator;
             },
             array())

// Get all numeric IDs
array_reduce($inputs,
             function($accumulator, $element) {
               $id = get_id($element);
               if (is_numeric($id)) $accumulator[] = $id;
               return $accumulator;
             },
             array())

NOTE: My implementations of array_map and array_filter above won't behave exactly like PHP's, since my array_map can only handle one array at a time and my array_filter won't use "empty" as its default $function. Also, neither will preserve keys.

It's not difficult to make them behave like PHP's, but I felt that these complications would make the core idea harder to spot.

How to execute the start script with Nodemon

It will depend on types of your Nodemon installation. If you install Nodemon globally by using commands (npm install nodemon --global or npm install nodemon -g), you do not have to specify any script for Nodemon in your package.json file. Just executing command nodemon index.js will run your project.

But if you install Nodemon locally by command npm install nodemon then you have to specify the script. If you name it as start then npm run start or npm start will trigger the server to run.

// Absolutely no need for global installation
 "scripts": {
    "start": "nodemon index.js"
  }

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

Removing elements by class name?

One line

document.querySelectorAll(".remove").forEach(el => el.remove());

For example you can do in this page to remove userinfo

document.querySelectorAll(".user-info").forEach(el => el.remove());

Difference between HashSet and HashMap?

HashSet

  1. HashSet class implements the Set interface
  2. In HashSet, we store objects(elements or values) e.g. If we have a HashSet of string elements then it could depict a set of HashSet elements: {“Hello”, “Hi”, “Bye”, “Run”}
  3. HashSet does not allow duplicate elements that mean you can not store duplicate values in HashSet.
  4. HashSet permits to have a single null value.
  5. HashSet is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

                          add      contains next     notes
    HashSet               O(1)     O(1)     O(h/n)   h is the table 
    

HashMap

  1. HashMap class implements the Map interface
  2. HashMap is used for storing key & value pairs. In short, it maintains the mapping of key & value (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This is how you could represent HashMap elements if it has integer key and value of String type: e.g. {1->”Hello”, 2->”Hi”, 3->”Bye”, 4->”Run”}
  3. HashMap does not allow duplicate keys however it allows having duplicate values.
  4. HashMap permits single null key and any number of null values.
  5. HashMap is not synchronized which means they are not suitable for thread-safe operations until unless synchronized explicitly.[similarity]

                           get      containsKey next     Notes
     HashMap               O(1)     O(1)        O(h/n)   h is the table 
    

Please refer this article to find more information.

What exactly is a Maven Snapshot and why do we need it?

Snapshot simply means depending on your configuration Maven will check latest changes on a special dependency. Snapshot is unstable because it is under development but if on a special project needs to has a latest changes you must configure your dependency version to snapshot version. This scenario occurs in big organizations with multiple products that these products related to each other very closely.

How to insert strings containing slashes with sed?

The easiest way would be to use a different delimiter in your search/replace lines, e.g.:

s:?page=one&:pageone:g

You can use any character as a delimiter that's not part of either string. Or, you could escape it with a backslash:

s/\//foo/

Which would replace / with foo. You'd want to use the escaped backslash in cases where you don't know what characters might occur in the replacement strings (if they are shell variables, for example).

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

How to click an element in Selenium WebDriver using JavaScript

By XPath: inspect the element on target page, copy Xpath and use the below script:worked for me.

WebElement nameInputField = driver.findElement(By.xpath("html/body/div[6]/div[1]/div[3]/div/div/div[1]/div[3]/ul/li[4]/a"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", nameInputField);

Can't accept license agreement Android SDK Platform 24

I'm not exactly sure how cordova works, but once the licenses are accepted it creates a file. You could create that file manually. It is described on this question, but here's the commands to create the required license file.

Linux:

mkdir "$ANDROID_HOME/licenses"
echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" > "$ANDROID_HOME/licenses/android-sdk-license"

Windows:

mkdir "%ANDROID_HOME%\licenses"
echo |set /p="8933bad161af4178b1185d1a37fbf41ea5269c55" > "%ANDROID_HOME%\licenses\android-sdk-license"

AngularJS disable partial caching on dev machine

Building on @Valentyn's answer a bit, here's one way to always automatically clear the cache whenever the ng-view content changes:

myApp.run(function($rootScope, $templateCache) {
   $rootScope.$on('$viewContentLoaded', function() {
      $templateCache.removeAll();
   });
});

Recommended way to get hostname in Java

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        Enumeration<InetAddress> addresses = nic.getInetAddresses();
        while (hostName == null && addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            if (!address.isLoopbackAddress()) {
                hostName = address.getHostName();
            }
        }
    }
}

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

How to read/write from/to file using Go?

With newer Go versions, reading/writing to/from file is easy. To read from a file:

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    data, err := ioutil.ReadFile("text.txt")
    if err != nil {
        return
    }
    fmt.Println(string(data))
}

To write to a file:

package main

import "os"

func main() {
    file, err := os.Create("text.txt")
    if err != nil {
        return
    }
    defer file.Close()

    file.WriteString("test\nhello")
}

This will overwrite the content of a file (create a new file if it was not there).

Use LIKE %..% with field values in MySQL

  SELECT t1.a, t2.b
  FROM t1
  JOIN t2 ON t1.a LIKE '%'+t2.b +'%'

because the last answer not work

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

TensorFlow, "'module' object has no attribute 'placeholder'"

If you get this on tensorflow 2.0.0+, it's very likely because the code isn't compatible with the newer version of tensorflow.

To fix this, run the tf_upgrade_v2 script.

tf_upgrade_v2 --infile=YOUR_SCRIPT.py --outfile=YOUR_SCRIPT.py

Single statement across multiple lines in VB.NET without the underscore character

No, the underscore is the only continuation character. Personally I prefer the occasional use of a continuation character to being forced to use it always as in C#, but apart from the comments issue (which I'd agree is sometimes annoying), getting things to line up is not an issue.

With VS2008 at any rate, just select the second and following lines, hit the tab key several times, and it moves the whole lot across.

If it goes a tiny bit too far, you can delete the excess space a character at a time. It's a little fiddly, but it stays put once it's saved.

On the rare cases where this isn't good enough, I sometimes use the following technique to get it all to line up:

dim results as String = ""
results += "from a in articles "
results += "where a.articleID = 4 " 'and now you can add comments
results += "select a.articleName"

It's not perfect, and I know those that prefer C# will be tut-tutting, but there it is. It's a style choice, but I still prefer it to endless semi-colons.

Now I'm just waiting for someone to tell me I should have used a StringBuilder ;-)

MySQL Multiple Where Clause

May be using this query you don't get any result or empty result. You need to use OR instead of AND in your query like below.

$query = mysql_query("SELECT image_id FROM list WHERE (style_id = 24 AND style_value = 'red') OR (style_id = 25 AND style_value = 'big') OR (style_id = 27 AND style_value = 'round');

Try out this query.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I had set everything correctly (cardinalities and dependent properties) but could not figure out why I keep receiving error. Finally figured out that, EF generated a column in dependent table on its own (table_tablecolumn) and it does not have any relation to the table, so no mapping was specified. I had to delete the column in EDMX file and rebuild the solution which fixed the issue. I am using DB approach.

How to Ping External IP from Java Android

Run the ping utility in Android's command and parse output (assuming you have root permissions)

See the following Java code snippet:

executeCmd("ping -c 1 -w 1 google.com", false);

public static String executeCmd(String cmd, boolean sudo){
    try {

        Process p;
        if(!sudo)
            p= Runtime.getRuntime().exec(cmd);
        else{
            p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
        }
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String s;
        String res = "";
        while ((s = stdInput.readLine()) != null) {
            res += s + "\n";
        }
        p.destroy();
        return res;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";

}

java.math.BigInteger cannot be cast to java.lang.Integer

As we see from the javaDoc, BigInteger is not a subclass of Integer:

java.lang.Object                      java.lang.Object
   java.lang.Number                       java.lang.Number
      java.math.BigInteger                    java.lang.Integer

And that's the reason why casting from BigInteger to Integer is impossible.

Casting of java primitives will do some conversion (like casting from double to int) while casting of types will never transform classes.

What is the OR operator in an IF statement

Just for completeness, the || and && are the conditional version of the | and & operators.

A reference to the ECMA C# Language specification is here.

From the specification:

3 The operation x || y corresponds to the operation x | y, except that y is evaluated only if x is false.

In the | version both sides are evaluated.

The conditional version short circuits evaluation and so allows for code like:

if (x == null || x.Value == 5)
    // Do something 

Or (no pun intended) using your example:

if (title == "User greeting" || title == "User name") 
    // {do stuff} 

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How do I know if jQuery has an Ajax request pending?

$.active returns the number of active Ajax requests.

More info here

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

Optimistic vs. Pessimistic locking

Lot of good things have been said above about optimistic and pessimistic locking. One important point to consider is as follows:

When using optimistic locking, we need to cautious of the fact that how will application recover from these failures.

Specially in asynchronous message driven architectures, this can lead of out of order message processing or lost updates.

Failures scenarios need to be thought through.

How to generate a HTML page dynamically using PHP?

I was wondering if/how I can 'create' a html page for each database row?

You just need to create one php file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST or GET and then get the info form the database.

I'm assuming this would be better for SEO?

Search Engine as Google interpret that example.php?id=33 and example.php?id=44 are different pages, and yes, this way is better than single listing page from the SEO point of view, so you just need two php files at least (listing.php and single.php), because is better link this pages from the listing.php.

Extra advice:

example.php?id=33 is really ugly and not very seo friendly, maybe you need some url rewriting code. Something like example/properties/property-name is better ;)

How to find all the dependencies of a table in sql server

SELECT referencing_schema_name, referencing_entity_name,
case when is_caller_dependent=0 then 'NO' ELSE 'Yes'
END AS is_caller_dependent FROM sys.dm_sql_referencing_entities ('Tablename', 'OBJECT');

Java Equivalent of C# async/await?

The await uses a continuation to execute additional code when the asynchronous operation completes (client.GetStringAsync(...)).

So, as the most close approximation I would use a CompletableFuture<T> (the Java 8 equivalent to .net Task<TResult>) based solution to process the Http request asynchronously.

UPDATED on 25-05-2016 to AsyncHttpClient v.2 released on Abril 13th of 2016:

So the Java 8 equivalent to the OP example of AccessTheWebAsync() is the following:

CompletableFuture<Integer> AccessTheWebAsync()
{
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    return asyncHttpClient
       .prepareGet("http://msdn.microsoft.com")
       .execute()
       .toCompletableFuture()
       .thenApply(Response::getResponseBody)
       .thenApply(String::length);
}

This usage was taken from the answer to How do I get a CompletableFuture from an Async Http Client request? and which is according to the new API provided in version 2 of AsyncHttpClient released on Abril 13th of 2016, that has already intrinsic support for CompletableFuture<T>.

Original answer using version 1 of AsyncHttpClient:

To that end we have two possible approaches:

  • the first one uses non-blocking IO and I call it AccessTheWebAsyncNio. Yet, because the AsyncCompletionHandler is an abstract class (instead of a functional interface) we cannot pass a lambda as argument. So it incurs in inevitable verbosity due to the syntax of anonymous classes. However, this solution is the most close to the execution flow of the given C# example.

  • the second one is slightly less verbose however it will submit a new Task that ultimately will block a thread on f.get() until the response is complete.

First approach, more verbose but non-blocking:

static CompletableFuture<Integer> AccessTheWebAsyncNio(){
    final AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    final CompletableFuture<Integer> promise = new CompletableFuture<>();
    asyncHttpClient
        .prepareGet("https://msdn.microsoft.com")
        .execute(new AsyncCompletionHandler<Response>(){
            @Override
            public Response onCompleted(Response resp) throws Exception {
                promise.complete(resp.getResponseBody().length());
                return resp;
            }
        });
    return promise;
}

Second approach less verbose but blocking a thread:

static CompletableFuture<Integer> AccessTheWebAsync(){
    try(AsyncHttpClient asyncHttpClient = new AsyncHttpClient()){
        Future<Response> f = asyncHttpClient
            .prepareGet("https://msdn.microsoft.com")
            .execute();
        return CompletableFuture.supplyAsync(
            () -> return f.join().getResponseBody().length());
    }
}

How to get the IP address of the docker host from inside a docker container

If you enabled the docker remote API (via -Htcp://0.0.0.0:4243 for instance) and know the host machine's hostname or IP address this can be done with a lot of bash.

Within my container's user's bashrc:

export hostIP=$(ip r | awk '/default/{print $3}')
export containerID=$(awk -F/ '/docker/{print $NF;exit;}' /proc/self/cgroup)
export proxyPort=$(
  curl -s http://$hostIP:4243/containers/$containerID/json |
  node -pe 'JSON.parse(require("fs").readFileSync("/dev/stdin").toString()).NetworkSettings.Ports["DESIRED_PORT/tcp"][0].HostPort'
)

The second line grabs the container ID from your local /proc/self/cgroup file.

Third line curls out to the host machine (assuming you're using 4243 as docker's port) then uses node to parse the returned JSON for the DESIRED_PORT.

How to get resources directory path programmatically

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

yii2 redirect in controller action does not work?

Redirects the browser to the specified URL.

This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:

return Yii::$app->getResponse()->redirect($url);

In other places, if you want to send out the "Location" header immediately, you should use the following code:

Yii::$app->getResponse()->redirect($url)->send();
return;

preventDefault() on an <a> tag

You can make use of return false; from the event call to stop the event propagation, it acts like an event.preventDefault(); negating it. Or you can use javascript:void(0) in href attribute to evaluate the given expression and then return undefined to the element.

Returning the event when it's called:

<a href="" onclick="return false;"> ... </a>

Void case:

<a href="javascript:void(0);"> ... </a>

You can see more about in: What's the effect of adding void(0) for href and 'return false' on click event listener of anchor tag?

SQL Server stored procedure creating temp table and inserting value

A SELECT INTO statement creates the table for you. There is no need for the CREATE TABLE statement before hand.

What is happening is that you create #ivmy_cash_temp1 in your CREATE statement, then the DB tries to create it for you when you do a SELECT INTO. This causes an error as it is trying to create a table that you have already created.

Either eliminate the CREATE TABLE statement or alter your query that fills it to use INSERT INTO SELECT format.

If you need a unique ID added to your new row then it's best to use SELECT INTO... since IDENTITY() only works with this syntax.

jQuery: Test if checkbox is NOT checked

To do it with .attr() like you have, to see if it's checked it would be .attr("checked", "checked"), and if it isn't it would be .attr("checked") == undefined

Vertical divider CSS

<div class="headerdivider"></div>

and

.headerdivider {
    border-left: 1px solid #38546d;
    background: #16222c;
    width: 1px;
    height: 80px;
    position: absolute;
    right: 250px;
    top: 10px;
}

How to convert an array of strings to an array of floats in numpy?

Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

However, if it's already a numpy array of strings, there's a better way. Use astype().

import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)

How to set data attributes in HTML elements

If you're using jQuery, use .data():

div.data('myval', 20);

You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

THis issue has been fixed with new mysql connectors, please use http://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.38

I used to get this error after updating the connector jar, issue resolved.

Javascript select onchange='this.form.submit()'

If you're using jQuery, it's as simple as this:

 $('#mySelect').change(function()
 {
     $('#myForm').submit();
 });

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

Put Excel-VBA code in module or sheet?

Definitely in Modules.

  • Sheets can be deleted, copied and moved with surprising results.
  • You can't call code in sheet "code-behind" from other modules without fully qualifying the reference. This will lead to coupling of the sheet and the code in other modules/sheets.
  • Modules can be exported and imported into other workbooks, and put under version control
  • Code in split logically into modules (data access, utilities, spreadsheet formatting etc.) can be reused as units, and are easier to manage if your macros get large.

Since the tooling is so poor in primitive systems such as Excel VBA, best practices, obsessive code hygiene and religious following of conventions are important, especially if you're trying to do anything remotely complex with it.

This article explains the intended usages of different types of code containers. It doesn't qualify why these distinctions should be made, but I believe most developers trying to develop serious applications on the Excel platform follow them.

There's also a list of VBA coding conventions I've found helpful, although they're not directly related to Excel VBA. Please ignore the crazy naming conventions they have on that site, it's all crazy hungarian.

Xcode is not currently available from the Software Update server

This error can occur if you are using a software update server which doesn't host the required package.

You can check this by running

defaults read /Library/Preferences/com.apple.SoftwareUpdate

and seeing if you have an entry called CatalogURL or AppleCatalogURL

You can point back at the Apple software update server by either removing this entry or using the command

sudo softwareupdate --clear-catalog

And then run the command line tools install again.

Excel function to make SQL-like queries on worksheet data?

Sometimes SUM_IF can get the job done.

Suppose you have a sheet of product information, including unique productID in column A and unit price in column P. And a sheet of purchase order entries with product IDs in column A, and you want column T to calculate the unit price for the entry.

The following formula will do the trick in cell Entries!T2 and can be copied to the other cells in the same column.

=SUMIF(Products!$A$2:$A$9999,Entries!$A2, Products!$P$2:$9999)

Then you could have another column with number of items per entry and multiply it with the unit price to get total cost for the entry.

How to draw border around a UILabel?

UILabel properties borderColor,borderWidth,cornerRadius in Swift 4

@IBOutlet weak var anyLabel: UILabel!
   override func viewDidLoad() {
        super.viewDidLoad()
        anyLabel.layer.borderColor = UIColor.black.cgColor
        anyLabel.layer.borderWidth = 2
        anyLabel.layer.cornerRadius = 5
        anyLabel.layer.masksToBounds = true
}

cpp / c++ get pointer value or depointerize pointer

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

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

value = *ptr;

value is now 9.

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

Find a commit on GitHub given the commit hash

The ability to search commits has recently been added to GitHub.

To search for a hash, just enter at least the first 7 characters in the search box. Then on the results page, click the "Commits" tab to see matching commits (but only on the default branch, usually master), or the "Issues" tab to see pull requests containing the commit.

To be more explicit you can add the hash: prefix to the search, but it's not really necessary.

There is also a REST API (at the time of writing it is still in preview).

How do I fix the npm UNMET PEER DEPENDENCY warning?

npm no longer installs peer dependencies so you need to install them manually, just do an npm install on the needed deps, and then try to install the main one again.


Reply to comment:

it's right in that message, it says which deps you're missing

UNMET PEER DEPENDENCY angular-animate@^1.5.0 +-- 
UNMET PEER DEPENDENCY angular-aria@^1.5.0 +-- [email protected] +
UNMET PEER DEPENDENCY angular-messages@^1.5.0 `-- [email protected]` 

So you need to npm install angular angular-animate angular-aria angular-material angular-messages mdi

How to pass boolean values to a PowerShell script from a command prompt

Running powershell scripts on linux from bash gives the same problem. Solved it almost the same as LarsWA's answer:

Working:

pwsh -f ./test.ps1 -bool:true

Not working:

pwsh -f ./test.ps1 -bool=1
pwsh -f ./test.ps1 -bool=true
pwsh -f ./test.ps1 -bool true
pwsh -f ./test.ps1 {-bool=true}
pwsh -f ./test.ps1 -bool=$true
pwsh -f ./test.ps1 -bool=\$true
pwsh -f ./test.ps1 -bool 1
pwsh -f ./test.ps1 -bool:1

Is JavaScript's "new" keyword considered harmful?

I wrote a post on how to mitigate the problem of calling a constructor without the new keyword.
It's mostly didactic, but it shows how you can create constructors that work with or without new and doesn't require you to add boilerplate code to test this in every constructor.

http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html

Here's the gist of the technique:

/**
 * Wraps the passed in constructor so it works with
 * or without the new keyword
 * @param {Function} realCtor The constructor function.
 *    Note that this is going to be wrapped
 *    and should not be used directly 
 */
function ctor(realCtor){
  // This is going to be the actual constructor
  return function wrapperCtor(){
    var obj; // object that will be created
    if (this instanceof wrapperCtor) {
      // Called with new
      obj = this;
    } else {
      // Called without new. Create an empty object of the
      // correct type without running that constructor
      surrogateCtor.prototype = wrapperCtor.prototype;
      obj = new surrogateCtor();
    }
    // Call the real constructor function
    realCtor.apply(obj, arguments);
    return obj;
  }

  function surrogateCtor() {}
}

Here's how to use it:

// Create our point constructor
Point = ctor(function(x,y){
  this.x = x;
  this.y = y;
});

// This is good
var pt = new Point(20,30);
// This is OK also
var pt2 = Point(20,30);

How do I wait for an asynchronously dispatched block to finish?

Sometimes, Timeout loops are also helpful. May you wait until you get some (may be BOOL) signal from async callback method, but what if no response ever, and you want to break out of that loop? Here below is solution, mostly answered above, but with an addition of Timeout.

#define CONNECTION_TIMEOUT_SECONDS      10.0
#define CONNECTION_CHECK_INTERVAL       1

NSTimer * timer;
BOOL timeout;

CCSensorRead * sensorRead ;

- (void)testSensorReadConnection
{
    [self startTimeoutTimer];

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);

    while (dispatch_semaphore_wait(sema, DISPATCH_TIME_NOW)) {

        /* Either you get some signal from async callback or timeout, whichever occurs first will break the loop */
        if (sensorRead.isConnected || timeout)
            dispatch_semaphore_signal(sema);

        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                                 beforeDate:[NSDate dateWithTimeIntervalSinceNow:CONNECTION_CHECK_INTERVAL]];

    };

    [self stopTimeoutTimer];

    if (timeout)
        NSLog(@"No Sensor device found in %f seconds", CONNECTION_TIMEOUT_SECONDS);

}

-(void) startTimeoutTimer {

    timeout = NO;

    [timer invalidate];
    timer = [NSTimer timerWithTimeInterval:CONNECTION_TIMEOUT_SECONDS target:self selector:@selector(connectionTimeout) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}

-(void) stopTimeoutTimer {
    [timer invalidate];
    timer = nil;
}

-(void) connectionTimeout {
    timeout = YES;

    [self stopTimeoutTimer];
}

error running apache after xampp install

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

I was getting this error when trying to start Apache, there is no error with Apache. It's an dependency error on windows 8 - probably the same for 7. Just right click and run as Admin :)

If you're still getting an error check your Antivirus/Firewall is not blocking Xampp or port 443.

How to drop a database with Mongoose?

An updated answer, for 4.6.0+, if you have a preference for promises (see docs):

mongoose.connect('mongodb://localhost/mydb', { useMongoClient: true })
.then((connection) => {
   connection.db.dropDatabase();
   // alternatively:
   // mongoose.connection.db.dropDatabase();
});

I tested this code in my own code, using mongoose 4.13.6. Also, note the use of the useMongoClient option (see docs). Docs indicate:

Mongoose's default connection logic is deprecated as of 4.11.0. Please opt in to the new connection logic using the useMongoClient option, but make sure you test your connections first if you're upgrading an existing codebase!

Get parent of current directory from Python script

import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__ you can do simplify things a bit.

Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.

from __future__ import division

def Pythag(league):
    def win_percentages():
        for team, (runs_scored, runs_allowed) in league.iteritems():
            win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
            yield win_percentage

    for win_percentage in win_percentages():
        print win_percentage

Remove "Using default security password" on Spring Boot

On spring boot 2 with webflux you need to define a ReactiveAuthenticationManager

Installing jQuery?

There is no installation per se.

You download jQuery and include it in your html files like this:

<script src="jquery.js" type="text/javascript"></script>

Of course, modify the filename so that it's the same as the downloaded script file.

Done!

C# : Out of Memory exception

Data stored in database compared to memory in your application is very different.

There isn't a way to get the exact size of your object but you could do this:

GC.GetTotalMemory() 

After a certain amount of objects have been loaded and see how much your memory is changing as you load the list.

If it is the list that is causing the excessive memory usage then we can look at ways to minimize it. Such as why do you want 50,000 objects loaded into memory all at once in the first place. Wouldn't it be best to call the DB as you require them?

If you take a look here: http://www.dotnetperls.com/array-memory you will also see that objects in .NET are greater than their actual data. A generic list is even more of a memory hog than an array. If you have a generic list inside your object then it will grow even faster.

How do I create a message box with "Yes", "No" choices and a DialogResult?

DialogResult dr = MessageBox.Show("Are you happy now?", 
                      "Mood Test", MessageBoxButtons.YesNo);
switch(dr)
{
   case DialogResult.Yes:
      break;
   case DialogResult.No:
      break;
}

MessageBox class is what you are looking for.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

SELECT  RIGHT(RTRIM(column), 3),
        LEFT(column, LEN(column) - 3)
FROM    table

Use RIGHT w/ RTRIM (to avoid complications with a fixed-length column), and LEFT coupled with LEN (to only grab what you need, exempt of the last 3 characters).

if there's ever a situation where the length is <= 3, then you're probably going to have to use a CASE statement so the LEFT call doesn't get greedy.

JUnit: how to avoid "no runnable methods" in test utils classes

Annotate your util classes with @Ignore. This will cause JUnit not to try and run them as tests.

Clone private git repo with dockerfile

My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)

FROM ubuntu

MAINTAINER Luke Crooks "[email protected]"

# Update aptitude with new repo
RUN apt-get update

# Install software 
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/

# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa

# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

How to git commit a single file/directory

Your arguments are in the wrong order. Try git commit -m 'my notes' path/to/my/file.ext, or if you want to be more explicit, git commit -m 'my notes' -- path/to/my/file.ext.

Incidentally, git v1.5.2.1 is 4.5 years old. You may want to update to a newer version (1.7.8.3 is the current release).

Why does modulus division (%) only work with integers?

"The mathematical notion of modulo arithmetic works for floating point values as well, and this is one of the first issues that Donald Knuth discusses in his classic The Art of Computer Programming (volume I). I.e. it was once basic knowledge."

The floating point modulus operator is defined as follows:

m = num - iquot*den ; where iquot = int( num/den )

As indicated, the no-op of the % operator on floating point numbers appears to be standards related. The CRTL provides 'fmod', and usually 'remainder' as well, to perform % on fp numbers. The difference between these two lies in how they handle the intermediate 'iquot' rounding.

'remainder' uses round-to-nearest, and 'fmod' uses simple truncate.

If you write your own C++ numerical classes, nothing prevents you from amending the no-op legacy, by including an overloaded operator %.

Best Regards

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

How do you turn a Mongoose document into a plain object?

The lean option tells Mongoose to skip hydrating the result documents. This makes queries faster and less memory intensive, but the result documents are plain old JavaScript objects (POJOs), not Mongoose documents.

const leanDoc = await MyModel.findOne().lean();

not necessary to use JSON.parse() method

How to do a SOAP Web Service call from Java class?

Or just use Apache CXF's wsdl2java to generate objects you can use.

It is included in the binary package you can download from their website. You can simply run a command like this:

$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl

It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):

DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);

There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html

Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315

Split a string into an array of strings based on a delimiter

This will solve your problem

interface
   TArrayStr = Array Of string;

implementation

function SplitString(Text: String): TArrayStr;
var
   intIdx: Integer;
   intIdxOutput: Integer;
const
   Delimiter = ';';
begin
   intIdxOutput := 0;
   SetLength(Result, 1);
   Result[0] := ''; 

   for intIdx := 1 to Length(Text) do
   begin
      if Text[intIdx] = Delimiter then
      begin
         intIdxOutput := intIdxOutput + 1;
         SetLength(Result, Length(Result) + 1);
      end
      else
         Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
   end;
end;

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

I had the same issue. The problem was, the performSegueWithIdentifier was triggered by a notification, as soon as I put the notification on the main thread the warning message was gone.

Compiling/Executing a C# Source File in Command Prompt

Another way to compile C# programs (without using Visual Studio or without having it installed) is to create a user variable in environment variables, namely "PATH".

Copy the following path in this variable:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319"

or depending upon which .NET your PC have.

So you don't have to mention the whole path every time you compile a code. Simply use

"C:\Users\UserName\Desktop>csc [options] filename.cs"

or wherever the path of your code is.

Now you are good to go.

Determining if an Object is of primitive type

Integer is not a primitive, Class.isPrimitive() is not lying.

Get string between two strings in a string

Depending on how robust/flexible you want your implementation to be, this can actually be a bit tricky. Here's the implementation I use:

public static class StringExtensions {
    /// <summary>
    /// takes a substring between two anchor strings (or the end of the string if that anchor is null)
    /// </summary>
    /// <param name="this">a string</param>
    /// <param name="from">an optional string to search after</param>
    /// <param name="until">an optional string to search before</param>
    /// <param name="comparison">an optional comparison for the search</param>
    /// <returns>a substring based on the search</returns>
    public static string Substring(this string @this, string from = null, string until = null, StringComparison comparison = StringComparison.InvariantCulture)
    {
        var fromLength = (from ?? string.Empty).Length;
        var startIndex = !string.IsNullOrEmpty(from) 
            ? @this.IndexOf(from, comparison) + fromLength
            : 0;

        if (startIndex < fromLength) { throw new ArgumentException("from: Failed to find an instance of the first anchor"); }

            var endIndex = !string.IsNullOrEmpty(until) 
            ? @this.IndexOf(until, startIndex, comparison) 
            : @this.Length;

        if (endIndex < 0) { throw new ArgumentException("until: Failed to find an instance of the last anchor"); }

        var subString = @this.Substring(startIndex, endIndex - startIndex);
        return subString;
    }
}

// usage:
var between = "a - to keep x more stuff".Substring(from: "-", until: "x");
// returns " to keep "

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.

 <telerik:RadScriptBlock ID="radSript1" runat="server">
   <script type="text/javascript">
        //Your javascript
   </script>
</telerik>

Regards Örvar

What's the best three-way merge tool?

I love Ediff. It comes built-in with GNU Emacs.

To do a three-way diff, use ediff-files3 (for selecting three files) or ediff-buffer3 (for selecting three already-open buffers). You'll get a screen looking like this:

three-way diff in emacs

Note the word-difference higlighting.

You can hit n or p to go to the next/previous diffs, while ab will copy the region from buffer a (the leftmost one) to buffer b (the middle one), and similarly for other two-letter combinations of a, b, c; rb will restore the region in buffer b. Hit ? for a quick help menu, or read the fine manual on diff3 merging in Emacs.

Create a button programmatically and set a background image

You need check for image is not nil before assign it to button.

Example:

let button   = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
if let image  = UIImage(named: "imagename.png") {
    button.setImage(image, forState: .Normal)
}

button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)
self.view.addSubview(button)

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

This is a great sample:

String base64String = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAA...";
String base64Image = base64String.split(",")[1];
byte[] decodedString = Base64.decode(base64Image, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imageView.setImageBitmap(decodedByte);

Sample found at: https://freakycoder.com/android-notes-44-how-to-convert-base64-string-to-bitmap-53f98d5e57af

This is the only code that worked for me in the past.

C++ sorting and keeping track of indexes

If it's possible, you can build the position array using find function, and then sort the array.

Or maybe you can use a map where the key would be the element, and the values a list of its position in the upcoming arrays (A, B and C)

It depends on later uses of those arrays.

How to reference Microsoft.Office.Interop.Excel dll?

Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.