Programs & Examples On #Rpath

rpath is an option used with the runtime linker (ld.so) to insert an RPATH header in either binaries or shared libraries. This header specifies the path search order for locating libraries.

I don't understand -Wl,-rpath -Wl,

You could also write

-Wl,-rpath=.

To get rid of that pesky space. It's arguably more readable than adding extra commas (it's exactly what gets passed to ld).

Create a shortcut on Desktop

Without additional reference:

using System;
using System.Runtime.InteropServices;

public class Shortcut
{

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

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

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

To create Shortcut on Desktop:

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

Override standard close (X) button in a Windows Form

One situation where it is quite useful to be able to handle the x-button click event is when you are using a Form that is an MDI container. The reason is that the closeing and closed events are raised first with children and lastly with the parent. So in one scenario a user clicks the x-button to close the application and the MDI parent asks for a confirmation to proceed. In case he decides to not close the application but carry on whatever he is doing the children will already have processed the closing event potentially lost information/work whatever. One solution is to intercept the WM_CLOSE message from the Windows message loop in your main application form (i.e. which closed, terminates the application) like so:

    protected override void WndProc(ref Message m)
    {
        if (m.Msg == 0x0010) // WM_CLOSE
        {
            // If we don't want to close this window 
            if (ShowConfirmation("Are you sure?") != DialogResult.Yes) return;
        }

        base.WndProc(ref m);
    }

How to display a JSON representation and not [Object Object] on the screen

There are 2 ways in which you can get the values:-

  1. Access the property of the object using dot notation (obj.property) .
  2. Access the property of the object by passing in key value for example obj["property"]

How to uninstall Eclipse?

Right click on eclipse icon and click on open file location then delete the eclipse folder from drive(Save backup of your eclipse workspace if you want). Also delete eclipse icon. Thats it..

Clear form fields with jQuery

$('#editPOIForm').each(function(){ 
    this.reset();
});

where editPOIForm is the id attribute of your form.

How do I put a border around an Android textview?

Actually, it is very simple. If you want a simple black rectangle behind the Textview, just add android:background="@android:color/black" within the TextView tags. Like this:

<TextView
    android:textSize="15pt" android:textColor="#ffa7ff04"
    android:layout_alignBottom="@+id/webView1"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:background="@android:color/black"/>

How to assign Php variable value to Javascript variable?

Essentially:

<?php
//somewhere set a value
$var = "a value";
?>

<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';

// then
alert(spge);

</script>

Java: How to resolve java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException

The dependency versions that I needed to use when compiling for Java 8 target. Tested application in Java 8, 11, and 12 JREs.

        <!-- replace dependencies that have been removed from JRE's starting with Java v11 -->
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.8</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-core</artifactId>
            <version>2.2.8-b01</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.8-b01</version>
        </dependency>
        <!-- end replace dependencies that have been removed from JRE's starting with Java v11 -->

Using wire or reg with input or output in Verilog

An output reg foo is just shorthand for output foo_wire; reg foo; assign foo_wire = foo. It's handy when you plan to register that output anyway. I don't think input reg is meaningful for module (perhaps task). input wire and output wire are the same as input and output: it's just more explicit.

How to get rid of punctuation using NLTK tokenizer?

I think you need some sort of regular expression matching (the following code is in Python 3):

import string
import re
import nltk

s = "I can't do this now, because I'm so tired.  Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)

Output:

['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']

Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize.

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

Memcached vs. Redis?

I got the opportunity to use both memcached and redis together in the caching proxy that i have worked on , let me share you where exactly i have used what and reason behind same....

Redis >

1) Used for indexing the cache content , over the cluster . I have more than billion keys in spread over redis clusters , redis response times is quite less and stable .

2) Basically , its a key/value store , so where ever in you application you have something similar, one can use redis with bothering much.

3) Redis persistency, failover and backup (AOF ) will make your job easier .

Memcache >

1) yes , an optimized memory that can be used as cache . I used it for storing cache content getting accessed very frequently (with 50 hits/second)with size less than 1 MB .

2) I allocated only 2GB out of 16 GB for memcached that too when my single content size was >1MB .

3) As the content grows near the limits , occasionally i have observed higher response times in the stats(not the case with redis) .

If you ask for overall experience Redis is much green as it is easy to configure, much flexible with stable robust features.

Further , there is a benchmarking result available at this link , below are few higlight from same,

enter image description here

enter image description here

Hope this helps!!

AngularJS app.run() documentation?

Specifically...

How and where is app.run() used? After module definition or after app.config(), after app.controller()?

Where:

In your package.js E.g. /packages/dashboard/public/controllers/dashboard.js

How:

Make it look like this

var app = angular.module('mean.dashboard', ['ui.bootstrap']);

app.controller('DashboardController', ['$scope', 'Global', 'Dashboard',
    function($scope, Global, Dashboard) {
        $scope.global = Global;
        $scope.package = {
            name: 'dashboard'
        };
        // ...
    }
]);

app.run(function(editableOptions) {
    editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

Excel VBA - Sum up a column

I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell. rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:

dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))

or

dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))

The worksheet function sum will correctly ignore blank spaces.

Let me know if this helps!

Embedding Windows Media Player for all browsers

December 2020 :

  • We have now Firefox 83.0 and Chrome 87.0
  • Internet Explorer is dead, it has been replaced by the new Chromium-based Edge 87.0
  • Silverlight is dead
  • Windows XP is dead
  • WMV is not a standard : https://www.w3schools.com/html/html_media.asp

To answer the question :

  • You have to convert your WMV file to another format : MP4, WebM or Ogg video.
  • Then embed it in your page with the HTML 5 <video> element.

I think this question should be closed.

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

Getting user input

Use the raw_input() function to get input from users (2.x):

print "Enter a file name:",
filename = raw_input()

or just:

filename = raw_input('Enter a file name: ')

or if in Python 3.x:

filename = input('Enter a file name: ')

How to remove/ignore :hover css style on touch devices

Try this (i use background and background-color in this example):

var ClickEventType = ((document.ontouchstart !== null) ? 'click' : 'touchstart');

if (ClickEventType == 'touchstart') {
            $('a').each(function() { // save original..
                var back_color = $(this).css('background-color');
                var background = $(this).css('background');
                $(this).attr('data-back_color', back_color);
                $(this).attr('data-background', background);
            });

            $('a').on('touchend', function(e) { // overwrite with original style..
                var background = $(this).attr('data-background');
                var back_color = $(this).attr('data-back_color');
                if (back_color != undefined) {
                    $(this).css({'background-color': back_color});
                }
                if (background != undefined) {
                    $(this).css({'background': background});
                }
            }).on('touchstart', function(e) { // clear added stlye="" elements..
                $(this).css({'background': '', 'background-color': ''});
            });
}

css:

a {
    -webkit-touch-callout: none;
    -webkit-tap-highlight-color: transparent;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

How do you get a list of the names of all files present in a directory in Node.js?

If many of the above options seem too complex or not what you are looking for here is another approach using node-dir - https://github.com/fshost/node-dir

npm install node-dir

Here is a somple function to list all .xml files searching in subdirectories

import * as nDir from 'node-dir' ;

listXMLs(rootFolderPath) {
    let xmlFiles ;

    nDir.files(rootFolderPath, function(err, items) {
        xmlFiles = items.filter(i => {
            return path.extname(i) === '.xml' ;
        }) ;
        console.log(xmlFiles) ;       
    });
}

How to sort alphabetically while ignoring case sensitive?

I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

How can I set the focus (and display the keyboard) on my EditText programmatically

Try this:

EditText editText = (EditText) findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

http://developer.android.com/reference/android/view/View.html#requestFocus()

how does unix handle full path name with space and arguments?

Since spaces are used to separate command line arguments, they have to be escaped from the shell. This can be done with either a backslash () or quotes:

"/path/with/spaces in it/to/a/file"
somecommand -spaced\ option
somecommand "-spaced option"
somecommand '-spaced option'

This is assuming you're running from a shell. If you're writing code, you can usually pass the arguments directly, avoiding the problem:

Example in perl. Instead of doing:

print("code sample");system("somecommand -spaced option");

you can do

print("code sample");system("somecommand", "-spaced option");

Since when you pass the system() call a list, it doesn't break arguments on spaces like it does with a single argument call.

Background color for Tk in Python

Its been updated so

root.configure(background="red")

is now:

root.configure(bg="red")

'ssh' is not recognized as an internal or external command

Actually you have 2 problems here: First is that you don't have ssh installed, second is that you don't know how to deploy

Install SSH

It seems that ssh is not installed on your computer.

You can install openssh from here : http://openssh.en.softonic.com/download

Generate your key

Than you will have to geneate your ssh-key. There's a good tutorial about this here:

https://help.github.com/articles/generating-ssh-keys#platform-windows

Deploy

To deploy, you just have to push your code over git. Something like this:

git push fort master

If you get permission denied, be sure that you have put your public_key in the dashboard in the git tab.

SSH

The ssh command gives you access to your remote node. You should have received a password by email and now that you have ssh installed, you should be asked for a password when trying to connect. just input that password. If you want to use your private ssh key to connect to your server rather then typing that password, you can follow this : http://fortrabbit.com/docs/how-to/ssh-sftp/enable-public-key-authentication

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

Anton,

As a best practice one should n't create user objects in the primary filegroup. When you have bandwidth, create a new file group and move the user objects and leave the system objects in primary.

The following queries will help you identify the space used in each file and the top tables that have highest number of rows and if there are any heaps. Its a good starting point to investigate this issue.

SELECT  
ds.name as filegroupname
, df.name AS 'FileName' 
, physical_name AS 'PhysicalName'
, size/128 AS 'TotalSizeinMB'
, size/128.0 - CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS 'AvailableSpaceInMB' 
, CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0 AS 'ActualSpaceUsedInMB'
, (CAST(FILEPROPERTY(df.name, 'SpaceUsed') AS int)/128.0)/(size/128)*100. as '%SpaceUsed'
FROM sys.database_files df LEFT OUTER JOIN sys.data_spaces ds  
    ON df.data_space_id = ds.data_space_id;

EXEC xp_fixeddrives
select  t.name as TableName,  
    i.name as IndexName, 
    p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
    on fg.data_space_id = df.data_space_id join sys.indexes i (nolock) 
    on df.data_space_id = i.data_space_id join sys.tables t (nolock)
    on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id  
where fg.name = 'PRIMARY' and t.type = 'U'  
order by rows desc
select  t.name as TableName,  
    i.name as IndexName, 
    p.rows as Rows
from sys.filegroups fg (nolock) join sys.database_files df (nolock)
    on fg.data_space_id = df.data_space_id join sys.indexes i (nolock) 
    on df.data_space_id = i.data_space_id join sys.tables t (nolock)
    on i.object_id = t.object_id join sys.partitions p (nolock)
on t.object_id = p.object_id and i.index_id = p.index_id  
where fg.name = 'PRIMARY' and t.type = 'U' and i.index_id = 0 
order by rows desc

How do you log all events fired by an element in jQuery?

Old thread, I know. I needed also something to monitor events and wrote this very handy (excellent) solution. You can monitor all events with this hook (in windows programming this is called a hook). This hook does not affects the operation of your software/program.

In the console log you can see something like this:

console log

Explanation of what you see:

In the console log you will see all events you select (see below "how to use") and shows the object-type, classname(s), id, <:name of function>, <:eventname>. The formatting of the objects is css-like.

When you click a button or whatever binded event, you will see it in the console log.

The code I wrote:

function setJQueryEventHandlersDebugHooks(bMonTrigger, bMonOn, bMonOff)
{
   jQuery.fn.___getHookName___ = function()    
       {
          // First, get object name
         var sName = new String( this[0].constructor ),
         i = sName.indexOf(' ');
         sName = sName.substr( i, sName.indexOf('(')-i );    

         // Classname can be more than one, add class points to all
         if( typeof this[0].className === 'string' )
         {
           var sClasses = this[0].className.split(' ');
           sClasses[0]='.'+sClasses[0];
           sClasses = sClasses.join('.');
           sName+=sClasses;
         }
         // Get id if there is one
         sName+=(this[0].id)?('#'+this[0].id):'';
         return sName;
       };

   var bTrigger        = (typeof bMonTrigger !== "undefined")?bMonTrigger:true,
       bOn             = (typeof bMonOn !== "undefined")?bMonOn:true,
       bOff            = (typeof bMonOff !== "undefined")?bMonOff:true,
       fTriggerInherited = jQuery.fn.trigger,
       fOnInherited    = jQuery.fn.on,
       fOffInherited   = jQuery.fn.off;

   if( bTrigger )
   {
    jQuery.fn.trigger = function()
    {
     console.log( this.___getHookName___()+':trigger('+arguments[0]+')' );
     return fTriggerInherited.apply(this,arguments);
    };
   }

   if( bOn )
   {
    jQuery.fn.on = function()
    {
     if( !this[0].__hooked__ ) 
     {
       this[0].__hooked__ = true; // avoids infinite loop!
       console.log( this.___getHookName___()+':on('+arguments[0]+') - binded' );
       $(this).on( arguments[0], function(e)
       {
         console.log( $(this).___getHookName___()+':'+e.type );
       });
     }
     var uResult = fOnInherited.apply(this,arguments);
     this[0].__hooked__ = false; // reset for another event
     return uResult;
    };
   }

   if( bOff )
   {
    jQuery.fn.off = function()
    {
     if( !this[0].__unhooked__ ) 
     {
       this[0].__unhooked__ = true; // avoids infinite loop!
       console.log( this.___getHookName___()+':off('+arguments[0]+') - unbinded' );
       $(this).off( arguments[0] );
     }

     var uResult = fOffInherited.apply(this,arguments);
     this[0].__unhooked__ = false; // reset for another event
     return uResult;
    };
   }
}

Examples how to use it:

Monitor all events:

setJQueryEventHandlersDebugHooks();

Monitor all triggers only:

setJQueryEventHandlersDebugHooks(true,false,false);

Monitor all ON events only:

setJQueryEventHandlersDebugHooks(false,true,false);

Monitor all OFF unbinds only:

setJQueryEventHandlersDebugHooks(false,false,true);

Remarks/Notice:

  • Use this for debugging only, turn it off when using in product final version
  • If you want to see all events, you have to call this function directly after jQuery is loaded
  • If you want to see only less events, you can call the function on the time you need it
  • If you want to auto execute it, place ( )(); around function

Hope it helps! ;-)

Android Call an method from another class

In Class1:

Class2 inst = new Class2();
inst.UpdateEmployee();

equivalent to push() or pop() for arrays?

You can use LinkedList. It has methods peek, poll and offer.

HTTP GET in VB.NET

You can use the HttpWebRequest class to perform a request and retrieve a response from a given URL. You'll use it like:

Try
    Dim fr As System.Net.HttpWebRequest
    Dim targetURI As New Uri("http://whatever.you.want.to.get/file.html")         

    fr = DirectCast(HttpWebRequest.Create(targetURI), System.Net.HttpWebRequest)
    If (fr.GetResponse().ContentLength > 0) Then
        Dim str As New System.IO.StreamReader(fr.GetResponse().GetResponseStream())
        Response.Write(str.ReadToEnd())
        str.Close(); 
    End If   
Catch ex As System.Net.WebException
   'Error in accessing the resource, handle it
End Try

HttpWebRequest is detailed at: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

A second option is to use the WebClient class, this provides an easier to use interface for downloading web resources but is not as flexible as HttpWebRequest:

Sub Main()
    'Address of URL
    Dim URL As String = http://whatever.com
    ' Get HTML data
    Dim client As WebClient = New WebClient()
    Dim data As Stream = client.OpenRead(URL)
    Dim reader As StreamReader = New StreamReader(data)
    Dim str As String = ""
    str = reader.ReadLine()
    Do While str.Length > 0
        Console.WriteLine(str)
        str = reader.ReadLine()
    Loop
End Sub

More info on the webclient can be found at: http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx

Where to place $PATH variable assertions in zsh?

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.

   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:

/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

Returning a value even if no result

MySQL has a function to return a value if the result is null. You can use it on a whole query:

SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

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

do it like this:

"abc%s" % 9
#or
"abc" + str(9)

Integer.valueOf() vs. Integer.parseInt()

The difference between these two methods is:

  • parseXxx() returns the primitive type
  • valueOf() returns a wrapper object reference of the type.

How to delete an array element based on key?

this looks like PHP to me. I'll delete if it's some other language.

Simply unset($arr[1]);

How to check if a table exists in MS Access for vb macros

This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.

Basically, which works fastest depends on what database object you use with it.

Adding space/padding to a UILabel

If you want to stick with UILabel, without subclassing it, Mundi has given you a clear solution.

If alternatively, you would be willing to avoid wrapping the UILabel with a UIView, you could use UITextView to enable the use of UIEdgeInsets (padding) or subclass UILabel to support UIEdgeInsets.

Using a UITextView would only need to provide the insets (OBJ-C):

textView.textContainerInset = UIEdgeInsetsMake(10, 0, 10, 0);

Alternative, if you subclass UILabel, an example to this approach would be overriding the drawTextInRect method
(OBJ-C)

- (void)drawTextInRect:(CGRect)uiLabelRect {
    UIEdgeInsets myLabelInsets = {10, 0, 10, 0};
    [super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, myLabelInsets)];
}

You could additionally provide your new subclassed UILabel with insets variables for TOP, LEFT, BOTTOM and RIGHT.

An example code could be:

In .h (OBJ-C)

float topInset, leftInset,bottomInset, rightInset;

In .m (OBJ-C)

- (void)drawTextInRect:(CGRect)uiLabelRect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(uiLabelRect, UIEdgeInsetsMake(topInset,leftInset,bottomInset,rightInset))];
}

EDIT #1:

From what I have seen, it seems you have to override the intrinsicContentSize of the UILabel when subclassing it.

So you should override intrinsicContentSize like:

- (CGSize) intrinsicContentSize {
    CGSize intrinsicSuperViewContentSize = [super intrinsicContentSize] ;
    intrinsicSuperViewContentSize.height += topInset + bottomInset ;
    intrinsicSuperViewContentSize.width += leftInset + rightInset ;
    return intrinsicSuperViewContentSize ;
}

And add the following method to edit your insets, instead of editing them individually:

- (void) setContentEdgeInsets:(UIEdgeInsets)edgeInsets {
    topInset = edgeInsets.top;
    leftInset = edgeInsets.left;
    rightInset = edgeInsets.right; 
    bottomInset = edgeInsets.bottom;
    [self invalidateIntrinsicContentSize] ;
}

It will update the size of your UILabel to match the edge insets and cover the multiline necessity you referred to.

Edit #2

After searching a bit I have found this Gist with an IPInsetLabel. If none of those solutions work you could try it out.

Edit #3

There was a similar question (duplicate) about this matter.
For a full list of available solutions, see this answer: UILabel text margin

Is there a way to detect if a browser window is not currently active?

This is really tricky. There seems to be no solution given the following requirements.

  • The page includes iframes that you have no control over
  • You want to track visibility state change regardless of the change being triggered by a TAB change (ctrl+tab) or a window change (alt+tab)

This happens because:

  • The page Visibility API can reliably tell you of a tab change (even with iframes), but it can't tell you when the user changes windows.
  • Listening to window blur/focus events can detect alt+tabs and ctrl+tabs, as long as the iframe doesn't have focus.

Given these restrictions, it is possible to implement a solution that combines - The page Visibility API - window blur/focus - document.activeElement

That is able to:

  • 1) ctrl+tab when parent page has focus: YES
  • 2) ctrl+tab when iframe has focus: YES
  • 3) alt+tab when parent page has focus: YES
  • 4) alt+tab when iframe has focus: NO <-- bummer

When the iframe has focus, your blur/focus events don't get invoked at all, and the page Visibility API won't trigger on alt+tab.

I built upon @AndyE's solution and implemented this (almost good) solution here: https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test1.html (sorry, I had some trouble with JSFiddle).

This is also available on Github: https://github.com/qmagico/estante-components

This works on chrome/chromium. It kind works on firefox, except that it doesn't load the iframe contents (any idea why?)

Anyway, to resolve the last problem (4), the only way you can do that is to listen for blur/focus events on the iframe. If you have some control over the iframes, you can use the postMessage API to do that.

https://dl.dropboxusercontent.com/u/2683925/estante-components/visibility_test2.html

I still haven't tested this with enough browsers. If you can find more info about where this doesn't work, please let me know in the comments below.

How to set default vim colorscheme

Put a colorscheme directive in your .vimrc file, for example:

colorscheme morning

See here: http://vim.wikia.com/wiki/Change_the_color_scheme

Stick button to right side of div

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
    <div style="clear:both;"></div>
</div>

css

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-right:10px;

}

Ajax - 500 Internal Server Error

Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".

So log on the server and debug from there.

Adding +1 to a variable inside a function

You could also pass points to the function: Small example:

def test(points):
    addpoint = raw_input ("type ""add"" to add a point")
    if addpoint == "add":
        points = points + 1
    else:
        print "asd"
    return points;
if __name__ == '__main__':
    points = 0
    for i in range(10):
        points = test(points)
        print points

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me it was because I hadn't set an active class on any of the slides.

How to decrypt a password from SQL server?

The SQL Server password hashing algorithm:

hashBytes = 0x0100 | fourByteSalt | SHA1(utf16EncodedPassword+fourByteSalt)

For example, to hash the password "correct horse battery staple". First we generate some random salt:

fourByteSalt = 0x9A664D79;

And then hash the password (encoded in UTF-16) along with the salt:

 SHA1("correct horse battery staple" + 0x9A66D79);
=SHA1(0x63006F007200720065006300740020006200610074007400650072007900200068006F00720073006500200073007400610070006C006500 0x9A66D79)
=0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

The value stored in the syslogins table is the concatenation of:

[header] + [salt] + [hash]
0x0100 9A664D79 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

Which you can see in SQL Server:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins
WHERE name = 'sa'

name  PasswordHash
====  ======================================================
sa    0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
  • Version header: 0100
  • Salt (four bytes): 9A664D79
  • Hash: 6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3 (SHA-1 is 20 bytes; 160 bits)

Validation

You validate a password by performing the same hash:

  • grab the salt from the saved PasswordHash: 0x9A664D79

and perform the hash again:

SHA1("correct horse battery staple" + 0x9A66D79);

which will come out to the same hash, and you know the password is correct.

What once was good, but now is weak

The hashing algorithm introduced with SQL Server 7, in 1999, was good for 1999.

  • It is good that the password hash salted.
  • It is good to append the salt to the password, rather than prepend it.

But today it is out-dated. It only runs the hash once, where it should run it a few thousand times, in order to thwart brute-force attacks.

In fact, Microsoft's Baseline Security Analyzer will, as part of it's checks, attempt to bruteforce passwords. If it guesses any, it reports the passwords as weak. And it does get some.

Brute Forcing

To help you test some passwords:

DECLARE @hash varbinary(max)
SET @hash = 0x01009A664D796EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3
--Header: 0x0100
--Salt:   0x9A664D79
--Hash:   0x6EDB2FA35E3B8FAB4DBA2FFB62F5426B67FE54A3

DECLARE @password nvarchar(max)
SET @password = 'password'

SELECT
    @password AS CandidatePassword,
    @hash AS PasswordHash,

    --Header
    0x0100
    +
    --Salt
    CONVERT(VARBINARY(4), SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))
    +
    --SHA1 of Password + Salt
    HASHBYTES('SHA1', @password + SUBSTRING(CONVERT(NVARCHAR(MAX), @hash), 2, 2))

SQL Server 2012 and SHA-512

Starting with SQL Server 2012, Microsoft switched to using SHA-2 512-bit:

hashBytes = 0x0200 | fourByteSalt | SHA512(utf16EncodedPassword+fourByteSalt)

Changing the version prefix to 0x0200:

SELECT 
   name, CAST(password AS varbinary(max)) AS PasswordHash
FROM sys.syslogins

name  PasswordHash
----  --------------------------------
xkcd  0x02006A80BA229556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38
  • Version: 0200 (SHA-2 256-bit)
  • Salt: 6A80BA22
  • Hash (64 bytes): 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

This means we hash the UTF-16 encoded password, with the salt suffix:

  • SHA512("correct horse battery staple"+6A80BA22)
  • SHA512(63006f0072007200650063007400200068006f0072007300650020006200610074007400650072007900200073007400610070006c006500 + 6A80BA22)
  • 9556EB280AA7818FAF63A0DA8D6B7B120C6760F0EB0CB5BB320A961B04BD0836 0C0E8CC4C326220501147D6A9ABD2A006B33DEC99FCF1A822393FC66226B7D38

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

How can I select from list of values in Oracle

There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select '1,2,3,a,b,c,d' str from dual
  3  )
  4   select regexp_substr(str,'[^,]+',1,level) element
  5     from x
  6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /

ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d

7 rows selected.

Or in PL/SQL

SQL> create type str_tbl is table of varchar2(100);
  2  /

Type created.

SQL> create or replace function parse_list( p_list in varchar2 )
  2    return str_tbl
  3    pipelined
  4  is
  5  begin
  6    for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
  7                from dual
  8             connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
  9    loop
 10      pipe row( x.element );
 11    end loop
 12    return;
 13  end;
 14
 15  /

Function created.

SQL> select *
  2    from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));

COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f

9 rows selected.

Java difference between FileWriter and BufferedWriter

From the Java API specification:

FileWriter

Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable.

BufferedWriter

Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Reloading submodules in IPython

On Jupyter Notebooks on Anaconda, doing this:

%load_ext autoreload
%autoreload 2

produced the message:

The autoreload extension is already loaded. To reload it, use: %reload_ext autoreload

It looks like it's preferable to do:

%reload_ext autoreload
%autoreload 2

Version information:

The version of the notebook server is 5.0.0 and is running on: Python 3.6.2 |Anaconda, Inc.| (default, Sep 20 2017, 13:35:58) [MSC v.1900 32 bit (Intel)]

What is the purpose of backbone.js?

Backbone.js is a JavaScript framework that helps you organize your code. It is literally a backbone upon which you build your application. It doesn't provide widgets (like jQuery UI or Dojo).

It gives you a cool set of base classes that you can extend to create clean JavaScript code that interfaces with RESTful endpoints on your server.

How can I do factory reset using adb in android?

I have made it from fastboot mode (Phone - Xiomi Mi5 Android 6.0.1)

Here is steps:

# check if device available
fastboot devices
# remove user data
fastboot erase userdata
# remove cache
fastboot erase cache 
# reboot device
fastboot reboot

Call to a member function fetch_assoc() on boolean in <path>

This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.

How to evaluate http response codes from bash/shell script?

curl --write-out "%{http_code}\n" --silent --output /dev/null "$URL"

works. If not, you have to hit return to view the code itself.

Create normal zip file programmatically

My 2 cents:

    using (ZipArchive archive = ZipFile.Open(zFile, ZipArchiveMode.Create))
    {
        foreach (var fPath in filePaths)
        {
            archive.CreateEntryFromFile(fPath,Path.GetFileName(fPath));
        }
    }

So Zip files could be created directly from files/dirs.

Laravel Eloquent limit and offset

You can use skip and take functions as below:

$products = $art->products->skip($offset*$limit)->take($limit)->get();

// skip should be passed param as integer value to skip the records and starting index

// take gets an integer value to get the no. of records after starting index defined by skip

EDIT

Sorry. I was misunderstood with your question. If you want something like pagination the forPage method will work for you. forPage method works for collections.

REf : https://laravel.com/docs/5.1/collections#method-forpage

e.g

$products = $art->products->forPage($page,$limit);

Vue - Deep watching an array of objects and calculating the change?

Your comparison function between old value and new value is having some issue. It is better not to complicate things so much, as it will increase your debugging effort later. You should keep it simple.

The best way is to create a person-component and watch every person separately inside its own component, as shown below:

<person-component :person="person" v-for="person in people"></person-component>

Please find below a working example for watching inside person component. If you want to handle it on parent side, you may use $emit to send an event upwards, containing the id of modified person.

_x000D_
_x000D_
Vue.component('person-component', {_x000D_
    props: ["person"],_x000D_
    template: `_x000D_
        <div class="person">_x000D_
            {{person.name}}_x000D_
            <input type='text' v-model='person.age'/>_x000D_
        </div>`,_x000D_
    watch: {_x000D_
        person: {_x000D_
            handler: function(newValue) {_x000D_
                console.log("Person with ID:" + newValue.id + " modified")_x000D_
                console.log("New age: " + newValue.age)_x000D_
            },_x000D_
            deep: true_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
new Vue({_x000D_
    el: '#app',_x000D_
    data: {_x000D_
        people: [_x000D_
          {id: 0, name: 'Bob', age: 27},_x000D_
          {id: 1, name: 'Frank', age: 32},_x000D_
          {id: 2, name: 'Joe', age: 38}_x000D_
        ]_x000D_
    }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<body>_x000D_
    <div id="app">_x000D_
        <p>List of people:</p>_x000D_
        <person-component :person="person" v-for="person in people"></person-component>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to split() a delimited string to a List<String>

string.Split() returns an array - you can convert it to a list using ToList():

listStrLineElements = line.Split(',').ToList();

Note that you need to import System.Linq to access the .ToList() function.

Swift apply .uppercaseString to only the first letter of a string

Swift 5.1 or later

extension StringProtocol {
    var firstUppercased: String { prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { prefix(1).capitalized + dropFirst() }
}

Swift 5

extension StringProtocol {
    var firstUppercased: String { return prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { return prefix(1).capitalized + dropFirst() }
}

"Swift".first  // "S"
"Swift".last   // "t"
"hello world!!!".firstUppercased  // "Hello world!!!"

"?".firstCapitalized   // "?"
"?".firstCapitalized   // "?"
"?".firstCapitalized   // "?"

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

Checking if a variable exists in javascript

It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,

if (window.variableName)

is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.

That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.

if ( variableName  && typeof variableName !== 'undefined' )

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

How can I detect when an Android application is running in the emulator?

How about this solution (class implementation of SystemProperties is available here):

private var sIsProbablyRunningOnEmulator: Boolean? = null

fun isProbablyRunningOnEmulator(): Boolean {
    var result = sIsProbablyRunningOnEmulator
    if (result != null)
        return result
    // Android SDK emulator
    result = (Build.FINGERPRINT.startsWith("google/sdk_gphone_")
            && Build.FINGERPRINT.endsWith(":user/release-keys")
            && Build.MANUFACTURER == "Google" && Build.PRODUCT.startsWith("sdk_gphone_") && Build.BRAND == "google"
            && Build.MODEL.startsWith("sdk_gphone_"))
            //
            || Build.FINGERPRINT.startsWith("generic")
            || Build.FINGERPRINT.startsWith("unknown")
            || Build.MODEL.contains("google_sdk")
            || Build.MODEL.contains("Emulator")
            || Build.MODEL.contains("Android SDK built for x86")
            //bluestacks
            || "QC_Reference_Phone" == Build.BOARD && !"Xiaomi".equals(Build.MANUFACTURER, ignoreCase = true) //bluestacks
            || Build.MANUFACTURER.contains("Genymotion")
            || Build.HOST.startsWith("Build") //MSI App Player
            || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic")
            || Build.PRODUCT == "google_sdk"
            // another Android SDK emulator check
            || SystemProperties.getProp("ro.kernel.qemu") == "1"
    sIsProbablyRunningOnEmulator = result
    return result
}

Note that some emulators fake exact specs of real devices, so it might be impossible to detect it. I've added what I could, but I don't think there is a 100% way to detect if it's really an emulator or not.

Here a tiny snippet you can make in the APK to show various things about it, so you could add your own rules:

        textView.text = "FINGERPRINT:${Build.FINGERPRINT}\n" +
                "MODEL:${Build.MODEL}\n" +
                "MANUFACTURER:${Build.MANUFACTURER}\n" +
                "BRAND:${Build.BRAND}\n" +
                "DEVICE:${Build.DEVICE}\n" +
                "BOARD:${Build.BOARD}\n" +
                "HOST:${Build.HOST}\n" +
                "PRODUCT:${Build.PRODUCT}\n"

What does void mean in C, C++, and C#?

It means "no value". You use void to indicate that a function doesn't return a value or that it has no parameters or both. Pretty much consistent with typical uses of word void in English.

Failed to install *.apk on device 'emulator-5554': EOF

Wipe Data and restart the virtual device again fix the issue in my case.

enter image description here

How can I force WebKit to redraw/repaint to propagate style changes?

I stumbled upon this today: Element.redraw() for prototype.js

Using:

Element.addMethods({
  redraw: function(element){
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    (function(){n.parentNode.removeChild(n)}).defer();
    return element;
  }
});

However, I've noticed sometimes that you must call redraw() on the problematic element directly. Sometimes redrawing the parent element won't solve the problem the child is experiencing.

Good article about the way browsers render elements: Rendering: repaint, reflow/relayout, restyle

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

Considering only one row is returned, only one loop will be done in both cases. Though it will check for the loop entering condition twice on each.

scrollTop jquery, scrolling to div with id?

if you want to scroll just only some div, can use the div id instead of 'html, body'

$('html, body').animate(...

use

$('#mydivid').animate(...

Debug assertion failed. C++ vector subscript out of range

this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to array
for(int i=0; i<10; i++){
   arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}

the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.

How to get a list of images on docker registry v2

Get catalogs

Default, registry api return 100 entries of catalog, there is the code:

When you curl the registry api:

curl --cacert domain.crt https://your.registry:5000/v2/_catalog

it equivalents with:

curl --cacert domain.crt https://your.registry:5000/v2/_catalog?n=100

This is a pagination methond.

When the sum of entries beyond 100, you can do in two ways:

First: give a bigger number

curl --cacert domain.crt https://your.registry:5000/v2/_catalog?n=2000

Sencond: parse the next linker url

curl --cacert domain.crt https://your.registry:5000/v2/_catalog

A link element contained in response header:

curl --cacert domain.crt https://your.registry:5000/v2/_catalog

response header:

Link: </v2/_catalog?last=pro-octopus-ws&n=100>; rel="next"

The link element have the last entry of this request, then you can request the next 'page':

curl --cacert domain.crt https://your.registry:5000/v2/_catalog?last=pro-octopus-ws

If the response header contains link element, you can do it in a loop.

Get Images

When you get the result of catalog, it like follows:

{ "repositories": [ "busybox", "ceph/mds" ] }

you can get the images in every catalog:

curl --cacert domain.crt https://your.registry:5000/v2/busybox/tags/list

returns:

{"name":"busybox","tags":["latest"]}

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Here is one implemented using sort() and JSON.stringify()

https://gist.github.com/korczis/7598657

function removeDuplicates(vals) {
    var res = [];
    var tmp = vals.sort();

    for (var i = 0; i < tmp.length; i++) {
        res.push(tmp[i]);
                    while (JSON.stringify(tmp[i]) == JSON.stringify(tmp[i + 1])) {
            i++;
        }
    }

    return res;
}
console.log(removeDuplicates([1,2,3,4,5,4,3,3,2,1,]));

When adding a Javascript library, Chrome complains about a missing source map, why?

I had similar problem when i was trying to work with coco-ssd. I think this problem is caused because of the version. I changed version of tfjs to 0.9.0 and coco-ssd version to 1.1.0 and it worked for me. (you can search for posenet versions on : https://www.jsdelivr.com/package/npm/@tensorflow-models/posenet)

<!-- Load TensorFlow.js-->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/[email protected]"></script>
<!-- Load the coco-ssd model. -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/[email protected]"</script>

Show a popup/message box from a Windows batch file

msg * /server:127.0.0.1 Type your message here

What is the difference between Bootstrap .container and .container-fluid classes?

Use .container-fluid when you want your page to shapeshift with every little difference in its viewport size.

Use .container when you want your page to shapeshift to only 4 kinds of sizes, which are also known as "breakpoints".

The breakpoints corresponding to their sizes are:

  • Extra Small: (Only Mobile Resolution)
  • Small: 768px (Tablets)
  • Medium: 992px (Laptops)
  • Large: 1200px (Laptops/Desktops)

The view 'Index' or its master was not found.

This error can also surface if your MSI installer failed to actually deploy the file.

In my case this happened because I converted the .aspx files to .cshtml files and visual studio thought these were brand new files and set the build action to none instead of content.

How to upload files to server using JSP/Servlet?

Sending multiple file for file we have to use enctype="multipart/form-data"
and to send multiple file use multiple="multiple" in input tag

<form action="upload" method="post" enctype="multipart/form-data">
 <input type="file" name="fileattachments"  multiple="multiple"/>
 <input type="submit" />
</form>

After installing with pip, "jupyter: command not found"

if you are in a virtual environment, just run this:

conda install jupyter

INNER JOIN same table

You can also use UNION like

SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_id = $_GET[id]
UNION
SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_parent_id = $_GET[id]

How to insert new cell into UITableView in Swift

Use beginUpdates and endUpdates to insert a new cell when the button clicked.

As @vadian said in comment, begin/endUpdates has no effect for a single insert/delete/move operation

First of all, append data in your tableview array

Yourarray.append([labeltext])  

Then update your table and insert a new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload the whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

dataGridView1.Columns is probably of a length less than 5. Accessing dataGridView1.Columns[4] then will be outside the list.

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

How to get all keys with their values in redis

I have written a small code for this particular requirement using hiredis , please find the code with a working example at http://rachitjain1.blogspot.in/2013/10/how-to-get-all-keyvalue-in-redis-db.html

Here is the code that I have written,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "hiredis.h"

int main(void)
{
        unsigned int i,j=0;char **str1;
        redisContext *c; char *t;
        redisReply *reply, *rep;

        struct timeval timeout = { 1, 500000 }; // 1.5 seconds
        c = redisConnectWithTimeout((char*)"127.0.0.2", 6903, timeout);
        if (c->err) {
                printf("Connection error: %s\n", c->errstr);
                exit(1);
        }

        reply = redisCommand(c,"keys *");
        printf("KEY\t\tVALUE\n");
        printf("------------------------\n");
        while ( reply->element[j]->str != NULL)
        {
                rep = redisCommand(c,"GET  %s", reply->element[j]->str);
                if (strstr(rep->str,"ERR Operation against a key holding"))
                {
                        printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                        break;
                }
                printf("%s\t\t%s\n",  reply->element[j]->str,rep->str);
                j++;
                freeReplyObject(rep);
        }
}

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to turn off page breaks in Google Docs?

Turn off "Print Layout" from the "View" menu.

react-native: command not found

If you're using yarn, you may have to run commands with yarn in front. Example:

yarn react-native info

Creating a new ArrayList in Java

Java 8

In order to create a non-empty list of fixed size where different operations like add, remove, etc won't be supported:

List<Integer> fixesSizeList= Arrays.asList(1, 2);

Non-empty mutable list:

List<Integer> mutableList = new ArrayList<>(Arrays.asList(3, 4));

Java 9

With Java 9 you can use the List.of(...) static factory method:

List<Integer> immutableList = List.of(1, 2);

List<Integer> mutableList = new ArrayList<>(List.of(3, 4));

Java 10

With Java 10 you can use the Local Variable Type Inference:

var list1 = List.of(1, 2);

var list2 = new ArrayList<>(List.of(3, 4));

var list3 = new ArrayList<String>();

Check out more ArrayList examples here.

Javascript receipt printing using POS Printer

Maybe you could have a look at this if your printer is an epson. There is a javascript driver

http://spsrprofessionals.com/ClientSite/readers/ePOS-Print_SDK_141020E/JavaScript/ePOS-Print_SDK_JS_en_revB.pdf

EDIT:

Previous link seems to be broken

All details about how to use epos of epson are on epson website:

https://reference.epson-biz.com/modules/ref_epos_device_js_en/index.php?content_id=139

Is it possible to delete an object's property in PHP?

This also works specially if you are looping over an object.

unset($object[$key])

Update

Newer versions of PHP throw fatal error Fatal error: Cannot use object of type Object as array as mentioned by @CXJ . In that case you can use brackets instead

unset($object->{$key})

CentOS 64 bit bad ELF interpreter

You're on a 64-bit system, and don't have 32-bit library support installed.

To install (baseline) support for 32-bit executables

(if you don't use sudo in your setup read note below)

Most desktop Linux systems in the Fedora/Red Hat family:

 pkcon install glibc.i686

Possibly some desktop Debian/Ubuntu systems?:

pkcon install ia32-libs

Fedora or newer Red Hat, CentOS:

 sudo dnf install glibc.i686

Older RHEL, CentOS:

   sudo yum install glibc.i686

Even older RHEL, CentOS:

  sudo yum install glibc.i386

Debian or Ubuntu:

   sudo apt-get install ia32-libs

should grab you the (first, main) library you need.

Once you have that, you'll probably need support libs

Anyone needing to install glibc.i686 or glibc.i386 will probably run into other library dependencies, as well. To identify a package providing an arbitrary library, you can use

 ldd /usr/bin/YOURAPPHERE

if you're not sure it's in /usr/bin you can also fall back on

 ldd $(which YOURAPPNAME)

The output will look like this:

    linux-gate.so.1 =>  (0xf7760000)
    libpthread.so.0 => /lib/libpthread.so.0 (0xf773e000)
    libSM.so.6 => not found

Check for missing libraries (e.g. libSM.so.6 in the above output), and for each one you need to find the package that provides it.

Commands to find the package per distribution family

Fedora/Red Hat Enterprise/CentOS:

 dnf provides /usr/lib/libSM.so.6

or, on older RHEL/CentOS:

 yum provides /usr/lib/libSM.so.6

or, on Debian/Ubuntu:

first, install and download the database for apt-file

 sudo apt-get install apt-file && apt-file update

then search with

 apt-file find libSM.so.6

Note the prefix path /usr/lib in the (usual) case; rarely, some libraries still live under /lib for historical reasons … On typical 64-bit systems, 32-bit libraries live in /usr/lib and 64-bit libraries live in /usr/lib64.

(Debian/Ubuntu organise multi-architecture libraries differently.)

Installing packages for missing libraries

The above should give you a package name, e.g.:

libSM-1.2.0-2.fc15.i686 : X.Org X11 SM runtime library
Repo        : fedora
Matched from:
Filename    : /usr/lib/libSM.so.6

In this example the name of the package is libSM and the name of the 32bit version of the package is libSM.i686.

You can then install the package to grab the requisite library using pkcon in a GUI, or sudo dnf/yum/apt-get as appropriate…. E.g pkcon install libSM.i686. If necessary you can specify the version fully. E.g sudo dnf install ibSM-1.2.0-2.fc15.i686.

Some libraries will have an “epoch” designator before their name; this can be omitted (the curious can read the notes below).

Notes

Warning

Incidentially, the issue you are facing either implies that your RPM (resp. DPkg/DSelect) database is corrupted, or that the application you're trying to run wasn't installed through the package manager. If you're new to Linux, you probably want to avoid using software from sources other than your package manager, whenever possible...

If you don't use "sudo" in your set-up

Type

su -c

every time you see sudo, eg,

su -c dnf install glibc.i686

About the epoch designator in library names

The “epoch” designator before the name is an artifact of the way that the underlying RPM libraries handle version numbers; e.g.

2:libpng-1.2.46-1.fc16.i686 : A library of functions for manipulating PNG image format files
Repo        : fedora
Matched from:
Filename    : /usr/lib/libpng.so.3

Here, the 2: can be omitted; just pkcon install libpng.i686 or sudo dnf install libpng-1.2.46-1.fc16.i686. (It vaguely implies something like: at some point, the version number of the libpng package rolled backwards, and the “epoch” had to be incremented to make sure the newer version would be considered “newer” during updates. Or something similar happened. Twice.)


Updated to clarify and cover the various package manager options more fully (March, 2016)

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

Does C# have a String Tokenizer like Java's?

use Regex.Split(string,"#|#");

Getting raw SQL query string from PDO prepared statements

Somewhat related... if you are just trying to sanitize a particular variable you can use PDO::quote. For example, to search for multiple partial LIKE conditions if you're stuck with a limited framework like CakePHP:

$pdo = $this->getDataSource()->getConnection();
$results = $this->find('all', array(
    'conditions' => array(
        'Model.name LIKE ' . $pdo->quote("%{$keyword1}%"),
        'Model.name LIKE ' . $pdo->quote("%{$keyword2}%"),
    ),
);

Strip spaces/tabs/newlines - python

import re

mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)

Output : IwanttoRemoveallwhitespacesnewlinesandtabs

How to set a session variable when clicking a <a> link

    session_start();
    if(isset($_SESSION['current'])){
         $_SESSION['oldlink']=$_SESSION['current'];
    }else{
         $_SESSION['oldlink']='no previous page';
    }
    $_SESSION['current']=$_SERVER['PHP_SELF'];

Maybe this is what you're looking for? It will remember the old link/page you're coming from (within your website).

Put that piece on top of each page.

If you want to make it 'refresh proof' you can add another check:

   if(isset($_SESSION['current']) && $_SESSION['current']!=$_SERVER['PHP_SELF'])

This will make the page not remember itself.

UPDATE: Almost the same as @Brandon though... Just use a php variable, I know this looks like a security risk, but when done correct it isn't.

 <a href="home.php?a=register">Register Now!</a>

PHP:

 if(isset($_GET['a']) /*you can validate the link here*/){
    $_SESSION['link']=$_GET['a'];
 }

Why even store the GET in a session? Just use it. Please tell me why you do not want to use GET. « Validate for more security. I maybe can help you with a better script.

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

In addition to all the concerns expressed about why you give a rat's ass what the ID value is (all are correct that you shouldn't), let me add this to the mix:

If you've deleted all the records from the table, compacting the database will reset the seed value back to its original value.

For a table where there are still records, and you've inserted a value into the Autonumber field that is lower than the highest value, you have to use @Remou's method to reset the seed value. This also applies if you want to reset to the Max+1 in a table where records have been deleted, e.g., 300 records, last ID of 300, delete 201-300, compact won't reset the counter (you have to use @Remou's method -- this was not the case in earlier versions of Jet, and, indeed, in early versions of Jet 4, the first Jet version that allowed manipulating the seed value programatically).

wget command to download a file and save as a different filename

Also notice the order of parameters on the command line. At least on some systems (e.g. CentOS 6):

wget -O FILE URL

works. But:

wget URL -O FILE

does not work.

What is the difference between Cygwin and MinGW?

Cygwin emulates entire POSIX environment, while MinGW is minimal tool set for compilation only (compiles native Win application.) So if you want to make your project cross-platform the choice between the two is obvious, MinGW.

Although you might consider using VS on Windows, GCC on Linux/Unices. Most open source projects do that (e.g. Firefox or Python).

Dynamic function name in javascript?

This is BEST solution, better then new Function('return function name(){}')().

Eval is fastest solution:

enter image description here

var name = 'FuncName'
var func = eval("(function " + name + "(){})")

Font is not available to the JVM with Jasper Reports

There are three method to avoid such a problem.

Method 1 : by setting ignore missing font property.

JRProperties.setProperty("net.sf.jasperreports.awt.ignore.missing.font", "true");

or you can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>

Method 2 : by setting default font property.

JRProperties.setProperty("net.sf.jasperreports.default.font.name", "Sans Serif");

or you can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.default.font.name" value="Sans Serif"/>

Method 3 : by adding missing font property.

Firstly install missing fonts in IReport by selecting " Tools >> Options >> Fonts >> Install Font " then select the all font and Export this By clicking on "Export as Extension" with .jar Extension.

You can use this jar for Jasperreports-font.X.X.X.jar which will be present in your project library or classpath.

How to concatenate text from multiple rows into a single text string in SQL server?

on top of Chris Shaffer answer

if your data may get repeated Such as

Tom
Ali
John
Ali
Tom
Mike

Instead of having Tom,Ali,John,Ali,Tom,Mike

You can use DISTINCT to avoid duplicates and get Tom,Ali,John,Mike

DECLARE @Names VARCHAR(8000) 
SELECT DISTINCT @Names = COALESCE(@Names + ',', '') + Name
FROM People
WHERE Name IS NOT NULL
SELECT @Names

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

How to read a file byte by byte in Python and how to print a bytelist as a binary?

To answer the second part of your question, to convert to binary you can use a format string and the ord function:

>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'

Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.

Cannot connect to SQL Server named instance from another SQL Server

well after spending about 10 days trying to solve this issue, i finally figured it out today and decide to post the solution

in the start menu, type RUN, open it the in the run box, type SERVICES.MSC, click okay

ensure that these two services are started SQL Server(MSSQLSERVER) SQL Server Vss writer

Question mark characters displaying within text, why is this?

I usually curse MS word and then run the following Wscript.

// replace with path to a file that needs cleaning
PATH = "test.html"

var go=WScript.CreateObject("Scripting.FileSystemObject");
var content=go.GetFile(PATH).OpenAsTextStream().ReadAll();
var out=go.CreateTextFile("clean-"+PATH, true);

// symbols
content=content.replace(/“/g,'"');
content=content.replace(/”/g,'"');
content=content.replace(/’/g,"'");
content=content.replace(/–/g,"-");
content=content.replace(/©/g,"&copy;");
content=content.replace(/®/g,"&reg;");
content=content.replace(/°/g,"&deg;");
content=content.replace(/¶/g,"<p>");
content=content.replace(/¿/g,"&iquest;");
content=content.replace(/¡/g,'&iexcl;');
content=content.replace(/¢/g,'&cent;');
content=content.replace(/£/g,'&pound;');
content=content.replace(/¥/g,'&yen;');

out.Write(content);

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I needed to use this as a cell function (like SUM or VLOOKUP) and found that it was easy to:

  1. Make sure you are in a Macro Enabled Excel File (save as xlsm).
  2. Open developer tools Alt + F11
  3. Add Microsoft VBScript Regular Expressions 5.5 as in other answers
  4. Create the following function either in workbook or in its own module:

    Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
        Dim regex As New VBScript_RegExp_55.RegExp
        Dim strInput As String
    
        strInput = myRange.Value
    
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
    
        REGPLACE = regex.Replace(strInput, outputPattern)
    
    End Function
    
  5. Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2") (ex: "A 243" to "A243")

Launch Bootstrap Modal on page load

You can activate the modal without writing any JavaScript simply via data attributes.

The option "show" set to true shows the modal when initialized:

<div class="modal fade" tabindex="-1" role="dialog" data-show="true"></div>

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

Get the correct week number of a given date

In .NET 3.0 and later you can use the ISOWeek.GetWeekOfDate-Method.

Note that the year in the year + week number format might differ from the year of the DateTime because of weeks that cross the year boundary.

How to remove all namespaces from XML with C#?

The obligatory answer using XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="no" encoding="UTF-8"/>

  <xsl:template match="/|comment()|processing-instruction()">
    <xsl:copy>
      <xsl:apply-templates/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="*">
    <xsl:element name="{local-name()}">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="@*">
    <xsl:attribute name="{local-name()}">
      <xsl:value-of select="."/>
    </xsl:attribute>
  </xsl:template>

</xsl:stylesheet>

How do you check if a certain index exists in a table?

A slight deviation from the original question however may prove useful for future people landing here wanting to DROP and CREATE an index, i.e. in a deployment script.

You can bypass the exists check simply by adding the following to your create statement:

CREATE INDEX IX_IndexName
ON dbo.TableName
WITH (DROP_EXISTING = ON);

Read more here: CREATE INDEX (Transact-SQL) - DROP_EXISTING Clause

N.B. As mentioned in the comments, the index must already exist for this clause to work without throwing an error.

Listing available com ports with Python

A possible refinement to Thomas's excellent answer is to have Linux and possibly OSX also try to open ports and return only those which could be opened. This is because Linux, at least, lists a boatload of ports as files in /dev/ which aren't connected to anything. If you're running in a terminal, /dev/tty is the terminal in which you're working and opening and closing it can goof up your command line, so the glob is designed to not do that. Code:

    # ... Windows code unchanged ...

    elif sys.platform.startswith ('linux'):
        temp_list = glob.glob ('/dev/tty[A-Za-z]*')

    result = []
    for a_port in temp_list:

        try:
            s = serial.Serial(a_port)
            s.close()
            result.append(a_port)
        except serial.SerialException:
            pass

    return result

This modification to Thomas's code has been tested on Ubuntu 14.04 only.

How to specify multiple conditions in an if statement in javascript

the whole if should be enclosed in brackets and the or operator is || an not !!, so

if ((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == '')) { ...

Mongoimport of json file

If you try to export this test collection:

> db.test.find()
{ "_id" : ObjectId("5131c2bbfcb94ddb2549d501"), "field" : "Sat Mar 02 2013 13:13:31 GMT+0400"}
{"_id" : ObjectId("5131c2d8fcb94ddb2549d502"), "field" : ISODate("2012-05-31T11:59:39Z")}

with mongoexport (the first date created with Date(...) and the second one created with new Date(...) (if use ISODate(...) will be the same as in the second line)) so mongoexport output will be looks like this:

{ "_id" : { "$oid" : "5131c2bbfcb94ddb2549d501" }, "field" : "Sat Mar 02 2013 13:13:31 GMT+0400" }
{ "_id" : { "$oid" : "5131c2d8fcb94ddb2549d502" }, "field" : { "$date" : 1338465579000 } }

So you should use the same notation, because strict JSON doesn't have type Date( <date> ).

Also your JSON is not valid: all fields name must be enclosed in double quotes, but mongoimport works fine without them.

You can find additional information in mongodb documentation and here.

Opposite of append in jquery

Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

How to detect a mobile device with JavaScript?

Simply use DeviceDetection

deviceDetection.deviceType // phone | tablet according to device

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Found other similar question, but not the answer.

It would have been interesting to know, where you have found this question.

As far as I can remember and according com.jcraft.jsch.JSchException: Auth cancel try to add to method .addIdentity() a passphrase. You can use "" in case you generated a keyfile without one. Another source of error is the fingerprint string. If it doesn't match you will get an authentication failure either (depends from on the target server).

And at last here my working source code - after I could solve the ugly administration tasks:

public void connect(String host, int port, 
                    String user, String pwd,
                    String privateKey, String fingerPrint,
                    String passPhrase
                  ) throws JSchException{
    JSch jsch = new JSch();

    String absoluteFilePathPrivatekey = "./";
    File tmpFileObject = new File(privateKey);
    if (tmpFileObject.exists() && tmpFileObject.isFile())
    {
      absoluteFilePathPrivatekey = tmpFileObject.getAbsolutePath();
    }

    jsch.addIdentity(absoluteFilePathPrivatekey, passPhrase);
    session = jsch.getSession(user, host, port);

    //Password and fingerprint will be given via UserInfo interface.
    UserInfo ui = new UserInfoImpl(pwd, fingerPrint);
    session.setUserInfo(ui);

    session.connect();

    Channel channel = session.openChannel("sftp");
    channel.connect();
    c = (ChannelSftp) channel;
}

'negative' pattern matching in python

Use a negative match. (Also note that whitespace is significant, by default, inside a regex so don't space things out. Alternatively, use re.VERBOSE.)

for item in output:
    matchObj = re.search("^(OK|\\.)", item)
    if not matchObj:
        print "got item " + item

How to get Android crash logs?

I have created this library to solve all your problems. Crash Reporter is a handy tool to capture all your crashes and log them in device locally

Just add this dependency and you're good to go.

compile 'com.balsikandar.android:crashreporter:1.0.1'

Find all your crashes in device locally and fix them at your convenience. Crashes are saved using date and time format easy to track. Plus it also provides API for capture Logged Exceptions using below method.

CrashRepoter.logException(Exception e)

How can I test a PDF document if it is PDF/A compliant?

pdf validation with OPEN validator:

DROID (Digital Record Object Identification) http://sourceforge.net/projects/droid/

JHOVE - JSTOR/Harvard Object Validation Environment http://hul.harvard.edu/jhove/

Change div height on button click

Just remove the "px" in the style.height assignation, like:

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200px"> </button>

Should be

<button type="button" onClick = "document.getElementById('chartdiv').style.height = 200">Click Me!</button>

Swift Bridging Header import issue

"we need to tell Xcode where to look for the header files we’re listing in our bridging header. Find the Search Paths section, and change the project-level setting for User Header Search Paths, adding a recursive entry for the ‘Pods’ directory: Pods/** " http://swiftalicio.us/2014/11/using-cocoapods-from-swift/

How to delete all files and folders in a directory?

IO.Directory.Delete(HttpContext.Current.Server.MapPath(path), True)

You don't need more than that

How do I get the current date in JavaScript?

Try

`${Date()}`.slice(4,15)

_x000D_
_x000D_
console.log( `${Date()}`.slice(4,15) )
_x000D_
_x000D_
_x000D_

We use here standard JS functionalities: template literals, Date object which is cast to string, and slice. This is probably shortest solution which meet OP requirements (no time, only date)

Convert JSONObject to Map

This is what worked for me:

    public static Map<String, Object> toMap(JSONObject jsonobj)  throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();
        Iterator<String> keys = jsonobj.keys();
        while(keys.hasNext()) {
            String key = keys.next();
            Object value = jsonobj.get(key);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            } else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }   
            map.put(key, value);
        }   return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if (value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }
            else if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }   return list;
}

Most of this is from this question: How to convert JSONObject to new Map for all its keys using iterator java

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

Focusable EditText inside ListView

Sorry, answered my own question. It may not be the most correct or most elegant solution, but it works for me, and gives a pretty solid user experience. I looked into the code for ListView to see why the two behaviors are so different, and came across this from ListView.java:

    public void setItemsCanFocus(boolean itemsCanFocus) {
        mItemsCanFocus = itemsCanFocus;
        if (!itemsCanFocus) {
            setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
        }
    }

So, when calling setItemsCanFocus(false), it's also setting descendant focusability such that no child can get focus. This explains why I couldn't just toggle mItemsCanFocus in the ListView's OnItemSelectedListener -- because the ListView was then blocking focus to all children.

What I have now:

<ListView
    android:id="@android:id/list" 
    android:layout_height="match_parent" 
    android:layout_width="match_parent"
    android:descendantFocusability="beforeDescendants"
    />

I use beforeDescendants because the selector will only be drawn when the ListView itself (not a child) has focus, so the default behavior needs to be that the ListView takes focus first and draws selectors.

Then in the OnItemSelectedListener, since I know which header view I want to override the selector (would take more work to dynamically determine if any given position contains a focusable view), I can change descendant focusability, and set focus on the EditText. And when I navigate out of that header, change it back it again.

public void onItemSelected(AdapterView<?> listView, View view, int position, long id)
{
    if (position == 1)
    {
        // listView.setItemsCanFocus(true);

        // Use afterDescendants, because I don't want the ListView to steal focus
        listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
        myEditText.requestFocus();
    }
    else
    {
        if (!listView.isFocused())
        {
            // listView.setItemsCanFocus(false);

            // Use beforeDescendants so that the EditText doesn't re-take focus
            listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
            listView.requestFocus();
        }
    }
}

public void onNothingSelected(AdapterView<?> listView)
{
    // This happens when you start scrolling, so we need to prevent it from staying
    // in the afterDescendants mode if the EditText was focused 
    listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}

Note the commented-out setItemsCanFocus calls. With those calls, I got the correct behavior, but setItemsCanFocus(false) caused focus to jump from the EditText, to another widget outside of the ListView, back to the ListView and displayed the selector on the next selected item, and that jumping focus was distracting. Removing the ItemsCanFocus change, and just toggling descendant focusability got me the desired behavior. All items draw the selector as normal, but when getting to the row with the EditText, it focused on the text field instead. Then when continuing out of that EditText, it started drawing the selector again.

sh: react-scripts: command not found after running npm start

If you are having this issue in a Docker container just make sure that node_modules are not added in the .dockerignore file.

I had the same issue sh1 : react scripts not found. For me this was the solution

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

In order to use two-way data binding for form inputs you need to import the FormsModule package in your Angular module.

import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
         FormsModule      
    ]

EDIT

Since there are lot of duplicate questions with the same problem, I am enhancing this answer.

There are two possible reasons

  • Missing FormsModule, hence Add this to your Module,

    import { FormsModule } from '@angular/forms';
    
    @NgModule({
        imports: [
            FormsModule      
        ]
    
  • Check the syntax/spelling of [(ngModel)] in the input tag

Hashcode and Equals for Hashset

Because in 2nd case you adding same reference twice and HashSet have check against this in HashMap.put() on which HashSet is based:

        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }

As you can see, equals will be called only if hash of key being added equals to the key already present in set and references of these two are different.

Convert php array to Javascript

Below is a pretty simple trick to convert PHP array to JavaScript array:

$array = array("one","two","three");

JS below:

// Use PHP tags for json_encode()

var js_json =  json_encode($array);
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string);

alert(js_json_array.length);

It works like a charm.

What does axis in pandas mean?

I have been trying to figure out the axis for the last hour as well. The language in all the above answers, and also the documentation is not at all helpful.

To answer the question as I understand it now, in Pandas, axis = 1 or 0 means which axis headers do you want to keep constant when applying the function.

Note: When I say headers, I mean index names

Expanding your example:

+------------+---------+--------+
|            |  A      |  B     |
+------------+---------+---------
|      X     | 0.626386| 1.52325|
+------------+---------+--------+
|      Y     | 0.626386| 1.52325|
+------------+---------+--------+

For axis=1=columns : We keep columns headers constant and apply the mean function by changing data. To demonstrate, we keep the columns headers constant as:

+------------+---------+--------+
|            |  A      |  B     |

Now we populate one set of A and B values and then find the mean

|            | 0.626386| 1.52325|  

Then we populate next set of A and B values and find the mean

|            | 0.626386| 1.52325|

Similarly, for axis=rows, we keep row headers constant, and keep changing the data: To demonstrate, first fix the row headers:

+------------+
|      X     |
+------------+
|      Y     |
+------------+

Now populate first set of X and Y values and then find the mean

+------------+---------+
|      X     | 0.626386
+------------+---------+
|      Y     | 0.626386
+------------+---------+

Then populate the next set of X and Y values and then find the mean:

+------------+---------+
|      X     | 1.52325 |
+------------+---------+
|      Y     | 1.52325 |
+------------+---------+

In summary,

When axis=columns, you fix the column headers and change data, which will come from the different rows.

When axis=rows, you fix the row headers and change data, which will come from the different columns.

Is it possible to get the current spark context settings in PySpark?

Not sure if you can get all the default settings easily, but specifically for the worker dir, it's quite straigt-forward:

from pyspark import SparkFiles
print SparkFiles.getRootDirectory()

File name without extension name VBA

This gets the file type as from the last character (so avoids the problem with dots in file names)

Function getFileType(fn As String) As String

''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String

strIndex = Len(fn)
For x = 1 To Len(fn)

    myChar = Mid(fn, strIndex, 1)

    If myChar = "." Then
        Exit For
    End If

    strIndex = strIndex - 1

Next x

getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))

End Function

jQuery Determine if a matched class has a given id

Let's say that you're iterating through some DOM objects and you wanna find and catch an element with a certain ID

<div id="myDiv">
    <div id="fo"><div>
    <div id="bar"><div>
</div>

You can either write something like to find

$('#myDiv').find('#bar')

Note that if you were to use a class selector, the find method will return all the matching elements.

or you could write an iterating function that will do more advanced work

<div id="myDiv">
    <div id="fo"><div>
    <div id="bar"><div>
    <div id="fo1"><div>
    <div id="bar1"><div>
    <div id="fo2"><div>
    <div id="bar2"><div>
</div>

$('#myDiv div').each(function() {
   if($(this).attr('id') == 'bar1')
       //do something with bar1
});

Same code could be easily modified for class selector.

<div id="myDiv">
    <div class="fo"><div>
    <div class="bar"><div>
    <div class="fo"><div>
    <div class="bar"><div>
    <div class="fo"><div>
    <div class="bar"><div>
</div>

$('#myDiv div').each(function() {
   if($(this).hasClass('bar'))
       //do something with bar
});

I'm glad you solved your problem with index(), what ever works for you.I hope this will help others with the same problem. Cheers :)

Facebook Oauth Logout

it's simple just type : $facebook->setSession(null); for logout

How do I change data-type of pandas data frame to string with a defined format?

I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:

s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])

How to prevent the "Confirm Form Resubmission" dialog?

It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.

How to "flatten" a multi-dimensional array to simple one in PHP?

any of this didnt work for me ... so had to run it myself. works just fine:

function arrayFlat($arr){
$out = '';
    foreach($arr as $key => $value){

        if(!is_array($value)){
            $out .= $value.',';
        }else{
            $out .= $key.',';
            $out .= arrayFlat($value);
        }

    }
    return trim($out,',');
}


$result = explode(',',arrayFlat($yourArray));
echo '<pre>';
print_r($result);
echo '</pre>';

Should I use Java's String.format() if performance is important?

Here is modified version of hhafez entry. It includes a string builder option.

public class BLA
{
public static final String BLAH = "Blah ";
public static final String BLAH2 = " Blah";
public static final String BLAH3 = "Blah %d Blah";


public static void main(String[] args) {
    int i = 0;
    long prev_time = System.currentTimeMillis();
    long time;
    int numLoops = 1000000;

    for( i = 0; i< numLoops; i++){
        String s = BLAH + i + BLAH2;
    }
    time = System.currentTimeMillis() - prev_time;

    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<numLoops; i++){
        String s = String.format(BLAH3, i);
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<numLoops; i++){
        StringBuilder sb = new StringBuilder();
        sb.append(BLAH);
        sb.append(i);
        sb.append(BLAH2);
        String s = sb.toString();
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

}

}

Time after for loop 391 Time after for loop 4163 Time after for loop 227

Angular 2.0 and Modal Dialog

Here is my full implementation of modal bootstrap angular2 component:

I assume that in your main index.html file (with <html> and <body> tags) at the bottom of <body> tag you have:

  <script src="assets/js/jquery-2.1.1.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>

modal.component.ts:

import { Component, Input, Output, ElementRef, EventEmitter, AfterViewInit } from '@angular/core';

declare var $: any;// this is very importnant (to work this line: this.modalEl.modal('show')) - don't do this (becouse this owerride jQuery which was changed by bootstrap, included in main html-body template): let $ = require('../../../../../node_modules/jquery/dist/jquery.min.js');

@Component({
  selector: 'modal',
  templateUrl: './modal.html',
})
export class Modal implements AfterViewInit {

    @Input() title:string;
    @Input() showClose:boolean = true;
    @Output() onClose: EventEmitter<any> = new EventEmitter();

    modalEl = null;
    id: string = uniqueId('modal_');

    constructor(private _rootNode: ElementRef) {}

    open() {
        this.modalEl.modal('show');
    }

    close() {
        this.modalEl.modal('hide');
    }

    closeInternal() { // close modal when click on times button in up-right corner
        this.onClose.next(null); // emit event
        this.close();
    }

    ngAfterViewInit() {
        this.modalEl = $(this._rootNode.nativeElement).find('div.modal');
    }

    has(selector) {
        return $(this._rootNode.nativeElement).find(selector).length;
    }
}

let modal_id: number = 0;
export function uniqueId(prefix: string): string {
    return prefix + ++modal_id;
}

modal.html:

<div class="modal inmodal fade" id="{{modal_id}}" tabindex="-1" role="dialog"  aria-hidden="true" #thisModal>
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header" [ngClass]="{'hide': !(has('mhead') || title) }">
                <button *ngIf="showClose" type="button" class="close" (click)="closeInternal()"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <ng-content select="mhead"></ng-content>
                <h4 *ngIf='title' class="modal-title">{{ title }}</h4>
            </div>
            <div class="modal-body">
                <ng-content></ng-content>
            </div>

            <div class="modal-footer" [ngClass]="{'hide': !has('mfoot') }" >
                <ng-content select="mfoot"></ng-content>
            </div>
        </div>
    </div>
</div>

And example of usage in client Editor component: client-edit-component.ts:

import { Component } from '@angular/core';
import { ClientService } from './client.service';
import { Modal } from '../common';

@Component({
  selector: 'client-edit',
  directives: [ Modal ],
  templateUrl: './client-edit.html',
  providers: [ ClientService ]
})
export class ClientEdit {

    _modal = null;

    constructor(private _ClientService: ClientService) {}

    bindModal(modal) {this._modal=modal;}

    open(client) {
        this._modal.open();
        console.log({client});
    }

    close() {
        this._modal.close();
    }

}

client-edit.html:

<modal [title]='"Some standard title"' [showClose]='true' (onClose)="close()" #editModal>{{ bindModal(editModal) }}
    <mhead>Som non-standart title</mhead>
    Some contents
    <mfoot><button calss='btn' (click)="close()">Close</button></mfoot>
</modal>

Ofcourse title, showClose, <mhead> and <mfoot> ar optional parameters/tags.

String or binary data would be truncated. The statement has been terminated

In my case, I was getting this error because my table had

varchar(50)

but I was injecting 67 character long string, which resulted in thi error. Changing it to

varchar(255)

fixed the problem.

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

How do you create a remote Git branch?

Heres an example I only have two branches that were local first: origin and mobile-test.

Nothing for me worked until I used this in command line to actually show my updated files in a remote branch.

git push --set-upstream origin mobile-test

How do I print a double value without scientific notation using Java?

I think everyone had the right idea, but all answers were not straightforward. I can see this being a very useful piece of code. Here is a snippet of what will work:

System.out.println(String.format("%.8f", EnterYourDoubleVariableHere));

the ".8" is where you set the number of decimal places you would like to show.

I am using Eclipse and it worked no problem.

Hope this was helpful. I would appreciate any feedback!

How to view hierarchical package structure in Eclipse package explorer

Package Explorer / View Menu / Package Presentation... / Hierarchical

The "View Menu" can be opened with Ctrl + F10, or the small arrow-down icon in the top-right corner of the Package Explorer.

Linq Select Group By

This will give you sequence of anonymous objects, containing date string and two properties with average price:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new { 
               LogDate = g.Key,
               AvgGoldPrice = (int)g.Average(x => x.GoldPrice), 
               AvgSilverPrice = (int)g.Average(x => x.SilverPrice)
            };

If you need to get list of PriceLog objects:

var query = from p in PriceLogList
            group p by p.LogDateTime.ToString("MMM yyyy") into g
            select new PriceLog { 
               LogDateTime = DateTime.Parse(g.Key),
               GoldPrice = (int)g.Average(x => x.GoldPrice), 
               SilverPrice = (int)g.Average(x => x.SilverPrice)
            };

How to Auto-start an Android Application?

Edit your AndroidManifest.xml to add RECEIVE_BOOT_COMPLETED permission

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

Edit your AndroidManifest.xml application-part for below Permission

<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</receiver>

Now write below in Activity.

public class BootUpReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent i = new Intent(context, MyActivity.class);  
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);  
    }
}

stopPropagation vs. stopImmediatePropagation

A small example to demonstrate how both these propagation stoppages work.

_x000D_
_x000D_
var state = {_x000D_
  stopPropagation: false,_x000D_
  stopImmediatePropagation: false_x000D_
};_x000D_
_x000D_
function handlePropagation(event) {_x000D_
  if (state.stopPropagation) {_x000D_
    event.stopPropagation();_x000D_
  }_x000D_
_x000D_
  if (state.stopImmediatePropagation) {_x000D_
    event.stopImmediatePropagation();_x000D_
  }_x000D_
}_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("First event handler on #child");_x000D_
});_x000D_
_x000D_
_x000D_
$("#child").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Second event handler on #child");_x000D_
});_x000D_
_x000D_
// First this event will fire on the child element, then propogate up and_x000D_
// fire for the parent element._x000D_
$("div").click(function(e) {_x000D_
  handlePropagation(e);_x000D_
  console.log("Event handler on div: #" + this.id);_x000D_
});_x000D_
_x000D_
_x000D_
// Enable/disable propogation_x000D_
$("button").click(function() {_x000D_
  var objectId = this.id;_x000D_
  $(this).toggleClass('active');_x000D_
  state[objectId] = $(this).hasClass('active');_x000D_
  console.log('---------------------');_x000D_
});
_x000D_
div {_x000D_
  padding: 1em;_x000D_
}_x000D_
_x000D_
#parent {_x000D_
  background-color: #CCC;_x000D_
}_x000D_
_x000D_
#child {_x000D_
  background-color: #000;_x000D_
  padding: 5em;_x000D_
}_x000D_
_x000D_
button {_x000D_
  padding: 1em;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
.active {_x000D_
  background-color: green;_x000D_
  color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="parent">_x000D_
  <div id="child">&nbsp;</div>_x000D_
</div>_x000D_
_x000D_
<button id="stopPropagation">Stop Propogation</button>_x000D_
<button id="stopImmediatePropagation" ">Stop Immediate Propogation</button>
_x000D_
_x000D_
_x000D_

There are three event handlers bound. If we don’t stop any propagation, then there should be four alerts - three on the child div, and one on the parent div.

If we stop the event from propagating, then there will be 3 alerts (all on the inner child div). Since the event won’t propagate up the DOM hierarchy, the parent div won’t see it, and its handler won’t fire.

If we stop propagation immediately, then there will only be 1 alert. Even though there are three event handlers attached to the inner child div, only 1 is executed and any further propagation is killed immediately, even within the same element.

Replace substring with another substring C++

I think all solutions will fail if the length of the replacing string is different from the length of the string to be replaced. (search for "abc" and replace by "xxxxxx") A general approach might be:

void replaceAll( string &s, const string &search, const string &replace ) {
    for( size_t pos = 0; ; pos += replace.length() ) {
        // Locate the substring to replace
        pos = s.find( search, pos );
        if( pos == string::npos ) break;
        // Replace by erasing and inserting
        s.erase( pos, search.length() );
        s.insert( pos, replace );
    }
}

Convert json to a C# array?

Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects.

See their examples:

string myJsonString = @"{
  "Name": "Apple",
  "Expiry": "\/Date(1230375600000+1300)\/",
  "Price": 3.99,
  "Sizes": [
    "Small",
    "Medium",
    "Large"
  ]
}";

// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);

Is there a way to represent a directory tree in a Github README.md?

For those who want a quick solution:

There is a way to get a output to the console similar to the output from tree, by typing the following command into your terminal:

ls -R YOURFOLDER | grep ':$' | sed -e 's/:$//' -e 's/[^\/]*\//|  /g' -e 's/|  \([^|]\)/|–– \1/g' 

This alternative is mentioned in this documentation: https://wiki.ubuntuusers.de/tree/

Then the output can be copied and encapsuled inside a .md file with code block back tics, like mentioned in Jonathas B.C.'s answer.

But be aware that it also outputs all node modules folders in a node project. And in tree you can do something like

tree -I node_modules

to exlude the node modules folder.

How do I check whether an array contains a string in TypeScript?

TS has many utility methods for arrays which are available via the prototype of Arrays. There are multiple which can achieve this goal but the two most convenient for this purpose are:

  1. Array.indexOf() Takes any value as an argument and then returns the first index at which a given element can be found in the array, or -1 if it is not present.
  2. Array.includes() Takes any value as an argument and then determines whether an array includes a this value. The method returning true if the value is found, otherwise false.

Example:

const channelArray: string[] = ['one', 'two', 'three'];

console.log(channelArray.indexOf('three'));      // 2
console.log(channelArray.indexOf('three') > -1); // true
console.log(channelArray.indexOf('four') > -1);  // false
console.log(channelArray.includes('three'));     // true

How to limit the maximum files chosen when using multiple file input

You could run some jQuery client-side validation to check:

$(function(){
    $("input[type='submit']").click(function(){
        var $fileUpload = $("input[type='file']");
        if (parseInt($fileUpload.get(0).files.length)>2){
         alert("You can only upload a maximum of 2 files");
        }
    });    
});?

http://jsfiddle.net/Curt/u4NuH/

But remember to check on the server side too as client-side validation can be bypassed quite easily.

Does Python SciPy need BLAS?

For Windows users there is a nice binary package by Chris (warning: it's a pretty large download, 191 MB):

How to simulate browsing from various locations?

The only thing that springs to mind for this is to use a proxy server based in Europe. Either have your colleague set one up [if possible] or find a free proxy. A quick Google search came up with http://www.anonymousinet.com/ as the top result.

How to update the value of a key in a dictionary in Python?

You are modifying the list book_shop.values()[i], which is not getting updated in the dictionary. Whenever you call the values() method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.

MINGW64 "make build" error: "bash: make: command not found"

You have to install mingw-get and after that you can run mingw-get install msys-make to have the command make available.

Here is a link for what you want http://www.mingw.org/wiki/getting_started

Merge 2 DataTables and store in a new one

DataTable dtAll = new DataTable();
DataTable dt= new DataTable();
foreach (int id in lst)
{
    dt.Merge(GetDataTableByID(id)); // Get Data Methode return DataTable
}
dtAll = dt;

Increasing (or decreasing) the memory available to R processes

To increase the amount of memory allocated to R you can use memory.limit

memory.limit(size = ...)

Or

memory.size(max = ...)

About the arguments

  • size - numeric. If NA report the memory limit, otherwise request a new limit, in Mb. Only values of up to 4095 are allowed on 32-bit R builds, but see ‘Details’.
  • max - logical. If TRUE the maximum amount of memory obtained from the OS is reported, if FALSE the amount currently in use, if NA the memory limit.

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

<script>
var deg = 0

function rotate(id)
{
    deg = deg+45;
    var txt = 'rotate('+deg+'deg)';
    $('#'+id).css('-webkit-transform',txt);
}
</script>

What I do is something very easy... declare a global variable at the start... and then increment the variable however much I like, and use .css of jquery to increment.

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

import matplotlib.pyplot as plt
import datetime
import numpy as np

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

Angularjs simple file download causes router to redirect

If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.

I hope it, will be helpfull.

HTML :

<a href="#" class="btn btn-default" file-name="'fileName.extension'"  ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>

DIRECTIVE :

directive('fileDownload',function(){
    return{
        restrict:'A',
        scope:{
            fileDownload:'=',
            fileName:'=',
        },

        link:function(scope,elem,atrs){


            scope.$watch('fileDownload',function(newValue, oldValue){

                if(newValue!=undefined && newValue!=null){
                    console.debug('Downloading a new file'); 
                    var isFirefox = typeof InstallTrigger !== 'undefined';
                    var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
                    var isIE = /*@cc_on!@*/false || !!document.documentMode;
                    var isEdge = !isIE && !!window.StyleMedia;
                    var isChrome = !!window.chrome && !!window.chrome.webstore;
                    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
                    var isBlink = (isChrome || isOpera) && !!window.CSS;

                    if(isFirefox || isIE || isChrome){
                        if(isChrome){
                            console.log('Manage Google Chrome download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var downloadLink = angular.element('<a></a>');//create a new  <a> tag element
                            downloadLink.attr('href',fileURL);
                            downloadLink.attr('download',scope.fileName);
                            downloadLink.attr('target','_self');
                            downloadLink[0].click();//call click function
                            url.revokeObjectURL(fileURL);//revoke the object from URL
                        }
                        if(isIE){
                            console.log('Manage IE download>10');
                            window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName); 
                        }
                        if(isFirefox){
                            console.log('Manage Mozilla Firefox download');
                            var url = window.URL || window.webkitURL;
                            var fileURL = url.createObjectURL(scope.fileDownload);
                            var a=elem[0];//recover the <a> tag from directive
                            a.href=fileURL;
                            a.download=scope.fileName;
                            a.target='_self';
                            a.click();//we call click function
                        }


                    }else{
                        alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
                    }
                }
            });

        }
    }
})

IN CONTROLLER:

$scope.myBlobObject=undefined;
$scope.getFile=function(){
        console.log('download started, you can show a wating animation');
        serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
        .then(function(data){//is important that the data was returned as Aray Buffer
                console.log('Stream download complete, stop animation!');
                $scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
        },function(fail){
                console.log('Download Error, stop animation and show error message');
                                    $scope.myBlobObject=[];
                                });
                            }; 

IN SERVICE:

function getStream(params){
                 console.log("RUNNING");
                 var deferred = $q.defer();

                 $http({
                     url:'../downloadURL/',
                     method:"PUT",//you can use also GET or POST
                     data:params,
                     headers:{'Content-type': 'application/json'},
                     responseType : 'arraybuffer',//THIS IS IMPORTANT
                    })
                    .success(function (data) {
                        console.debug("SUCCESS");
                        deferred.resolve(data);
                    }).error(function (data) {
                         console.error("ERROR");
                         deferred.reject(data);
                    });

                 return deferred.promise;
                };

BACKEND(on SPRING):

@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
        @RequestBody Map<String,String> spParams
        ) throws IOException {
        OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

How do I iterate through the files in a directory in Java?

You can use File#isDirectory() to test if the given file (path) is a directory. If this is true, then you just call the same method again with its File#listFiles() outcome. This is called recursion.

Here's a basic kickoff example:

package com.stackoverflow.q3154488;

import java.io.File;

public class Demo {

    public static void main(String... args) {
        File dir = new File("/path/to/dir");
        showFiles(dir.listFiles());
    }

    public static void showFiles(File[] files) {
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("Directory: " + file.getAbsolutePath());
                showFiles(file.listFiles()); // Calls same method again.
            } else {
                System.out.println("File: " + file.getAbsolutePath());
            }
        }
    }
}

Note that this is sensitive to StackOverflowError when the tree is deeper than the JVM's stack can hold. If you're already on Java 8 or newer, then you'd better use Files#walk() instead which utilizes tail recursion:

package com.stackoverflow.q3154488;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class DemoWithJava8 {

    public static void main(String... args) throws Exception {
        Path dir = Paths.get("/path/to/dir");
        Files.walk(dir).forEach(path -> showFile(path.toFile()));
    }

    public static void showFile(File file) {
        if (file.isDirectory()) {
            System.out.println("Directory: " + file.getAbsolutePath());
        } else {
            System.out.println("File: " + file.getAbsolutePath());
        }
    }
}

do-while loop in R

Noticing that user 42-'s perfect approach {
* "do while" = "repeat until not"
* The code equivalence:

do while (condition) # in other language
..statements..
endo

repeat{ # in R
  ..statements..
  if(! condition){ break } # Negation is crucial here!
}

} did not receive enough attention from the others, I'll emphasize and bring forward his approach via a concrete example. If one does not negate the condition in do-while (via ! or by taking negation), then distorted situations (1. value persistence 2. infinite loop) exist depending on the course of the code.

In Gauss:

proc(0)=printvalues(y);
DO WHILE y < 5;    
y+1;
 y=y+1;
ENDO;
ENDP;
printvalues(0); @ run selected code via F4 to get the following @
       1.0000000 
       2.0000000 
       3.0000000 
       4.0000000 
       5.0000000 

In R:

printvalues <- function(y) {
repeat {
 y=y+1;
print(y)
if (! (y < 5) ) {break}   # Negation is crucial here!
}
}
printvalues(0)
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5

I still insist that without the negation of the condition in do-while, Salcedo's answer is wrong. One can check this via removing negation symbol in the above code.

jQuery - setting the selected value of a select control via its text description

To avoid all jQuery version complications, I honestly recommend using one of these really simple javascript functions...

function setSelectByValue(eID,val)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].value==val) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

function setSelectByText(eID,text)
{ //Loop through sequentially//
  var ele=document.getElementById(eID);
  for(var ii=0; ii<ele.length; ii++)
    if(ele.options[ii].text==text) { //Found!
      ele.options[ii].selected=true;
      return true;
    }
  return false;
}

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:

    public string insertSpacesAtEnd(string input, int longest)
    {
        string output = input;
        string spaces = "";
        int inputLength = input.Length;
        int numToInsert = longest - inputLength;

        for (int i = 0; i < numToInsert; i++)
        {
            spaces += " ";
        }

        output += spaces;

        return output;
    }

    public int findLongest(List<Results> theList)
    {
        int longest = 0;

        for (int i = 0; i < theList.Count; i++)
        {
            if (longest < theList[i].title.Length)
                longest = theList[i].title.Length;
        }
        return longest;
    }

    ////Usage////
    for (int i = 0; i < storageList.Count; i++)
    {
        output += insertSpacesAtEnd(storageList[i].title, longest + 5) +   storageList[i].rank.Trim() + "     " + storageList[i].term.Trim() + "         " + storageList[i].name + "\r\n";
    }

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

How to SHUTDOWN Tomcat in Ubuntu?

Try

/etc/init.d/tomcat stop

(maybe you have to write something after tomcat, just press tab one time)

Edit: And you also need to do it as root.

ReCaptcha API v2 Styling

You can also choose between a dark or light ReCaptcha theme. I used this in one of my Angular 8 Apps

JS. How to replace html element with another element/text, represented in string?

Using jQuery you can do this:

var str = '<td>1</td><td>2</td>';
$('#__TABLE__').replaceWith(str);

http://jsfiddle.net/hZBeW/4/

Or in pure javascript:

var str = '<td>1</td><td>2</td>';
var tdElement = document.getElementById('__TABLE__');
var trElement = tdElement.parentNode;
trElement.removeChild(tdElement);
trElement.innerHTML = str + trElement.innerHTML;

http://jsfiddle.net/hZBeW/1/

How do I check if an HTML element is empty using jQuery?

document.getElementById("id").innerHTML == "" || null

or

$("element").html() == "" || null

Shall we always use [unowned self] inside closure in Swift

If self could be nil in the closure use [weak self].

If self will never be nil in the closure use [unowned self].

The Apple Swift documentation has a great section with images explaining the difference between using strong, weak, and unowned in closures:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Debugging Spring configuration

Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this

<category name="org.springframework.beans">
    <priority value="debug" />
</category>

or

<category name="org.springframework">
    <priority value="debug" />
</category>

I would advise you to test this problem in isolation using JUnit test, You can do this by using spring testing module in conjunction with Junit. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:springContext.xml"})
@Transactional
public class SpringDAOTest 
{
    @Autowired
    private SpringDAO dao;

    @Autowired
    private ApplicationContext appContext;

    @Test
    public void checkConfig()
    {
        AnySpringBean bean =  appContext.getBean(AnySpringBean.class);
        Assert.assertNotNull(bean);
    }
}

UPDATE

I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file

<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>/WEB-INF/log4j.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

UPDATE log4j config file


I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use debug not info as @Rayan Stewart mentioned.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" />
        </layout>
    </appender>

    <appender name="springAppender" class="org.apache.log4j.RollingFileAppender"> 
        <param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /> 
        <param name="append" value="true" /> 
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern"
                value="%d{MM/dd/yyyy HH:mm:ss}  [%t]:%c{5}.%M()%L %m%n" />
        </layout>
    </appender>

    <category name="org.springframework">
        <priority value="debug" />
    </category>

    <category name="org.springframework.beans">
        <priority value="debug" />
    </category>

    <category name="org.springframework.security">
        <priority value="debug" />
    </category>

    <category
        name="org.springframework.beans.CachedIntrospectionResults">
        <priority value="debug" />
    </category>

    <category name="org.springframework.jdbc.core">
        <priority value="debug" />
    </category>

    <category name="org.springframework.transaction.support.TransactionSynchronizationManager">
        <priority value="debug" />
    </category>

    <root>
        <priority value="debug" />
        <appender-ref ref="springAppender" />
        <!-- <appender-ref ref="STDOUT"/>  -->
    </root>
</log4j:configuration>

Creating an abstract class in Objective-C

Cocoa doesn’t provide anything called abstract. We can create a class abstract which gets checked only at runtime, and at compile time this is not checked.

How to uninstall Golang?

On a Mac-OS Catalina

  1. need to add sudo before rm -rf /usr/local/go sudo rm -rf /usr/local/go otherwise, we will run into permission denial.

  2. sudo vim ~/.profile or sudo ~/.bash_profile remove export PATH=$PATH:$GOPATH/BIN or anything related to go lang

  3. If you use Zsh shell, then you need to remove the above line to ~/.zshrc file.

Hope it helps you :)

Where are Docker images stored on the host machine?

The contents of the /var/lib/docker directory vary depending on the driver Docker is using for storage.

By default this will be aufs but can fall back to overlay, overlay2, btrfs, devicemapper or zfs depending on your kernel support. In most places this will be aufs but the RedHats went with devicemapper.

You can manually set the storage driver with the -s or --storage-driver= option to the Docker daemon.

  • /var/lib/docker/{driver-name} will contain the driver specific storage for contents of the images.
  • /var/lib/docker/graph/<id> now only contains metadata about the image, in the json and layersize files.

In the case of aufs:

  • /var/lib/docker/aufs/diff/<id> has the file contents of the images.
  • /var/lib/docker/repositories-aufs is a JSON file containing local image information. This can be viewed with the command docker images.

In the case of devicemapper:

  • /var/lib/docker/devicemapper/devicemapper/data stores the images
  • /var/lib/docker/devicemapper/devicemapper/metadata the metadata
  • Note these files are thin provisioned "sparse" files so aren't as big as they seem.

Why does .NET foreach loop throw NullRefException when collection is null?

It is the fault of Do.Something(). The best practice here would be to return an array of size 0 (that is possible) instead of a null.

Pandas - 'Series' object has no attribute 'colNames' when using apply()

When you use df.apply(), each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label].

So this should work:

df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1)) 

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For Centos I was missing php-mysql library:

yum install php-mysql

service httpd restart

There is no need to enable any extension in php.ini, it is loaded by default.

Laravel 5: Retrieve JSON array from $request

You need to change your Ajax call to

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    contentType: "json",
    processData: false,
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

change the dataType to contentType and add the processData option.

To retrieve the JSON payload from your controller, use:

dd(json_decode($request->getContent(), true));

instead of

dd($request->all());

My httpd.conf is empty

OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:

/etc/apache2/sites-available/default

which on my system is linked to from /etc/apache2/sites-enabled/

if you want to have different sites with different options, copy the file and then change those...

How can I get query string values in JavaScript?

function GET() {
        var data = [];
        for(x = 0; x < arguments.length; ++x)
            data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
                return data;
    }


example:
data = GET("id","name","foo");
query string : ?id=3&name=jet&foo=b
returns:
    data[0] // 3
    data[1] // jet
    data[2] // b
or
    alert(GET("id")[0]) // return 3

Strip out HTML and Special Characters

All the other solutions are creepy because they are from someone that arrogantly simply thinks that English is the only language in the world :)

All those solutions strip also diacritics like ç or à.

The perfect solution, as stated in PHP documentation, is simply:

$clear = strip_tags($des);

How do I ignore a directory with SVN?

Important to mention:

On the commandline you can't use

svn add *

This will also add the ignored files, because the command line expands * and therefore svn add believes that you want all files to be added. Therefore use this instead:

svn add --force .

Formatting text in a TextBlock

Check out this example from Charles Petzolds Bool Application = Code + markup

//----------------------------------------------
// FormatTheText.cs (c) 2006 by Charles Petzold
//----------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Petzold.FormatTheText
{
    class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }
        public FormatTheText()
        {
            Title = "Format the Text";

            TextBlock txt = new TextBlock();
            txt.FontSize = 32; // 24 points
            txt.Inlines.Add("This is some ");
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and let's cap it off with some ");
            txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;

            Content = txt;
        }
    }
}

How to debug Lock wait timeout exceeded on MySQL?

The big problem with this exception is that its usually not reproducible in a test environment and we are not around to run innodb engine status when it happens on prod. So in one of the projects I put the below code into a catch block for this exception. That helped me catch the engine status when the exception happened. That helped a lot.

Statement st = con.createStatement();
ResultSet rs =  st.executeQuery("SHOW ENGINE INNODB STATUS");
while(rs.next()){
    log.info(rs.getString(1));
    log.info(rs.getString(2));
    log.info(rs.getString(3));
}

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

make an html svg object also a clickable link

This is very late, but I was wondering why energee's solution works: specifically, how the <object> element affects its parent elements.

tl;dr You cannot click on an anchor that has an <object> element in it because the click events are being captured by whatever is inside of the <object> element, which then doesn't bubble it back out.

jsfiddle


To expand on the symptom described in the original question: not only will an <object> element inside an anchor element cause the anchor to become unclickable, it seems that an <object> element as a child of any element will cause click, mousedown, and mouseup events (possibly touch events too) to not fire on the parent element, (when you are clicking inside the <object>'s bounding rect.)

<span>
    <object type="image/svg+xml" data="https://icons.getbootstrap.com/icons/three-dots.svg">
    </object>
</span>
document
    .querySelector('span')
    .addEventListener('click', console.log) // will not fire

Now, <object> elements behave somewhat "like" <iframe>s, in the sense that they will establish new browsing contexts, including when the content is an <svg> document. In JavaScript, this is manifested through the existence of the HTMLObjectElement.contentDocument and HTMLObjectElement.contentWindow properties.

This means that if you add an event listener to the <svg> element inside the <object>:

document
    .querySelector('object')
    .contentDocument  // returns null if cross-origin: the same-origin policy
    .querySelector('svg')
    .addEventListener('click', console.log)

and then click on the image, you will see the events being fired.

Then it becomes clear why the pointer-events: none; solution works:

  • Without this style, any MouseEvent that is considered "interactive" (such as click and mousedown, but not mouseenter) is sent to the nested browsing context inside the <object>, which will never bubble out of it.

  • With this style, the MouseEvents aren't sent into the <object> in the first place, then the <object>'s parent elements will receive the events as usual.

This should explain the z-index solution as well: as long as you can prevent click events from being sent to the nested document, the clicking should work as expected.

(In my test, the z-index solution will work as long as the parent element is not inline and the <object> is positioned and has a negative z-index)

(Alternatively, you can find a way to bubble the event back up):

let objectElem = document.querySelector('object')
let svgElemt = objectElem.contentDocument.querySelector('svg')

svgElem.addEventListener('click', () => {
    window.postMessage('Take this click event please.')
    // window being the outermost window
})

window.addEventListener('message', console.log)

Relative paths in Python

In the file that has the script, you want to do something like this:

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its package resources API instead.

UPDATE: I'm responding to a comment here so I can paste a code sample. :-)

Am I correct in thinking that __file__ is not always available (e.g. when you run the file directly rather than importing it)?

I'm assuming you mean the __main__ script when you mention running the file directly. If so, that doesn't appear to be the case on my system (python 2.5.1 on OS X 10.5.7):

#foo.py
import os
print os.getcwd()
print __file__

#in the interactive interpreter
>>> import foo
/Users/jason
foo.py

#and finally, at the shell:
~ % python foo.py
/Users/jason
foo.py

However, I do know that there are some quirks with __file__ on C extensions. For example, I can do this on my Mac:

>>> import collections #note that collections is a C extension in Python 2.5
>>> collections.__file__
'/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-
dynload/collections.so'

However, this raises an exception on my Windows machine.

SHA-1 fingerprint of keystore certificate

If you are using Google Play App Signing, instead of getting the SHA from the keystore, an easier way is to go to the Google Play Console > Your app > Release Management > App signing and look for your upload certificate.

Screenshot of the page where you get this info