Programs & Examples On #Compound key

SQLite table constraint - unique on multiple columns

Be careful how you define the table for you will get different results on insert. Consider the following



CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title') 
    ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
    ('Alice', 'Some title'),
    ('Bob', 'Palindromic guy'),
    ('Charles', 'chucky cheese'),
    ('Alice', 'Some other title');

$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title') 
   ...>     ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
   ...>     ('Alice', 'Some title'),
   ...>     ('Bob', 'Palindromic guy'),
   ...>     ('Charles', 'chucky cheese'),
   ...>     ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id          a           b               
----------  ----------  ----------------
1           Alice       Some other title
2           Bob         Palindromic guy 
3           Charles     chucky cheese   
sqlite> select * from t2;
id          a           b              
----------  ----------  ---------------
2           Bob         Palindromic guy
3           Charles     chucky cheese  
4           Alice       Some other titl
sqlite> 

While the insert/update effect is the same, the id changes based on the table definition type (see the second table where 'Alice' now has id = 4; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.

Inheriting from a template class in c++

class Rectangle : public Area<int> {
};

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

CyMySQL https://github.com/nakagami/CyMySQL

I have installed pip on my windows 7, with python 3.3 just pip install cymysql

(you don't need cython) quick and painless

How to swap two variables in JavaScript

How could we miss these classic oneliners

var a = 1, b = 2
a = ({a:b, _:(b=a)}).a;

And

var a = 1, b = 2
a = (_=b,b=a,_);

The last one exposes global variable '_' but that should not matter as typical javascript convention is to use it as 'dont care' variable.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

Are you talking about drag and drop, when you say copy and paste? If yes, you can also use Rightclick on object on your main computer and click copy. And then you go into the Virtual Machine and Rightclick the position where you want the file to get copied to.

If this doesn't work use the method KaiserM11 explained and get yourselfe VMware Tools like in this Video: https://www.youtube.com/watch?v=McjwI_6BKZY

Hope my answer was helpfull to you and happy coding :D

I need to learn Web Services in Java. What are the different types in it?

If your application often uses http protocol then REST is best because of its light weight, and knowing that your application uses only http protocol choosing SOAP is not so good because it heavy,Better to make decision on web service selection based on the protocols we use in our applications.

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

I think you need OpenSessionInViewFilter to keep your session open during view rendering (but it is not too good practice).

rsync: difference between --size-only and --ignore-times

On a Scientific Linux 6.7 system, the man page on rsync says:

--ignore-times          don't skip files that match size and time

I have two files with identical contents, but with different creation dates:

[root@windstorm ~]# ls -ls /tmp/master/usercron /tmp/new/usercron
4 -rwxrwx--- 1 root root 1595 Feb 15 03:45 /tmp/master/usercron
4 -rwxrwx--- 1 root root 1595 Feb 16 04:52 /tmp/new/usercron

[root@windstorm ~]# diff /tmp/master/usercron /tmp/new/usercron
[root@windstorm ~]# md5sum /tmp/master/usercron /tmp/new/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/master/usercron
368165347b09204ce25e2fa0f61f3bbd  /tmp/new/usercron

With --size-only, the two files are regarded the same:

[root@windstorm ~]# rsync -v --size-only -n  /tmp/new/usercron /tmp/master/usercron

sent 29 bytes  received 12 bytes  82.00 bytes/sec
total size is 1595  speedup is 38.90 (DRY RUN)

With --ignore-times, the two files are regarded different:

[root@windstorm ~]# rsync -v --ignore-times -n  /tmp/new/usercron /tmp/master/usercron
usercron

sent 32 bytes  received 15 bytes  94.00 bytes/sec
total size is 1595  speedup is 33.94 (DRY RUN)

So it does not looks like --ignore-times has any effect at all.

Calling Python in Java?

GraalVM is a good choice. I've done Java+Javascript combination with GraalVM for microservice design (Java with Javascript reflection). They recently added support for python, I'd give it a try especially with how big its community has grown over the years.

CSS endless rotation animation

<style>
div
{  
     height:200px;
     width:200px;
     -webkit-animation: spin 2s infinite linear;    
}
@-webkit-keyframes spin {
    0%  {-webkit-transform: rotate(0deg);}
    100% {-webkit-transform: rotate(360deg);}   
}

</style>
</head>

<body>
<div><img src="1.png" height="200px" width="200px"/></div>
</body>

Is there any simple way to convert .xls file to .csv file? (Excel)

I need to do the same thing. I ended up with something similar to Kman

       static void ExcelToCSVCoversion(string sourceFile,  string targetFile)
    {
        Application rawData = new Application();

        try
        {
            Workbook workbook = rawData.Workbooks.Open(sourceFile);
            Worksheet ws = (Worksheet) workbook.Sheets[1];
            ws.SaveAs(targetFile, XlFileFormat.xlCSV);
            Marshal.ReleaseComObject(ws);
        }

        finally
        {
            rawData.DisplayAlerts = false;
            rawData.Quit();
            Marshal.ReleaseComObject(rawData);
        }


        Console.WriteLine();
        Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format).");
        Console.WriteLine();
    }

If there are multiple sheets this is lost in the conversion but you could loop over the number of sheets and save each one as csv.

How can I extract substrings from a string in Perl?

You could do something like this:

my $data = <<END;
1) Scheme ID: abc-456-hu5t10 (High priority) *
2) Scheme ID: frt-78f-hj542w (Balanced)
3) Scheme ID: 23f-f974-nm54w (super formula run) *
END

foreach (split(/\n/,$data)) {
  $_ =~ /Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?/ || next;
  my ($id,$word,$star) = ($1,$2,$3);
  print "$id $word $star\n";
}

The key thing is the Regular expression:

Scheme ID: ([a-z0-9-]+)\s+\(([^)]+)\)\s*(\*)?

Which breaks up as follows.

The fixed String "Scheme ID: ":

Scheme ID: 

Followed by one or more of the characters a-z, 0-9 or -. We use the brackets to capture it as $1:

([a-z0-9-]+)

Followed by one or more whitespace characters:

\s+

Followed by an opening bracket (which we escape) followed by any number of characters which aren't a close bracket, and then a closing bracket (escaped). We use unescaped brackets to capture the words as $2:

\(([^)]+)\)

Followed by some spaces any maybe a *, captured as $3:

\s*(\*)?

Selecting a Record With MAX Value

The query answered by sandip giri was the correct answer, here a similar example getting the maximum id (PresupuestoEtapaActividadHistoricoId), after calculate the maximum value(Base)

select * 
from (
    select PEAA.PresupuestoEtapaActividadId,
        PEAH.PresupuestoEtapaActividadHistoricoId,             
        sum(PEAA.ValorTotalDesperdicioBase) as Base,
        sum(PEAA.ValorTotalDesperdicioEjecucion) as Ejecucion
    from hgc.PresupuestoActividadAnalisis as PEAA
    inner join hgc.PresupuestoEtapaActividad as PEA
        on PEAA.PresupuestoEtapaActividadId = PEA.PresupuestoEtapaActividadId
    inner join hgc.PresupuestoEtapaActividadHistorico as PEAH
        on PEA.PresupuestoEtapaActividadId = PEAH.PresupuestoEtapaActividadId                                                         
    group by PEAH.PresupuestoEtapaActividadHistoricoId, PEAA.PresupuestoEtapaActividadId    
) as t
where exists (
    select 1 
    from (
        select MAX(PEAH.PresupuestoEtapaActividadHistoricoId) as PresupuestoEtapaActividadHistoricoId                                                                     
        from hgc.PresupuestoEtapaActividadHistorico as PEAH                       
        group by PEAH.PresupuestoEtapaActividadId  
    ) as ti
    where t.PresupuestoEtapaActividadHistoricoId = ti.PresupuestoEtapaActividadHistoricoId 
)

MySQL direct INSERT INTO with WHERE clause

Example of how to perform a INSERT INTO SELECT with a WHERE clause.

INSERT INTO #test2 (id) SELECT id FROM #test1 WHERE id > 2

How to rename a pane in tmux?

Do you mean tmux window? Ctrl + b + , if you have C-b as send prefix (it's by default)

Also C-b :rename-window <new name> and tmux rename-window <new name> work too.

As I know you can't rename pane

How to solve "Fatal error: Class 'MySQLi' not found"?

How to Enable mysqli in php.ini

  1. Edit/uncomment by removing ';'(colon) the following config in php.ini: 1st (uncomment and add config):
    include_path = "C:\php\includes"
    
    2nd (uncomment):
    extension_dir = "ext"
    
    3rd (uncomment and edit config):
    extension=C:/PHP/ext/php_mysql.dll
    extension=C:/PHP/ext/php_mysqli.dll
    
  2. Restart the IIS server
  3. Make sure that mysql is running on the system.

How to load php.ini file

  1. Rename any one of the file php.ini-production/php.ini-development to php.ini from C:\PHP(note now the extention will be ini i.e "php.ini").
  2. After renaming to php.ini file restart server
  3. See the changes in http://localhost/phpinfo.php

using extern template (C++11)

extern template is only needed if the template declaration is complete

This was hinted at in other answers, but I don't think enough emphasis was given to it.

What this means is that in the OPs examples, the extern template has no effect because the template definitions on the headers were incomplete:

  • void f();: just declaration, no body
  • class foo: declares method f() but has no definition

So I would recommend just removing the extern template definition in that particular case: you only need to add them if the classes are completely defined.

For example:

TemplHeader.h

template<typename T>
void f();

TemplCpp.cpp

template<typename T>
void f(){}

// Explicit instantiation for char.
template void f<char>();

Main.cpp

#include "TemplHeader.h"

// Commented out from OP code, has no effect.
// extern template void f<T>(); //is this correct?

int main() {
    f<char>();
    return 0;
}

compile and view symbols with nm:

g++ -std=c++11 -Wall -Wextra -pedantic -c -o TemplCpp.o TemplCpp.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -c -o Main.o Main.cpp
g++ -std=c++11 -Wall -Wextra -pedantic -o Main.out Main.o TemplCpp.o
echo TemplCpp.o
nm -C TemplCpp.o | grep f
echo Main.o
nm -C Main.o | grep f

output:

TemplCpp.o
0000000000000000 W void f<char>()
Main.o
                 U void f<char>()

and then from man nm we see that U means undefined, so the definition did stay only on TemplCpp as desired.

All this boils down to the tradeoff of complete header declarations:

  • upsides:
    • allows external code to use our template with new types
    • we have the option of not adding explicit instantiations if we are fine with object bloat
  • downsides:
    • when developing that class, header implementation changes will lead smart build systems to rebuild all includers, which could be many many files
    • if we want to avoid object file bloat, we need not only to do explicit instantiations (same as with incomplete header declarations) but also add extern template on every includer, which programmers will likely forget to do

Further examples of those are shown at: Explicit template instantiation - when is it used?

Since compilation time is so critical in large projects, I would highly recommend incomplete template declarations, unless external parties absolutely need to reuse your code with their own complex custom classes.

And in that case, I would first try to use polymorphism to avoid the build time problem, and only use templates if noticeable performance gains can be made.

Tested in Ubuntu 18.04.

How can I push a specific commit to a remote, and not previous commits?

Cherry-pick works best compared to all other methods while pushing a specific commit.

The way to do that is:

Create a new branch -

git branch <new-branch>

Update your new-branch with your origin branch -

git fetch

git rebase

These actions will make sure that you exactly have the same stuff as your origin has.

Cherry-pick the sha id that you want to do push -

git cherry-pick <sha id of the commit>

You can get the sha id by running

git log

Push it to your origin -

git push

Run gitk to see that everything looks the same way you wanted.

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

Differences in string compare methods in C#

Here are the rules for how these functions work:

stringValue.CompareTo(otherStringValue)

  1. null comes before a string
  2. it uses CultureInfo.CurrentCulture.CompareInfo.Compare, which means it will use a culture-dependent comparison. This might mean that ß will compare equal to SS in Germany, or similar

stringValue.Equals(otherStringValue)

  1. null is not considered equal to anything
  2. unless you specify a StringComparison option, it will use what looks like a direct ordinal equality check, i.e. ß is not the same as SS, in any language or culture

stringValue == otherStringValue

  1. Is not the same as stringValue.Equals().
  2. The == operator calls the static Equals(string a, string b) method (which in turn goes to an internal EqualsHelper to do the comparison.
  3. Calling .Equals() on a null string gets null reference exception, while on == does not.

Object.ReferenceEquals(stringValue, otherStringValue)

Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.


Note that with the options above that use method calls, there are overloads with more options to specify how to compare.

My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use .CompareTo or .Equals, depending on the choice.

PuTTY scripting to log onto host

When you use the -m option putty does not allocate a tty, it runs the command and quits. If you want to run an interactive script (such as a sql client), you need to tell it to allocate a tty with -t, see 3.8.3.12 -t and -T: control pseudo-terminal allocation. You'll avoid keeping a script on the server, as well as having to invoke it once you're connected.

Here's what I'm using to connect to mysql from a batch file:

#mysql.bat start putty -t -load "sessionname" -l username -pw password -m c:\mysql.sh

#mysql.sh mysql -h localhost -u username --password="foo" mydb

https://superuser.com/questions/587629/putty-run-a-remote-command-after-login-keep-the-shell-running

Swift - How to convert String to Double

In Swift 2.0 the best way is to avoid thinking like an Objective-C developer. So you should not "convert a String to a Double" but you should "initialize a Double from a String". Apple doc over here: https://developer.apple.com/library/ios//documentation/Swift/Reference/Swift_Double_Structure/index.html#//apple_ref/swift/structctr/Double/s:FSdcFMSdFSSGSqSd_

It's an optional init so you can use the nil coalescing operator (??) to set a default value. Example:

let myDouble = Double("1.1") ?? 0.0

How to recursively download a folder via FTP on Linux

You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:

wget -r ftp://user:[email protected]/

You can also use -m which is suitable for mirroring. It is currently equivalent to -r -N -l inf.

If you've some special characters in the credential details, you can specify the --user and --password arguments to get it to work. Example with custom login with specific characters:

wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/

As pointed out by @asmaier, watch out that even if -r is for recursion, it has a default max level of 5:

-r
--recursive
    Turn on recursive retrieving.

-l depth
--level=depth
    Specify recursion maximum depth level depth.  The default maximum depth is 5.

If you don't want to miss out subdirs, better use the mirroring option, -m:

-m
--mirror
    Turn on options suitable for mirroring.  This option turns on recursion and time-stamping, sets infinite
    recursion depth and keeps FTP directory listings.  It is currently equivalent to -r -N -l inf
    --no-remove-listing.

Get protocol, domain, and port from URL

ES6 style with configurable parameters.

/**
 * Get the current URL from `window` context object.
 * Will return the fully qualified URL if neccessary:
 *   getCurrentBaseURL(true, false) // `http://localhost/` - `https://localhost:3000/`
 *   getCurrentBaseURL(true, true) // `http://www.example.com` - `https://www.example.com:8080`
 *   getCurrentBaseURL(false, true) // `www.example.com` - `localhost:3000`
 *
 * @param {boolean} [includeProtocol=true]
 * @param {boolean} [removeTrailingSlash=false]
 * @returns {string} The current base URL.
 */
export const getCurrentBaseURL = (includeProtocol = true, removeTrailingSlash = false) => {
  if (!window || !window.location || !window.location.hostname || !window.location.protocol) {
    console.error(
      `The getCurrentBaseURL function must be called from a context in which window object exists. Yet, window is ${window}`,
      [window, window.location, window.location.hostname, window.location.protocol],
    )
    throw new TypeError('Whole or part of window is not defined.')
  }

  const URL = `${includeProtocol ? `${window.location.protocol}//` : ''}${window.location.hostname}${
    window.location.port ? `:${window.location.port}` : ''
  }${removeTrailingSlash ? '' : '/'}`

  // console.log(`The URL is ${URL}`)

  return URL
}

How to enable GZIP compression in IIS 7.5

Filing this under #wow

Turns out that IIS has different levels of compression configurable from 1-9.

Some of my dynamic SOAP requests have been getting out of control recently. With the uncompressed SOAP being about 14MB and compressed 3MB.

I noticed that in Fiddler when I compressed my request under Transformer it came to about 470KB instead of the 3MB - so I figured there must be some way to get better compression.

Eventually found this very informative blog post

http://weblogs.asp.net/owscott/iis-7-compression-good-bad-how-much

I went ahead and ran this commnd (followed by iisreset):

C:\Windows\System32\Inetsrv\Appcmd.exe set config -section:httpCompression -[name='gzip'].staticCompressionLevel:9 -[name='gzip'].dynamicCompressionLevel:9

Changed dynamic level up to 9 and now my compressed soap matches what Fiddler gave me - and it about 1/7th the size of the existing compressed file.

Milage will vary, but for SOAP this is a massive massive improvement.

VB.Net .Clear() or txtbox.Text = "" textbox clear methods

Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:

TextBox1.Items.Clear()

If you are using VBA, then the use this code :

TextBox1.Text = "" or TextBox1.Clear()

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

How do I suspend painting for a control and its children?

Based on ng5000's answer, I like using this extension:

        #region Suspend
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
        private const int WM_SETREDRAW = 11;
        public static IDisposable BeginSuspendlock(this Control ctrl)
        {
            return new suspender(ctrl);
        }
        private class suspender : IDisposable
        {
            private Control _ctrl;
            public suspender(Control ctrl)
            {
                this._ctrl = ctrl;
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, false, 0);
            }
            public void Dispose()
            {
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, true, 0);
                this._ctrl.Refresh();
            }
        }
        #endregion

Use:

using (this.BeginSuspendlock())
{
    //update GUI
}

Linking to a specific part of a web page

Create a "jump link" using the following format:

http://www.somesite.com/somepage#anchor

Where anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to.

If the element doesnt have an id and you dont control that site then you cant do it.

Unable to verify leaf signature

For Create React App (where this error occurs too and this question is the #1 Google result), you are probably using HTTPS=true npm start and a proxy (in package.json) which goes to some HTTPS API which itself is self-signed, when in development.

If that's the case, consider changing proxy like this:

"proxy": {
  "/api": {
    "target": "https://localhost:5001",
    "secure": false
  }
}

secure decides whether the WebPack proxy checks the certificate chain or not and disabling that ensures the API self-signed certificate is not verified so that you get your data.

How can I display just a portion of an image in HTML/CSS?

One way to do it is to set the image you want to display as a background in a container (td, div, span etc) and then adjust background-position to get the sprite you want.

Incrementing a date in JavaScript

Two methods:

1:

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)

2: Similar to the previous method

var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)

Best place to insert the Google Analytics code

As google says:

Paste it into your web page, just before the closing </head> tag.

One of the main advantages of the asynchronous snippet is that you can position it at the top of the HTML document. This increases the likelihood that the tracking beacon will be sent before the user leaves the page. It is customary to place JavaScript code in the <head> section, and we recommend placing the snippet at the bottom of the <head> section for best performance

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

Append a dictionary to a dictionary

You can do

orig.update(extra)

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy()
dest.update(extra)

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2}
>>> d2 = {2: 'ha!', 3: 3}
>>> d1.update(d2)
>>> d1
{1: 1, 2: 'ha!', 3: 3}

Mean Squared Error in Numpy?

The standard numpy methods for calculation mean squared error (variance) and its square root (standard deviation) are numpy.var() and numpy.std(), see here and here. They apply to matrices and have the same syntax as numpy.mean().

I suppose that the question and the preceding answers might have been posted before these functions became available.

Sharing link on WhatsApp from mobile website (not application) for Android

I'm afraid that WhatsApp for Android does not currently support to be called from a web browser.

I had the same requirement for my current project, and since I couldn't find any proper information I ended up downloading the APK file.

In Android, if an application wants to be called from a web browser, it needs to define an Activity with the category android.intent.category.BROWSABLE.

You can find more information about this here: https://developers.google.com/chrome/mobile/docs/intents

If you take a look to the WhatsApp AndroidManifest.xml file, the only Activiy with category BROWSABLE is this one:

<activity android:name="com.whatsapp.Conversation"   android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:windowSoftInputMode="stateUnchanged">
        <intent-filter>
            <action android:name="android.intent.action.SENDTO" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="sms" />
            <data android:scheme="smsto" />
        </intent-filter>
    </activity>

I've been playing with it for a while, and I couldn't make it to work. The most I got was to open the WhatsApp application from Chrome, but I couldn't figure out a way to set the message content and recipient.

Since it is not documented by the WhatsApp team, I think this is still work in progress. It looks like in the future WhatsApp will handle SMS too.

The only way to get more information is by reaching the WhatsApp dev team, what I tried, but I'm still waiting for a response.

Regards!

Is there a float input type in HTML5?

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

This worked for me and i think is the easiest way to make the input field accept any decimal number irrespective of how long the decimal part is. Step attribute actually shows the input field how many decimal points should be accepted. E.g, step="0.01" will accept only two decimal points.

Conditional Formatting (IF not empty)

In Excel 2003 you should be able to create a formatting rule like:

=A1<>"" and then drag/copy this to other cells as needed.

If that doesn't work, try =Len(A1)>0.

If there may be spaces in the cell which you will consider blank, then do:

=Len(Trim(A1))>0

Let me know if you can't get any of these to work. I have an old machine running XP and Office 2003, I can fire it up to troubleshoot if needed.

Warning: comparison with string literals results in unspecified behaviour

You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp().

If you want to compare a character you need to compare to a character, not a string. "a" is the string a, which occupies two bytes (the a and the terminating null byte), while the character a is represented by 'a' in C.

How do I read the first line of a file using cat?

This may not be possible with cat. Is there a reason you have to use cat?

If you simply need to do it with a bash command, this should work for you:

head -n 1 file.txt

Various ways to remove local Git changes

It all depends on exactly what you are trying to undo/revert. Start out by reading the post in Ube's link. But to attempt an answer:

Hard reset

git reset --hard [HEAD]

completely remove all staged and unstaged changes to tracked files.

I find myself often using hard resetting, when I'm like "just undo everything like if I had done a complete re-clone from the remote". In your case, where you just want your repo pristine, this would work.

Clean

git clean [-f]

Remove files that are not tracked.

For removing temporary files, but keep staged and unstaged changes to already tracked files. Most times, I would probably end up making an ignore-rule instead of repeatedly cleaning - e.g. for the bin/obj folders in a C# project, which you would usually want to exclude from your repo to save space, or something like that.

The -f (force) option will also remove files, that are not tracked and are also being ignored by git though ignore-rule. In the case above, with an ignore-rule to never track the bin/obj folders, even though these folders are being ignored by git, using the force-option will remove them from your file system. I've sporadically seen a use for this, e.g. when scripting deployment, and you want to clean your code before deploying, zipping or whatever.

Git clean will not touch files, that are already being tracked.

Checkout "dot"

git checkout .

I had actually never seen this notation before reading your post. I'm having a hard time finding documentation for this (maybe someone can help), but from playing around a bit, it looks like it means:

"undo all changes in my working tree".

I.e. undo unstaged changes in tracked files. It apparently doesn't touch staged changes and leaves untracked files alone.

Stashing

Some answers mention stashing. As the wording implies, you would probably use stashing when you are in the middle of something (not ready for a commit), and you have to temporarily switch branches or somehow work on another state of your code, later to return to your "messy desk". I don't see this applies to your question, but it's definitely handy.

To sum up

Generally, if you are confident you have committed and maybe pushed to a remote important changes, if you are just playing around or the like, using git reset --hard HEAD followed by git clean -f will definitively cleanse your code to the state, it would be in, had it just been cloned and checked out from a branch. It's really important to emphasize, that the resetting will also remove staged, but uncommitted changes. It will wipe everything that has not been committed (except untracked files, in which case, use clean).

All the other commands are there to facilitate more complex scenarios, where a granularity of "undoing stuff" is needed :)

I feel, your question #1 is covered, but lastly, to conclude on #2: the reason you never found the need to use git reset --hard was that you had never staged anything. Had you staged a change, neither git checkout . nor git clean -f would have reverted that.

Hope this covers.

How can I manually generate a .pyc file from a .py file

In Python2 you could use:

python -m compileall <pythonic-project-name>

which compiles all .py files to .pyc files in a project which contains packages as well as modules.


In Python3 you could use:

python3 -m compileall <pythonic-project-name>

which compiles all .py files to __pycache__ folders in a project which contains packages as well as modules.

Or with browning from this post:

You can enforce the same layout of .pyc files in the folders as in Python2 by using:

python3 -m compileall -b <pythonic-project-name>

The option -b triggers the output of .pyc files to their legacy-locations (i.e. the same as in Python2).

Free XML Formatting tool

If you are a programmer, many XML parsing programming libraries will let you parse XML, then output it - and generating pretty printed, indented output is an output option.

Android: converting String to int

try this

String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());

boolean ins = myDB.adddata(t1,t2);

public boolean adddata(String name, Integer price)

UPDATE and REPLACE part of a string

CREATE TABLE tbl_PersonalDetail
(ID INT IDENTITY ,[Date] nvarchar(20), Name nvarchar(20), GenderID int);

INSERT INTO Tbl_PersonalDetail VALUES(N'18-4-2015', N'Monay', 2),
                                     (N'31-3-2015', N'Monay', 2),
                                     (N'28-12-2015', N'Monay', 2),
                                     (N'19-4-2015', N'Monay', 2)

DECLARE @Date Nvarchar(200)

SET @Date = (SELECT [Date] FROM Tbl_PersonalDetail WHERE ID = 2)

Update Tbl_PersonalDetail SET [Date] = (REPLACE(@Date , '-','/')) WHERE ID = 2 

How can I encode a string to Base64 in Swift?

Swift 3 / 4 / 5.1

Here is a simple String extension, allowing for preserving optionals in the event of an error when decoding.

extension String {
    /// Encode a String to Base64
    func toBase64() -> String {
        return Data(self.utf8).base64EncodedString()
    }

    /// Decode a String from Base64. Returns nil if unsuccessful.
    func fromBase64() -> String? {
        guard let data = Data(base64Encoded: self) else { return nil }
        return String(data: data, encoding: .utf8)
    }
}

Example:

let testString = "A test string."

let encoded = testString.toBase64() // "QSB0ZXN0IHN0cmluZy4="

guard let decoded = encoded.fromBase64() // "A test string."
    else { return } 

Laravel Eloquent - distinct() and count() not working properly together

I had a similar problem, and found a way to work around it.

The problem is the way Laravel's query builder handles aggregates. It takes the first result returned and then returns the 'aggregate' value. This is usually fine, but when you combine count with groupBy you're returning a count per grouped item. So the first row's aggregate is just a count of the first group (so something low like 1 or 2 is likely).

So Laravel's count is out, but I combined the Laravel query builder with some raw SQL to get an accurate count of my grouped results.

For your example, I expect the following should work (and let you avoid the get):

$query = $ad->getcodes()->groupby('pid')->distinct();
$count = count(\DB::select($query->toSql(), $query->getBindings()));

If you want to make sure you're not wasting time selecting all the columns, you can avoid that when building your query:

 $query = $ad->select(DB::raw(1))->getcodes()->groupby('pid')->distinct();

What is the difference between Serialization and Marshaling?

My vies is:

Problem: Object belongs to some process(VM) and it's lifetime is the same

Serialisation - transform object state into stream of bytes(JSON, XML...) for saving, sharing, transforming...

Marshalling - contains Serialisation + codebase. Usually it used by Remote procedure call(RPC) -> Java Remote Method Invocation(Java RMI) where you are able to invoke a object's method which is hosted on remote Java processes.

codebase - is a place or URL to class definition where it can be downloaded by ClassLoader. CLASSPATH[About] is as a local codebase

JVM -> Class Loader -> load class definition -> class

Very simple diagram for RMI

Serialisation - state
Marshalling - state + class definition

Official doc

How to create a popup windows in javafx

You can either create a new Stage, add your controls into it or if you require the POPUP as Dialog box, then you may consider using DialogsFX or ControlsFX(Requires JavaFX8)

For creating a new Stage, you can use the following snippet

@Override
public void start(final Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Open Dialog");
    btn.setOnAction(
        new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                final Stage dialog = new Stage();
                dialog.initModality(Modality.APPLICATION_MODAL);
                dialog.initOwner(primaryStage);
                VBox dialogVbox = new VBox(20);
                dialogVbox.getChildren().add(new Text("This is a Dialog"));
                Scene dialogScene = new Scene(dialogVbox, 300, 200);
                dialog.setScene(dialogScene);
                dialog.show();
            }
         });
    }

If you don't want it to be modal (block other windows), use:

dialog.initModality(Modality.NONE);

Naming convention - underscore in C++ and C# variables

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

Return index of highest value in an array

Something like this should do the trick

function array_max_key($array) {
  $max_key = -1;
  $max_val = -1;

  foreach ($array as $key => $value) {
    if ($value > $max_val) {
      $max_key = $key;
      $max_val = $value;
    }
  }

  return $max_key;
}

WPF Label Foreground Color

I checked your XAML, it works fine - e.g. both labels have a gray foreground.
My guess is that you have some style which is affecting the way it looks...

Try moving your XAML to a brand-new window and see for yourself... Then, check if you have any themes or styles (in the Window.Resources for instance) which might be affecting the labels...

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

How to output an Excel *.xls file from classic ASP

You can always just export the HTML table to an XLS document. Excel does a pretty good job understanding HTML tables.

Another possiblitly is to export the HTML tables as a CSV or TSV file, but you would need to setup the formatting in your code. This isn't too difficult to accomplish.

There's some classes in the Microsoft.Office.Interop that allow you to create an Excel file programatically, but I have always found them to be a little clumsy. You can find a .NET version of creating a spreadsheet here, which should be pretty easy to modify for classic ASP.

As for .NET, I've always liked CarlosAG's Excel XML Writer Library. It has a nice generator so you can setup your Excel file, save it as an XML spreadsheet and it generates the code to do all the formatting and everything. I know it's not classic ASP, but I thought that I would throw it out there.


With what you're trying above, try adding the header:

"Content-Disposition", "attachment; filename=excelTest.xls"

See if that works. Also, I always use this for the content type:

  Response.ContentType = "application/octet-stream"
    Response.ContentType = "application/vnd.ms-excel"

count files in specific folder and display the number into 1 cel

Try below code :

Assign the path of the folder to variable FolderPath before running the below code.

Sub sample()

    Dim FolderPath As String, path As String, count As Integer
    FolderPath = "C:\Documents and Settings\Santosh\Desktop"

    path = FolderPath & "\*.xls"

    Filename = Dir(path)

    Do While Filename <> ""
       count = count + 1
        Filename = Dir()
    Loop

    Range("Q8").Value = count
    'MsgBox count & " : files found in folder"
End Sub

How to set a:link height/width with css?

Your problem is probably that a elements are display: inline by nature. You can't set the width and height of inline elements.

You would have to set display: block on the a, but that will bring other problems because the links start behaving like block elements. The most common cure to that is giving them float: left so they line up side by side anyway.

What's the best way to get the current URL in Spring MVC?

You can also add a UriComponentsBuilder to the method signature of your controller method. Spring will inject an instance of the builder created from the current request.

@GetMapping
public ResponseEntity<MyResponse> doSomething(UriComponentsBuilder uriComponentsBuilder) {
    URI someNewUriBasedOnCurrentRequest = uriComponentsBuilder
            .replacePath(null)
            .replaceQuery(null)
            .pathSegment("some", "new", "path")
            .build().toUri();
  //...
}

Using the builder you can directly start creating URIs based on the current request e.g. modify path segments.

See also UriComponentsBuilderMethodArgumentResolver

Exposing the current state name with ui router

In my current project the solution looks like this:

I created an abstract Language State

$stateProvider.state('language', {
    abstract: true,
    url: '/:language',
    template: '<div ui-view class="lang-{{language}}"></div>'
});

Every state in the project has to depend on this state

$stateProvider.state('language.dashboard', {
    url: '/dashboard'
    //....
});

The language switch buttons calls a custom function:

<a ng-click="footer.setLanguage('de')">de</a>

And the corresponding function looks like this (inside a controller of course):

this.setLanguage = function(lang) {
    FooterLog.log('switch to language', lang);
    $state.go($state.current, { language: lang }, {
        location: true,
        reload: true,
        inherit: true
    }).then(function() {
        FooterLog.log('transition successfull');
    });
};

This works, but there is a nicer solution just changing a value in the state params from html:

<a ui-sref="{ language: 'de' }">de</a>

Unfortunately this does not work, see https://github.com/angular-ui/ui-router/issues/1031

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Is a DIV inside a TD a bad idea?

I have faced the problem by placing a <div> inside <td>.

I was unable to identify the div using document.getElementById() if i place that inside td. But outside, it was working fine.

Convert String to int array in java

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet

SQL datetime format to date only

After perusing your previous questions I eventually determined you are probably on SQL Server 2005. For US format you would use style 101

select Subject, 
       CONVERT(varchar,DeliveryDate,101) as DeliveryDate
from Email_Administration 
where MerchantId =@MerchantID 

Spring Boot: Cannot access REST Controller on localhost (404)

Replace @RequestMapping( "/item" ) with @GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE).

Maybe it will help somebody.

how concatenate two variables in batch script?

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

How to use lodash to find and return an object from Array?

Fetch id basing on name

 {
    "roles": [
     {
      "id": 1,
      "name": "admin",
     },
     {
      "id": 3,
      "name": "manager",
     }
    ]
    }



    fetchIdBasingOnRole() {
          const self = this;
          if (this.employee.roles) {
            var roleid = _.result(
              _.find(this.getRoles, function(obj) {
                return obj.name === self.employee.roles;
              }),
              "id"
            );
          }
          return roleid;
        },

What is cURL in PHP?

Php curl function (POST,GET,DELETE,PUT)

function curl($post = array(), $url, $token = '', $method = "POST", $json = false, $ssl = true){
    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    if($method == 'POST'){
        curl_setopt($ch, CURLOPT_POST, 1);
    }
    if($json == true){
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json','Authorization: Bearer '.$token,'Content-Length: ' . strlen($post)));
    }else{
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSLVERSION, 6);
    if($ssl == false){
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    // curl_setopt($ch, CURLOPT_HEADER, 0);     
    $r = curl_exec($ch);    
    if (curl_error($ch)) {
        $statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err = curl_error($ch);
        print_r('Error: ' . $err . ' Status: ' . $statusCode);
        // Add error
        $this->error = $err;
    }
    curl_close($ch);
    return $r;
}

Get list from pandas dataframe column or row?

Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist() on to turn them into a Python list. Alternatively you cast it with list(x).

import pandas as pd

data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
             'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(data_dict)

print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")

col_one_list = df['one'].tolist()

col_one_arr = df['one'].to_numpy()

print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")

Output:

DataFrame:
   one  two
a  1.0    1
b  2.0    2
c  3.0    3
d  NaN    4

column types:
one    float64
two      int64
dtype: object

col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>

col_one_arr:
[ 1.  2.  3. nan]
type:<class 'numpy.ndarray'>

Clang vs GCC - which produces faster binaries?

The only way to determine this is to try it. FWIW I have seen some really good improvements using Apple's LLVM gcc 4.2 compared to the regular gcc 4.2 (for x86-64 code with quite a lot of SSE), but YMMV for different code bases. Assuming you're working with x86/x86-64 and that you really do care about the last few percent then you ought to try Intel's ICC too, as this can often beat gcc - you can get a 30 day evaluation license from intel.com and try it.

Converting HTML to XML

I did found a way to convert (even bad) html into well formed XML. I started to base this on the DOM loadHTML function. However during time several issues occurred and I optimized and added patches to correct side effects.

  function tryToXml($dom,$content) {
    if(!$content) return false;

    // xml well formed content can be loaded as xml node tree
    $fragment = $dom->createDocumentFragment();
    // wonderfull appendXML to add an XML string directly into the node tree!

    // aappendxml will fail on a xml declaration so manually skip this when occurred
    if( substr( $content,0, 5) == '<?xml' ) {
      $content = substr($content,strpos($content,'>')+1);
      if( strpos($content,'<') ) {
        $content = substr($content,strpos($content,'<'));
      }
    }

    // if appendXML is not working then use below htmlToXml() for nasty html correction
    if(!@$fragment->appendXML( $content )) {
      return $this->htmlToXml($dom,$content);
    }

    return $fragment;
  }



  // convert content into xml
  // dom is only needed to prepare the xml which will be returned
  function htmlToXml($dom, $content, $needEncoding=false, $bodyOnly=true) {

    // no xml when html is empty
    if(!$content) return false;

    // real content and possibly it needs encoding
    if( $needEncoding ) {
      // no need to convert character encoding as loadHTML will respect the content-type (only)
      $content =  '<meta http-equiv="Content-Type" content="text/html;charset='.$this->encoding.'">' . $content;
    }

    // return a dom from the content
    $domInject = new DOMDocument("1.0", "UTF-8");
    $domInject->preserveWhiteSpace = false;
    $domInject->formatOutput = true;

    // html type
    try {
      @$domInject->loadHTML( $content );
    } catch(Exception $e){
      // do nothing and continue as it's normal that warnings will occur on nasty HTML content
    }
        // to check encoding: echo $dom->encoding
        $this->reworkDom( $domInject );

    if( $bodyOnly ) {
      $fragment = $dom->createDocumentFragment();

      // retrieve nodes within /html/body
      foreach( $domInject->documentElement->childNodes as $elementLevel1 ) {
       if( $elementLevel1->nodeName == 'body' and $elementLevel1->nodeType == XML_ELEMENT_NODE ) {
         foreach( $elementLevel1->childNodes as $elementInject ) {
           $fragment->insertBefore( $dom->importNode($elementInject, true) );
         }
        }
      }
    } else {
      $fragment = $dom->importNode($domInject->documentElement, true);
    }

    return $fragment;
  }



    protected function reworkDom( $node, $level = 0 ) {

        // start with the first child node to iterate
        $nodeChild = $node->firstChild;

        while ( $nodeChild )  {
            $nodeNextChild = $nodeChild->nextSibling;

            switch ( $nodeChild->nodeType ) {
                case XML_ELEMENT_NODE:
                    // iterate through children element nodes
                    $this->reworkDom( $nodeChild, $level + 1);
                    break;
                case XML_TEXT_NODE:
                case XML_CDATA_SECTION_NODE:
                    // do nothing with text, cdata
                    break;
                case XML_COMMENT_NODE:
                    // ensure comments to remove - sign also follows the w3c guideline
                    $nodeChild->nodeValue = str_replace("-","_",$nodeChild->nodeValue);
                    break;
                case XML_DOCUMENT_TYPE_NODE:  // 10: needs to be removed
                case XML_PI_NODE: // 7: remove PI
                    $node->removeChild( $nodeChild );
                    $nodeChild = null; // make null to test later
                    break;
                case XML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                case XML_HTML_DOCUMENT_NODE:
                    // should not appear as it's always the root, just to be complete
                    // however generate exception!
                default:
                    throw new exception("Engine: reworkDom type not declared [".$nodeChild->nodeType. "]");
            }
            $nodeChild = $nodeNextChild;
        } ;
    }

Now this also allows to add more html pieces into one XML which I needed to use myself. In general it can be used like this:

        $c='<p>test<font>two</p>';
    $dom=new DOMDocument('1.0', 'UTF-8');

$n=$dom->appendChild($dom->createElement('info')); // make a root element

if( $valueXml=tryToXml($dom,$c) ) {
  $n->appendChild($valueXml);
}
    echo '<pre/>'. htmlentities($dom->saveXml($n)). '</pre>';

In this example '<p>test<font>two</p>' will nicely be outputed in well formed XML as '<info><p>test<font>two</font></p></info>'. The info root tag is added as it will also allow to convert '<p>one</p><p>two</p>' which is not XML as it has not one root element. However if you html does for sure have one root element then the extra root <info> tag can be skipped.

With this I'm getting real nice XML out of unstructured and even corrupted HTML!

I hope it's a bit clear and might contribute to other people to use it.

Viewing unpushed Git commits

If you want to see all commits on all branches that aren't pushed yet, you might be looking for something like this:

git log --branches --not --remotes

And if you only want to see the most recent commit on each branch, and the branch names, this:

git log --branches --not --remotes --simplify-by-decoration --decorate --oneline

Turn off textarea resizing

This is works for me

_x000D_
_x000D_
<textarea_x000D_
  type='text'_x000D_
  style="resize: none"_x000D_
>_x000D_
Some text_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

How to find a user's home directory on linux or unix?

Find a Java wrapper for getpwuid/getpwnam(3) functions, they ask the system for user information by uid or by login name and you get back all info including the default home directory.

How to implement a confirmation (yes/no) DialogPreference?

Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below

intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
    Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);

    intentClearCookies.setIntent(clearcookies);
    intentClearCookies.setTitle(R.string.ClearCookies);
    intentClearCookies.setEnabled(true);
    launchPrefCat.addPreference(intentClearCookies);

And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.

public class ClearCookies extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);

    showDialog();
}

/**
 * @throws NotFoundException
 */
private void showDialog() throws NotFoundException {
    new AlertDialog.Builder(this)
            .setTitle(getResources().getString(R.string.ClearCookies))
            .setMessage(
                    getResources().getString(R.string.ClearCookieQuestion))
            .setIcon(
                    getResources().getDrawable(
                            android.R.drawable.ic_dialog_alert))
            .setPositiveButton(
                    getResources().getString(R.string.PostiveYesButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here

                        }
                    })
            .setNegativeButton(
                    getResources().getString(R.string.NegativeNoButton),
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog,
                                int which) {
                            //Do Something Here
                        }
                    }).show();
}}

As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.

How can I set a dynamic model name in AngularJS?

http://jsfiddle.net/DrQ77/

You can simply put javascript expression in ng-model.

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

If you are working with Python, e.g. PyCharm, you should install the library to the Python library path like this:

pip install --target=C:\Users\<...>\lib <Library-Name>

real e.g.

pip install --target=C:\Users\devel\AppData\Local\Programs\Python\Python36\Lib requests <br>

PS: If you want to check if it's installed,

<Library-Name> --version

will not work correctly.

Pass multiple parameters in Html.BeginForm MVC

Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.

public ActionResult ClientIdSearch(int cid)
{
  var action = String.Format("Details/{0}", cid);

  return RedirectToAction(action, "Accounts");
}

I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.

How to insert array of data into mysql using php

I would avoid to do a query for each entry.

if(is_array($EMailArr)){

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ";

    $valuesArr = array();
    foreach($EMailArr as $row){

        $R_ID = (int) $row['R_ID'];
        $email = mysql_real_escape_string( $row['email'] );
        $name = mysql_real_escape_string( $row['name'] );

        $valuesArr[] = "('$R_ID', '$email', '$name')";
    }

    $sql .= implode(',', $valuesArr);

    mysql_query($sql) or exit(mysql_error()); 
}

Check if value exists in column in VBA

If you want to do this without VBA, you can use a combination of IF, ISERROR, and MATCH.

So if all values are in column A, enter this formula in column B:

=IF(ISERROR(MATCH(12345,A:A,0)),"Not Found","Value found on row " & MATCH(12345,A:A,0))

This will look for the value "12345" (which can also be a cell reference). If the value isn't found, MATCH returns "#N/A" and ISERROR tries to catch that.

If you want to use VBA, the quickest way is to use a FOR loop:

Sub FindMatchingValue()
    Dim i as Integer, intValueToFind as integer
    intValueToFind = 12345
    For i = 1 to 500    ' Revise the 500 to include all of your values
        If Cells(i,1).Value = intValueToFind then 
            MsgBox("Found value on row " & i)
            Exit Sub
        End If
    Next i

    ' This MsgBox will only show if the loop completes with no success
    MsgBox("Value not found in the range!")  
End Sub

You can use Worksheet Functions in VBA, but they're picky and sometimes throw nonsensical errors. The FOR loop is pretty foolproof.

Making a POST call instead of GET using urllib2

Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.

url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age'  : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()

As suggested by @Michael Kent do consider requests, it's great.

EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.

How to specify a editor to open crontab file? "export EDITOR=vi" does not work

You can use below command to open it in VIM editor.

export VISUAL=vim; crontab -e

Note: Please make sure VIM editor is installed on your server.

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

Concat strings by & and + in VB.Net

Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.

Dim I, J, K, L As Integer
Dim K1, L1 As String

K1 = K
L1 = L
Cells(2, 1) = K1 & " - uploaded"
Cells(3, 1) = L1 & " - expanded"

MsgBox "records uploaded " & K & " records expanded " & L

How to make a JSONP request from Javascript without JQuery?

Just pasting an ES6 version of sobstel's nice answer:

send(someUrl + 'error?d=' + encodeURI(JSON.stringify(json)) + '&callback=c', 'c', 5)
    .then((json) => console.log(json))
    .catch((err) => console.log(err))

function send(url, callback, timeout) {
    return new Promise((resolve, reject) => {
        let script = document.createElement('script')
        let timeout_trigger = window.setTimeout(() => {
            window[callback] = () => {}
            script.parentNode.removeChild(script)
            reject('No response')
        }, timeout * 1000)

        window[callback] = (data) => {
            window.clearTimeout(timeout_trigger)
            script.parentNode.removeChild(script)
            resolve(data)
        }

        script.type = 'text/javascript'
        script.async = true
        script.src = url

        document.getElementsByTagName('head')[0].appendChild(script)
    })
}

Angular2 multiple router-outlet in the same template

Yes you can as said by @tomer above. i want to add some point to @tomer answer.

  • firstly you need to provide name to the router-outlet where you want to load the second routing view in your view. (aux routing angular2.)
  • In angular2 routing few important points are here.

    • path or aux (requires exactly one of these to give the path you have to show as the url).
    • component, loader, redirectTo (requires exactly one of these, which component you want to load on routing)
    • name or as (optional) (requires exactly one of these, the name which specify at the time of routerLink)
    • data (optional, whatever you want to send with the routing that you have to get using routerParams at the receiver end.)

for more info read out here and here.

import {RouteConfig, AuxRoute} from 'angular2/router';
@RouteConfig([
  new AuxRoute({path: '/home', component: HomeCmp})
])
class MyApp {}

How to run a task when variable is undefined in ansible?

As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined keyword.

tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

ReactJS - How to use comments?

Besides the other answers, it's also possible to use single line comments just before and after the JSX begines or ends. Here is a complete summary:

Valid

(
  // this is a valid comment
  <div>
    ...
  </div>
  // this is also a valid comment
  /* this is also valid */
)

If we were to use comments inside the JSX rendering logic:

(
  <div>
    {/* <h1>Valid comment</h1> */}
  </div>
)

When declaring props single line comments can be used:

(
  <div
    className="content" /* valid comment */
    onClick={() => {}} // valid comment
  >
    ...
  </div>
)

Invalid

When using single line or multiline comments inside the JSX without wrapping them in { }, the comment will be rendered to the UI:

(
  <div>
    // invalid comment, renders in the UI
  </div>
)

How are cookies passed in the HTTP protocol?

create example script as resp :

#!/bin/bash

http_code=200
mime=text/html

echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"

then make executable and execute like this.

./resp | nc -l -p 12346

open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser

    [aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346
    GET / HTTP/1.1
    Host: xxx.xxx.xxx.xxx:12346
    Connection: keep-alive
    Cache-Control: max-age=0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,ru;q=0.6
    Cookie: name=F

inserting characters at the start and end of a string

If you want to insert other string somewhere else in existing string, you may use selection method below.

Calling character on second position:

>>> s = "0123456789"
>>> s[2]
'2'

Calling range with start and end position:

>>> s[4:6]
'45'

Calling part of a string before that position:

>>> s[:6]
'012345'

Calling part of a string after that position:

>>> s[4:]
'456789'

Inserting your string in 5th position.

>>> s = s[:5] + "L" + s[5:]
>>> s
'01234L56789'

Also s is equivalent to s[:].

With your question you can use all your string, i.e.

>>> s = "L" + s + "LL"

or if "L" is a some other string (for example I call it as l), then you may use that code:

>>> s = l + s + (l * 2)

Find when a file was deleted in Git

Try:

git log --stat | grep file

Add a space (" ") after an element using :after

element::after { 
    display: block;
    content: " ";
}

This worked for me.

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

Moving from position A to position B slowly with animation

You can animate it after the fadeIn completes using the callback as shown below:

$("#Friends").fadeIn('slow',function(){
  $(this).animate({'top': '-=30px'},'slow');
});

How to reset the bootstrap modal when it gets closed and open it fresh again?

also, you can clone your modal before open ;)

$('#myModal')
    .clone()
    .modal()
    .on('hidden.bs.modal', function(e) {
        $(this).remove();
    });

Types in Objective-C on iOS

Update for the new 64bit arch

Ranges:
CHAR_MIN:   -128
CHAR_MAX:   127
SHRT_MIN:   -32768
SHRT_MAX:   32767
INT_MIN:    -2147483648
INT_MAX:    2147483647
LONG_MIN:   -9223372036854775808
LONG_MAX:   9223372036854775807
ULONG_MAX:  18446744073709551615
LLONG_MIN:  -9223372036854775808
LLONG_MAX:  9223372036854775807
ULLONG_MAX: 18446744073709551615

wampserver doesn't go green - stays orange

Also in device manager, first click "show all processes", put a stop to HTTP

After this fix I got an IIS page issue on localhost which got solved when we did the step below:
Check your hosts file in the C:\Windows\System32\Drivers\etc\ folder, if entry 127.0.0.1 localhost is commented then uncomment it by removing the # in front of that line.

Determining image file size + dimensions via Javascript?

Most folks have answered how a downloaded image's dimensions can be known so I'll just try to answer other part of the question - knowing downloaded image's file-size.

You can do this using resource timing api. Very specifically transferSize, encodedBodySize and decodedBodySize properties can be used for the purpose.

Check out my answer here for code snippet and more information if you seek : JavaScript - Get size in bytes from HTML img src

Center align a column in twitter bootstrap

I tried the approaches given above, but these methods fail when dynamically the height of the content in one of the cols increases, it basically pushes the other cols down.

for me the basic table layout solution worked.

// Apply this to the enclosing row
.row-centered {
  text-align: center;
  display: table-row;
}
// Apply this to the cols within the row
.col-centered {
  display: table-cell;
  float: none;
  vertical-align: top;
}

Maven: How to rename the war file for the project?

You need to configure the war plugin:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.3</version>
        <configuration>
          <warName>bird.war</warName>
        </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>

More info here

How to convert a string with Unicode encoding to a string of letters

try

private static final Charset UTF_8 = Charset.forName("UTF-8");
private String forceUtf8Coding(String input) {return new String(input.getBytes(UTF_8), UTF_8))}

Cannot use object of type stdClass as array?

Use true as the second parameter to json_decode. This will decode the json into an associative array instead of stdObject instances:

$my_array = json_decode($my_json, true);

See the documentation for more details.

Global keyboard capture in C# application

private void buttonHook_Click(object sender, EventArgs e)
{
    // Hooks only into specified Keys (here "A" and "B").
    // (***) Use this constructor

    _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

    // Hooks into all keys.
    // (***) Or this - not both

    _globalKeyboardHook = new GlobalKeyboardHook();
    _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
}

And then is working fine.

Calling Javascript function from server side

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "javascript:test();", true);

Forbidden You don't have permission to access / on this server

Found my solution thanks to Error with .htaccess and mod_rewrite
For Apache 2.4 and in all *.conf files (e.g. httpd-vhosts.conf, http.conf, httpd-autoindex.conf ..etc) use

Require all granted

instead of

Order allow,deny
Allow from all

The Order and Allow directives are deprecated in Apache 2.4.

ImportError: No module named win32com.client

Try both pip install pywin32 and pip install pypiwin32.

It works.

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

How to access to a child method from the parent in vue.js

Parent-Child communication in VueJS

Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

The VueJS documentation warns against this specifically for two very good reasons:

  • It tightly couples the parent to the child (and vice versa)
  • You can't rely on the parent's state, given that it can be modified by a child component.

The solution is to use Vue's custom event interface

The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:

  1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
  2. $emit() - allows you to trigger events on the same instance (self)

Example using $on() and $emit():

_x000D_
_x000D_
const events = new Vue({}),_x000D_
    parentComponent = new Vue({_x000D_
      el: '#parent',_x000D_
      ready() {_x000D_
        events.$on('eventGreet', () => {_x000D_
          this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
        });_x000D_
      },_x000D_
      data: {_x000D_
        parentMsg: 'I am listening for an event..',_x000D_
        counter: 0_x000D_
      }_x000D_
    }),_x000D_
    childComponent = new Vue({_x000D_
      el: '#child',_x000D_
      methods: {_x000D_
      greet: function () {_x000D_
        events.$emit('eventGreet');_x000D_
        this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
      }_x000D_
    },_x000D_
    data: {_x000D_
      childMsg: 'I am getting ready to fire an event.',_x000D_
      counter: 0_x000D_
    }_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
  <h2>Parent Component</h2>_x000D_
  <p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
  <h2>Child Component</h2>_x000D_
  <p>{{childMsg}}</p>_x000D_
  <button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Answer taken from the original post: Communicating between components in VueJS

For vs. while in C programming?

WHILE is more flexible. FOR is more concise in those instances in which it applies.

FOR is great for loops which have a counter of some kind, like

for (int n=0; n<max; ++n)

You can accomplish the same thing with a WHILE, of course, as others have pointed out, but now the initialization, test, and increment are broken across three lines. Possibly three widely-separated lines if the body of the loop is large. This makes it harder for the reader to see what you're doing. After all, while "++n" is a very common third piece of the FOR, it's certainly not the only possibility. I've written many loops where I write "n+=increment" or some more complex expression.

FOR can also work nicely with things other than a counter, of course. Like

for (int n=getFirstElementFromList(); listHasMoreElements(); n=getNextElementFromList())

Etc.

But FOR breaks down when the "next time through the loop" logic gets more complicated. Consider:

initializeList();
while (listHasMoreElements())
{
  n=getCurrentElement();
  int status=processElement(n);
  if (status>0)
  {
    skipElements(status);
    advanceElementPointer();
  }
  else
  {
    n=-status;
    findElement(n);
  }
}

That is, if the process of advancing may be different depending on conditions encountered while processing, a FOR statement is impractical. Yes, sometimes you could make it work with a complicated enough expressions, use of the ternary ?: operator, etc, but that usually makes the code less readable rather than more readable.

In practice, most of my loops are either stepping through an array or structure of some kind, in which case I use a FOR loop; or are reading a file or a result set from a database, in which case I use a WHILE loop ("while (!eof())" or something of that sort).

How to export a Hive table into a CSV file?

Below is the end-to-end solution that I use to export Hive table data to HDFS as a single named CSV file with a header.
(it is unfortunate that it's not possible to do with one HQL statement)
It consists of several commands, but it's quite intuitive, I think, and it does not rely on the internal representation of Hive tables, which may change from time to time.
Replace "DIRECTORY" with "LOCAL DIRECTORY" if you want to export the data to a local filesystem versus HDFS.

# cleanup the existing target HDFS directory, if it exists
sudo -u hdfs hdfs dfs -rm -f -r /tmp/data/my_exported_table_name/*

# export the data using Beeline CLI (it will create a data file with a surrogate name in the target HDFS directory)
beeline -u jdbc:hive2://my_hostname:10000 -n hive -e "INSERT OVERWRITE DIRECTORY '/tmp/data/my_exported_table_name' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' SELECT * FROM my_exported_table_name"

# set the owner of the target HDFS directory to whatever UID you'll be using to run the subsequent commands (root in this case)
sudo -u hdfs hdfs dfs -chown -R root:hdfs /tmp/data/my_exported_table_name

# write the CSV header record to a separate file (make sure that its name is higher in the sort order than for the data file in the target HDFS directory)
# also, obviously, make sure that the number and the order of fields is the same as in the data file
echo 'field_name_1,field_name_2,field_name_3,field_name_4,field_name_5' | hadoop fs -put - /tmp/data/my_exported_table_name/.header.csv

# concatenate all (2) files in the target HDFS directory into the final CSV data file with a header
# (this is where the sort order of the file names is important)
hadoop fs -cat /tmp/data/my_exported_table_name/* | hadoop fs -put - /tmp/data/my_exported_table_name/my_exported_table_name.csv

# give the permissions for the exported data to other users as necessary
sudo -u hdfs hdfs dfs -chmod -R 777 /tmp/data/hive_extr/drivers

Stop executing further code in Java

There are two way to stop current method/process :

  1. Throwing Exception.
  2. returnning the value even if it is void method.

Option : you can also kill the current thread to stop it.

For example :

public void onClick(){

    if(condition == true){
        return;
        <or>
        throw new YourException();
    }
    string.setText("This string should not change if condition = true");
}

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

Safely override C++ virtual functions

Your compiler may have a warning that it can generate if a base class function becomes hidden. If it does, enable it. That will catch const clashes and differences in parameter lists. Unfortunately this won't uncover a spelling error.

For example, this is warning C4263 in Microsoft Visual C++.

Number prime test in JavaScript

function isPrime(num) { // returns boolean
  if (num <= 1) return false; // negatives
  if (num % 2 == 0 && num > 2) return false; // even numbers
  const s = Math.sqrt(num); // store the square to loop faster
  for(let i = 3; i <= s; i += 2) { // start from 3, stop at the square, increment in twos
      if(num % i === 0) return false; // modulo shows a divisor was found
  }
  return true;
}
console.log(isPrime(121));

Thanks to Zeph for fixing my mistakes.

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

This is good version:

package main

import (
  "io/ioutil"; 
  )


func main() {
  contents,_ := ioutil.ReadFile("plikTekstowy.txt")
  println(string(contents))
  ioutil.WriteFile("filename", contents, 0644)
}

callback to handle completion of pipe

Here's a solution that handles errors in requests and calls a callback after the file is written:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });

Rename all files in a folder with a prefix in a single command

I think this is just what you'er looking for:

ls | xargs -I {} mv {} Unix_{}

Yes, it is simple yet elegant and powerful, and also one-liner. You can get more detailed intro from me on the page:Rename Files and Directories (Add Prefix)

How can I measure the actual memory usage of an application or process?

I'm using htop; it's a very good console program similar to Windows Task Manager.

How to select date without time in SQL

Try this.

SELECT DATEADD(DD, 0, DATEDIFF(DD, 0, GETDATE()))

Finding the type of an object in C++

Use overloaded functions. Does not require dynamic_cast or even RTTI support:

class A {};
class B : public A {};

class Foo {
public:
    void Bar(A& a) {
        // do something
    }
    void Bar(B& b) {
        Bar(static_cast<A&>(b));
        // do B specific stuff
    }
};

Iterate through the fields of a struct in Go

Taking Chetan Kumar solution and in case you need to apply to a map[string]int

package main

import (
    "fmt"
    "reflect"
)

type BaseStats struct {
    Hp           int
    HpMax        int
    Mp           int
    MpMax        int
    Strength     int
    Speed        int
    Intelligence int
}

type Stats struct {
    Base map[string]int
    Modifiers []string
}

func StatsCreate(stats BaseStats) Stats {
    s := Stats{
        Base: make(map[string]int),
    }

    //Iterate through the fields of a struct
    v := reflect.ValueOf(stats)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        val := v.Field(i).Interface().(int)
        s.Base[typeOfS.Field(i).Name] = val
    }
    return s
}

func (s Stats) GetBaseStat(id string) int {
    return s.Base[id]
}


func main() {
    m := StatsCreate(BaseStats{300, 300, 300, 300, 10, 10, 10})

    fmt.Println(m.GetBaseStat("Hp"))
}


write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

How to check if "Radiobutton" is checked?

You can use switch like this:

XML Layout

<RadioGroup
            android:id="@+id/RG"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <RadioButton
                android:id="@+id/R1"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R1" />

            <RadioButton
                android:id="@+id/R2"
                android:layout_width="wrap_contnet"
                android:layout_height="wrap_content"
                android:text="R2" />
</RadioGroup>

And JAVA Activity

switch (RG.getCheckedRadioButtonId()) {
        case R.id.R1:
            regAuxiliar = ultimoRegistro;
        case R.id.R2:
            regAuxiliar = objRegistro;
        default:
            regAuxiliar = null; // none selected
    }

You will also need to implement an onClick function with button or setOnCheckedChangeListener function to get required functionality.

How to configure encoding in Maven?

Try this:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.7</version>
        <configuration>
          ...
          <encoding>UTF-8</encoding>
          ...
        </configuration>
      </plugin>
    </plugins>
    ...
  </build>
  ...
</project>

How do I get Bin Path?

var assemblyPath = Assembly.GetExecutingAssembly().CodeBase;

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

How do I make a dotted/dashed line in Android?

None of these answers worked for me. Most of these answers give you a half-transparent border. To avoid this, you need to wrap your container once again with another container with your preferred color. Here is an example:

This is how it looks

dashed_border_layout.xml

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/black"
android:background="@drawable/dashed_border_out">
<LinearLayout
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:padding="5dp"
    android:background="@drawable/dashed_border_in"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is&#10;Dashed Container"
        android:textSize="16sp" />
</LinearLayout>

dashed_border_in.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="10dp" />
        <solid android:color="#ffffff" />
        <stroke
            android:dashGap="5dp"
            android:dashWidth="5dp"
            android:width="3dp"
            android:color="#0000FF" />
        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />
    </shape>
</item>

dashed_border_out.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="12dp" />
    </shape>
</item>

Set environment variables from file of key/value pairs

Improving on Silas Paul's answer

exporting the variables on a subshell makes them local to the command.

(export $(cat .env | xargs) && rails c)

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

how to get the first and last days of a given month

Print only current month week:

function my_week_range($date) {
    $ts = strtotime($date);
    $start = (date('w', $ts) == 0) ? $ts : strtotime('last sunday', $ts);
    echo $currentWeek = ceil((date("d",strtotime($date)) - date("w",strtotime($date)) - 1) / 7) + 1;
    $start_date = date('Y-m-d', $start);$end_date=date('Y-m-d', strtotime('next saturday', $start));
    if($currentWeek==1)
        {$start_date = date('Y-m-01', strtotime($date));}
    else if($currentWeek==5)
       {$end_date = date('Y-m-t', strtotime($date));}
    else
       {}
    return array($start_date, $end_date );
}

$date_range=list($start_date, $end_date) = my_week_range($new_fdate);

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

How do I check if a variable exists?

Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.

For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:

my_variable = None

def InitMyVariable():
  global my_variable
  if my_variable is None:
    my_variable = ...

Is there a way to automatically generate getters and setters in Eclipse?

There is an open source jar available know as Lombok , you just add jar and then annotate your POJO with @Getter & @Setter it will create getters and setters automatically.

Apart from this we can use other features like @ToString ,@EqualsAndHashCode and pretty other cool stuff which removes vanilla code from your application

Batch file to delete files older than N days

Gosh, a lot of answers already. A simple and convenient route I found was to execute ROBOCOPY.EXE twice in sequential order from a single Windows command line instruction using the & parameter.

ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 & ROBOCOPY.EXE SOURCE-DIR TARGET-DIR *.* /MOV /MINAGE:30 /PURGE

In this example it works by picking all files (.) that are older than 30 days old and moving them to the target folder. The second command does the same again with the addition of the PURGE command which means remove files in the target folder that don’t exist in the source folder. So essentially, the first command MOVES files and the second DELETES because they no longer exist in the source folder when the second command is invoked.

Consult ROBOCOPY's documentation and use the /L switch when testing.

Does a finally block always get executed in Java?

Try this code, you will understand the code in finally block is get executed after return statement.

public class TestTryCatchFinally {
    static int x = 0;

    public static void main(String[] args){
        System.out.println(f1() );
        System.out.println(f2() );
    }

    public static int f1(){
        try{
            x = 1;
            return x;
        }finally{
            x = 2;
        }
    }

    public static int f2(){
        return x;
    }
}

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

What is the use of the JavaScript 'bind' method?

Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:

_x000D_
_x000D_
var x = 9; // this refers to global "window" object here in the browser_x000D_
var person = {_x000D_
  x: 81,_x000D_
  getX: function() {_x000D_
    return this.x;_x000D_
  }_x000D_
};_x000D_
_x000D_
var y = person.getX; // It will return 9, because it will call global value of x(var x=9)._x000D_
_x000D_
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81)._x000D_
_x000D_
document.getElementById("demo1").innerHTML = y();_x000D_
document.getElementById("demo2").innerHTML = x2();
_x000D_
<p id="demo1">0</p>_x000D_
<p id="demo2">0</p>
_x000D_
_x000D_
_x000D_

How to return a struct from a function in C++?

studentType newStudent() // studentType doesn't exist here
{   
    struct studentType // it only exists within the function
    {
        string studentID;
        string firstName;
        string lastName;
        string subjectName;
        string courseGrade;

        int arrayMarks[4];

        double avgMarks;

    } newStudent;
...

Move it outside the function:

struct studentType
{
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;

    int arrayMarks[4];

    double avgMarks;

};

studentType newStudent()
{
    studentType newStudent
    ...
    return newStudent;
}

Fast Linux file count for a large number of files

I realized that not using in memory processing, when you have a huge amount of data, is faster than "piping" the commands. So I saved the result to a file and analyzed it afterwards:

ls -1 /path/to/dir > count.txt && cat count.txt | wc -l

AFNetworking Post Request

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                       height, @"user[height]",
                       weight, @"user[weight]",
                       nil];

AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:
                                             [NSURL URLWithString:@"http://localhost:8080/"]];

[client postPath:@"/mypage.php" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSString *text = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
     NSLog(@"Response: %@", text);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     NSLog(@"%@", [error localizedDescription]);
}];

How do I download a file using VBA (without Internet Explorer)

Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Sub Example()
    DownloadFile$ = "someFile.ext" 'here the name with extension
    URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address
    LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory
    MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0
End Sub

Source

I found the above when looking for downloading from FTP with username and address in URL. Users supply information and then make the calls.

This was helpful because our organization has Kaspersky AV which blocks active FTP.exe, but not web connections. We were unable to develop in house with ftp.exe and this was our solution. Hope this helps other looking for info!

An internal error occurred during: "Updating Maven Project". java.lang.NullPointerException

Eclipse has an error log. There you will see the complete stack trace. In my case it seems to be caused by a bad jar file combined with the java.util.zip libs not throwing a proper exception, just a NullPointerException.

How to know the git username and email saved during configuration?

Considering what @Robert said, I tried to play around with the config command and it seems that there is a direct way to know both the name and email.

To know the username, type:

git config user.name

To know the email, type:

git config user.email

These two output just the name and email respectively and one doesn't need to look through the whole list. Comes in handy.

Show loading image while $.ajax is performed

I've always liked the BlockUI plugin: http://jquery.malsup.com/block/

It allows you to block certain elements of a page, or the entire page while an ajax request is running.

Uninstall Node.JS using Linux command line?

I think Manoj Gupta had the best answer from what I'm seeing. However, the remove command doesn't get rid of any configuration folders or files that may be leftover. Use:

sudo apt-get purge --auto-remove nodejs

The purge command should remove the package and then clean up any configuration files. (see this question for more info on the difference between purge and remove). The auto-remove flag will do the same for packages that were installed by NodeJS.

See the accepted answer on this question for a better explanation.

Although don't forget to handle NPM! Josh's answer covers that.

Is it possible to add an HTML link in the body of a MAILTO link

The specification for 'mailto' body says:

The body of a message is simply lines of US-ASCII characters. The only two limitations on the body are as follows:

  • CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.
  • Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.

https://tools.ietf.org/html/rfc5322#section-2.3

Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

Eclipse filters out folders that are marked as source from the "raw" folder path. That is, they are visible only as source folders:

example project

If you can't see them in either place, then they

  • are either filtered out in the settings: check your settings for Package Explorer (the Package Explorer bar, downwards menu arrow -> Filters...)
  • or they were created externally and Eclipse haven't noticed them: Refresh your project in this case.
  • or they don't exist: right-click on the project, select New->Folder and input the path, e.g. src/test/java (not "Source Folder"). After you use Maven->Update Project... on the project, they will be automatically added as source folders, provided you have the default configuration.

Now, as I said, those folder will only be used as source if you preserved the default configuration in your POM. If you defined other resources and/or testResources, those will be used instead. In general, Eclipse m2e synchronizes Eclipse's project source folder configuration with what's in your POM.

EDIT: maybe this is unclear - see those folders at the top? The ones labeled with the /-separated paths? These are your folders. These are the same folders that you would expect to find in main and test, just represented differently.

How can I check that JButton is pressed? If the isEnable() is not work?

JButton#isEnabled changes the user interactivity of a component, that is, whether a user is able to interact with it (press it) or not.

When a JButton is pressed, it fires a actionPerformed event.

You are receiving Add button is pressed when you press the confirm button because the add button is enabled. As stated, it has nothing to do with the pressed start of the button.

Based on you code, if you tried to check the "pressed" start of the add button within the confirm button's ActionListener it would always be false, as the button will only be in the pressed state while the add button's ActionListeners are being called.

Based on all this information, I would suggest you might want to consider using a JCheckBox which you can then use JCheckBox#isSelected to determine if it has being checked or not.

Take a closer look at How to Use Buttons for more details

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion

Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

I use the format: major.minor. This would result in:

[assembly: AssemblyVersion("1.0")]

If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.

AssemblyFileVersion

Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

In Windows, it can be viewed in the file properties.

The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

[assembly: AssemblyFileVersion("1.3.2.254")]

Be aware that System.Version names these parts as major.minor.build.revision!

AssemblyInformationalVersion

The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

I use the format: major.minor[.patch] [revision as string]. This would result in:

[assembly: AssemblyInformationalVersion("1.0 RC1")]

How to find the largest file in a directory and its subdirectories?

That is quite simpler way to do it:

ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***

And you'll get this: 8445 examples.desktop

How may I align text to the left and text to the right in the same line?

While several of the solutions here will work, none handle overlap well and end up moving one item to below the other. If you are trying to layout data that will be dynamically bound you won't know until runtime that it looks bad.

What I like to do is simply create a single row table and apply the right float on the second cell. No need to apply a left-align on the first, that happens by default. This handles overlap perfectly by word-wrapping.

HTML

<table style="width: 100%;">
  <tr><td>Left aligned stuff</td>
      <td class="alignRight">Right aligned stuff</td></tr>
</table>

CSS

.alignRight {
  float: right;
}

https://jsfiddle.net/esoyke/7wddxks5/

How to return a complex JSON response with Node.js?

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

How to set a Postgresql default value datestamp like 'YYYYMM'?

Why would you want to do this?

IMHO you should store the date as default type and if needed fetch it transforming to desired format.

You could get away with specifying column's format but with a view. I don't know other methods.

Edited:

Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:

create table sample_table ( id serial primary key, timestamp date); 

and than

create view v_example_table as select id, to_char(date, 'yyyymmmm');

And use v_example_table in your application.

How to access your website through LAN in ASP.NET

You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.

Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.

Can I access variables from another file?

I may be doing this a little differently. I'm not sure why I use this syntax, copied it from some book a long time ago. But each of my js files defines a variable. The first file, for no reason at all, is called R:

    var R = 
    { 
        somevar: 0,
        othervar: -1,

        init: function() {
          ...
        } // end init function

        somefunction: function(somearg) {
          ...
        }  // end somefunction

        ...

    }; // end variable R definition


    $( window ).load(function() {
       R.init();
    })

And then if I have a big piece of code that I want to segregate, I put it in a separate file and a different variable name, but I can still reference the R variables and functions. I called the new one TD for no good reason at all:

    var TD = 
    { 
        xvar: 0,
        yvar: -1,

        init: function() {
           ...
        } // end init function

        sepfunction: function() {
           ...
           R.somefunction(xvar);
           ...
        }  // end somefunction

        ...

    }; // end variable TD definition


    $( window ).load(function() {
       TD.init();
    })

You can see that where in the TD 'sepfunction' I call the R.somefunction. I realize this doesn't give any runtime efficiencies because both scripts to need to load, but it does help me keep my code organized.

history.replaceState() example?

According to MDN History doc
There is clearly said that second argument is for future used not for now. You are right that second argument is deal with web-page title but currently it's ignored by all major browser.

Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

Bootstrap Alert Auto Close

For a smooth slideup:

$("#success-alert").fadeTo(2000, 500).slideUp(500, function(){
    $("#success-alert").slideUp(500);
});

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("#success-alert").hide();_x000D_
  $("#myWish").click(function showAlert() {_x000D_
    $("#success-alert").fadeTo(2000, 500).slideUp(500, function() {_x000D_
      $("#success-alert").slideUp(500);_x000D_
    });_x000D_
  });_x000D_
});
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
_x000D_
<div class="product-options">_x000D_
  <a id="myWish" href="javascript:;" class="btn btn-mini">Add to Wishlist </a>_x000D_
  <a href="" class="btn btn-mini"> Purchase </a>_x000D_
</div>_x000D_
<div class="alert alert-success" id="success-alert">_x000D_
  <button type="button" class="close" data-dismiss="alert">x</button>_x000D_
  <strong>Success! </strong> Product have added to your wishlist._x000D_
</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Disable the postback on an <ASP:LinkButton>

In the jquery ready function you can do something like below -

var hrefcode = $('a[id*=linkbutton]').attr('href').split(':');
var onclickcode = "javascript: if`(Condition()) {" + hrefcode[1] + ";}";
$('a[id*=linkbutton]').attr('href', onclickcode);

Extract digits from string - StringUtils Java

You can use str = str.replaceAll("\\D+","");

Do subclasses inherit private fields?

Memory Layout in Java vis-a-vis inheritance

enter image description here

Padding bits/Alignment and the inclusion of Object Class in the VTABLE is not considered. So the object of the subclass does have a place for the private members of the Super class. However, it cannot be accessed from the subclass's objects...

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

How does Django's Meta class work?

In Django, it acts as a configuration class and keeps the configuration data in one place!!

How to get the root dir of the Symfony2 application?

UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...

How to define relative paths in Visual Studio Project?

By default, all paths you define will be relative. The question is: relative to what? There are several options:

  1. Specifying a file or a path with nothing before it. For example: "mylib.lib". In that case, the file will be searched at the Output Directory.
  2. If you add "..\", the path will be calculated from the actual path where the .sln file resides.

Please note that following a macro such as $(SolutionDir) there is no need to add a backward slash "\". Just use $(SolutionDir)mylibdir\mylib.lib. In case you just can't get it to work, open the project file externally from Notepad and check it.

What data type to use for hashed password field and what length?

Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.

For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.

$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Use the SQL data type CHAR(60) to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.

Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.


It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX() function to reduce a string of hex digits by half.

  • MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)
  • SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)
  • SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)
  • SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)
  • SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)
  • SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)
  • BCrypt generates an implementation-dependent 448-bit hash value. You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)

As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.

Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.

Calling JavaScript Function From CodeBehind

this works for me

object Json_Object=maintainerService.Convert_To_JSON(Jobitem);
ScriptManager.RegisterClientScriptBlock(this,GetType(), "Javascript", "SelectedJobsMaintainer("+Json_Object+"); ",true);

async/await - when to return a Task vs void?

My answer is simple you can not await void method

Error   CS4008  Cannot await 'void' TestAsync   e:\test\TestAsync\TestAsyncProgram.cs

So if the method is async it is better to be awaitable, because you can loose async advantage.

Disallow Twitter Bootstrap modal window from closing

Just set the backdrop property to 'static'.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

You may also want to set the keyboard property to false because that prevents the modal from being closed by pressing the Esc key on the keyboard.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal is the ID of the div that contains your modal content.

Reimport a module in python while interactive

Although the provided answers do work for a specific module, they won't reload submodules, as noted in This answer:

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

However, if using the __all__ variable to define the public API, it is possible to automatically reload all publicly available modules:

# Python >= 3.5
import importlib
import types


def walk_reload(module: types.ModuleType) -> None:
    if hasattr(module, "__all__"):
        for submodule_name in module.__all__:
            walk_reload(getattr(module, submodule_name))
    importlib.reload(module)


walk_reload(my_module)

The caveats noted in the previous answer are still valid though. Notably, modifying a submodule that is not part of the public API as described by the __all__ variable won't be affected by a reload using this function. Similarly, removing an element of a submodule won't be reflected by a reload.

Writing to a new file if it doesn't exist, and appending to a file if it does

It's not clear to me exactly where the high-score that you're interested in is stored, but the code below should be what you need to check if the file exists and append to it if desired. I prefer this method to the "try/except".

import os
player = 'bob'

filename = player+'.txt'

if os.path.exists(filename):
    append_write = 'a' # append if already exists
else:
    append_write = 'w' # make a new file if not

highscore = open(filename,append_write)
highscore.write("Username: " + player + '\n')
highscore.close()

Regular expression to limit number of characters to 10

It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/

How to delete all data from solr and hbase

If you need to clean out all data, it might be faster to recreate collection, e.g.

solrctl --zk localhost:2181/solr collection --delete <collectionName>
solrctl --zk localhost:2181/solr collection --create <collectionName> -s 1

Get current value when change select option - Angular2

Template:

<select class="randomClass" id="randomId" (change) = 
"filterSelected($event.target.value)">

<option *ngFor = 'let type of filterTypes' [value]='type.value'>{{type.display}} 
</option>

</select>

Component:

public filterTypes = [{
  value : 'New', display : 'Open'
},
{
  value : 'Closed', display : 'Closed'
}]


filterSelected(selectedValue:string){
  console.log('selected value= '+selectedValue)

}

How to use a decimal range() step value?

import numpy as np
for i in np.arange(0, 1, 0.1): 
    print i 

How to get the list of all printers in computer

If you need more information than just the name of the printer you can use the System.Management API to query them:

var printerQuery = new ManagementObjectSearcher("SELECT * from Win32_Printer");
foreach (var printer in printerQuery.Get())
{
    var name = printer.GetPropertyValue("Name");
    var status = printer.GetPropertyValue("Status");
    var isDefault = printer.GetPropertyValue("Default");
    var isNetworkPrinter = printer.GetPropertyValue("Network");

    Console.WriteLine("{0} (Status: {1}, Default: {2}, Network: {3}", 
                name, status, isDefault, isNetworkPrinter);
}

How do I decrease the size of my sql server log file?

Welcome to the fickle world of SQL Server log management.

SOMETHING is wrong, though I don't think anyone will be able to tell you more than that without some additional information. For example, has this database ever been used for Transactional SQL Server replication? This can cause issues like this if a transaction hasn't been replicated to a subscriber.

In the interim, this should at least allow you to kill the log file:

  1. Perform a full backup of your database. Don't skip this. Really.
  2. Change the backup method of your database to "Simple"
  3. Open a query window and enter "checkpoint" and execute
  4. Perform another backup of the database
  5. Change the backup method of your database back to "Full" (or whatever it was, if it wasn't already Simple)
  6. Perform a final full backup of the database.

You should now be able to shrink the files (if performing the backup didn't do that for you).

Good luck!

Java logical operator short-circuiting

In plain terms, short-circuiting means stopping evaluation once you know that the answer can no longer change. For example, if you are evaluating a chain of logical ANDs and you discover a FALSE in the middle of that chain, you know the result is going to be false, no matter what are the values of the rest of the expressions in the chain. Same goes for a chain of ORs: once you discover a TRUE, you know the answer right away, and so you can skip evaluating the rest of the expressions.

You indicate to Java that you want short-circuiting by using && instead of & and || instead of |. The first set in your post is short-circuiting.

Note that this is more than an attempt at saving a few CPU cycles: in expressions like this

if (mystring != null && mystring.indexOf('+') > 0) {
    ...
}

short-circuiting means a difference between correct operation and a crash (in the case where mystring is null).

Update div with jQuery ajax response html

Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.

Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way

$('#submitform').click(function() {
     $.ajax({
     url: "getinfo.asp",
     data: {
         txtsearch: $('#appendedInputButton').val()
     },
     type: "GET",
     dataType : "html",
     success: function (data){
         $('#showresults').html($('#showresults',data).html());
         // similar to $(data).find('#showresults')
     },
});

or with replaceWith()

// codes

success: function (data){
   $('#showresults').replaceWith($('#showresults',data));
},

What permission do I need to access Internet from an Android application?

if just using internet then use-

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

if you are getting the state of internet then use also -

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

just above the application tag.

How to call multiple JavaScript functions in onclick event?

ES6 React

<MenuItem
  onClick={() => {
    this.props.toggleTheme();
    this.handleMenuClose();
  }}
>

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

How to add one day to a date?

Java 8 LocalDate API

LocalDate.now().plusDays(1L);

Sorting a List<int>

List<int> list = new List<int> { 5, 7, 3 };  
list.Sort((x,y)=> y.CompareTo(x));  
list.ForEach(action => { Console.Write(action + " "); });

Installing NumPy and SciPy on 64-bit Windows (with Pip)

If you are on windows , you wouldn't need wheel anyway! You can directly install package by downloading the 32-bit package as win32 from this link [http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy] and then move that downloaded package to cmd's current directory and open cmd and write following codepip install numpy-1.13.1+mkl-cp36-cp36m-win32.whl then do it same for scipy

For 64-bit you need to install mingw-w64 as it is gcc and compiles numpy and scipy as precompiled status.

Currently it works fine with 32-bit.So I had opted for win32 package both for numpy+mkl and scipy in that link.

Hope This works! Give a try

Hide/encrypt password in bash file to stop accidentally seeing it

Following line in above code is not working

DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)

Correct line is:

DB_PASSWORD=`echo $PASSWORD|base64 -d`

And save the password in other file as PASSWORD.

Sending message through WhatsApp

I'm really late here but I believe that nowadays we have shorter and better solutions to send messages through WhatsApp.

You can use the following to call the system picker, then choose which app you will use to share whatever you want.

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);

If you are really need to send through WhatsApp all you need to do is the following (You will skip the system picker)

 Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
    sendIntent.setType("text/plain");
    // Put this line here
    sendIntent.setPackage("com.whatsapp");
    //
    startActivity(sendIntent);

If you need more information you can find it here: WhatsApp FAQ

Fastest way to find second (third...) highest/lowest value in vector or column

Here is an easy way to find the indices of N smallest/largest values in a vector(Example for N = 3):

N <- 3

N Smallest:

ndx <- order(x)[1:N]

N Largest:

ndx <- order(x, decreasing = T)[1:N]

So you can extract the values as:

x[ndx]

How to get a URL parameter in Express?

You can do something like req.param('tagId')

How do I change the hover over color for a hover over table in Bootstrap?

This worked for me:

.table tbody tr:hover td, .table tbody tr:hover th {
    background-color: #eeeeea;
}

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

The source was not found, but some or all event logs could not be searched

Inaccessible logs: Security

A new event source needs to have a unique name across all logs including Security (which needs admin privilege when it's being read).

So your app will need admin privilege to create a source. But that's probably an overkill.

I wrote this powershell script to create the event source at will. Save it as *.ps1 and run it with any privilege and it will elevate itself.

# CHECK OR RUN AS ADMIN

If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{   
    $arguments = "& '" + $myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

# CHECK FOR EXISTENCE OR CREATE

$source = "My Service Event Source";
$logname = "Application";

if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
    [System.Diagnostics.EventLog]::CreateEventSource($source, $logname);
    Write-Host $source -f white -nonewline; Write-Host " successfully added." -f green;
}
else
{
    Write-Host $source -f white -nonewline; Write-Host " already exists.";
}

# DONE

Write-Host -NoNewLine 'Press any key to continue...';
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');

How to click a href link using Selenium

You can use xpath as follows, try this one :

driver.findElement(By.xpath("(.//[@href='/docs/configuration'])")).click();

jQuery: Can I call delay() between addClass() and such?

AFAIK the delay method only works for numeric CSS modifications.

For other purposes JavaScript comes with a setTimeout method:

window.setTimeout(function(){$("#div").removeClass("error");}, 1000);

How to find elements by class

The following should work

soup.find('span', attrs={'class':'totalcount'})

replace 'totalcount' with your class name and 'span' with tag you are looking for. Also, if your class contains multiple names with space, just choose one and use.

P.S. This finds the first element with given criteria. If you want to find all elements then replace 'find' with 'find_all'.

In NetBeans how do I change the Default JDK?

If I remember correctly, you'll need to set the netbeans_jdkhome property in your netbeans config file. Should be in your etc/netbeans.conf file.

How can I get href links from HTML using Python?

Simplest way for me:

from urlextract import URLExtract
from requests import get

url = "sample.com/samplepage/"
req = requests.get(url)
text = req.text
# or if you already have the html source:
# text = "This is html for ex <a href='http://google.com/'>Google</a> <a href='http://yahoo.com/'>Yahoo</a>"
text = text.replace(' ', '').replace('=','')
extractor = URLExtract()
print(extractor.find_urls(text))

output:

['http://google.com/', 'http://yahoo.com/']

Test class with a new() call in it with Mockito

For the future I would recommend Eran Harel's answer (refactoring moving new to factory that can be mocked). But if you don't want to change the original source code, use very handy and unique feature: spies. From the documentation:

You can create spies of real objects. When you use the spy then the real methods are called (unless a method was stubbed).

Real spies should be used carefully and occasionally, for example when dealing with legacy code.

In your case you should write:

TestedClass tc = spy(new TestedClass());
LoginContext lcMock = mock(LoginContext.class);
when(tc.login(anyString(), anyString())).thenReturn(lcMock);

In Perl, how do I create a hash whose keys come from a given array?

You could also use Perl6::Junction.

use Perl6::Junction qw'any';

my @arr = ( 1, 2, 3 );

if( any(@arr) == 1 ){ ... }

How to implement an android:background that doesn't stretch?

You can create an xml bitmap and use it as background for the view. To prevent stretching you can specify android:gravity attribute.

for example:

<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/dvdr"
    android:tileMode="disabled" android:gravity="top" >
</bitmap>

There are a lot of options you can use to customize the rendering of the image

http://developer.android.com/guide/topics/resources/drawable-resource.html#Bitmap