Programs & Examples On #Utf 16le

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

In my case this worked (Mac, Excel 2011, both Cyrillic and Latin characters with Czech diacritics):

  • Charset UTF-16LE (simply UTF-16 was not enough)
  • BOM "\xFF\xFE"
  • \t (tab) as separator
  • Don't forget to encode also separator and CRLFs :-)
  • Use iconv instead of mb_convert_encoding

Using json_encode on objects in PHP (regardless of scope)

Following code worked for me:

public function jsonSerialize()
{
    return get_object_vars($this);
}

Is there a macro to conditionally copy rows to another worksheet?

This is partially pseudocode, but you will want something like:

rows = ActiveSheet.UsedRange.Rows
n = 0

while n <= rows
  if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
     ActiveSheet.Rows(n).CopyTo(DestinationSheet)
  endif
  n = n + 1
wend

Should composer.lock be committed to version control?

  1. You shouldn't update your dependencies directly on Production.
  2. You should version control your composer.lock file.
  3. You shouldn't version control your actual dependencies.

1. You shouldn't update your dependencies directly on Production, because you don't know how this will affect the stability of your code. There could be bugs introduced with the new dependencies, it might change the way the code behaves affecting your own, it could be incompatible with other dependencies, etc. You should do this in a dev environment, following by proper QA and regression testing, etc.

2. You should version control your composer.lock file, because this stores information about your dependencies and about the dependencies of your dependencies that will allow you to replicate the current state of the code. This is important, because, all your testing and development has been done against specific code. Not caring about the actual version of the code that you have is similar to uploading code changes to your application and not testing them. If you are upgrading your dependencies versions, this should be a willingly act, and you should take the necessary care to make sure everything still works. Losing one or two hours of up time reverting to a previous release version might cost you a lot of money.

One of the arguments that you will see about not needing the composer.lock is that you can set the exact version that you need in your composer.json file, and that in this way, every time someone runs composer install, it will install them the same code. This is not true, because, your dependencies have their own dependencies, and their configuration might be specified in a format that it allows updates to subversions, or maybe even entire versions.

This means that even when you specify that you want Laravel 4.1.31 in your composer.json, Laravel in its composer.json file might have its own dependencies required as Symfony event-dispatcher: 2.*. With this kind of config, you could end up with Laravel 4.1.31 with Symfony event-dispatcher 2.4.1, and someone else on your team could have Laravel 4.1.31 with event-dispatcher 2.6.5, it would all depend on when was the last time you ran the composer install.

So, having your composer.lock file in the version system will store the exact version of this sub-dependencies, so, when you and your teammate does a composer install (this is the way that you will install your dependencies based on a composer.lock) you both will get the same versions.

What if you wanna update? Then in your dev environment run: composer update, this will generate a new composer.lock file (if there is something new) and after you test it, and QA test and regression test it and stuff. You can push it for everyone else to download the new composer.lock, since its safe to upgrade.

3. You shouldn't version control your actual dependencies, because it makes no sense. With the composer.lock you can install the exact version of the dependencies and you wouldn't need to commit them. Why would you add to your repo 10000 files of dependencies, when you are not supposed to be updating them. If you require to change one of this, you should fork it and make your changes there. And if you are worried about having to fetch the actual dependencies each time of a build or release, composer has different ways to alleviate this issue, cache, zip files, etc.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I was getting a same error. I found out the solution that I had created the primary key in the main table as BIGINT UNSIGNED and was declaring it as a foreign key in the second table as only BIGINT.

When I declared my foreign key as BIGINT UNSIGED in second table, everything worked fine, even didn't need any indexes to be created.

So it was a datatype mismatch between the primary key and the foreign key :)

Find the files existing in one directory but not in the other

vim's DirDiff plugin is another very useful tool for comparing directories.

vim -c "DirDiff dir1 dir2"

It not only lists which files are different between the directories, but also allows you to inspect/modify with vimdiff the files that are different.

How to retrieve field names from temporary table (SQL Server 2008)

you can do it by following way too ..

create table #test (a int, b char(1))

select * From #test

exec tempdb..sp_columns '#test'

WPF global exception handler

I use the following code in my WPF apps to show a "Sorry for the inconvenience" dialog box whenever an unhandled exception occurs. It shows the exception message, and asks user whether they want to close the app or ignore the exception and continue (the latter case is convenient when a non-fatal exceptions occur and user can still normally continue to use the app).

In App.xaml add the Startup event handler:

<Application .... Startup="Application_Startup">

In App.xaml.cs code add Startup event handler function that will register the global application event handler:

using System.Windows.Threading;

private void Application_Startup(object sender, StartupEventArgs e)
{
    // Global exception handling  
    Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);    
}

void AppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{    
    \#if DEBUG   // In debug mode do not custom-handle the exception, let Visual Studio handle it

    e.Handled = false;

    \#else

    ShowUnhandledException(e);    

    \#endif     
}

void ShowUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true;

    string errorMessage = string.Format("An application error occurred.\nPlease check whether your data is correct and repeat the action. If this error occurs again there seems to be a more serious malfunction in the application, and you better close it.\n\nError: {0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)",

    e.Exception.Message + (e.Exception.InnerException != null ? "\n" + 
    e.Exception.InnerException.Message : null));

    if (MessageBox.Show(errorMessage, "Application Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)   {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
    {
        Application.Current.Shutdown();
    } 
}

How to TryParse for Enum value?

This method will convert a type of enum:

  public static TEnum ToEnum<TEnum>(object EnumValue, TEnum defaultValue)
    {
        if (!Enum.IsDefined(typeof(TEnum), EnumValue))
        {
            Type enumType = Enum.GetUnderlyingType(typeof(TEnum));
            if ( EnumValue.GetType() == enumType )
            {
                string name = Enum.GetName(typeof(HLink.ViewModels.ClaimHeaderViewModel.ClaimStatus), EnumValue);
                if( name != null)
                    return (TEnum)Enum.Parse(typeof(TEnum), name);
                return defaultValue;
            }
        }
        return (TEnum)Enum.Parse(typeof(TEnum), EnumValue.ToString());
    } 

It checks the underlying type and get the name against it to parse. If everything fails it will return default value.

How to export private key from a keystore of self-signed certificate

It is a little tricky. First you can use keytool to put the private key into PKCS12 format, which is more portable/compatible than Java's various keystore formats. Here is an example taking a private key with alias 'mykey' in a Java keystore and copying it into a PKCS12 file named myp12file.p12. [note that on most screens this command extends beyond the right side of the box: you need to scroll right to see it all]

keytool -v -importkeystore -srckeystore .keystore -srcalias mykey -destkeystore myp12file.p12 -deststoretype PKCS12
Enter destination keystore password:  
Re-enter new password: 
Enter source keystore password:  
[Storing myp12file.p12]

Now the file myp12file.p12 contains the private key in PKCS12 format which may be used directly by many software packages or further processed using the openssl pkcs12 command. For example,

openssl pkcs12 -in myp12file.p12 -nocerts -nodes
Enter Import Password:
MAC verified OK
Bag Attributes
    friendlyName: mykey
    localKeyID: 54 69 6D 65 20 31 32 37 31 32 37 38 35 37 36 32 35 37 
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIIC...
.
.
.
-----END RSA PRIVATE KEY-----

Prints out the private key unencrypted.

Note that this is a private key, and you are responsible for appreciating the security implications of removing it from your Java keystore and moving it around.

How to compare two lists in python?

If you mean lists, try ==:

l1 = [1,2,3]
l2 = [1,2,3,4]

l1 == l2 # False

If you mean array:

l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False

If you want to compare strings (per your comment):

date_string  = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False

How to fire an event when v-model changes?

Just to add to the correct answer above, in Vue.JS v1.0 you can write

<a v-on:click="doSomething">

So in this example it would be

 v-on:change="foo"

See: http://v1.vuejs.org/guide/syntax.html#Arguments

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Get full query string in C# ASP.NET

Request.QueryString returns you a collection of Key/Value pairs representing the Query String. Not a String. Don't think that would cause a Object Reference error though. The reason your getting that is because as Mauro pointed out in the comments. It's QueryString and not Querystring.

Try:

Request.QueryString.ToString();

or

<%                                 
    string URL = Request.Url.AbsoluteUri 
    System.Net.WebClient wc = new System.Net.WebClient();
    string data = wc.DownloadString(URL);
    Response.Output.Write(data);
%>

Same as your code but Request.Url.AbsoluteUri will return the full path, including the query string.

How to change TextField's height and width?

If you use "suffixIcon" to collapse the height of the TextField add: suffixIconConstraints

TextField(
                    style: TextStyle(fontSize: r * 1.8, color: Colors.black87),
                    decoration: InputDecoration(
                      isDense: true,
                      contentPadding: EdgeInsets.symmetric(vertical: r * 1.6, horizontal: r * 1.6),
                      suffixIcon: Icon(Icons.search, color: Colors.black54),
                      suffixIconConstraints: BoxConstraints(minWidth: 32, minHeight: 32),
                    ),
                  )

Convert binary to ASCII and vice versa

I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.

First, you need to strip the 0b prefix, and left-zero-pad the string so it's length is divisible by 8, to make dividing the bitstring up into characters easy:

bitstring = bitstring[2:]
bitstring = -len(bitstring) % 8 * '0' + bitstring

Then you divide the string up into blocks of eight binary digits, convert them to ASCII characters, and join them back into a string:

string_blocks = (bitstring[i:i+8] for i in range(0, len(bitstring), 8))
string = ''.join(chr(int(char, 2)) for char in string_blocks)

If you actually want to treat it as a number, you still have to account for the fact that the leftmost character will be at most seven digits long if you want to go left-to-right instead of right-to-left.

Regex any ASCII character

[ -~]

It was seen here. It matches all ASCII characters from the space to the tilde.

So your implementation would be:

xxx[ -~]+xxx

Entity Framework: table without primary key

I`m very happy my problem is solved.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

and do this : Look below that line and find the tag. It will have a big ol' select statement in it. Remove the tag and it's contents..

now without changing DB T I can insert to a table which has not PK

thanks all and thank Pharylon

Remove Duplicate objects from JSON Array

You can use lodash, download here (4.17.15)

Example code:

var object = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];

_.uniqWith(object, _.isEqual);

// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]

Is there an embeddable Webkit component for Windows / C# development?

There's a WebKit-Sharp component on Mono's GitHub Repository. I can't find any web-viewable documentation on it, and I'm not even sure if it's WinForms or GTK# (can't grab the source from here to check at the moment), but it's probably your best bet, either way.

What is the difference between .py and .pyc files?

Python compiles the .py and saves files as .pyc so it can reference them in subsequent invocations.

There's no harm in deleting them, but they will save compilation time if you're doing lots of processing.

phpmailer: Reply using only "Reply To" address

I have found the answer to this, and it is annoyingly/frustratingly simple! Basically the reply to addresses needed to be added before the from address as such:

$mail->addReplyTo('[email protected]', 'Reply to name');
$mail->SetFrom('[email protected]', 'Mailbox name');

Looking at the phpmailer code in more detail this is the offending line:

public function SetFrom($address, $name = '',$auto=1) {
   $address = trim($address);
   $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
   if (!self::ValidateAddress($address)) {
     $this->SetError($this->Lang('invalid_address').': '. $address);
     if ($this->exceptions) {
       throw new phpmailerException($this->Lang('invalid_address').': '.$address);
     }
     echo $this->Lang('invalid_address').': '.$address;
     return false;
   }
   $this->From = $address;
   $this->FromName = $name;
   if ($auto) {
      if (empty($this->ReplyTo)) {
         $this->AddAnAddress('ReplyTo', $address, $name);
      }
      if (empty($this->Sender)) {
         $this->Sender = $address;
      }
   }
   return true;
}

Specifically this line:

if (empty($this->ReplyTo)) {
   $this->AddAnAddress('ReplyTo', $address, $name);
}

Thanks for your help everyone!

How can I change the app display name build with Flutter?

You can change it in iOS without opening Xcode by editing file *project/ios/Runner/info.plist. Set <key>CFBundleDisplayName</key> to the string that you want as your name.

For Android, change the app name from the Android folder, in the AndroidManifest.xml file, android/app/src/main. Let the android label refer to the name you prefer, for example,

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    <application
        android:label="test"
        // The rest of the code
    </application>
</manifest>

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

How to use the "required" attribute with a "radio" input field

Here is a very basic but modern implementation of required radio buttons with native HTML5 validation:

_x000D_
_x000D_
fieldset { 
  display: block;
  margin-left: 0;
  margin-right: 0;
  padding-top: 0;
  padding-bottom: 0;
  padding-left: 0;
  padding-right: 0;
  border: none;
}
body {font-size: 15px; font-family: serif;}
input {
  background: transparent;
  border-radius: 0px;
  border: 1px solid black;
  padding: 5px;
  box-shadow: none!important;
  font-size: 15px; font-family: serif;
}
input[type="submit"] {padding: 5px 10px; margin-top: 5px;}
label {display: block; padding: 0 0 5px 0;}
form > div {margin-bottom: 1em; overflow: auto;}
.hidden {
  opacity: 0; 
  position: absolute; 
  pointer-events: none;
}
.checkboxes label {display: block; float: left;}
input[type="radio"] + span {
  display: block;
  border: 1px solid black;
  border-left: 0;
  padding: 5px 10px;
}
label:first-child input[type="radio"] + span {border-left: 1px solid black;}
input[type="radio"]:checked + span {background: silver;}
_x000D_
<form>
  <div>
    <label for="name">Name (optional)</label>
    <input id="name" type="text" name="name">
  </div>
  <fieldset>
  <legend>Gender</legend>
  <div class="checkboxes">
    <label for="male"><input id="male" type="radio" name="gender" value="male" class="hidden" required="required"><span>Male</span></label>
    <label for="female"><input id="female" type="radio" name="gender" value="female" class="hidden" required="required"><span>Female </span></label>
    <label for="other"><input id="other" type="radio" name="gender" value="other" class="hidden" required="required"><span>Other</span></label>
  </div>
  </fieldset>
  <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_

Although I am a big fan of the minimalistic approach of using native HTML5 validation, you might want to replace it with Javascript validation on the long run. Javascript validation gives you far more control over the validation process and it allows you to set real classes (instead of pseudo classes) to improve the styling of the (in)valid fields. This native HTML5 validation can be your fall-back in case of broken (or lack of) Javascript. You can find an example of that here, along with some other suggestions on how to make Better forms, inspired by Andrew Cole.

What is the default access specifier in Java?

It depends on what the thing is.

  • Top-level types (that is, classes, enums, interfaces, and annotation types not declared inside another type) are package-private by default. (JLS §6.6.1)

  • In classes, all members (that means fields, methods, and nested type declarations) and constructors are package-private by default. (JLS §6.6.1)

    • When a class has no explicitly declared constructor, the compiler inserts a default zero-argument constructor which has the same access specifier as the class. (JLS §8.8.9) The default constructor is commonly misstated as always being public, but in rare cases that's not equivalent.
  • In enums, constructors are private by default. Indeed, enum contructors must be private, and it is an error to specify them as public or protected. Enum constants are always public, and do not permit any access specifier. Other members of enums are package-private by default. (JLS §8.9)

  • In interfaces and annotation types, all members (again, that means fields, methods, and nested type declarations) are public by default. Indeed, members of interfaces and annotation types must be public, and it is an error to specify them as private or protected. (JLS §9.3 to 9.5)

  • Local classes are named classes declared inside a method, constructor, or initializer block. They are scoped to the {..} block in which they are declared and do not permit any access specifier. (JLS §14.3) Using reflection, you can instantiate local classes from elsewhere, and they are package-private, although I'm not sure if that detail is in the JLS.

  • Anonymous classes are custom classes created with new which specify a class body directly in the expression. (JLS §15.9.5) Their syntax does not permit any access specifier. Using reflection, you can instantiate anonymous classes from elsewhere, and both they and their generated constructors are are package-private, although I'm not sure if that detail is in the JLS.

  • Instance and static initializer blocks do not have access specifiers at the language level (JLS §8.6 & 8.7), but static initializer blocks are implemented as a method named <clinit> (JVMS §2.9), so the method must, internally, have some access specifier. I examined classes compiled by javac and by Eclipse's compiler using a hex editor and found that both generate the method as package-private. However, you can't call <clinit>() within the language because the < and > characters are invalid in a method name, and the reflection methods are hardwired to deny its existence, so effectively its access specifier is no access. The method can only be called by the VM, during class initialization. Instance initializer blocks are not compiled as separate methods; their code is copied into each constructor, so they can't be accessed individually, even by reflection.

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

How to secure MongoDB with username and password

Here is a javascript code to add users.

  1. Start mongod with --auth = true

  2. Access admin database from mongo shell and pass the javascript file.

    mongo admin "Filename.js"

    "Filename.js"

    // Adding admin user
    db.addUser("admin_username", " admin_password");
    // Authenticate admin user
    db.auth("admin_username ", " admin_password ");
    // use  database code from java script
    db = db.getSiblingDB("newDatabase");
    // Adding newDatabase database user  
    db.addUser("database_username ", " database_ password ");
    
  3. Now user addition is complete, we can verify accessing the database from mongo shell

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

Try this:

net use * /delete /y

The /y key makes it select Yes in prompt silently

How do I vertical center text next to an image in html/css?

One basic way that comes to mind would be to put the item into a table and have two cells, one with the text, the other with the image, and use style="valign:center" with the tags.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

How to subtract a day from a date?

Subtract datetime.timedelta(days=1)

Find all paths between two graph nodes

Here is an algorithm finding and printing all paths from s to t using modification of DFS. Also dynamic programming can be used to find the count of all possible paths. The pseudo code will look like this:

AllPaths(G(V,E),s,t)
 C[1...n]    //array of integers for storing path count from 's' to i
 TopologicallySort(G(V,E))  //here suppose 's' is at i0 and 't' is at i1 index

  for i<-0 to n
      if i<i0
          C[i]<-0  //there is no path from vertex ordered on the left from 's' after the topological sort
      if i==i0
         C[i]<-1
      for j<-0 to Adj(i)
          C[i]<- C[i]+C[j]

 return C[i1]

Bootstrap - floating navbar button right

In bootstrap 4 use:

<ul class="nav navbar-nav ml-auto">

This will push the navbar to the right. Use mr-auto to push it to the left, this is the default behaviour.

What does !important mean in CSS?

It is used to influence sorting in the CSS cascade when sorting by origin is done. It has nothing to do with specificity like stated here in other answers.

Here is the priority from lowest to highest:

  1. browser styles
  2. user style sheet declarations (without !important)
  3. author style sheet declarations (without !important)
  4. !important author style sheets
  5. !important user style sheets

After that specificity takes place for the rules still having a finger in the pie.

References:

Restrict SQL Server Login access to only one database

this is to topup to what was selected as the correct answer. It has one missing step that when not done, the user will still be able to access the rest of the database. First, do as @DineshDB suggested

  1. Connect to your SQL server instance using management studio
   2. Goto Security -> Logins -> (RIGHT CLICK) New Login
   3. fill in user details
   4. Under User Mapping, select the databases you want the user to be able to access and configure

the missing step is below:

5. Under user mapping, ensure that "sysadmin" is NOT CHECKED and select "db_owner" as the role for the new user.

And thats it.

SQL Server : Arithmetic overflow error converting expression to data type int

declare @d real
set @d=1.0;
select @d*40000*(192+2)*20000+150000

Which is fastest? SELECT SQL_CALC_FOUND_ROWS FROM `table`, or SELECT COUNT(*)

IMHO, the reason why 2 queries

SELECT * FROM count_test WHERE b = 666 ORDER BY c LIMIT 5;
SELECT count(*) FROM count_test WHERE b = 666;

are faster than using SQL_CALC_FOUND_ROWS

SELECT SQL_CALC_FOUND_ROWS * FROM count_test WHERE b = 555 ORDER BY c LIMIT 5;

has to be seen as a particular case.

It in facts depends on the selectivity of the WHERE clause compared to the selectivity of the implicit one equivalent to the ORDER + LIMIT.

As Arvids told in comment (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-1174394), the fact that the EXPLAIN use, or not, a temporay table, should be a good base for knowing if SCFR will be faster or not.

But, as I added (http://www.mysqlperformanceblog.com/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/#comment-8166482), the result really, really depends on the case. For a particular paginator, you could get to the conclusion that “for the 3 first pages, use 2 queries; for the following pages, use a SCFR” !

In a Bash script, how can I exit the entire script if a certain condition occurs?

A SysOps guy once taught me the Three-Fingered Claw technique:

yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
try() { "$@" || die "cannot $*"; }

These functions are *NIX OS and shell flavor-robust. Put them at the beginning of your script (bash or otherwise), try() your statement and code on.

Explanation

(based on flying sheep comment).

  • yell: print the script name and all arguments to stderr:
    • $0 is the path to the script ;
    • $* are all arguments.
    • >&2 means > redirect stdout to & pipe 2. pipe 1 would be stdout itself.
  • die does the same as yell, but exits with a non-0 exit status, which means “fail”.
  • try uses the || (boolean OR), which only evaluates the right side if the left one failed.

Clear listview content?

Just put the code ListView.Items.Clear(); on your method

Print text in Oracle SQL Developer SQL Worksheet window

You could set echo to on:

set echo on
REM Querying table
select * from dual;

In SQLDeveloper, hit F5 to run as a script.

git - pulling from specific branch

It's often clearer to separate the two actions git pull does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch. The second is that it then merges in changes, which can of course be done with git merge, though other options such as git rebase are occasionally useful.

Highlight label if checkbox is checked

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

Excel how to find values in 1 column exist in the range of values in another

Use the formula by tigeravatar:

=COUNTIF($B$2:$B$5,A2)>0 – tigeravatar Aug 28 '13 at 14:50

as conditional formatting. Highlight column A. Choose conditional formatting by forumula. Enter the formula (above) - this finds values in col B that are also in A. Choose a format (I like to use FILL and a bold color).

To find all of those values, highlight col A. Data > Filter and choose Filter by color.

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Excel VBA function to print an array to the workbook

As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:

  1. Convert your 1D array into a 2D array first, then print it on sheet (as a Range).
  2. Convert your 1D array into a string and print it in a single cell (as a String).

Here is an example depicting both options:

Sub PrintArrayIn1Cell(myArr As Variant, cell As Range)
    cell = Join(myArr, ",")
End Sub
Sub PrintArrayAsRange(myArr As Variant, cell As Range)
    cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr
End Sub
Sub TestPrintArrayIntoSheet()  '2dArrayToSheet
    Dim arr As Variant
    arr = Split("a  b  c", "  ")

    'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c):
    PrintArrayIn1Cell arr, [A1]

    'Printing in SEPARATE-CELLS: To print array-elements in separate cells:
    Dim arr2D As Variant
    arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array
    PrintArrayAsRange arr2D, Range("B1:B3")
End Sub

Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.

HTH

Error: 'int' object is not subscriptable - Python

'int' object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

list1 = [1, 2, 3]
print(list1[0][0])

If we run the code, you will receive the same TypeError in Python3.

TypeError: 'int' object is not subscriptable

Here the index of the list is out of range. If the code was modified to:

print(list1[0])

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

1

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

int([x[age1]])

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Hence, it's better to code this way:

name = input("What's your name? ")
age = int(input('How old are you? '))
twenty_one = 21 - age
if(twenty_one < 0):
    print('Hi {0}, you are above 21 years' .format(name))
elif(twenty_one == 0):
    print('Hi {0}, you are 21 years old' .format(name))
else:
    print('Hi {0}, you will be 21 years in {1} year(s)' .format(name, twenty_one))

The output:

What's your name? Steve
How old are you? 21
Hi Steve, you are 21 years old

Defining private module functions in python

Python has three modes via., private, public and protected .While importing a module only public mode is accessible .So private and protected modules cannot be called from outside of the module i.e., when it is imported .

Moving up one directory in Python

Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath

so that you could do something like this:

>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'

Asynchronous shell exec in PHP

The only way that I found that truly worked for me was:

shell_exec('./myscript.php | at now & disown')

Exception thrown in catch and finally clause

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.

Exception currentException = null;

As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.

Also, the finally blocks always run before the method exits. You could then requite the code snippet to:

public class C1 {

    public static void main(String [] argv) throws Exception {
        try {
            System.out.print(1);
            q();

        }
        catch ( Exception i ) {
            // <-- currentException = Exception, as thrown by q()'s finally block
            throw( new MyExc2() ); // <-- currentException = MyExc2
        }
        finally {
             // <-- currentException = MyExc2, thrown from main()'s catch block
            System.out.print(2);
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }

    }  // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.

    static void q() throws Exception {
        try {
            throw( new MyExc1() ); // <-- currentException = MyExc1
        }
        catch( Exception y ) {
           // <-- currentException = null, because the exception is caught and not rethrown
        }
        finally {
            System.out.print(3);
            throw( new Exception() ); // <-- currentException = Exception
        }
    }
}

The order in which the application executes is:

main()
{
  try
    q()
    {
      try
      catch
      finally
    }
  catch
  finally
}

How to use apply a custom drawable to RadioButton?

Give your radiobutton a custom style:

<style name="MyRadioButtonStyle" parent="@android:style/Widget.CompoundButton.RadioButton">
    <item name="android:button">@drawable/custom_btn_radio</item>
</style>

custom_btn_radio.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_on" />
    <item android:state_checked="false" android:state_window_focused="false"
          android:drawable="@drawable/btn_radio_off" />

    <item android:state_checked="true" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_on_pressed" />
    <item android:state_checked="false" android:state_pressed="true"
          android:drawable="@drawable/btn_radio_off_pressed" />

    <item android:state_checked="true" android:state_focused="true"
          android:drawable="@drawable/btn_radio_on_selected" />
    <item android:state_checked="false" android:state_focused="true"
          android:drawable="@drawable/btn_radio_off_selected" />

    <item android:state_checked="false" android:drawable="@drawable/btn_radio_off" />
    <item android:state_checked="true" android:drawable="@drawable/btn_radio_on" />
</selector>

Replace the drawables with your own.

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

Responsive image map

Working for me (remember to change 3 things in code):

  • previousWidth (original size of image)

  • map_ID (id of your image map)

  • img_ID (id of your image)

HTML:

<div style="width:100%;">
    <img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>

Javascript:

window.onload = function () {
    var ImageMap = function (map, img) {
            var n,
                areas = map.getElementsByTagName('area'),
                len = areas.length,
                coords = [],
                previousWidth = 128;
            for (n = 0; n < len; n++) {
                coords[n] = areas[n].coords.split(',');
            }
            this.resize = function () {
                var n, m, clen,
                    x = img.offsetWidth / previousWidth;
                for (n = 0; n < len; n++) {
                    clen = coords[n].length;
                    for (m = 0; m < clen; m++) {
                        coords[n][m] *= x;
                    }
                    areas[n].coords = coords[n].join(',');
                }
                previousWidth = img.offsetWidth;
                return true;
            };
            window.onresize = this.resize;
        },
        imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
    imageMap.resize();
    return;
}

JSFiddle: http://jsfiddle.net/p7EyT/154/

What is the best free SQL GUI for Linux for various DBMS systems

For Oracle, I highly recommend the free Oracle SQL Developer

http://www.oracle.com/technology/products/database/sql_developer/index.html

The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle

Comparing two branches in Git?

git diff branch_1..branch_2

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

git diff branch_1...branch_2

How to call getResources() from a class which has no context?

It can easily be done if u had declared a class that extends from Application

This class will be like a singleton, so when u need a context u can get it just like this:

I think this is the better answer and the cleaner

Here is my code from Utilities package:

 public static String getAppNAme(){
     return MyOwnApplication.getInstance().getString(R.string.app_name);
 }

Get clicked element using jQuery on event?

You are missing the event parameter on your function.

$(document).on("click",".appDetails", function (event) {
    alert(event.target.id);
});

Jenkins: Can comments be added to a Jenkinsfile?

The Jenkinsfile is written in groovy which uses the Java (and C) form of comments:

/* this
   is a
   multi-line comment */

// this is a single line comment

TSQL Default Minimum DateTime

I think this would work...

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT ((0))
)

Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...

How can I decrypt a password hash in PHP?

it seems someone finally has created a script to decrypt password_hash. checkout this one: https://pastebin.com/Sn19ShVX

<?php
error_reporting(0);

# Coded by L0c4lh34rtz - IndoXploit

# \n -> linux
# \r\n -> windows
$list = explode("\n", file_get_contents($argv[1])); # change \n to \r\n if you're using windows
# ------------------- #

$hash = '$2y$10$BxO1iVD3HYjVO83NJ58VgeM4wNc7gd3gpggEV8OoHzB1dOCThBpb6'; # hash here, NB: use single quote (') , don't use double quote (")

if(isset($argv[1])) {
    foreach($list as $wordlist) {
        print " [+]"; print (password_verify($wordlist, $hash)) ? "$hash -> $wordlist (OK)\n" : "$hash -> $wordlist (SALAH)\n";
    }
} else {
    print "usage: php ".$argv[0]." wordlist.txt\n";
}
?>

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Can also use the dayjs relativeTime plugin to solve this.

import * as dayjs from 'dayjs';
import * as relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);
dayjs(dayjs('1990')).fromNow(); // x years ago

How do I add a resources folder to my Java project in Eclipse

If you have multiple sub-projects then you need to add the resources folder to each project's run configuration class path like so:

class path

Ensure the new path is top of the entries and then the runtime will check that path first for any resources (before checking sub-paths)

How to debug heap corruption errors?

You can use VC CRT Heap-Check macros for _CrtSetDbgFlag: _CRTDBG_CHECK_ALWAYS_DF or _CRTDBG_CHECK_EVERY_16_DF.._CRTDBG_CHECK_EVERY_1024_DF.

Error pushing to GitHub - insufficient permission for adding an object to repository database

I guess many like me ends up in forums like this when the git problem as described above occoures. However, there are so many causes that may lead to the problem that I just wanna share what caused my troubles for others to learn as I already learned from above.

I have my repos on a Linux NAS from sitecom (Never buy NAS from Sitecom, pleeaaase). I have a repo here that is cloned on many computers but which I suddenly was denied pushing to. Recently I installed a plugin so that my NAS could stand as a squeezebox server.

This server scans for media to share. What I did not know was that, possible because of a bug, the server changes the user and group setting to squeeze:user for all files it looks into. And that is ALL files. Thus altering the rights I had to push.

Server is gone and proper rights settings are re-established and everything works perfectly.

I used

chmod -R g+ws *
chown -R <myuser>:<mygroup> *

Where myuser and mygroup off-course must be replaced with proper settings for your system. try git:git or gituser:gituser or something else you might like.,

Iterating Through a Dictionary in Swift

Arrays are ordered collections but dictionaries and sets are unordered collections. Thus you can't predict the order of iteration in a dictionary or a set.

Read this article to know more about Collection Types: Swift Programming Language

C++ auto keyword. Why is it magic?

The auto keyword is an important and frequently used keyword for C ++.When initializing a variable, auto keyword is used for type inference(also called type deduction).

There are 3 different rules regarding the auto keyword.

First Rule

auto x = expr; ----> No pointer or reference, only variable name. In this case, const and reference are ignored.

int  y = 10;
int& r = y;
auto x = r; // The type of variable x is int. (Reference Ignored)

const int y = 10;
auto x = y; // The type of variable x is int. (Const Ignored)

int y = 10;
const int& r = y;
auto x = r; // The type of variable x is int. (Both const and reference Ignored)

const int a[10] = {};
auto x = a; //  x is const int *. (Array to pointer conversion)

Note : When the name defined by auto is given a value with the name of a function,
       the type inference will be done as a function pointer.

Second Rule

auto& y = expr; or auto* y = expr; ----> Reference or pointer after auto keyword.

Warning : const is not ignored in this rule !!! .

int y = 10;
auto& x = y; // The type of variable x is int&.

Warning : In this rule, array to pointer conversion (array decay) does not occur !!!.

auto& x = "hello"; // The type of variable x is  const char [6].

static int x = 10;
auto y = x; // The variable y is not static.Because the static keyword is not a type. specifier 
            // The type of variable x is int.

Third Rule

auto&& z = expr; ----> This is not a Rvalue reference.

Warning : If the type inference is in question and the && token is used, the names introduced like this are called "Forwarding Reference" (also called Universal Reference).

auto&& r1 = x; // The type of variable r1 is int&.Because x is Lvalue expression. 

auto&& r2 = x+y; // The type of variable r2 is int&&.Because x+y is PRvalue expression. 

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

How do I get the path of a process in Unix / Linux

You can find the exe easily by these ways, just try it yourself.

  • ll /proc/<PID>/exe
  • pwdx <PID>
  • lsof -p <PID> | grep cwd

Delete all rows in table

You can rename the table in question, create a table with an identical schema, and then drop the original table at your leisure.

See the MySQL 5.1 Reference Manual for the [RENAME TABLE][1] and [CREATE TABLE][2] commands.

RENAME TABLE tbl TO tbl_old;

CREATE TABLE tbl LIKE tbl_old;

DROP TABLE tbl_old; -- at your leisure

This approach can help minimize application downtime.

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Checking for installed php modules and packages

In addition to running

php -m

to get the list of installed php modules, you will probably find it helpful to get the list of the currently installed php packages in Ubuntu:

sudo dpkg --get-selections | grep -v deinstall | grep php

This is helpful since Ubuntu makes php modules available via packages.

You can then install the needed modules by selecting from the available Ubuntu php packages, which you can view by running:

sudo apt-cache search php | grep "^php5-"

Or, for Ubuntu 16.04 and higher:

sudo apt-cache search php | grep "^php7"

As you have mentioned, there is plenty of information available on the actual installation of the packages that you might require, so I won't go into detail about that here.

Related: Enabling / disabling installed php modules

It is possible that an installed module has been disabled. In that case, it won't show up when running php -m, but it will show up in the list of installed Ubuntu packages.

Modules can be enabled/disabled via the php5enmod tool (phpenmod on later distros) which is part of the php-common package.

Ubuntu 12.04:

Enabled modules are symlinked in /etc/php5/conf.d

Ubuntu 12.04: (with PHP 5.4+)

To enable an installed module:

php5enmod <modulename>

To disable an installed module:

php5dismod <modulename>

Ubuntu 16.04 (php7) and higher:

To enable an installed module:

phpenmod <modulename>

To disable an installed module:

phpdismod <modulename>

Reload Apache

Remember to reload Apache2 after enabling/disabling:

service apache2 reload

Format price in the current locale and currency

By this code for formating price in product list

echo Mage::helper('core')->currency($_product->getPrice());

Adding an img element to a div with javascript

document.getElementById("placehere").appendChild(elem);

not

document.getElementById("placehere").appendChild("elem");

and use the below to set the source

elem.src = 'images/hydrangeas.jpg';

What is the difference between a .cpp file and a .h file?

Others have already offered good explanations, but I thought I should clarify the differences between the various extensions:

  Source Files for C: .c
  Header Files for C: .h

  Source Files for C++: .cpp
  Header Files for C++: .hpp

Of course, as it has already been pointed out, these are just conventions. The compiler doesn't actually pay any attention to them - it's purely for the benefit of the coder.

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Test file upload using HTTP PUT method

If you're using PHP you can test your PUT upload using the code below:

#Initiate cURL object
$curl = curl_init();
#Set your URL
curl_setopt($curl, CURLOPT_URL, 'https://local.simbiat.ru');
#Indicate, that you plan to upload a file
curl_setopt($curl, CURLOPT_UPLOAD, true);
#Indicate your protocol
curl_setopt($curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
#Set flags for transfer
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
#Disable header (optional)
curl_setopt($curl, CURLOPT_HEADER, false);
#Set HTTP method to PUT
curl_setopt($curl, CURLOPT_PUT, 1);
#Indicate the file you want to upload
curl_setopt($curl, CURLOPT_INFILE, fopen('path_to_file', 'rb'));
#Indicate the size of the file (it does not look like this is mandatory, though)
curl_setopt($curl, CURLOPT_INFILESIZE, filesize('path_to_file'));
#Only use below option on TEST environment if you have a self-signed certificate!!! On production this can cause security issues
#curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
#Execute
curl_exec($curl);

How to close the command line window after running a batch file?

For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I'm using 'call' command instead of 'start' in my batch files. My startWLS.cmd file then looks like:

call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd

After Ctrl+C(and 'Y' answer) cmd window is automatically closed.

Most recent previous business day in Python

Maybe this code could help:

lastBusDay = datetime.datetime.today()
shift = datetime.timedelta(max(1,(lastBusDay.weekday() + 6) % 7 - 3))
lastBusDay = lastBusDay - shift

The idea is that on Mondays yo have to go back 3 days, on Sundays 2, and 1 in any other day.

The statement (lastBusDay.weekday() + 6) % 7 just re-bases the Monday from 0 to 6.

Really don't know if this will be better in terms of performance.

Usage of \b and \r in C

The characters are exactly as documented - \b equates to a character code of 0x08 and \r equates to 0x0d. The thing that varies is how your OS reacts to those characters. Back when displays were trying to emulate an old teletype those actions were standardized, but they are less useful in modern environments and compatibility is not guaranteed.

Copy entire contents of a directory to another using php

Full thanks must go to Felix Kling for his excellent answer which I have gratefully used in my code. I offer a small enhancement of a boolean return value to report success or failure:

function recurse_copy($src, $dst) {

  $dir = opendir($src);
  $result = ($dir === false ? false : true);

  if ($result !== false) {
    $result = @mkdir($dst);

    if ($result === true) {
      while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' ) && $result) { 
          if ( is_dir($src . '/' . $file) ) { 
            $result = recurse_copy($src . '/' . $file,$dst . '/' . $file); 
          }     else { 
            $result = copy($src . '/' . $file,$dst . '/' . $file); 
          } 
        } 
      } 
      closedir($dir);
    }
  }

  return $result;
}

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

How do I get time of a Python program's execution?

I've looked at the timeit module, but it seems it's only for small snippets of code. I want to time the whole program.

$ python -mtimeit -n1 -r1 -t -s "from your_module import main" "main()"

It runs your_module.main() function one time and print the elapsed time using time.time() function as a timer.

To emulate /usr/bin/time in Python see Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?.

To measure CPU time (e.g., don't include time during time.sleep()) for each function, you could use profile module (cProfile on Python 2):

$ python3 -mprofile your_module.py

You could pass -p to timeit command above if you want to use the same timer as profile module uses.

See How can you profile a Python script?

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's a code snippet that fixes that behavior of IE (v['date'] is a comma separated date-string, e.g. "2010,4,1"):

if($.browser.msie){
    $.lst = v['date'].split(',');
    $.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
    $.tmp = new Date(v['date']);
}

The previous approach didn't consider that JS Date month is ZERO based...

Sorry for not explaining too much, I'm at work and just thought this might help.

Get original URL referer with PHP?

try this

(isset ($_SERVER['HTTP_CLIENT_IP']) ? 
    $_SERVER['HTTP_CLIENT_IP'] : 
    (isset ($_SERVER['HTTP_X_FORWARDED_FOR']) ? 
        $_SERVER['HTTP_X_FORWARDED_FOR'] : 
        $_SERVER['REMOTE_ADDR']
    )
)

How to create local notifications?

-(void)kundanselect
{
    NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    NSArray *allControllersCopy = [allControllers copy];
    if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]]) 
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
        [self performSegueWithIdentifier:@"kundansegue" sender:self];
    }
}

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];

Preloading images with jQuery

Quick and easy:

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

// Usage:

preload([
    'img/imageName.jpg',
    'img/anotherOne.jpg',
    'img/blahblahblah.jpg'
]);

Or, if you want a jQuery plugin:

$.fn.preload = function() {
    this.each(function(){
        $('<img/>')[0].src = this;
    });
}

// Usage:

$(['img1.jpg','img2.jpg','img3.jpg']).preload();

What is a semaphore?

Think of semaphores as bouncers at a nightclub. There are a dedicated number of people that are allowed in the club at once. If the club is full no one is allowed to enter, but as soon as one person leaves another person might enter.

It's simply a way to limit the number of consumers for a specific resource. For example, to limit the number of simultaneous calls to a database in an application.

Here is a very pedagogic example in C# :-)

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TheNightclub
{
    public class Program
    {
        public static Semaphore Bouncer { get; set; }

        public static void Main(string[] args)
        {
            // Create the semaphore with 3 slots, where 3 are available.
            Bouncer = new Semaphore(3, 3);

            // Open the nightclub.
            OpenNightclub();
        }

        public static void OpenNightclub()
        {
            for (int i = 1; i <= 50; i++)
            {
                // Let each guest enter on an own thread.
                Thread thread = new Thread(new ParameterizedThreadStart(Guest));
                thread.Start(i);
            }
        }

        public static void Guest(object args)
        {
            // Wait to enter the nightclub (a semaphore to be released).
            Console.WriteLine("Guest {0} is waiting to entering nightclub.", args);
            Bouncer.WaitOne();          

            // Do some dancing.
            Console.WriteLine("Guest {0} is doing some dancing.", args);
            Thread.Sleep(500);

            // Let one guest out (release one semaphore).
            Console.WriteLine("Guest {0} is leaving the nightclub.", args);
            Bouncer.Release(1);
        }
    }
}

How to "properly" print a list?

You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.

lst = ['x', 3, 'b']

print str(lst).translate(None, "'")

# [x, 3, b]

If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:

import string

print string.translate(str(lst), None, "'")

Using the string.translate() function will also work in 2.6+, so using it might be preferable.

What is logits, softmax and softmax_cross_entropy_with_logits?

Whatever goes to softmax is logit, this is what J. Hinton repeats in coursera videos all the time.

Xcode 4 - "Valid signing identity not found" error on provisioning profiles on a new Macintosh install

No one has mentioned this yet, and this may not be a common problem, but I had a similar problem with Xcode 5: Make sure you have a default keychain selected in the Mac's Keychain Access. I trying out a fresh install of Mountain Lion and deleted one keychain, which happened to be the default. After setting another keychain as the default (right-click on the keychain and select Make Keychain "Keychain_name" default"), Xcode was able to set up the valid signing identities.

Is it possible to make desktop GUI application in .NET Core?

AvaloniaUI now has support for running on top of .NET Core on Windows, OS X, and Linux. XAML, bindings and control templates included.

E.g. to develop on macOS with Rider:

  1. Follow instructions to install the Avalonia dotnet new templates
  2. Open JetBrains Rider and from the Welcome screen,
  3. Choose New Solution ? (near the top of the Templates List) ? More Templates ? Button Install Template...* ? browse to the directory where you cloned the templates at step 1.
  4. Click the Reload Button
  5. Behold! Avalonia Templates now appear in the New Solution Templates List!
  6. Choose an Avalonia template
  7. Build and run. See the GUI open before your eyes.

GUI steps to install a dotnet new template into JetBrains Rider

Difference between DTO, VO, POJO, JavaBeans?

JavaBeans

A JavaBean is a class that follows the JavaBeans conventions as defined by Sun. Wikipedia has a pretty good summary of what JavaBeans are:

JavaBeans are reusable software components for Java that can be manipulated visually in a builder tool. Practically, they are classes written in the Java programming language conforming to a particular convention. They are used to encapsulate many objects into a single object (the bean), so that they can be passed around as a single bean object instead of as multiple individual objects. A JavaBean is a Java Object that is serializable, has a nullary constructor, and allows access to properties using getter and setter methods.

In order to function as a JavaBean class, an object class must obey certain conventions about method naming, construction, and behavior. These conventions make it possible to have tools that can use, reuse, replace, and connect JavaBeans.

The required conventions are:

  • The class must have a public default constructor. This allows easy instantiation within editing and activation frameworks.
  • The class properties must be accessible using get, set, and other methods (so-called accessor methods and mutator methods), following a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties.
  • The class should be serializable. This allows applications and frameworks to reliably save, store, and restore the bean's state in a fashion that is independent of the VM and platform.

Because these requirements are largely expressed as conventions rather than by implementing interfaces, some developers view JavaBeans as Plain Old Java Objects that follow specific naming conventions.

POJO

A Plain Old Java Object or POJO is a term initially introduced to designate a simple lightweight Java object, not implementing any javax.ejb interface, as opposed to heavyweight EJB 2.x (especially Entity Beans, Stateless Session Beans are not that bad IMO). Today, the term is used for any simple object with no extra stuff. Again, Wikipedia does a good job at defining POJO:

POJO is an acronym for Plain Old Java Object. The name is used to emphasize that the object in question is an ordinary Java Object, not a special object, and in particular not an Enterprise JavaBean (especially before EJB 3). The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie in September 2000:

"We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."

The term continues the pattern of older terms for technologies that do not use fancy new features, such as POTS (Plain Old Telephone Service) in telephony, and PODS (Plain Old Data Structures) that are defined in C++ but use only C language features, and POD (Plain Old Documentation) in Perl.

The term has most likely gained widespread acceptance because of the need for a common and easily understood term that contrasts with complicated object frameworks. A JavaBean is a POJO that is serializable, has a no-argument constructor, and allows access to properties using getter and setter methods. An Enterprise JavaBean is not a single class but an entire component model (again, EJB 3 reduces the complexity of Enterprise JavaBeans).

As designs using POJOs have become more commonly-used, systems have arisen that give POJOs some of the functionality used in frameworks and more choice about which areas of functionality are actually needed. Hibernate and Spring are examples.

Value Object

A Value Object or VO is an object such as java.lang.Integer that hold values (hence value objects). For a more formal definition, I often refer to Martin Fowler's description of Value Object:

In Patterns of Enterprise Application Architecture I described Value Object as a small object such as a Money or date range object. Their key property is that they follow value semantics rather than reference semantics.

You can usually tell them because their notion of equality isn't based on identity, instead two value objects are equal if all their fields are equal. Although all fields are equal, you don't need to compare all fields if a subset is unique - for example currency codes for currency objects are enough to test equality.

A general heuristic is that value objects should be entirely immutable. If you want to change a value object you should replace the object with a new one and not be allowed to update the values of the value object itself - updatable value objects lead to aliasing problems.

Early J2EE literature used the term value object to describe a different notion, what I call a Data Transfer Object. They have since changed their usage and use the term Transfer Object instead.

You can find some more good material on value objects on the wiki and by Dirk Riehle.

Data Transfer Object

Data Transfer Object or DTO is a (anti) pattern introduced with EJB. Instead of performing many remote calls on EJBs, the idea was to encapsulate data in a value object that could be transfered over the network: a Data Transfer Object. Wikipedia has a decent definition of Data Transfer Object:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

The difference between data transfer objects and business objects or data access objects is that a DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).

In a traditional EJB architecture, DTOs serve dual purposes: first, they work around the problem that entity beans are not serializable; second, they implicitly define an assembly phase where all data to be used by the view is fetched and marshalled into the DTOs before returning control to the presentation tier.


So, for many people, DTOs and VOs are the same thing (but Fowler uses VOs to mean something else as we saw). Most of time, they follow the JavaBeans conventions and are thus JavaBeans too. And all are POJOs.

PostgreSQL: days/months/years between two dates

Almost the same function as you needed (based on atiruz's answer, shortened version of UDF from here)

CREATE OR REPLACE FUNCTION datediff(type VARCHAR, date_from DATE, date_to DATE) RETURNS INTEGER LANGUAGE plpgsql
AS
$$
DECLARE age INTERVAL;
BEGIN
    CASE type
        WHEN 'year' THEN
            RETURN date_part('year', date_to) - date_part('year', date_from);
        WHEN 'month' THEN
            age := age(date_to, date_from);
            RETURN date_part('year', age) * 12 + date_part('month', age);
        ELSE
            RETURN (date_to - date_from)::int;
    END CASE;
END;
$$;

Usage:

/* Get months count between two dates */
SELECT datediff('month', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 10 */

/* Get years count between two dates */
SELECT datediff('year', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 1 */

/* Get days count between two dates */
SELECT datediff('day', '2015-02-14'::date, '2016-01-03'::date);
/* Result: 323 */

/* Get months count between specified and current date */
SELECT datediff('month', '2015-02-14'::date, NOW()::date);
/* Result: 47 */

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

how to make jni.h be found?

You have to tell your compiler where is the include directory. Something like this:

gcc -I/usr/lib/jvm/jdk1.7.0_07/include

But it depends on your makefile.

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

How to create a remote Git repository from a local one?

In current code folder.

git remote add origin http://yourdomain-of-git.com/project.git
git push --set-upstream origin master

Then review by

git remote --v

PowerShell To Set Folder Permissions

$path = "C:\DemoFolder"
$acl = Get-Acl $path
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$Attribs = $username, "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow"
$AccessRule = New-Object System.Security.AcessControl.FileSystemAccessRule($Attribs)
$acl.SetAccessRule($AccessRule)
$acl | Set-Acl $path
Get-ChildItem -Path "$path" -Recourse -Force | Set-Acl -aclObject $acl -Verbose

What is the command to exit a Console application in C#?

Console applications will exit when the main function has finished running. A "return" will achieve this.

    static void Main(string[] args)
    {
        while (true)
        {
            Console.WriteLine("I'm running!");
            return; //This will exit the console application's running thread
        }
    }

If you're returning an error code you can do it this way, which is accessible from functions outside of the initial thread:

    System.Environment.Exit(-1);

How to get the real and total length of char * (char array)?

If the char * is 0-terminated, you can use strlen

Otherwise, there is no way to determine that information

Why does Eclipse automatically add appcompat v7 library support whenever I create a new project?

As stated in Android's Support Library Overview, it is considered good practice to include the support library by default because of the large diversity of devices and the fragmentation that exists between the different versions of Android (and thus, of the provided APIs).

This is the reason why Android code templates tools included in Eclipse through the Android Development Tools (ADT) integrate them by default.

I noted that you target API 15 in your sample, but the miminum required SDK for your package is API 10, for which the compatibility libraries can provide a tremendous amount of backward compatible APIs. An example would be the ability of using the Fragment API which appeard on API 11 (Android 3.0 Honeycomb) on a device that runs an older version of this system.

It is also to be noted that you can deactivate automatic inclusion of the Support Library by default.

What is syntax for selector in CSS for next element?

You can use the sibling selector ~:

h1.hc-reform ~ p{
     clear:both;
}

This selects all the p elements that come after .hc-reform, not just the first one.

MySQL Query - Records between Today and Last 30 Days

SELECT
    *
FROM
    < table_name >
WHERE
    < date_field > BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY)
AND NOW();

How to export non-exportable private key from store

Unfortunately, the tool mentioned above is blocked by several antivirus vendors. If this is the case for you then take a look at the following.

Open the non-exportable cert in the cert store and locate the Thumbprint value.

Next, open regedit to the path below and locate the registry key matching the thumbprint value.

An export of the registry key will contain the complete certificate including the private key. Once exported, copy the export to the other server and import it into the registry.

The cert will appear in the certificate manager with the private key included.

Machine Store: HKLM\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates User Store: HKCU\SOFTWARE\Microsoft\SystemCertificates\MY\Certificates

In a pinch, you could save the export as a backup of the certificate.

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

Characters allowed in a URL

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding)

http://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters

says these are RFC 3986 unreserved characters (sec. 2.3) as well as reserved characters (sec 2.2) if they need to retain their special meaning. And also a percent character as part of a percent-encoding.

How can I remove the string "\n" from within a Ruby string?

use chomp or strip functions from Ruby:

"abcd\n".chomp => "abcd"
"abcd\n".strip => "abcd"

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

'was not declared in this scope' error

The scope of a variable is always the block it is inside. For example if you do something like

if(...)
{
     int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
     int y = 8; //y is created
} //y leaves scope, since the block ends.

cout << y << endl; //Gives error since y is not defined.

The solution is to define y outside of the if blocks

int y; //y is created

if(...)
{
     y = 5;
} 
else
{
     y = 8;
} 

cout << y << endl; //Ok

In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:

//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
    int y, c;
    int d=date;

    if (month==1||month==2)
    {
         y=((year-1)%100);
         c=(year-1)/100;
    }
    else
    {
         y=year%100;
         c=year/100;
    }
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

How to send a message to a particular client with socket.io

In a project of our company we are using "rooms" approach and it's name is a combination of user ids of all users in a conversation as a unique identifier (our implementation is more like facebook messenger), example:

|id | name |1 | Scott |2 | Susan

"room" name will be "1-2" (ids are ordered Asc.) and on disconnect socket.io automatically cleans up the room

this way you send messages just to that room and only to online (connected) users (less packages sent throughout the server).

How do I uninstall a package installed using npm link?

If you've done something like accidentally npm link generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.

git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;

Simplest two-way encryption using PHP

Edited:

You should really be using openssl_encrypt() & openssl_decrypt()

As Scott says, Mcrypt is not a good idea as it has not been updated since 2007.

There is even an RFC to remove Mcrypt from PHP - https://wiki.php.net/rfc/mcrypt-viking-funeral

What is the easiest way to remove all packages installed by pip?

In my case, I had accidentally installed a number of packages globally using a Homebrew-installed pip on macOS. The easiest way to revert to the default packages was a simple:

$ brew reinstall python

Or, if you were using pip3:

$ brew reinstall python3

C# how to wait for a webpage to finish loading before continuing

If you are using the InternetExplorer.Application COM object, check the ReadyState property for the value of 4.

HAProxy redirecting http to https (ssl)

The best guaranteed way to redirect everything http to https is:

frontend http-in
   bind *:80
   mode http
   redirect scheme https code 301

This is a little fancier using ‘code 301', but might as well let the client know it’s permanent. The ‘mode http’ part is not essential with default configuration, but can’t hurt. If you have mode tcp in defaults section (like I did), then it’s necessary.

How to solve error message: "Failed to map the path '/'."

You don't have to reset IIS, you can just recycle the app pool.

Regular cast vs. static_cast vs. dynamic_cast

Static cast

The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char.
char c = 10;       // 1 byte
int *p = (int*)&c; // 4 bytes

Since this results in a 4-byte pointer pointing to 1 byte of allocated memory, writing to this pointer will either cause a run-time error or will overwrite some adjacent memory.

*p = 5; // run-time error: stack corruption

In contrast to the C-style cast, the static cast will allow the compiler to check that the pointer and pointee data types are compatible, which allows the programmer to catch this incorrect pointer assignment during compilation.

int *q = static_cast<int*>(&c); // compile-time error

Reinterpret cast

To force the pointer conversion, in the same way as the C-style cast does in the background, the reinterpret cast would be used instead.

int *r = reinterpret_cast<int*>(&c); // forced conversion

This cast handles conversions between certain unrelated types, such as from one pointer type to another incompatible pointer type. It will simply perform a binary copy of the data without altering the underlying bit pattern. Note that the result of such a low-level operation is system-specific and therefore not portable. It should be used with caution if it cannot be avoided altogether.

Dynamic cast

This one is only used to convert object pointers and object references into other pointer or reference types in the inheritance hierarchy. It is the only cast that makes sure that the object pointed to can be converted, by performing a run-time check that the pointer refers to a complete object of the destination type. For this run-time check to be possible the object must be polymorphic. That is, the class must define or inherit at least one virtual function. This is because the compiler will only generate the needed run-time type information for such objects.

Dynamic cast examples

In the example below, a MyChild pointer is converted into a MyBase pointer using a dynamic cast. This derived-to-base conversion succeeds, because the Child object includes a complete Base object.

class MyBase 
{ 
  public:
  virtual void test() {}
};
class MyChild : public MyBase {};



int main()
{
  MyChild *child = new MyChild();
  MyBase  *base = dynamic_cast<MyBase*>(child); // ok
}

The next example attempts to convert a MyBase pointer to a MyChild pointer. Since the Base object does not contain a complete Child object this pointer conversion will fail. To indicate this, the dynamic cast returns a null pointer. This gives a convenient way to check whether or not a conversion has succeeded during run-time.

MyBase  *base = new MyBase();
MyChild *child = dynamic_cast<MyChild*>(base);

 
if (child == 0) 
std::cout << "Null pointer returned";

If a reference is converted instead of a pointer, the dynamic cast will then fail by throwing a bad_cast exception. This needs to be handled using a try-catch statement.

#include <exception>
// …  
try
{ 
  MyChild &child = dynamic_cast<MyChild&>(*base);
}
catch(std::bad_cast &e) 
{ 
  std::cout << e.what(); // bad dynamic_cast
}

Dynamic or static cast

The advantage of using a dynamic cast is that it allows the programmer to check whether or not a conversion has succeeded during run-time. The disadvantage is that there is a performance overhead associated with doing this check. For this reason using a static cast would have been preferable in the first example, because a derived-to-base conversion will never fail.

MyBase *base = static_cast<MyBase*>(child); // ok

However, in the second example the conversion may either succeed or fail. It will fail if the MyBase object contains a MyBase instance and it will succeed if it contains a MyChild instance. In some situations this may not be known until run-time. When this is the case dynamic cast is a better choice than static cast.

// Succeeds for a MyChild object
MyChild *child = dynamic_cast<MyChild*>(base);

If the base-to-derived conversion had been performed using a static cast instead of a dynamic cast the conversion would not have failed. It would have returned a pointer that referred to an incomplete object. Dereferencing such a pointer can lead to run-time errors.

// Allowed, but invalid
MyChild *child = static_cast<MyChild*>(base);
 
// Incomplete MyChild object dereferenced
(*child);

Const cast

This one is primarily used to add or remove the const modifier of a variable.

const int myConst = 5;
int *nonConst = const_cast<int*>(&myConst); // removes const

Although const cast allows the value of a constant to be changed, doing so is still invalid code that may cause a run-time error. This could occur for example if the constant was located in a section of read-only memory.

*nonConst = 10; // potential run-time error

Const cast is instead used mainly when there is a function that takes a non-constant pointer argument, even though it does not modify the pointee.

void print(int *p) 
{
   std::cout << *p;
}

The function can then be passed a constant variable by using a const cast.

print(&myConst); // error: cannot convert 
                 // const int* to int*
 
print(nonConst); // allowed

Source and More Explanations

Oracle database: How to read a BLOB?

What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?

And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.

I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.

MVC 4 client side validation not working

  @section Scripts
 {
<script src="../Scripts/jquery.validate-vsdoc.js"></script>
<script src="../Scripts/jquery.validate.js"></script>
<script src="../Scripts/jquery.validate.min.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.js"></script>
<script src="../Scripts/jquery.validate.unobtrusive.min.js"></script>
}

Get the current first responder without using a private API

The first responder can be any instance of the class UIResponder, so there are other classes that might be the first responder despite the UIViews. For example UIViewController might also be the first responder.

In this gist you will find a recursive way to get the first responder by looping through the hierarchy of controllers starting from the rootViewController of the application's windows.

You can retrieve then the first responder by doing

- (void)foo
{
    // Get the first responder
    id firstResponder = [UIResponder firstResponder];

    // Do whatever you want
    [firstResponder resignFirstResponder];      
}

However, if the first responder is not a subclass of UIView or UIViewController, this approach will fail.

To fix this problem we can do a different approach by creating a category on UIResponder and perform some magic swizzeling to be able to build an array of all living instances of this class. Then, to get the first responder we can simple iterate and ask each object if -isFirstResponder.

This approach can be found implemented in this other gist.

Hope it helps.

disable editing default value of text input

I'm not sure I understand the question correctly, but if you want to prevent people from writing in the input field you can use the disabled attribute.

<input disabled="disabled" id="price_from" value="price from ">

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How to save a plot as image on the disk?

If you want to keep seeing the plot in R, another option is to use dev.copy:

X11 ()
plot (x,y)

dev.copy(jpeg,filename="plot.jpg");
dev.off ();

If you reach a clutter of too many plot windows in R, use graphics.off() to close all of the plot windows.

How to link to specific line number on github

Many editors (but also see the Commands section below) support linking to a file's line number or range on GitHub or BitBucket (or others). Here's a short list:

Atom

Open on GitHub

Emacs

git-link

Sublime Text

GitLink

Vim

gitlink-vim


Commands

  • git-link - Git subcommand for getting a repo-browser link to a git object
  • ghwd - Open the github URL that matches your shell's current branch and working directory

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

The icon will adopt the color from value of the color css property of it's parent.

You can either add this directly to the style:

<span class="glyphicon glyphicon-user" style="color:blue"></span>

Or you can add it as a class to your icon and then set the font color to it in CSS

HTML

<span class="glyphicon glyphicon-search"></span>
<span class="glyphicon glyphicon-user blue"></span>
<span class="glyphicon glyphicon-trash"></span>

CSS

.blue {
    color: blue;
}

This fiddle has an example.

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

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "AnotherViewController")
        self.navigationController?.pushViewController(controller, animated: true)

    }

}



import UIKit
class AnotherViewController: UIViewController {

    var name : String!

    deinit {
        print("Deint AnotherViewController")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(CFGetRetainCount(self))

        /*
            When you test please comment out or vice versa

         */

//        // Should not use unowned here. Because unowned is used where not deallocated. or gurranted object alive. If you immediate click back button app will crash here. Though there will no retain cycles
//        clouser(string: "") { [unowned self] (boolValue)  in
//            self.name = "some"
//        }
//


//
//        // There will be a retain cycle. because viewcontroller has a strong refference to this clouser and as well as clouser (self.name) has a strong refferennce to the viewcontroller. Deint AnotherViewController will not print
//        clouser(string: "") { (boolValue)  in
//            self.name = "some"
//        }
//
//


//        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser (self.name) has a weak refferennce to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
//
//        clouser(string: "") { [weak self] (boolValue)  in
//            self?.name = "some"
//        }


        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser nos refference to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)

        clouser(string: "") {  (boolValue)  in
            print("some")
            print(CFGetRetainCount(self))

        }

    }


    func clouser(string: String, completion: @escaping (Bool) -> ()) {
        // some heavy task
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            completion(true)
        }

    }

}

If you do not sure about [unowned self] then use [weak self]

wait until all threads finish their work in java

You do

for (Thread t : new Thread[] { th1, th2, th3, th4, th5 })
    t.join()

After this for loop, you can be sure all threads have finished their jobs.

How to disable spring security for particular url

This may be not the full answer to your question, however if you are looking for way to disable csrf protection you can do:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/web/admin/**").hasAnyRole(ADMIN.toString(), GUEST.toString())
                .anyRequest().permitAll()
                .and()
                .formLogin().loginPage("/web/login").permitAll()
                .and()
                .csrf().ignoringAntMatchers("/contact-email")
                .and()
                .logout().logoutUrl("/web/logout").logoutSuccessUrl("/web/").permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles(ADMIN.toString())
                .and()
                .withUser("guest").password("guest").roles(GUEST.toString());
    }

}

I have included full configuration but the key line is:

.csrf().ignoringAntMatchers("/contact-email")

Git:nothing added to commit but untracked files present

Please Follow this process

First of all install git bash and create a repository on git

1) Go to working directory where the file exist which you want to push on remote and create .git folder by

$ git init

2) Add the files in your new local repository.

$ git add .

Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity

3) Commit the files that you've staged in your local repository.

$ git commit -m "First commit"**

4) after this go to git repository and copy remote URL

$ git remote add origin *remote repository URL

5)

$ git remote -v

Note: this will ask for user.email and user.name just put it as per config

6)

$ git push origin master

this will push whole committed code to FILE.git on repository

And I think we done

How to parse unix timestamp to time.Time

According to the go documentation, Unix returns a local time.

Unix returns the local Time corresponding to the given Unix time

This means the output would depend on the machine your code runs on, which, most often is what you need, but sometimes, you may want to have the value in UTC.

To do so, I adapted the snippet to make it return a time in UTC:

i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
    panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm.UTC())

This prints on my machine (in CEST)

2014-07-16 20:55:46 +0000 UTC

java: Class.isInstance vs Class.isAssignableFrom

For brevity, we can understand these two APIs like below:

  1. X.class.isAssignableFrom(Y.class)

If X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

  1. X.class.isInstance(y)

Say y is an instance of class Y, if X and Y are the same class, or X is Y's super class or super interface, return true, otherwise, false.

Get the _id of inserted document in Mongo database in NodeJS

As ktretyak said, to get inserted document's ID best way is to use insertedId property on result object. In my case result._id didn't work so I had to use following:

db.collection("collection-name")
  .insertOne(document)
  .then(result => {
    console.log(result.insertedId);
  })
  .catch(err => {
    // handle error
  });

It's the same thing if you use callbacks.

Can we rely on String.isEmpty for checking null condition on a String in Java?

You can't use String.isEmpty() if it is null. Best is to have your own method to check null or empty.

public static boolean isBlankOrNull(String str) {
    return (str == null || "".equals(str.trim()));
}

Replace string within file contents

If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.

Xpath for href element

have you tried:

//a[@id='oldcontent']/u[text()='Re-Call']

Sorting objects by property values

Let us say we have to sort a list of objects in ascending order based on a particular property, in this example lets say we have to sort based on the "name" property, then below is the required code :

var list_Objects = [{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}];
Console.log(list_Objects);   //[{"name"="Bob"},{"name"="Jay"},{"name"="Abhi"}]
    list_Objects.sort(function(a,b){
        return a["name"].localeCompare(b["name"]); 
    });
Console.log(list_Objects);  //[{"name"="Abhi"},{"name"="Bob"},{"name"="Jay"}]

Install python 2.6 in CentOS

When you install your python version (in this case it is python2.6) then issue this command to create your virtualenv:

virtualenv -p /usr/bin/python2.6 /your/virtualenv/path/here/

Best way to overlay an ESRI shapefile on google maps?

I would not use KML. Instead, use GeoJSON which you can natively consume in Google Maps API now. It is a newer feature that didn't exist from the original responses.

In any case, simply open the SHP file in Quantum GIS, and then you can output it in any format you like (KML, GeoJSON).

If you are using Google Maps for Work, I found a premium extension that handles loading shapefiles directly where you can just connect direct to the shapefile that you generate from ESRI. I did a search on the CMaps site and found this snippet which loaded US by state shapefile: https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp

var cMap = new centigon.locationIntelligence.MapView();
    cMap.key([your_api_key]);


    cMap.layerNames(["Basic Shapes"]);
    cMap.dbfKeys([['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']]);
    cMap.userShapeKeys([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 
    cMap.labels([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 

    cMap.polyDataSources([centigon.locationIntelligence.CMapAnalytics.DATA_PROVIDERS.SHAPE_DATAPROVIDER]);
    cMap.layerTypes([centigon.mapping.Layer.TYPE.POLY]);
    cMap.locations([["https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp"]]);

    cMap.panTo("USA");
    cMap.zoomLevel(3);

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them.

There are different types of joins available in SQL:

INNER JOIN: returns rows when there is a match in both tables.

LEFT JOIN: returns all rows from the left table, even if there are no matches in the right table.

RIGHT JOIN: returns all rows from the right table, even if there are no matches in the left table.

FULL JOIN: It combines the results of both left and right outer joins.

The joined table will contain all records from both the tables and fill in NULLs for missing matches on either side.

SELF JOIN: is used to join a table to itself as if the table were two tables, temporarily renaming at least one table in the SQL statement.

CARTESIAN JOIN: returns the Cartesian product of the sets of records from the two or more joined tables.

WE can take each first four joins in Details :

We have two tables with the following values.

TableA

id  firstName                  lastName
.......................................
1   arun                        prasanth                 
2   ann                         antony                   
3   sruthy                      abc                      
6   new                         abc                                           

TableB

id2 age Place
................
1   24  kerala
2   24  usa
3   25  ekm
5   24  chennai

....................................................................

INNER JOIN

Note :it gives the intersection of the two tables, i.e. rows they have common in TableA and TableB

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 INNER JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 INNER JOIN TableB
    ON TableA.id = TableB.id2;

Result Will Be

firstName       lastName       age  Place
..............................................
arun            prasanth        24  kerala
ann             antony          24  usa
sruthy          abc             25  ekm

LEFT JOIN

Note : will give all selected rows in TableA, plus any common selected rows in TableB.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  LEFT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  LEFT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age   Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL

RIGHT JOIN

Note : will give all selected rows in TableB, plus any common selected rows in TableA.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
 RIGHT JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
 RIGHT JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age     Place
...............................................................................
arun                        prasanth                    24     kerala
ann                         antony                      24     usa
sruthy                      abc                         25     ekm
NULL                        NULL                        24     chennai

FULL JOIN

Note :It will return all selected values from both tables.

Syntax

SELECT table1.column1, table2.column2...
  FROM table1
  FULL JOIN table2
    ON table1.common_field = table2.common_field;

Apply it in our sample table :

SELECT TableA.firstName,TableA.lastName,TableB.age,TableB.Place
  FROM TableA
  FULL JOIN TableB
    ON TableA.id = TableB.id2;

Result

firstName                   lastName                    age    Place
...............................................................................
arun                        prasanth                    24    kerala
ann                         antony                      24    usa
sruthy                      abc                         25    ekm
new                         abc                         NULL  NULL
NULL                        NULL                        24    chennai

Interesting Fact

For INNER joins the order doesn't matter

For (LEFT, RIGHT or FULL) OUTER joins,the order matter

Better to go check this Link it will give you interesting details about join order

Initialize a long in Java

You need to add uppercase L at the end like so

long i = 12345678910L;

Same goes true for float with 3.0f

Which should answer both of your questions

Using setattr() in python

I'm here in general only to find out that through dict it is necessary to work inside setattr XD

Angular.js directive dynamic templateURL

I have an example about this.

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>

  <body>
    <div class="container-fluid body-content" ng-controller="formView">
        <div class="row">
            <div class="col-md-12">
                <h4>Register Form</h4>
                <form class="form-horizontal" ng-submit="" name="f" novalidate>
                    <div ng-repeat="item in elements" class="form-group">
                        <label>{{item.Label}}</label>
                        <element type="{{item.Type}}" model="item"></element>
                    </div>
                    <input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
                </form>
            </div>
        </div>
    </div>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
    <script src="app.js"></script>
  </body>

</html>

angular.module('app', [])
    .controller('formView', function ($scope) {
        $scope.elements = [{
            "Id":1,
            "Type":"textbox",
            "FormId":24,
            "Label":"Name",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":false,
            "Options":null,
            "SelectedOption":null
          },
          {
            "Id":2,
            "Type":"textarea",
            "FormId":24,
            "Label":"AD2",
            "PlaceHolder":"Place Holder Text",
            "Max":20,
            "Required":true,
            "Options":null,
            "SelectedOption":null
        }];
    })
    .directive('element', function () {
        return {
            restrict: 'E',
            link: function (scope, element, attrs) {
                scope.contentUrl = attrs.type + '.html';
                attrs.$observe("ver", function (v) {
                    scope.contentUrl = v + '.html';
                });
            },
            template: '<div ng-include="contentUrl"></div>'
        }
    })

UICollectionView - Horizontal scroll, horizontal layout?

From @Erik Hunter, I post full code for make horizontal UICollectionView

UICollectionViewFlowLayout *collectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
[collectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
self.myCollectionView.collectionViewLayout = collectionViewFlowLayout;

In Swift

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
self.myCollectionView.collectionViewLayout = layout

In Swift 3.0

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
self.myCollectionView.collectionViewLayout = layout

Hope this help

H2 in-memory database. Table not found

Hard to tell. I created a program to test this:

package com.gigaspaces.compass;

import org.testng.annotations.Test;

import java.sql.*;

public class H2Test {
@Test
public void testDatabaseNoMem() throws SQLException {
    testDatabase("jdbc:h2:test");
}
@Test
public void testDatabaseMem() throws SQLException {
    testDatabase("jdbc:h2:mem:test");
}

private void testDatabase(String url) throws SQLException {
    Connection connection= DriverManager.getConnection(url);
    Statement s=connection.createStatement();
    try {
    s.execute("DROP TABLE PERSON");
    } catch(SQLException sqle) {
        System.out.println("Table not found, not dropping");
    }
    s.execute("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
    PreparedStatement ps=connection.prepareStatement("select * from PERSON");
    ResultSet r=ps.executeQuery();
    if(r.next()) {
        System.out.println("data?");
    }
    r.close();
    ps.close();
    s.close();
    connection.close();
}
}

The test ran to completion, with no failures and no unexpected output. Which version of h2 are you running?

How to remove all click event handlers using jQuery?

If you used...

$(function(){
    function myFunc() {
        // ... do something ...
    };
    $('#saveBtn').click(myFunc);
});

... then it will be easier to unbind later.

How can I generate a list or array of sequential integers in Java?

This one might works for you....

void List<Integer> makeSequence(int begin, int end) {

  AtomicInteger ai=new AtomicInteger(begin);
  List<Integer> ret = new ArrayList(end-begin+1);

  while ( end-->begin) {

    ret.add(ai.getAndIncrement());

  }
  return ret;  
}

Android design support library for API 28 (P) not working

Important Update

Android will not update support libraries after 28.0.0.

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0.

So use library AndroidX.

  • Don't use both Support and AndroidX in project.
  • Your library module or dependencies can still have support libraries. Androidx Jetifier will handle it.
  • Use stable version of androidx or any library, because alpha, beta, rc can have bugs which you dont want to ship with your app.

In your case

dependencies {
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.1'

    implementation 'com.google.android.material:material:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
}

how to convert from int to char*?

You also can use casting.

example:

string s;
int value = 3;
s.push_back((char)('0' + value));

Force Java timezone as GMT/UTC

If you would like to get GMT time only with intiger: var currentTime = new Date(); var currentYear ='2010' var currentMonth = 10; var currentDay ='30' var currentHours ='20' var currentMinutes ='20' var currentSeconds ='00' var currentMilliseconds ='00'

currentTime.setFullYear(currentYear);
currentTime.setMonth((currentMonth-1)); //0is January
currentTime.setDate(currentDay);  
currentTime.setHours(currentHours);
currentTime.setMinutes(currentMinutes);
currentTime.setSeconds(currentSeconds);
currentTime.setMilliseconds(currentMilliseconds);

var currentTimezone = currentTime.getTimezoneOffset();
currentTimezone = (currentTimezone/60) * -1;
var gmt ="";
if (currentTimezone !== 0) {
  gmt += currentTimezone > 0 ? ' +' : ' ';
  gmt += currentTimezone;
}
alert(gmt)

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

To bypass this issue, we can use The Navigation Architecture Component , which was introduced in Google I/O 2018. The Navigation Architecture Component simplifies the implementation of navigation in an Android app.

How to create and download a csv file from php script?

Use the below code to convert a php array to CSV

<?php
   $ROW=db_export_data();//Will return a php array
   header("Content-type: application/csv");
   header("Content-Disposition: attachment; filename=test.csv");
   $fp = fopen('php://output', 'w');

   foreach ($ROW as $row) {
        fputcsv($fp, $row);
   }
   fclose($fp);

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

What is the difference between i++ and ++i?

int i = 0;
Console.WriteLine(i++); // Prints 0. Then value of "i" becomes 1.
Console.WriteLine(--i); // Value of "i" becomes 0. Then prints 0.

Does this answer your question ?

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

There may be a problem with Maven path configuration, if you used unix-like Operator System.

step 1: create new file in path ~/.bash_profile

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home
CLASSPAHT=.:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
PATH=$JAVA_HOME/bin:$PATH:
export JAVA_HOME
export CLASSPATH
export PATH

step 2: shell run source ~/.bash_profile OR modify zsh config file(add new line: source ~/.bash_profile)

Java Project: Failed to load ApplicationContext

I had the same problem, and I was using the following plugin for tests:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <useFile>true</useFile>
        <includes>
            <include>**/*Tests.java</include>
            <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
        <junitArtifactName>junit:junit</junitArtifactName>
        <parallel>methods</parallel>
        <threadCount>10</threadCount>
    </configuration>
</plugin>

The test were running fine in the IDE (eclipse sts), but failed when using command mvn test.

After a lot of trial and error, I figured the solution was to remove parallel testing, the following two lines from the plugin configuration above:

    <parallel>methods</parallel>
    <threadCount>10</threadCount>

Hope that this helps someone out!

How do I remove objects from an array in Java?

Arrgh, I can't get the code to show up correctly. Sorry, I got it working. Sorry again, I don't think I read the question properly.

String  foo[] = {"a","cc","a","dd"},
remove = "a";
boolean gaps[] = new boolean[foo.length];
int newlength = 0;

for (int c = 0; c<foo.length; c++)
{
    if (foo[c].equals(remove))
    {
        gaps[c] = true;
        newlength++;
    }
    else 
        gaps[c] = false;

    System.out.println(foo[c]);
}

String newString[] = new String[newlength];

System.out.println("");

for (int c1=0, c2=0; c1<foo.length; c1++)
{
    if (!gaps[c1])
    {
        newString[c2] = foo[c1];
        System.out.println(newString[c2]);
        c2++;
    }
}

How to change sender name (not email address) when using the linux mail command for autosending mail?

You just need to add a From: header. By default there is none.

echo "Test" | mail -a "From: Someone <[email protected]>" [email protected]

You can add any custom headers using -a:

echo "Test" | mail -a "From: Someone <[email protected]>" \
                   -a "Subject: This is a test" \
                   -a "X-Custom-Header: yes" [email protected]

Where is the application.properties file in a Spring Boot project?

Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:

  1. The classpath root
  2. The classpath /config package
  3. The current directory
  4. The /config subdirectory in the current directory
  5. Immediate child directories of the /config subdirectory

The list is ordered by precedence (with values from lower items overriding earlier ones).

More info you can find here https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-files

How to call a .NET Webservice from Android using KSOAP2?

You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet"); by DocumentElement

private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use   IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try {
    androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
    e.printStackTrace();
} //Next task is to get Response and format that response

SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");

for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
    obj3 = (SoapObject) obj2.getProperty(i);
    obj3.getProperty(0).toString(); //value of column 1
    obj3.getProperty(1).toString(); //value of column 2
    //like that you will get value from each column
}

If you have any problem regarding this you can write me..

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Error: SSL certificate problem: self signed certificate in certificate chain

Solution:
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);    
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string to either int or Guid, if you're still getting

EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.

EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.

you probably just forgot to specify the new key type on IdentityDbContext:

public class AppIdentityDbContext : IdentityDbContext<
    AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
    public AppIdentityDbContext()
        : base("MY_CONNECTION_STRING")
    {
    }
    ......
}

If you just have

public class AppIdentityDbContext : IdentityDbContext
{
    ......
}

or even

public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
    ......
}

you will get that 'no key defined' error when you are trying to add migrations or update the database.

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user)

Update: I've since written a very detailed explanation of the various ways you can install Ruby gems on a Mac. My original recommendation to use a script still stands, but my article goes into more detail: https://www.moncefbelyamani.com/the-definitive-guide-to-installing-ruby-gems-on-a-mac/

You are correct that macOS won't let you change anything with the Ruby version that comes installed with your Mac. However, it's possible to install gems like bundler using a separate version of Ruby that doesn't interfere with the one provided by Apple.

Using sudo to install gems, or changing permissions of system files and directories is strongly discouraged, even if you know what you are doing. Can we please stop providing this bad advice? Here's a detailed article I wrote showing how sudo gem install can wipe out your computer: https://www.moncefbelyamani.com/why-you-should-never-use-sudo-to-install-ruby-gems/

The solution involves two main steps:

  1. Install a separate version of Ruby that does not interfere with the one that came with your Mac.
  2. Update your PATH such that the location of the new Ruby version is first in the PATH. Some tools do this automatically for you. If you're not familiar with the PATH and how it works, read my guide.

There are several ways to install Ruby on a Mac. The best way that I recommend, and that I wish was more prevalent in the various installation instructions out there, is to use an automated script that will set up a proper Ruby environment for you. This drastically reduces the chances of running into an error due to inadequate instructions that make the user do a bunch of stuff manually and leaving it up to them to figure out all the necessary steps.

The other route you can take is to spend extra time doing everything manually and hoping for the best. First, you will want to install Homebrew, which installs the prerequisite command line tools, and makes it easy to install other necessary tools.

Then, the two easiest ways to install a separate version of Ruby are:

If you would like the flexibility of easily switching between many Ruby versions [RECOMMENDED]

Choose one of these four options:

  • chruby and ruby-install - my personal recommendations and the ones that are automatically installed by my script. These can be installed with Homebrew:
brew install chruby ruby-install

If you chose chruby and ruby-install, you can then install the latest Ruby like this:

ruby-install ruby

Once you've installed everything and configured your .zshrc or .bash_profile according to the instructions from the tools above, quit and restart Terminal, then switch to the version of Ruby that you want. In the case of chruby, it would be something like this:

chruby 2.7.2

Whether you need to configure .zshrc or .bash_profile depends on which shell you are using. If you're not sure, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

If you know for sure you don't need more than one version of Ruby at the same time (besides the one that came with macOS)

  • Install ruby with Homebrew:
brew install ruby

Then update your PATH by running (replace 2.7.0 with your newly installed version):

echo 'export PATH="/usr/local/opt/ruby/bin:/usr/local/lib/ruby/gems/2.7.0/bin:$PATH"' >> ~/.zshrc

Then "refresh" your shell for these changes to take effect:

source ~/.zshrc

Or you can open a new terminal tab, or quit and restart Terminal.

Replace .zshrc with .bash_profile if you are using Bash. If you're not sure which shell you are using, read this guide: https://www.moncefbelyamani.com/which-shell-am-i-using-how-can-i-switch/

To check that you're now using the non-system version of Ruby, you can run the following commands:

which ruby

It should be something other than /usr/bin/ruby

ruby -v

It should be something other than 2.6.3 if you're on macOS Catalina. As of today, 2.7.2 is the latest Ruby version.

Once you have this new version of Ruby installed, you can now install bundler (or any other gem):

gem install bundler

ASP.NET MVC - Find Absolute Path to the App_Data folder from Controller

I try to get in the habit of using HostingEnvironment instead of Server as it works within the context of WCF services too.

 HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");

Opening A Specific File With A Batch File?

you are in a situation where you cannot set a certain program as the default program to use when opening a certain type of file, I've found using a .bat file handy. In my case, Textpad runs on my machine via Microsoft Application Virtualization ("AppV"). The path to Textpad is in an "AppV directory" so to speak. My Textpad AppV shortcut has this as a target...

%ALLUSERSPROFILE%\Microsoft\AppV\Client\Integration\
 12345ABC-A1BC-1A23-1A23-1234567E1234\Root\TextPad.exe

To associate the textpad.exe with 'txt' files via a 'bat' file:

1) In Explorer, create a new ('txt') file and save as opentextpad.bat in an "appropriate" location

2) In the opentextpad.bat file, type this line:

textpad.exe %1  

3) Save and Close

4) In explorer, perform windows file association by right-clicking on a 'txt' file (e.g. 'dummy.txt') and choose 'Open with > Choose default program...' from the menu. In the 'Open with' window, click 'Browse...', then navigate to and select your textpad.bat file. Click 'Open'. You'll return to the 'Open with' window. Make sure to check the 'Always use the selected program to open this type of file' checkbox. Click 'OK' and the window will close.

When you open a 'txt' file now, it will open the file with 'textpad.exe'.

Hope this is useful.

Unknown SSL protocol error in connection

I was able to solve it by running

git config --list --show-origin

and then seeing that I had a line:

file:c:/Users/user/.gitconfig http.sslversion=sslv3

I edited the file, c:/Users/user/.gitconfig, and deleted the line [http] and the line sslversion=sslv3 and that fixed it for me.

Uppercase first letter of variable

You can use text-transform: capitalize; for this work -

HTML -

<input type="text" style="text-transform: capitalize;" />

JQuery -

$(document).ready(function (){
   var asdf = "WERTY UIOP";
   $('input').val(asdf.toLowerCase());
});

Try This

Note: It's only change visual representation of the string. If you alert this string it's always show original value of the string.

Is this the proper way to do boolean test in SQL?

A boolean in SQL is a bit field. This means either 1 or 0. The correct syntax is:

select * from users where active = 1 /* All Active Users */

or

select * from users where active = 0 /* All Inactive Users */

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

Get local IP address in Node.js

The correct one-liner for both Underscore.js and Lodash is:

var ip = require('underscore')
    .chain(require('os').networkInterfaces())
    .values()
    .flatten()
    .find({family: 'IPv4', internal: false})
    .value()
    .address;

React JS - Uncaught TypeError: this.props.data.map is not a function

It happens because the component is rendered before the async data arrived, you should control before to render.

I resolved it in this way:

render() {
    let partners = this.props && this.props.partners.length > 0 ?
        this.props.partners.map(p=>
            <li className = "partners" key={p.id}>
                <img src={p.img} alt={p.name}/> {p.name} </li>
        ) : <span></span>;

    return (
        <div>
            <ul>{partners}</ul>
        </div>
    );
}
  • Map can not resolve when the property is null/undefined, so I did a control first

this.props && this.props.partners.length > 0 ?

R adding days to a date

In addition to the simple addition shown by others, you can also use seq.Date or seq.POSIXt to find other increments or decrements (the POSIXt version does seconds, minutes, hours, etc.):

> seq.Date( Sys.Date(), length=2, by='3 months' )[2]
[1] "2012-07-25"

How can I check if a Perl module is installed on my system from the command line?

You can check for a module's installation path by:

perldoc -l XML::Simple

The problem with your one-liner is that, it is not recursively traversing directories/sub-directories. Hence, you get only pragmatic module names as output.

Horizontal ListView in Android?

For my application, I use a HorizontalScrollView containing LinearLayout inside, which has orientation set to horizontal. In order to add images inside, I create ImageViews inside the activity and add them to my LinearLayout. For example:

<HorizontalScrollView 
        android:id="@+id/photo_scroll"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:scrollbars="horizontal"
        android:visibility="gone">

        <LinearLayout 
            android:id="@+id/imageview_holder"
            android:layout_width="wrap_content"
            android:orientation="horizontal"
            android:layout_height="match_parent">

        </LinearLayout>
    </HorizontalScrollView>

An this works perfectly fine for me. In the activity all I have to do is something like the code below:

LinearLayout imgViewHolder = findViewById(R.id.imageview_holder);
ImageView img1 = new ImageView(getApplicationContext());
//set bitmap
//set img1 layout params
imgViewHolder.add(img1);
ImageView img2 = new ImageView(getApplicationContext());
//set bitmap
//set img2 layout params
imgViewHolder.add(img2); 

As I said that works for me, and I hope it helps somebody looking to achieve this as well.

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked.

So, you are getting a warning,

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property.

Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this:

  1. First close all the existing projects by right clicking in Project explorer.
  2. Remove all the projects already synchronized with the server.
  3. Remove the server and redeploy it.
  4. Create a new dynamic project, do nothing yet just try running this on the server.
  5. Check the console, do you get the warning now. (My case I didn't get any).
    This means that something is wrong with your project not with eclipse or the server.
  6. Now restart the server. Don't run any app yet.
    You probably know that the Tomcat container loads up context of all the synchronized apps at the start.
  7. It will load context of any already synchronized app.
  8. Here is the catch, if there is really something wrong in your project it will show the stack trace of the exceptions.Look carefully and you will find where is the bug in your app.

Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else.

And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one.

Why is Dictionary preferred over Hashtable in C#?

Dictionary:

  • It returns/throws Exception if we try to find a key which does not exist.

  • It is faster than a Hashtable because there is no boxing and unboxing.

  • Only public static members are thread safe.

  • Dictionary is a generic type which means we can use it with any data type (When creating, must specify the data types for both keys and values).

    Example: Dictionary<string, string> <NameOfDictionaryVar> = new Dictionary<string, string>();

  • Dictionay is a type-safe implementation of Hashtable, Keys and Values are strongly typed.

Hashtable:

  • It returns null if we try to find a key which does not exist.

  • It is slower than dictionary because it requires boxing and unboxing.

  • All the members in a Hashtable are thread safe,

  • Hashtable is not a generic type,

  • Hashtable is loosely-typed data structure, we can add keys and values of any type.

Passing an array to a query using a WHERE clause

We should take care of SQL injection vulnerabilities and an empty condition. I am going to handle both as below.

For a pure numeric array, use the appropriate type conversion viz intval or floatval or doubleval over each element. For string types mysqli_real_escape_string() which may also be applied to numeric values if you wish. MySQL allows numbers as well as date variants as string.

To appropriately escape the values before passing to the query, create a function similar to:

function escape($string)
{
    // Assuming $db is a link identifier returned by mysqli_connect() or mysqli_init()
    return mysqli_real_escape_string($db, $string);
}

Such a function would most likely be already available to you in your application, or maybe you've already created one.

Sanitize the string array like:

$values = array_map('escape', $gallaries);

A numeric array can be sanitized using intval or floatval or doubleval instead as suitable:

$values = array_map('intval', $gallaries);

Then finally build the query condition

$where  = count($values) ? "`id` = '" . implode("' OR `id` = '", $values) . "'" : 0;

or

$where  = count($values) ? "`id` IN ('" . implode("', '", $values) . "')" : 0;

Since the array can also be empty sometimes, like $galleries = array(); we should therefore note that IN () does not allow for an empty list. One can also use OR instead, but the problem remains. So the above check, count($values), is to ensure the same.

And add it to the final query:

$query  = 'SELECT * FROM `galleries` WHERE ' . $where;

TIP: If you want to show all records (no filtering) in case of an empty array instead of hiding all rows, simply replace 0 with 1 in the ternary's false part.

Difference between break and continue statement

A break statement results in the termination of the statement to which it applies (switch, for, do, or while).

A continue statement is used to end the current loop iteration and return control to the loop statement.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

AngularJS: How to run additional code after AngularJS has rendered a template?

You can use the 'jQuery Passthrough' module of the angular-ui utils. I successfully binded a jQuery touch carousel plugin to some images that I retrieve async from a web service and render them with ng-repeat.

Unable to cast object of type 'System.DBNull' to type 'System.String`

I use an extension to eliminate this problem for me, which may or may not be what you are after.

It goes like this:

public static class Extensions
{

    public String TrimString(this object item)
    {
        return String.Format("{0}", item).Trim();
    }

}

Note:

This extension does not return null values! If the item is null or DBNull.Value, it will return an empty String.

Usage:

public string GetCustomerNumber(Guid id)
{
    var obj = 
        DBSqlHelperFactory.ExecuteScalar(
            connectionStringSplendidmyApp, 
            CommandType.StoredProcedure, 
            "GetCustomerNumber", 
            new SqlParameter("@id", id)
        );
    return obj.TrimString();
}

Double precision - decimal places

In most contexts where double values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.

In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.

How to do an INNER JOIN on multiple columns

You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

SELECT 
    airline, flt_no, fairport, tairport, depart, arrive, fare
FROM 
    flights
INNER JOIN 
    airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
    airports to_port ON (to_port.code = flights.tairport)
WHERE 
    from_port.code = '?' OR to_port.code = '?' OR airports.city='?'

Note that the to_port and from_port are aliases for the first and second copies of the airports table.

C# Public Enums in Classes

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

What is a mutex?

When you have a multi-threaded application, the different threads sometimes share a common resource, such as a variable or similar. This shared source often cannot be accessed at the same time, so a construct is needed to ensure that only one thread is using that resource at a time.

The concept is called "mutual exclusion" (short Mutex), and is a way to ensure that only one thread is allowed inside that area, using that resource etc.

How to use them is language specific, but is often (if not always) based on a operating system mutex.

Some languages doesn't need this construct, due to the paradigm, for example functional programming (Haskell, ML are good examples).

Function is not defined - uncaught referenceerror

You must write that function body outside the ready();

because ready is used to call a function or to bind a function with binding id like this.

$(document).ready(function() {
    $("Some id/class name").click(function(){
        alert("i'm in");
    });
});

but you can't do this if you are calling "showAmount" function onchange/onclick event

$(document).ready(function() {
    function showAmount(value){
        alert(value);
    }

});

You have to write "showAmount" outside the ready();

function showAmount(value){
    alert(value);//will be called on event it is bind with
}
$(document).ready(function() {
    alert("will display on page load")
});

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

Query the sysdepends table:

SELECT distinct schema_name(dependentObject.uid) as schema, 
       dependentObject.*
 FROM sysdepends d 
INNER JOIN sysobjects o on d.id = o.id 
INNER JOIN sysobjects dependentObject on d.depid = dependentObject.id
WHERE o.name = 'TableName'

A way to look just for views/functions/triggers/procedures that reference the object (or any given text) by name is:

SELECT distinct schema_name(so.uid) + '.' + so.name 
  FROM syscomments sc 
 INNER JOIN  sysobjects so on sc.id = so.id 
 WHERE sc.text like '%Name%'

How to install MySQLi on MacOS

sudo apt-get -y -f install php7.0-mysql

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

In a separate terminal, connect your device to the computer and run the following commands:

react-native start 
cd user/Library/Android/sdk/platform-tools/
./adb reverse tcp:8081 tcp:8081

Application terminal:

react-native run-android 
install apk on your device from this location android/app/build/outputs/apk/app-debug.apk

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Sending a file over TCP sockets in Python

Client need to notify that it finished sending, using socket.shutdown (not socket.close which close both reading/writing part of the socket):

...
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()

UPDATE

Client sends Hello server! to the server; which is written to the file in the server side.

s.send("Hello server!")

Remove above line to avoid it.

Javascript to stop HTML5 video playback on modal window close

None of these worked for me using 4.1 video.js CDN. This code kills the video playing in a modal when the (.closemodal) is clicked. I had 3 videos. Someone else can refactor.


var myPlayer = videojs("my_video_1");
var myPlayer2 = videojs("my_video_2");
var myPlayer3 = videojs("my_video_3");
$(".closemodal").click(function(){
   myPlayer.pause();
myPlayer2.pause();
myPlayer3.pause();
});
});

as per their Api docs.

Bootstrap 3 dropdown select

We just switched our site to bootstrap 3 and we have a bunch of forms...wasn't fun but once you get the hang it's not too bad.

Is this what you are looking for? Demo Here

<div class="form-group">
  <label class="control-label col-sm-offset-2 col-sm-2" for="company">Company</label>
  <div class="col-sm-6 col-md-4">
    <select id="company" class="form-control">
      <option>small</option>
      <option>medium</option>
      <option>large</option>
    </select> 
  </div>
</div>

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_

git error: failed to push some refs to remote

For sourcetree users

First do an initial commit or make sure you have no uncommited changes, then at the side of sourcetree there is a "REMOTES", right-click on it, and then click 'Push to origin'. There you go.

What do \t and \b do?

\t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

When a 'blur' event occurs, how can I find out which element focus went *to*?

Can you reverse what you're checking and when? That is if you remeber what was blurred last:

<input id="myInput" onblur="lastBlurred=this;"></input>

and then in the onClick for your span, call function() with both objects:

<span id="mySpan" onClick="function(lastBlurred, this);">Hello World</span>

Your function could then decide whether or not to trigger the Ajax.AutoCompleter control. The function has the clicked object and the blurred object. The onBlur has already happened so it won't make the suggestions disappear.

Program "make" not found in PATH

Additional hint: If you have multiple projects with different toolchains open, check the build console header for the failing project's path.

I've just spent half an hour trying to fix a build that showed this error because another project with hopelessly outdated toolchain settings was open in the same workbench. Closing the other project re-enabled the build.