Programs & Examples On #Nsproxy

Does my application "contain encryption"?

I found this FAQ from the US Bureau of Industry and Security very helpful.

encryption

Question 15 (What is Note 4?) is the important point:

...

Examples of items that are excluded from Category 5, Part 2 by Note 4 include, but are not limited to, the following:

Consumer applications. Some examples:

piracy and theft prevention for software or music; music, movies, tunes/music, digital photos – players, recorders and organizers games/gaming – devices, runtime software, HDMI and other component interfaces, development tools LCD TV, Blu-ray / DVD, video on demand (VoD), cinema, digital video recorders (DVRs) / personal video recorders (PVRs) – devices, on-line media guides, commercial content integrity and protection, HDMI and other component interfaces (not videoconferencing); printers, copiers, scanners, digital cameras, Internet cameras – including parts and sub-assemblies household utilities and appliances

Check if application is installed - Android

If you want to try it without the try catch block, can use the following method, Create a intent and set the package of the app which you want to verify

val intent = Intent(Intent.ACTION_VIEW)
intent.data = uri
intent.setPackage("com.example.packageofapp")

and the call the following method to check if the app is installed

fun isInstalled(intent:Intent) :Boolean{
    val list = context.packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
    return list.isNotEmpty()
}

Reverse a string in Python

This is also an interesting way:

def reverse_words_1(s):
    rev = ''
    for i in range(len(s)):
        j = ~i  # equivalent to j = -(i + 1)
        rev += s[j]
    return rev

or similar:

def reverse_words_2(s):
    rev = ''
    for i in reversed(range(len(s)):
        rev += s[i]
    return rev

Another more 'exotic' way using byterarray which supports .reverse()

b = bytearray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')

will produce:

'!siht esreveR'

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

You can also change the pop-up options themselves, to be more convenient for your normal use. Summary:

  1. Run the SQL Management Studio Express 2008
  2. Click the Tools -> Options
  3. Select SQL Server Object Explorer . Now you should be able to see the options

    • Value for Edit Top Rows Command
    • Value for Select Top Rows Command
  4. Give the Values 0 here to select/ Edit all the Records

Full Instructions with screenshots are here: http://m-elshazly.blogspot.com/2011/01/sql-server-2008-change-edit-top-200.html

How to use php serialize() and unserialize()

When you want to make your php value storable, you have to turn it to be a string value, that is what serialize() does. And unserialize() does the reverse thing.

java.text.ParseException: Unparseable date

I found simple solution to get current date without any parsing error.

Calendar calendar;
calendar = Calendar.getInstance();
String customDate = "" + calendar.get(Calendar.YEAR) + "-" + (calendar.get(Calendar.MONTH) + 1) + "-" + calendar.get(Calendar.DAY_OF_MONTH);

HashMap - getting First Key value

Note that you should note that your logic flow must never rely on accessing the HashMap elements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

Back to the post, you already did half the job by loading the first element key:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key) to get the respective value:

Object myValue = statusName.get(myKey);

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

Adding :default => true to boolean in existing Rails column

change_column is a method of ActiveRecord::Migration, so you can't call it like that in the console.

If you want to add a default value for this column, create a new migration:

rails g migration add_default_value_to_show_attribute

Then in the migration created:

# That's the more generic way to change a column
def up
  change_column :profiles, :show_attribute, :boolean, default: true
end

def down
  change_column :profiles, :show_attribute, :boolean, default: nil
end

OR a more specific option:

def up
    change_column_default :profiles, :show_attribute, true
end

def down
    change_column_default :profiles, :show_attribute, nil
end

Then run rake db:migrate.

It won't change anything to the already created records. To do that you would have to create a rake task or just go in the rails console and update all the records (which I would not recommend in production).

When you added t.boolean :show_attribute, :default => true to the create_profiles migration, it's expected that it didn't do anything. Only migrations that have not already been ran are executed. If you started with a fresh database, then it would set the default to true.

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

Connects to both Office 365 and Exchange Online in one easy to use script.

REMINDER: You must have the following installed in order to manage Office 365 via PowerShell.

Microsoft Online Services Sign-in Assistant: http://go.microsoft.com/fwlink/?LinkId=286152

Azure AD Module for Windows PowerShell 32 bit - http://go.microsoft.com/fwlink/p/?linkid=236298 64 bit - http://go.microsoft.com/fwlink/p/?linkid=236297

MORE INFORMATION FOUND HERE: http://technet.microsoft.com/en-us/library/hh974317.aspx

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

If you find yourself doing things like this regularly it may be worth investigating the object-oriented interface to matplotlib. In your case:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(5)
y = np.exp(x)
fig1, ax1 = plt.subplots()
ax1.plot(x, y)
ax1.set_title("Axis 1 title")
ax1.set_xlabel("X-label for axis 1")

z = np.sin(x)
fig2, (ax2, ax3) = plt.subplots(nrows=2, ncols=1) # two axes on figure
ax2.plot(x, z)
ax3.plot(x, -z)

w = np.cos(x)
ax1.plot(x, w) # can continue plotting on the first axis

It is a little more verbose but it's much clearer and easier to keep track of, especially with several figures each with multiple subplots.

Is there a Python Library that contains a list of all the ascii characters?

No, there isn't, but you can easily make one:

    #Your ascii.py program:
    def charlist(begin, end):
        charlist = []
        for i in range(begin, end):
            charlist.append(chr(i))
        return ''.join(charlist)

    #Python shell:
    #import ascii
    #print(ascii.charlist(50, 100))
    #Comes out as:

    #23456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abc

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Get bytes from std::string in C++

If this is just plain vanilla C, then:

strcpy(buffer, text.c_str());

Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.

If encrypt() takes a 'const char *' then you can use

encrypt(text.c_str())

and you do not need to copy the string.

fatal: Not a git repository (or any of the parent directories): .git

The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo

  1. Are you in the right directory? Does typing ls show the right files?
  2. Have you initialized the repository yet? Typed git init? (git-init documentation)

Either of those would cause your error.

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

How to stop EditText from gaining focus at Activity startup in Android

A simpler solution exists. Set these attributes in your parent layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

And now, when the activity starts this main layout will get focus by default.

Also, we can remove focus from child views at runtime (e.g., after finishing child editing) by giving the focus to the main layout again, like this:

findViewById(R.id.mainLayout).requestFocus();

Good comment from Guillaume Perrot:

android:descendantFocusability="beforeDescendants" seems to be the default (integer value is 0). It works just by adding android:focusableInTouchMode="true".

Really, we can see that the beforeDescendants set as default in the ViewGroup.initViewGroup() method (Android 2.2.2). But not equal to 0. ViewGroup.FOCUS_BEFORE_DESCENDANTS = 0x20000;

Thanks to Guillaume.

Duplicate Symbols for Architecture arm64

For me, the issue was the style of creation of const, that worked fine until this iOS8.. i had a few lines as:

int const kView_LayoutCount = 3;

in my .h file. Six lines like resulted in 636 linker files once common blocks was set to NO. (14k+ if YES). Moved the lines to .m after stripping .h of the value declaration and compilation was good to go.

Hope this helps others!

Is there an equivalent of CSS max-width that works in HTML emails?

This is the solution that worked for me

https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz

<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
     <tr>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
        <td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->

             <!-- PLACE CONTENT HERE -->

        </td>
        <td style="padding:0px;margin:0px;">&nbsp;</td>
    </tr>
    <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20">&nbsp;</td></tr>
</table>

"continue" in cursor.forEach()

Use continue statement instead of return to skip an iteration in JS loops.

Decorators with parameters?

define this "decoratorize function" to generate customized decorator function:

def decoratorize(FUN, **kw):
    def foo(*args, **kws):
        return FUN(*args, **kws, **kw)
    return foo

use it this way:

    @decoratorize(FUN, arg1 = , arg2 = , ...)
    def bar(...):
        ...

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

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

How to export and import environment variables in windows?

My favorite method for doing this is to write it out as a batch script to combine both user variables and system variables into a single backup file like so, create an environment-backup.bat file and put in it:

@echo off
:: RegEdit can only export into a single file at a time, so create two temporary files.
regedit /e "%CD%\environment-backup1.reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\environment-backup2.reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

:: Concatenate into a single file and remove temporary files.
type "%CD%\environment-backup1.reg" "%CD%\environment-backup2.reg" > environment-backup.reg
del "%CD%\environment-backup1.reg"
del "%CD%\environment-backup2.reg"

This creates environment-backup.reg which you can use to re-import existing environment variables. This will add & override new variables, but not delete existing ones :)

Set the text in a span

Give an ID to your span and then change the text of target span.

$("#StatusTitle").text("Info");
$("#StatusTitleIcon").removeClass("fa-exclamation").addClass("fa-info-circle"); 

<i id="StatusTitleIcon" class="fa fa-exclamation fa-fw"></i>
<span id="StatusTitle">Error</span>

Here "Error" text will become "Info" and their fontawesome icons will be changed as well.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Parameterize an SQL IN clause

For a variable number of arguments like this the only way I'm aware of is to either generate the SQL explicitly or do something that involves populating a temporary table with the items you want and joining against the temp table.

How to represent multiple conditions in a shell if statement?

you can chain more than 2 conditions too :

if [ \( "$1" = '--usage' \) -o \( "$1" = '' \) -o \( "$1" = '--help' \) ]
then
   printf "\033[2J";printf "\033[0;0H"
   cat << EOF_PRINT_USAGE

   $0 - Purpose: upsert qto http json data to postgres db

   USAGE EXAMPLE:

   $0 -a foo -a bar



EOF_PRINT_USAGE
   exit 1
fi

On - window.location.hash - Change?

Another great implementation is jQuery History which will use the native onhashchange event if it is supported by the browser, if not it will use an iframe or interval appropriately for the browser to ensure all the expected functionality is successfully emulated. It also provides a nice interface to bind to certain states.

Another project worth noting as well is jQuery Ajaxy which is pretty much an extension for jQuery History to add ajax to the mix. As when you start using ajax with hashes it get's quite complicated!

Questions every good Java/Java EE Developer should be able to answer?

Advantages and disadvantages of thread-safe classes and explicitly synchronized code and examples of good applications of both. It is often not correct to trust on thread-safe classes as guarantees for data consistency in multi-threaded applications.

sql insert into table with select case values

Also you can use COALESCE instead of CASE expression. Because result of concatenating anything to NULL, even itself, is always NULL

INSERT TblStuff(FullName,Address,City,Zip)
SELECT COALESCE(Fname + ' ' + Middle + ' ' + Lname, Fname + LName) AS FullName,
       COALESCE(Address1 + ', ' + Address2, Address1) AS Address, City, Zip
FROM tblImport

Demo on SQLFiddle

MySQL Error 1264: out of range value for column

tl;dr

Make sure your AUTO_INCREMENT is not out of range. In that case, set a new value for it with:

ALTER TABLE table_name AUTO_INCREMENT=100 -- Change 100 to the desired number

Explanation

AUTO_INCREMENT can contain a number that is bigger than the maximum value allowed by the datatype. This can happen if you filled up a table that you emptied afterward but the AUTO_INCREMENT stayed the same, but there might be different reasons as well. In this case a new entry's id would be out of range.

Solution

If this is the cause of your problem, you can fix it by setting AUTO_INCREMENT to one bigger than the latest row's id. So if your latest row's id is 100 then:

ALTER TABLE table_name AUTO_INCREMENT=101

If you would like to check AUTO_INCREMENT's current value, use this command:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

Radio buttons not checked in jQuery

if ($("input").is(":not(:checked)"))

AFAIK, this should work, tested against the latest stable jQuery (1.2.6).

How do I read / convert an InputStream into a String in Java?

if You need to convert the string to a specific character set w/o external libraries then:

public String convertStreamToString(InputStream is) throws IOException {
  try( ByteArrayOutputStream baos = new ByteArrayOutputStream(); ) {
    is.transferTo( baos );
    return baos.toString( StandardCharsets.UTF_8 );
  }
}

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository

Rename a file in C#

Use:

public static class FileInfoExtensions
{
    /// <summary>
    /// Behavior when a new filename exists.
    /// </summary>
    public enum FileExistBehavior
    {
        /// <summary>
        /// None: throw IOException "The destination file already exists."
        /// </summary>
        None = 0,
        /// <summary>
        /// Replace: replace the file in the destination.
        /// </summary>
        Replace = 1,
        /// <summary>
        /// Skip: skip this file.
        /// </summary>
        Skip = 2,
        /// <summary>
        /// Rename: rename the file (like a window behavior)
        /// </summary>
        Rename = 3
    }


    /// <summary>
    /// Rename the file.
    /// </summary>
    /// <param name="fileInfo">the target file.</param>
    /// <param name="newFileName">new filename with extension.</param>
    /// <param name="fileExistBehavior">behavior when new filename is exist.</param>
    public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None)
    {
        string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName);
        string newFileNameExtension = System.IO.Path.GetExtension(newFileName);
        string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName);

        if (System.IO.File.Exists(newFilePath))
        {
            switch (fileExistBehavior)
            {
                case FileExistBehavior.None:
                    throw new System.IO.IOException("The destination file already exists.");

                case FileExistBehavior.Replace:
                    System.IO.File.Delete(newFilePath);
                    break;

                case FileExistBehavior.Rename:
                    int dupplicate_count = 0;
                    string newFileNameWithDupplicateIndex;
                    string newFilePathWithDupplicateIndex;
                    do
                    {
                        dupplicate_count++;
                        newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension;
                        newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex);
                    }
                    while (System.IO.File.Exists(newFilePathWithDupplicateIndex));

                    newFilePath = newFilePathWithDupplicateIndex;
                    break;

                case FileExistBehavior.Skip:
                    return;
            }
        }
        System.IO.File.Move(fileInfo.FullName, newFilePath);
    }
}

How to use this code

class Program
{
    static void Main(string[] args)
    {
        string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt");
        string newFileName = "Foo.txt";

        // Full pattern
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile);
        fileInfo.Rename(newFileName);

        // Or short form
        new System.IO.FileInfo(targetFile).Rename(newFileName);
    }
}

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

use Time::Piece;
print localtime->strftime('%Y-%m-%d');

or without the overridden localtime:

use Time::Piece (); 
print Time::Piece::localtime->strftime('%F %T');

Adding a Time to a DateTime in C#

   DateTime newDateTime = dtReceived.Value.Date.Add(TimeSpan.Parse(dtReceivedTime.Value.ToShortTimeString()));

Import and Export Excel - What is the best library?

I've been using ClosedXML and it works great!

ClosedXML makes it easier for developers to create Excel 2007/2010 files. It provides a nice object oriented way to manipulate the files (similar to VBA) without dealing with the hassles of XML Documents. It can be used by any .NET language like C# and Visual Basic (VB).

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

If it is a windows system, then it may be because you are using 32 bit winpcap library in a 64 bit pc or vie versa. If it is a 64 bit pc then copy the winpcap library and header packet.lib and wpcap.lib from winpcap/lib/x64 to the winpcap/lib directory and overwrite the existing

What is the meaning of <> in mysql query?

In MySQL, <> means Not Equal To, just like !=.

mysql> SELECT '.01' <> '0.01';
        -> 1
mysql> SELECT .01 <> '0.01';
        -> 0
mysql> SELECT 'zapp' <> 'zappp';
        -> 1

see the docs for more info

Uncaught ReferenceError: angular is not defined - AngularJS not working

Use the ng-click directive:

<button my-directive ng-click="alertFn()">Click Me!</button>

// In <script>:
app.directive('myDirective' function() {
  return function(scope, element, attrs) {
    scope.alertFn = function() { alert('click'); };
  };
};

Note that you don't need my-directive in this example, you just need something to bind alertFn on the current scope.

Update: You also want the angular libraries loaded before your <script> block.

How do you decompile a swf file

Usually 'lost' is a euphemism for "We stopped paying the developer and now he wont give us the source code."

That being said, I own a copy of Burak's ActionScript Viewer, and it works pretty well. A simple google search will find you many other SWF decompilers.

Remove trailing zeros

The following code could be used to not use the string type:

int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
    decimalResult = decimalResult / 10;
}
return decimalResult;

Returns 789.5

Pointer arithmetic for void pointer in C

cast it to a char pointer an increment your pointer forward x bytes ahead.

Reading specific columns from a text file in python

First of all we open the file and as datafile then we apply .read() method reads the file contents and then we split the data which returns something like: ['5', '10', '6', '6', '20', '1', '7', '30', '4', '8', '40', '3', '9', '23', '1', '4', '13', '6'] and the we applied list slicing on this list to start from the element at index position 1 and skip next 3 elements untill it hits the end of the loop.

with open("sample.txt", "r") as datafile:
    print datafile.read().split()[1::3]

Output:

['10', '20', '30', '40', '23', '13']

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

Strictly stated you must check all of the following: defined, not empty AND not None.

For "normal" variables it makes a difference if defined and set or not set. See foo and bar in the example below. Both are defined but only foo is set.

On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz and xyz.msg in the example below:

cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml

define() vs. const

Most of these answers are wrong or are only telling half the story.

  1. You can scope your constants by using namespaces.
  2. You can use the "const" keyword outside of class definitions. However, just like in classes the values assigned using the "const" keyword must be constant expressions.

For example:

const AWESOME = 'Bob'; // Valid

Bad example:

const AWESOME = whatIsMyName(); // Invalid (Function call)
const WEAKNESS = 4+5+6; // Invalid (Arithmetic) 
const FOO = BAR . OF . SOAP; // Invalid (Concatenation)

To create variable constants use define() like so:

define('AWESOME', whatIsMyName()); // Valid
define('WEAKNESS', 4 + 5 + 6); // Valid
define('FOO', BAR . OF . SOAP); // Valid

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Another way of doing this is using nested IF statements. Suppose you have companies table and you want to count number of records in it. A sample query would be something like this

SELECT IF(
      count(*) > 15,
      'good',
      IF(
          count(*) > 10,
          'average',
          'poor'
        ) 
      ) as data_count 
      FROM companies

Here second IF condition works when the first IF condition fails. So Sample Syntax of the IF statement would be IF ( CONDITION, THEN, ELSE). Hope it helps someone.

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

Auto-click button element on page load using jQuery

You would simply use jQuery like so...

<script>
jQuery(function(){
   jQuery('#modal').click();
});
</script>

Use the click function to auto-click the #modal button

How to install Guest addition in Mac OS as guest and Windows machine as host

You can use SSH and SFTP as suggested here.

  1. In the Guest OS (Mac OS X), open System Preferences > Sharing, then activate Remote Login; note the ip address specified in the Remote Login instructions, e.g. ssh [email protected]
  2. In VirtualBox, open Devices > Network > Network Settings > Advanced > Port Forwarding and specify Host IP = 127.0.0.1, Host Port 2222, Guest IP 10.0.2.15, Guest Port 22
  3. On the Host OS, run the following command sftp -P 2222 [email protected]; if you prefer a graphical interface, you can use FileZilla

Replace user and 10.0.2.15 with the appropriate values relevant to your configuration.

How do I break out of a loop in Perl?

Simply last would work here:

for my $entry (@array){
    if ($string eq "text"){
         last;
    }
}

If you have nested loops, then last will exit from the innermost loop. Use labels in this case:

LBL_SCORE: {
    for my $entry1 (@array1) {
        for my $entry2 (@array2) {
            if ($entry1 eq $entry2) { # Or any condition
                last LBL_SCORE;
            }
        }
    }
 }

Given a last statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.

How do I set the default page of my application in IIS7?

If you want to do something like,User enter url "www.xxxxxx.com/views/root/" & default page is displayed then I guess you have to set the default/home/welcome page attribute in IIS. But if user just enters "www.xxxxxx.com" and you still want to forward to your url, then you have write a line of code in the default page to forward to your desired url. This default page should be in root directory of your application, so www.xxxxx.com will load www.xxxx.com/index.html which will redirect the user to your desired url

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I had to change the Test Settings after changing the test projects CPU to x64. Then the tests where detected again.

Architecture

c++ exception : throwing std::string

It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.

Incidentally, throwing a std::string isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.

Total size of the contents of all the files in a directory

If you use busybox's "du" in emebedded system, you can not get a exact bytes with du, only Kbytes you can get.

BusyBox v1.4.1 (2007-11-30 20:37:49 EST) multi-call binary

Usage: du [-aHLdclsxhmk] [FILE]...

Summarize disk space used for each FILE and/or directory.
Disk space is printed in units of 1024 bytes.

Options:
        -a      Show sizes of files in addition to directories
        -H      Follow symbolic links that are FILE command line args
        -L      Follow all symbolic links encountered
        -d N    Limit output to directories (and files with -a) of depth < N
        -c      Output a grand total
        -l      Count sizes many times if hard linked
        -s      Display only a total for each argument
        -x      Skip directories on different filesystems
        -h      Print sizes in human readable format (e.g., 1K 243M 2G )
        -m      Print sizes in megabytes
        -k      Print sizes in kilobytes(default)

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Getting Hour and Minute in PHP

function get_time($time) {
    $duration = $time / 1000;
    $hours = floor($duration / 3600);
    $minutes = floor(($duration / 60) % 60);
    $seconds = $duration % 60;
    if ($hours != 0)
        echo "$hours:$minutes:$seconds";
    else
        echo "$minutes:$seconds";
}

get_time('1119241');

How to update a single pod without touching other dependencies

It's 2015

So because pod update SomePod touches everything in the latest versions of cocoapods, I found a workaround.

Follow the next steps:

  1. Remove SomePod from the Podfile

  2. Run pod install

pods will now remove SomePod from our project and from the Podfile.lock file.

  1. Put back SomePod into the Podfile

  2. Run pod install again

This time the latest version of our pod will be installed and saved in the Podfile.lock.

Numpy how to iterate over columns of array?

For example you want to find a mean of each column in matrix. Let's create the following matrix

mat2 = np.array([1,5,6,7,3,0,3,5,9,10,8,0], dtype=np.float64).reshape(3, 4)

The function for mean is

def my_mean(x):
    return sum(x)/len(x)

To do what is needed and store result in colon vector 'results'

results = np.zeros(4)
for i in range(0, 4):
    mat2[:, i] = my_mean(mat2[:, i])

results = mat2[1,:]      

The results are: array([4.33333333, 5. , 5.66666667, 4. ])

Difference between fprintf, printf and sprintf?

fprintf This is related with streams where as printf is a statement similar to fprintf but not related to streams, that is fprintf is file related

Javascript checkbox onChange

function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

Check if SQL Connection is Open or Closed

To check the database connection state you can just simple do the following

if(con.State == ConnectionState.Open){}

How to check size of a file using Bash?

ls -l $file | awk '{print $6}'

assuming that ls command reports filesize at column #6

How to find memory leak in a C++ code/project?

Neither "new" or "delete" should ever be used in application code. Instead, create a new type that uses the manager/worker idiom, in which the manager class allocates and frees memory and forwards all other operations to the worker object.

Unfortunately this is more work than it should be because C++ doesn't have overloading of "operator .". It is even more work in the presence of polymorphism.

But this is worth the effort because you then don't ever have to worry about memory leaks, which means you don't even have to look for them.

Maintaining Session through Angular.js

Here is a kind of snippet for you:

app.factory('Session', function($http) {
  var Session = {
    data: {},
    saveSession: function() { /* save session data to db */ },
    updateSession: function() { 
      /* load data from db */
      $http.get('session.json').then(function(r) { return Session.data = r.data;});
    }
  };
  Session.updateSession();
  return Session; 
});

Here is Plunker example how you can use that: http://plnkr.co/edit/Fg3uF4ukl5p88Z0AeQqU?p=preview

How do I make text bold in HTML?

use <strong> or <b> tag

also, you can try with css <span style="font-weight:bold">text</span>

Connect to SQL Server through PDO using SQL Server Driver

try
{

    $conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e)
{

    $e->getMessage();

}

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

This can be accomplished using only CSS. To change the carousel to a fade transition instead of slide, use one of the following snippets (LESS or standard CSS).

LESS

// Fade transition for carousel items
.carousel {
  .item {
    left: 0 !important;
    .transition(opacity .4s); //adjust timing here
  }
  .carousel-control {
    background-image: none; // remove background gradients on controls
  }
  // Fade controls with items
  .next.left,
  .prev.right {
    opacity: 1;
    z-index: 1;
  }
  .active.left,
  .active.right {
    opacity: 0;
    z-index: 2;
  }
}

Plain CSS:

/* Fade transition for carousel items */
.carousel .item {
    left: 0 !important;
      -webkit-transition: opacity .4s; /*adjust timing here */
         -moz-transition: opacity .4s;
           -o-transition: opacity .4s;
              transition: opacity .4s;
}
.carousel-control {
    background-image: none !important; /* remove background gradients on controls */
}
/* Fade controls with items */
.next.left,
.prev.right {
    opacity: 1;
    z-index: 1;
}
.active.left,
.active.right {
    opacity: 0;
    z-index: 2;
}

How do I solve the INSTALL_FAILED_DEXOPT error?

I got the same error and fixed it by increasing the size of internal storage.

The internal storage was initially set to 32MB(I know) and then I installed a couple of apks on it, which had left less space than what was needed for the one to be installed.

fatal: early EOF fatal: index-pack failed

The git-daemon issue seems to have been resolved in v2.17.0 (verified with a non working v2.16.2.1). I.e. workaround of selecting text in console to "lock output buffer" should no longer be required.

From https://github.com/git/git/blob/v2.17.0/Documentation/RelNotes/2.17.0.txt:

  • Assorted fixes to "git daemon". (merge ed15e58efe jk/daemon-fixes later to maint).

Passing base64 encoded strings in URL

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

Sending Email in Android using JavaMail API without using the default/built-in app

Those who are getting ClassDefNotFoundError try to move that Three jar files to lib folder of your Project,it worked for me!!

How can I throw a general exception in Java?

Java has a large number of built-in exceptions for different scenarios.

In this case, you should throw an IllegalArgumentException, since the problem is that the caller passed a bad parameter.

How to configure Visual Studio to use Beyond Compare

VS2013 on 64-bit Windows 7 requires these settings: Tools | Options | Source Control | Jazz Source Control

CHECK THE CHECKBOX Use an external compare tool ... (easy to miss this)

2-Way Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

3-Way Conflict Compare Location of Executable: C:\Program Files (x86)\Beyond Compare 3\BCompare.exe

Regular expression [Any number]

if("123".search(/^\d+$/) >= 0){
   // its a number
}

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

Importing large sql file to MySql via command line

You can import .sql file using the standard input like this:

mysql -u <user> -p<password> <dbname> < file.sql

Note: There shouldn't space between <-p> and <password>

Reference: http://dev.mysql.com/doc/refman/5.0/en/mysql-batch-commands.html

Note for suggested edits: This answer was slightly changed by suggested edits to use inline password parameter. I can recommend it for scripts but you should be aware that when you write password directly in the parameter (-p<password>) it may be cached by a shell history revealing your password to anyone who can read the history file. Whereas -p asks you to input password by standard input.

How to implement a Navbar Dropdown Hover in Bootstrap v4?

Google brought me here but... The examples provided work if the dropdown menu is overlaping (at least by 1px) with its parent when show. If not, it loses focus and nothing works as intended.

Here is a working solution with jQuery and Bootstrap 4.5.2 :

$('li.nav-item').mouseenter(function (e) {

        e.stopImmediatePropagation();

        if ($(this).hasClass('dropdown')) {

            // target element containing dropdowns, show it
            $(this).addClass('show');
            $(this).find('.dropdown-menu').addClass('show');

            // Close dropdown on mouseleave
            $('.dropdown-menu').mouseleave(function (e) {
                e.stopImmediatePropagation();
                $(this).removeClass('show');
            });

            // If you have a prenav above, this clears open dropdowns (since you probably will hover the nav-item going up and it will reopen its dropdown otherwise)
            $('#prenav').off().mouseenter(function (e) {
                e.stopImmediatePropagation();
                $('.dropdown-menu').removeClass('show');
            });

        } else {
            // unset open dropdowns if hover is on simple nav element
            $('.dropdown-menu').removeClass('show');
        }
    });

How can I remove a child node in HTML using JavaScript?

To answer the original question - there are various ways to do this, but the following would be the simplest.

If you already have a handle to the child node that you want to remove, i.e. you have a JavaScript variable that holds a reference to it:

myChildNode.parentNode.removeChild(myChildNode);

Obviously, if you are not using one of the numerous libraries that already do this, you would want to create a function to abstract this out:

function removeElement(node) {
    node.parentNode.removeChild(node);
}

EDIT: As has been mentioned by others: if you have any event handlers wired up to the node you are removing, you will want to make sure you disconnect those before the last reference to the node being removed goes out of scope, lest poor implementations of the JavaScript interpreter leak memory.

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

HTML table with fixed headers?

:)

Not-so-clean, but pure HTML/CSS solution.

table {
    overflow-x:scroll;
}

tbody {
    max-height: /*your desired max height*/
    overflow-y:scroll;
    display:block;
}

Updated for IE8+ JSFiddle example

How to use the gecko executable with Selenium

You can handle the Firefox driver automatically using WebDriverManager.

This library downloads the proper binary (geckodriver) for your platform (Mac, Windows, Linux) and then exports the proper value of the required Java environment variable (webdriver.gecko.driver).

Take a look at a complete example as a JUnit test case:

public class FirefoxTest {

  private WebDriver driver;

  @BeforeClass
  public static void setupClass() {
    WebDriverManager.firefoxdriver().setup();
  }

  @Before
  public void setupTest() {
    driver = new FirefoxDriver();
  }

  @After
  public void teardown() {
    if (driver != null) {
      driver.quit();
    }
  }

  @Test
  public void test() {
    // Your test code here
  }
}

If you are using Maven you have to put at your pom.xml:

<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>4.3.1</version>
</dependency>

WebDriverManager does magic for you:

  1. It checks for the latest version of the WebDriver binary
  2. It downloads the WebDriver binary if it's not present on your system
  3. It exports the required WebDriver Java environment variables needed by Selenium

So far, WebDriverManager supports Chrome, Opera, Internet Explorer, Microsoft Edge, PhantomJS, and Firefox.

How to import a module given the full path?

I have wrote my own global and portable import function, based on importlib module, for:

  • Be able to import both module as a submodule and to import content of a module to a parent module (or into a globals if has no parent module).
  • Be able to import modules with a period characters in a file name.
  • Be able to import modules with any extension.
  • Be able to use a standalone name for a submodule instead of a file name without extension which is by default.
  • Be able to define the import order based on previously imported module instead of dependent on sys.path or on a what ever search path storage.

The examples directory structure:

<root>
 |
 +- test.py
 |
 +- testlib.py
 |
 +- /std1
 |   |
 |   +- testlib.std1.py
 |
 +- /std2
 |   |
 |   +- testlib.std2.py
 |
 +- /std3
     |
     +- testlib.std3.py

Inclusion dependency and order:

test.py
  -> testlib.py
    -> testlib.std1.py
      -> testlib.std2.py
    -> testlib.std3.py 

Implementation:

Latest changes store: https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/python/tacklelib/tacklelib.py

test.py:

import os, sys, inspect, copy

SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("test::SOURCE_FILE: ", SOURCE_FILE)

# portable import to the global space
sys.path.append(TACKLELIB_ROOT) # TACKLELIB_ROOT - path to the library directory
import tacklelib as tkl

tkl.tkl_init(tkl)

# cleanup
del tkl # must be instead of `tkl = None`, otherwise the variable would be still persist
sys.path.pop()

tkl_import_module(SOURCE_DIR, 'testlib.py')

print(globals().keys())

testlib.base_test()
testlib.testlib_std1.std1_test()
testlib.testlib_std1.testlib_std2.std2_test()
#testlib.testlib.std3.std3_test()                             # does not reachable directly ...
getattr(globals()['testlib'], 'testlib.std3').std3_test()     # ... but reachable through the `globals` + `getattr`

tkl_import_module(SOURCE_DIR, 'testlib.py', '.')

print(globals().keys())

base_test()
testlib_std1.std1_test()
testlib_std1.testlib_std2.std2_test()
#testlib.std3.std3_test()                                     # does not reachable directly ...
globals()['testlib.std3'].std3_test()                         # ... but reachable through the `globals` + `getattr`

testlib.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("1 testlib::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/std1', 'testlib.std1.py', 'testlib_std1')

# SOURCE_DIR is restored here
print("2 testlib::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/std3', 'testlib.std3.py')

print("3 testlib::SOURCE_FILE: ", SOURCE_FILE)

def base_test():
  print('base_test')

testlib.std1.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std1::SOURCE_FILE: ", SOURCE_FILE)

tkl_import_module(SOURCE_DIR + '/../std2', 'testlib.std2.py', 'testlib_std2')

def std1_test():
  print('std1_test')

testlib.std2.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std2::SOURCE_FILE: ", SOURCE_FILE)

def std2_test():
  print('std2_test')

testlib.std3.py:

# optional for 3.4.x and higher
#import os, inspect
#
#SOURCE_FILE = os.path.abspath(inspect.getsourcefile(lambda:0)).replace('\\','/')
#SOURCE_DIR = os.path.dirname(SOURCE_FILE)

print("testlib.std3::SOURCE_FILE: ", SOURCE_FILE)

def std3_test():
  print('std3_test')

Output (3.7.4):

test::SOURCE_FILE:  <root>/test01/test.py
import : <root>/test01/testlib.py as testlib -> []
1 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']
import : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']
testlib.std2::SOURCE_FILE:  <root>/test01/std1/../std2/testlib.std2.py
2 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']
testlib.std3::SOURCE_FILE:  <root>/test01/std3/testlib.std3.py
3 testlib::SOURCE_FILE:  <root>/test01/testlib.py
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib'])
base_test
std1_test
std2_test
std3_test
import : <root>/test01/testlib.py as . -> []
1 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std1/testlib.std1.py as testlib_std1 -> ['testlib']
import : <root>/test01/std1/../std2/testlib.std2.py as testlib_std2 -> ['testlib', 'testlib_std1']
testlib.std2::SOURCE_FILE:  <root>/test01/std1/../std2/testlib.std2.py
2 testlib::SOURCE_FILE:  <root>/test01/testlib.py
import : <root>/test01/std3/testlib.std3.py as testlib.std3 -> ['testlib']
testlib.std3::SOURCE_FILE:  <root>/test01/std3/testlib.std3.py
3 testlib::SOURCE_FILE:  <root>/test01/testlib.py
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'os', 'sys', 'inspect', 'copy', 'SOURCE_FILE', 'SOURCE_DIR', 'TackleGlobalImportModuleState', 'tkl_membercopy', 'tkl_merge_module', 'tkl_get_parent_imported_module_state', 'tkl_declare_global', 'tkl_import_module', 'TackleSourceModuleState', 'tkl_source_module', 'TackleLocalImportModuleState', 'testlib', 'testlib_std1', 'testlib.std3', 'base_test'])
base_test
std1_test
std2_test
std3_test

Tested in Python 3.7.4, 3.2.5, 2.7.16

Pros:

  • Can import both module as a submodule and can import content of a module to a parent module (or into a globals if has no parent module).
  • Can import modules with periods in a file name.
  • Can import any extension module from any extension module.
  • Can use a standalone name for a submodule instead of a file name without extension which is by default (for example, testlib.std.py as testlib, testlib.blabla.py as testlib_blabla and so on).
  • Does not depend on a sys.path or on a what ever search path storage.
  • Does not require to save/restore global variables like SOURCE_FILE and SOURCE_DIR between calls to tkl_import_module.
  • [for 3.4.x and higher] Can mix the module namespaces in nested tkl_import_module calls (ex: named->local->named or local->named->local and so on).
  • [for 3.4.x and higher] Can auto export global variables/functions/classes from where being declared to all children modules imported through the tkl_import_module (through the tkl_declare_global function).

Cons:

  • [for 3.3.x and lower] Require to declare tkl_import_module in all modules which calls to tkl_import_module (code duplication)

Update 1,2 (for 3.4.x and higher only):

In Python 3.4 and higher you can bypass the requirement to declare tkl_import_module in each module by declare tkl_import_module in a top level module and the function would inject itself to all children modules in a single call (it's a kind of self deploy import).

Update 3:

Added function tkl_source_module as analog to bash source with support execution guard upon import (implemented through the module merge instead of import).

Update 4:

Added function tkl_declare_global to auto export a module global variable to all children modules where a module global variable is not visible because is not a part of a child module.

Update 5:

All functions has moved into the tacklelib library, see the link above.

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

How to find the array index with a value?

Use jQuery's function jQuery.inArray

jQuery.inArray( value, array [, fromIndex ] )
(or) $.inArray( value, array [, fromIndex ] )

Set a button background image iPhone programmatically

In case it helps anyone setBackgroundImage didn't work for me, but setImage did

Oracle SQL Developer spool output?

I have found that if I save my query(spool_script_file.sql) and call it using this

@c:\client\queries\spool_script_file.sql as script(F5)

My output now is just the results with out the commands at the top.

I found this solution on the oracle forums.

How to remove CocoaPods from a project?

There can be two aspects developer may face.

  • Either he wants to remove pods completely from project
  • developer wants to uninstall particular framework from project from pods.

In first case you have to use 'pod deintegrate' and follow several steps which are mentioned in the answers above.

For second case that is if you want to uninstall any particular framework which is installed there very simple way available in your pod file just comment the framework which you want to uninstall and run pod install command.

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
target 'ProjectName' do
  # Uncomment this line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!

    pod 'iCarousel', '~> 1.8'
#    pod 'Facebook-iOS-SDK', '~> 4.1'
#    pod 'ParseFacebookUtilsV4', '~> 1.11'
#    pod 'Parse', '~> 1.14'


end

Here I want to uninstall facebook and parse frameworks (which were installed using pods) and not iCarousel that is why I have updated my pod file like above.

Now if I run pod install it will keep iCarousel as it is in my project and will remove facebook and parse.

How to browse for a file in java swing library?

The following example creates a file chooser and displays it as first an open-file dialog and then as a save-file dialog:

String filename = File.separator+"tmp";
JFileChooser fc = new JFileChooser(new File(filename));

// Show open dialog; this method does not return until the dialog is closed
fc.showOpenDialog(frame);
File selFile = fc.getSelectedFile();

// Show save dialog; this method does not return until the dialog is closed
fc.showSaveDialog(frame);
selFile = fc.getSelectedFile();

Here is a more elaborate example that creates two buttons that create and show file chooser dialogs.

// This action creates and shows a modal open-file dialog.
public class OpenFileAction extends AbstractAction {
    JFrame frame;
    JFileChooser chooser;

    OpenFileAction(JFrame frame, JFileChooser chooser) {
        super("Open...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showOpenDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

// This action creates and shows a modal save-file dialog.
public class SaveFileAction extends AbstractAction {
    JFileChooser chooser;
    JFrame frame;

    SaveFileAction(JFrame frame, JFileChooser chooser) {
        super("Save As...");
        this.chooser = chooser;
        this.frame = frame;
    }

    public void actionPerformed(ActionEvent evt) {
        // Show dialog; this method does not return until dialog is closed
        chooser.showSaveDialog(frame);

        // Get the selected file
        File file = chooser.getSelectedFile();
    }
};

How do I include a JavaScript file in another JavaScript file?

There are a lot of potential answers for this question. My answer is obviously based on a number of them. This is what I ended up with after reading through all the answers.

The problem with $.getScript and really any other solution that requires a callback when loading is complete is that if you have multiple files that use it and depend on each other you no longer have a way to know when all scripts have been loaded (once they are nested in multiple files).

Example:

file3.js

var f3obj = "file3";

// Define other stuff

file2.js:

var f2obj = "file2";
$.getScript("file3.js", function(){

    alert(f3obj);

    // Use anything defined in file3.
});

file1.js:

$.getScript("file2.js", function(){
    alert(f3obj); //This will probably fail because file3 is only guaranteed to have loaded inside the callback in file2.
    alert(f2obj);

    // Use anything defined in the loaded script...
});

You are right when you say that you could specify Ajax to run synchronously or use XMLHttpRequest, but the current trend appears to be to deprecate synchronous requests, so you may not get full browser support now or in the future.

You could try to use $.when to check an array of deferred objects, but now you are doing this in every file and file2 will be considered loaded as soon as the $.when is executed not when the callback is executed, so file1 still continues execution before file3 is loaded. This really still has the same problem.

I decided to go backwards instead of forwards. Thank you document.writeln. I know it's taboo, but as long as it is used correctly this works well. You end up with code that can be debugged easily, shows in the DOM correctly and can ensure the order the dependencies are loaded correctly.

You can of course use $ ("body").append(), but then you can no longer debug correctly any more.

NOTE: You must use this only while the page is loading, otherwise you get a blank screen. In other words, always place this before / outside of document.ready. I have not tested using this after the page is loaded in a click event or anything like that, but I am pretty sure it'll fail.

I liked the idea of extending jQuery, but obviously you don't need to.

Before calling document.writeln, it checks to make sure the script has not already been loading by evaluating all the script elements.

I assume that a script is not fully executed until its document.ready event has been executed. (I know using document.ready is not required, but many people use it, and handling this is a safeguard.)

When the additional files are loaded the document.ready callbacks will get executed in the wrong order. To address this when a script is actually loaded, the script that imported it is re-imported itself and execution halted. This causes the originating file to now have its document.ready callback executed after any from any scripts that it imports.

Instead of this approach you could attempt to modify the jQuery readyList, but this seemed like a worse solution.

Solution:

$.extend(true,
{
    import_js : function(scriptpath, reAddLast)
    {
        if (typeof reAddLast === "undefined" || reAddLast === null)
        {
            reAddLast = true; // Default this value to true. It is not used by the end user, only to facilitate recursion correctly.
        }

        var found = false;
        if (reAddLast == true) // If we are re-adding the originating script we do not care if it has already been added.
        {
            found = $('script').filter(function () {
                return ($(this).attr('src') == scriptpath);
            }).length != 0; // jQuery to check if the script already exists. (replace it with straight JavaScript if you don't like jQuery.
        }

        if (found == false) {

            var callingScriptPath = $('script').last().attr("src"); // Get the script that is currently loading. Again this creates a limitation where this should not be used in a button, and only before document.ready.

            document.writeln("<script type='text/javascript' src='" + scriptpath + "'></script>"); // Add the script to the document using writeln

            if (reAddLast)
            {
                $.import_js(callingScriptPath, false); // Call itself with the originating script to fix the order.
                throw 'Readding script to correct order: ' + scriptpath + ' < ' + callingScriptPath; // This halts execution of the originating script since it is getting reloaded. If you put a try / catch around the call to $.import_js you results will vary.
            }
            return true;
        }
        return false;
    }
});

Usage:

File3:

var f3obj = "file3";

// Define other stuff
$(function(){
    f3obj = "file3docready";
});

File2:

$.import_js('js/file3.js');
var f2obj = "file2";
$(function(){
    f2obj = "file2docready";
});

File1:

$.import_js('js/file2.js');

// Use objects from file2 or file3
alert(f3obj); // "file3"
alert(f2obj); // "file2"

$(function(){
    // Use objects from file2 or file3 some more.
    alert(f3obj); //"file3docready"
    alert(f2obj); //"file2docready"
});

difference between css height : 100% vs height : auto

The default is height: auto in browser, but height: X% Defines the height in percentage of the containing block.

Make elasticsearch only return certain fields?

response_filtering

All REST APIs accept a filter_path parameter that can be used to reduce the response returned by elasticsearch. This parameter takes a comma separated list of filters expressed with the dot notation.

https://stackoverflow.com/a/35647027/844700

Can I underline text in an Android layout?

Most Easy Way

TextView tv = findViewById(R.id.tv);
tv.setText("some text");
setUnderLineText(tv, "some");

Also support TextView childs like EditText, Button, Checkbox

public void setUnderLineText(TextView tv, String textToUnderLine) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToUnderLine, 0);

        UnderlineSpan underlineSpan = new UnderlineSpan();
        SpannableString wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToUnderLine, ofs);
            if (ofe == -1)
                break;
            else {
                wordToSpan.setSpan(underlineSpan, ofe, ofe + textToUnderLine.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }

If you want

- Clickable underline text?

- Underline multiple parts of TextView?

Then Check This Answer

Http Basic Authentication in Java using HttpClient?

HttpBasicAuth works for me with smaller changes

  1. I use maven dependency

    <dependency>
        <groupId>net.iharder</groupId>
        <artifactId>base64</artifactId>
        <version>2.3.8</version>
    </dependency>
    
  2. Smaller change

    String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
    

What is the difference between functional and non-functional requirements?

FUNCTIONAL REQUIREMENTS the activities the system must perform

  • business uses functions the users carry out
  • use cases example if you are developing a payroll system required functions
  • generate electronic fund transfers
  • calculation commission amounts
  • calculate payroll taxes
  • report tax deduction to the IRS

Maven plugins can not be found in IntelliJ

Remove your local Maven unknown plugin and reimport all maven projects. This will fix this issue.

You can find it under View > Tool Windows > Maven :

enter image description here

What's the best way to send a signal to all members of a process group?

To add to Norman Ramsey's answer, it may be worth looking at at setsid if you want to create a process group.
http://pubs.opengroup.org/onlinepubs/009695399/functions/setsid.html

The setsid() function shall create a new session, if the calling process is not a process group leader. Upon return the calling process shall be the session leader of this new session, shall be the process group leader of a new process group, and shall have no controlling terminal. The process group ID of the calling process shall be set equal to the process ID of the calling process. The calling process shall be the only process in the new process group and the only process in the new session.

Which I take to mean that you can create a group from the starting process. I used this in php in order to be able to kill a whole process tree after starting it.

This may be a bad idea. I'd be interested in comments.

How to check if a number is between two values?

Here is the shortest method possible:

if (Math.abs(v-550)<50) console.log('short')
if ((v-500)*(v-600)<0) console.log('short')

Parametrized:

if (Math.abs(v-max+v-min)<max+min) console.log('short')
if ((v-min)*(v-max)<0) console.log('short')

You can divide both sides by 2 if you don't understand how the first one works;)

How do shift operators work in Java?

The typical usage of shifting a variable and assigning back to the variable can be rewritten with shorthand operators <<=, >>=, or >>>=, also known in the spec as Compound Assignment Operators.

For example,

i >>= 2

produces the same result as

i = i >> 2

How to get Activity's content view?

You can also override onContentChanged() which is among others fired when setContentView() has been called.

Iterating over arrays in Python 3

When you loop in an array like you did, your for variable(in this example i) is current element of your array.

For example if your ar is [1,5,10], the i value in each iteration is 1, 5, and 10. And because your array length is 3, the maximum index you can use is 2. so when i = 5 you get IndexError. You should change your code into something like this:

for i in ar:
    theSum = theSum + i

Or if you want to use indexes, you should create a range from 0 ro array length - 1.

for i in range(len(ar)):
    theSum = theSum + ar[i]

Should try...catch go inside or outside a loop?

PERFORMANCE:

There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.

Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html

The table is described about half-way down.

How to get the URL without any parameters in JavaScript?

Just one more alternative using URL

var theUrl = new URL(window.location.href);
theUrl.search = ""; //Remove any params
theUrl //as URL object
theUrl.href //as a string

How to declare a vector of zeros in R

X <- c(1:3)*0

Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c() function, which is very frequently cited in tutorials as a usual way to declare a vector.

As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.

Pretty printing JSON from Jackson 2.2's ObjectMapper

If others who view this question only have a JSON string (not in an object), then you can put it into a HashMap and still get the ObjectMapper to work. The result variable is your JSON string.

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

// Pretty-print the JSON result
try {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
} catch (JsonParseException e) {
    e.printStackTrace();
} catch (JsonMappingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

I had tried almost all the above methods.

Finally fixed it by including the

script src="{%static 'App/js/jquery.js' %}"

just after loading the staticfiles i.e {% load staticfiles %} in base.html

How to disable/enable a button with a checkbox if checked

Here is a clean way to disable and enable submit button:

<input type="submit" name="sendNewSms" class="inputButton" id="sendNewSms" value=" Send " />
<input type="checkbox" id="disableBtn" />

var submit = document.getElementById('sendNewSms'),
    checkbox = document.getElementById('disableBtn'),
    disableSubmit = function(e) {
        submit.disabled = this.checked
    };

checkbox.addEventListener('change', disableSubmit);

Here is a fiddle of it in action: http://jsfiddle.net/sYNj7/

Html helper for <input type="file" />

To use BeginForm, here's the way to use it:

 using(Html.BeginForm("uploadfiles", 
"home", FormMethod.POST, new Dictionary<string, object>(){{"type", "file"}})

What is the parameter "next" used for in Express?

Before understanding next, you need to have a little idea of Request-Response cycle in node though not much in detail. It starts with you making an HTTP request for a particular resource and it ends when you send a response back to the user i.e. when you encounter something like res.send(‘Hello World’);

let’s have a look at a very simple example.

app.get('/hello', function (req, res, next) {
  res.send('USER')
})

Here we do not need next(), because resp.send will end the cycle and hand over the control back to the route middleware.

Now let’s take a look at another example.

app.get('/hello', function (req, res, next) {
  res.send("Hello World !!!!");
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

Here we have 2 middleware functions for the same path. But you always gonna get the response from the first one. Because that is mounted first in the middleware stack and res.send will end the cycle.

But what if we always do not want the “Hello World !!!!” response back. For some conditions we may want the "Hello Planet !!!!" response. Let’s modify the above code and see what happens.

app.get('/hello', function (req, res, next) {
  if(some condition){
    next();
    return;
  }
  res.send("Hello World !!!!");  
});

app.get('/hello', function (req, res, next) {
  res.send("Hello Planet !!!!");
});

What’s the next doing here. And yes you might have gusses. It’s gonna skip the first middleware function if the condition is true and invoke the next middleware function and you will have the "Hello Planet !!!!" response.

So, next pass the control to the next function in the middleware stack.

What if the first middleware function does not send back any response but do execute a piece of logic and then you get the response back from second middleware function.

Something like below:-

app.get('/hello', function (req, res, next) {
  // Your piece of logic
  next();
});

app.get('/hello', function (req, res, next) {
  res.send("Hello !!!!");
});

In this case you need both the middleware functions to be invoked. So, the only way you reach the second middleware function is by calling next();

What if you do not make a call to next. Do not expect the second middleware function to get invoked automatically. After invoking the first function your request will be left hanging. The second function will never get invoked and you will not get back the response.

How do you run a Python script as a service in Windows?

Although I upvoted the chosen answer a couple of weeks back, in the meantime I struggled a lot more with this topic. It feels like having a special Python installation and using special modules to run a script as a service is simply the wrong way. What about portability and such?

I stumbled across the wonderful Non-sucking Service Manager, which made it really simple and sane to deal with Windows Services. I figured since I could pass options to an installed service, I could just as well select my Python executable and pass my script as an option.

I have not yet tried this solution, but I will do so right now and update this post along the process. I am also interested in using virtualenvs on Windows, so I might come up with a tutorial sooner or later and link to it here.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

My problem was one of my elements had the xmlns attribute:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE xmlns="blahblah">
        ...
    </RETS-RESPONSE>
</RETS>

No matter what I tried the xmlns attribute seemed to be breaking the serializer, so I removed any trace of xmlns="..." from the xml file:

<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
    <RETS-RESPONSE>
        ...
    </RETS-RESPONSE>
</RETS>

and voila! Everything worked.

I now parse the xml file to remove this attribute before deserializing. Not sure why this works, maybe my case is different since the element containing the xmlns attribute is not the root element.

Change onclick action with a Javascript function

Thanks to João Paulo Oliveira, this was my solution which includes a variable (which was my goal).

document.getElementById( "myID" ).setAttribute( "onClick", "myFunction("+VALUE+");" );

PG::ConnectionBad - could not connect to server: Connection refused

This is what really helped me.

$ cd /usr/local/var/postgres/
$ rm postmaster.pid

Reference: http://alumni.lewagon.org/questions/60

Convert String to Integer in XSLT 1.0

XSLT 1.0 does not have an integer data type, only double. You can use number() to convert a string to a number.

Convert HTML Character Back to Text Using Java Standard Library

As @jem suggested, it is possible to use jsoup.

With jSoup 1.8.3 it il possible to use the method Parser.unescapeEntities that retain the original html.

import org.jsoup.parser.Parser;
...
String html = Parser.unescapeEntities(original_html, false);

It seems that in some previous release this method is not present.

How to resolve Nodejs: Error: ENOENT: no such file or directory

Running

npm run scss
npm run start 

in that order in terminal solved the issue for me.

What exactly should be set in PYTHONPATH?

You don't have to set either of them. PYTHONPATH can be set to point to additional directories with private libraries in them. If PYTHONHOME is not set, Python defaults to using the directory where python.exe was found, so that dir should be in PATH.

how to convert rgb color to int in java

You may declare a value in color.xml, and thus you can get integer value by calling the code below.

context.getColor(int resId);

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

Google Gson - deserialize list<class> object? (generic type)

Method to deserialize generic collection:

import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;

...

Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);

Since several people in the comments have mentioned it, here's an explanation of how the TypeToken class is being used. The construction new TypeToken<...>() {}.getType() captures a compile-time type (between the < and >) into a runtime java.lang.reflect.Type object. Unlike a Class object, which can only represent a raw (erased) type, the Type object can represent any type in the Java language, including a parameterized instantiation of a generic type.

The TypeToken class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}, which is a necessary part of this expression).

Due to type erasure, the TypeToken class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken<List<T>>() {}.getType() for a type parameter T.)

For more information, see the documentation for the TypeToken class.

How do I reference a cell within excel named range?

"Do you know if there's a way to make this work with relative selections, so that the formula can be "dragged down"/applied across several cells in the same column?"

To make such selection relative simply use ROW formula for a row number in INDEX formula and COLUMN formula for column number in INDEX formula. To make this clearer here is the example:

=INDEX(named_range,ROW(A1),COLUMN(A1))

Assuming the named range starts at A1 this formula simply indexes that range by row and column number of referenced cell and since that reference is relative it changes when you drag the the cell down or to the side, which makes it possible to create whole array of cells easily.

Transaction marked as rollback only: How do I find the cause

apply the below code in productRepository

@Query("update Product set prodName=:name where prodId=:id ") @Transactional @Modifying int updateMyData(@Param("name")String name, @Param("id") Integer id);

while in junit test apply below code

@Test
public void updateData()
{
  int i=productRepository.updateMyData("Iphone",102);

  System.out.println("successfully updated ... ");
  assertTrue(i!=0);

}

it is working fine for my code

Linux: is there a read or recv from socket with timeout?

LINUX

struct timeval tv;
tv.tv_sec = 30;        // 30 Secs Timeout
tv.tv_usec = 0;        // Not init'ing this can cause strange errors
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv,sizeof(struct timeval));

WINDOWS

DWORD timeout = SOCKET_READ_TIMEOUT_SEC * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof(timeout));

NOTE: You have put this setting before bind() function call for proper run

How do I call a SQL Server stored procedure from PowerShell?

Consider calling osql.exe (the command line tool for SQL Server) passing as parameter a text file written for each line with the call to the stored procedure.

SQL Server provides some assemblies that could be of use with the name SMO that have seamless integration with PowerShell. Here is an article on that.

http://www.databasejournal.com/features/mssql/article.php/3696731

There are API methods to execute stored procedures that I think are worth being investigated. Here a startup example:

http://www.eggheadcafe.com/software/aspnet/29974894/smo-running-a-stored-pro.aspx

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

Algorithm for solving Sudoku

Here is my sudoku solver in python. It uses simple backtracking algorithm to solve the puzzle. For simplicity no input validations or fancy output is done. It's the bare minimum code which solves the problem.

Algorithm

  1. Find all legal values of a given cell
  2. For each legal value, Go recursively and try to solve the grid

Solution

It takes 9X9 grid partially filled with numbers. A cell with value 0 indicates that it is not filled.

Code

def findNextCellToFill(grid, i, j):
        for x in range(i,9):
                for y in range(j,9):
                        if grid[x][y] == 0:
                                return x,y
        for x in range(0,9):
                for y in range(0,9):
                        if grid[x][y] == 0:
                                return x,y
        return -1,-1

def isValid(grid, i, j, e):
        rowOk = all([e != grid[i][x] for x in range(9)])
        if rowOk:
                columnOk = all([e != grid[x][j] for x in range(9)])
                if columnOk:
                        # finding the top left x,y co-ordinates of the section containing the i,j cell
                        secTopX, secTopY = 3 *(i//3), 3 *(j//3) #floored quotient should be used here. 
                        for x in range(secTopX, secTopX+3):
                                for y in range(secTopY, secTopY+3):
                                        if grid[x][y] == e:
                                                return False
                        return True
        return False

def solveSudoku(grid, i=0, j=0):
        i,j = findNextCellToFill(grid, i, j)
        if i == -1:
                return True
        for e in range(1,10):
                if isValid(grid,i,j,e):
                        grid[i][j] = e
                        if solveSudoku(grid, i, j):
                                return True
                        # Undo the current cell for backtracking
                        grid[i][j] = 0
        return False

Testing the code


>>> input = [[5,1,7,6,0,0,0,3,4],[2,8,9,0,0,4,0,0,0],[3,4,6,2,0,5,0,9,0],[6,0,2,0,0,0,0,1,0],[0,3,8,0,0,6,0,4,7],[0,0,0,0,0,0,0,0,0],[0,9,0,0,0,0,0,7,8],[7,0,3,4,0,0,5,6,0],[0,0,0,0,0,0,0,0,0]]
>>> solveSudoku(input)
True
>>> input
[[5, 1, 7, 6, 9, 8, 2, 3, 4], [2, 8, 9, 1, 3, 4, 7, 5, 6], [3, 4, 6, 2, 7, 5, 8, 9, 1], [6, 7, 2, 8, 4, 9, 3, 1, 5], [1, 3, 8, 5, 2, 6, 9, 4, 7], [9, 5, 4, 7, 1, 3, 6, 8, 2], [4, 9, 5, 3, 6, 2, 1, 7, 8], [7, 2, 3, 4, 8, 1, 5, 6, 9], [8, 6, 1, 9, 5, 7, 4, 2, 3]]

The above one is very basic backtracking algorithm which is explained at many places. But the most interesting and natural of the sudoku solving strategies I came across is this one from here

Using an integer as a key in an associative array in JavaScript

Sometimes I use a prefixes for my keys. For example:

var pre = 'foo',
    key = pre + 1234

obj = {};

obj[key] = val;

Now you don't have any problem accessing them.

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How to get row count using ResultSet in Java?

I just made a getter method.

public int getNumberRows(){
    try{
       statement = connection.creatStatement();
       resultset = statement.executeQuery("your query here");
       if(resultset.last()){
          return resultset.getRow();
       } else {
           return 0; //just cus I like to always do some kinda else statement.
       }
    } catch (Exception e){
       System.out.println("Error getting row count");
       e.printStackTrace();
    }
    return 0;
}

Cannot create SSPI context

Had a really weird instance of this; All the web products that had connection strings containing the windows computer name of the SQL server worked fine, but the products that had a FQDN with the internal domain attached gave an SSPI error. i.e. COMPUTERNAME vs COMPUTERNAME.DOMAIN (ping always worked as expected)

This ONLY gave problems when a new SQL server was being used and hosts files pointed both the computer name and the computername as a FQDN for the connection strings.

Solution in this case was to set all the connection strings to the computer name only, removing the domain references.

SQL : 2008R2 SQL2012

IIS : 2008R2

JSON character encoding

The symptoms indicate that the JSON string which was originally in UTF-8 encoding was written to the HTTP response using ISO-8859-1 encoding and the webbrowser was instructed to display it as UTF-8. If it was written using UTF-8 and displayed as ISO-8859-1, then you would have seen aériennes. If it was written and displayed using ISO-8859-1, then you would have seen a�riennes.

To fix the problem of the JSON string incorrectly been written as ISO-8859-1, you need to configure your webapp / Spring to use UTF-8 as HTTP response encoding. Basically, it should be doing the following under the covers:

response.setCharacterEncoding("UTF-8");

Don't change your content type header. It's perfectly fine for JSON and it is been displayed as UTF-8.

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

How to loop through a directory recursively to delete files with certain extensions

There is no reason to pipe the output of find into another utility. find has a -delete flag built into it.

find /tmp -name '*.pdf' -or -name '*.doc' -delete

Xampp-mysql - "Table doesn't exist in engine" #1932

I also had same issue on my mac. I was running 5.3.0 version. I removed that version and installed 7.2.1 version. After this it is working in my case.

How to prevent favicon.ico requests?

You can use .htaccess or server directives to deny access to favicon.ico, but the server will send an access denied reply to the browser and this still slows page access.

You can stop the browser requesting favicon.ico when a user returns to your site, by getting it to stay in the browser cache.

First, provide a small favicon.ico image, could be blank, but as small as possible. I made a black and white one under 200 bytes. Then, using .htaccess or server directives, set the file Expires header a month or two in the future. When the same user comes back to your site it will be loaded from the browser cache and no request will go to your site. No more 404's in the server logs too.

If you have control over a complete Apache server or maybe a virtual server you can do this:-

If the server document root is say /var/www/html then add this to /etc/httpd/conf/httpd.conf:-

Alias /favicon.ico "/var/www/html/favicon.ico"
<Directory "/var/www/html">
    <Files favicon.ico>
       ExpiresActive On
       ExpiresDefault "access plus 1 month"
    </Files>
</Directory>

Then a single favicon.ico will work for all the virtual hosted sites since you are aliasing it. It will be drawn from the browser cache for a month after the users visit.

For .htaccess this is reported to work (not checked by me):-

AddType image/x-icon .ico
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"

How to Sort Multi-dimensional Array by Value?

If anyone need sort according to key best is to use below

usort($array, build_sorter('order'));

function build_sorter($key) {
   return function ($a, $b) use ($key) {
      return strnatcmp($a[$key], $b[$key]);
   };
}

Can a local variable's memory be accessed outside its scope?

After returning from a function, all identifiers are destroyed instead of kept values in a memory location and we can not locate the values without having an identifier.But that location still contains the value stored by previous function.

So, here function foo() is returning the address of a and a is destroyed after returning its address. And you can access the modified value through that returned address.

Let me take a real world example:

Suppose a man hides money at a location and tells you the location. After some time, the man who had told you the money location dies. But still you have the access of that hidden money.

Server Error in '/' Application. ASP.NET

The key information in this error is this line:

This error can be caused by a virtual directory not being configured as an application in IIS.

In IIS, you can have several applications, but they must be configured as an application. Generally, when you create a web project it maps directly to an IIS application.

Check with your hosting service on how to create an IIS application for your web app.

Edit - added If this is on your server, you can set this up yourself following the instructions in @Frazell Thomas's answer. He beat me to finding that link. To save yourself some reading, you should be able to focus in on the Creating Virtual Directories and Local Web Sites section.

res.sendFile absolute path

Another way to do this by writing less code.

app.use(express.static('public'));

app.get('/', function(req, res) {
   res.sendFile('index.html');
});

How to run Gulp tasks sequentially one after the other

To wait and see if the task is finished and then the rest, I have it this way:

gulp.task('default',
  gulp.series('set_env', gulp.parallel('build_scss', 'minify_js', 'minify_ts', 'minify_html', 'browser_sync_func', 'watch'),
    function () {
    }));

Kudos: https://fettblog.eu/gulp-4-parallel-and-series/

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How to show PIL images on the screen?

If you find that PIL has problems on some platforms, using a native image viewer may help.

img.save("tmp.png") #Save the image to a PNG file called tmp.png.

For MacOS:

import os
os.system("open tmp.png") #Will open in Preview.

For most GNU/Linux systems with X.Org and a desktop environment:

import os
os.system("xdg-open tmp.png")

For Windows:

import os
os.system("powershell -c tmp.png")

Display back button on action bar

In your onCreate() method add this line

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and, in the same Activity, add this method to handle the button click

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

What is the difference between declarations, providers, and import in NgModule?

imports are used to import supporting modules like FormsModule, RouterModule, CommonModule, or any other custom-made feature module.

declarations are used to declare components, directives, pipes that belong to the current module. Everyone inside declarations knows each other. For example, if we have a component, say UsernameComponent, which displays a list of the usernames and we also have a pipe, say toupperPipe, which transforms a string to an uppercase letter string. Now If we want to show usernames in uppercase letters in our UsernameComponent then we can use the toupperPipe which we had created before but the question is how UsernameComponent knows that the toupperPipe exists and how it can access and use that. Here come the declarations, we can declare UsernameComponent and toupperPipe.

Providers are used for injecting the services required by components, directives, pipes in the module.

How to define a Sql Server connection string to use in VB.NET?

The Connection String Which We Are Assigning from server side will be same as that From Web config File. The Catalog: Means To Database it is followed by Username and Password And DataClient The New sql connection establishes The connection to sql server by using the credentials in the connection string.. Then it is followed by sql command which retrives the required data in the dataset and then we assing them to required variables or controls to get the required task done

How to style components using makeStyles and still have lifecycle methods in Material UI?

Instead of converting the class to a function, an easy step would be to create a function to include the jsx for the component which uses the 'classes', in your case the <container></container> and then call this function inside the return of the class render() as a tag. This way you are moving out the hook to a function from the class. It worked perfectly for me. In my case it was a <table> which i moved to a function- TableStmt outside and called this function inside the render as <TableStmt/>

How to update a claim in ASP.NET Identity?

Multiple Cookies,Multiple Claims

public class ClaimsCookie
    {
        private readonly ClaimsPrincipal _user;
        private readonly HttpContext _httpContext;
        public ClaimsCookie(ClaimsPrincipal user, HttpContext httpContext = null)
        {
            _user = user;
            _httpContext = httpContext;
        }

        public string GetValue(CookieName cookieName, KeyName keyName)
        {
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            return cp.FindFirst(((KeyName)keyName).ToString()).Value;
        }
        public async void SetValue(CookieName cookieName, KeyName[] keyName, string[] value)
        {
            if (keyName.Length != value.Length)
            {
                return;
            }
            var principal = _user as ClaimsPrincipal;
            var cp = principal.Identities.First(i => i.AuthenticationType == ((CookieName)cookieName).ToString());
            for (int i = 0; i < keyName.Length; i++)
            {
                if (cp.FindFirst(((KeyName)keyName[i]).ToString()) != null)
                {
                    cp.RemoveClaim(cp.FindFirst(((KeyName)keyName[i]).ToString()));
                    cp.AddClaim(new Claim(((KeyName)keyName[i]).ToString(), value[i]));
                }

            }
            await _httpContext.SignOutAsync(CookieName.UserProfilCookie.ToString());
            await _httpContext.SignInAsync(CookieName.UserProfilCookie.ToString(), new ClaimsPrincipal(cp),
                new AuthenticationProperties
                {
                    IsPersistent = bool.Parse(cp.FindFirst(KeyName.IsPersistent.ToString()).Value),
                    AllowRefresh = true
                });
        }
        public enum CookieName
        {
            CompanyUserProfilCookie = 0, UserProfilCookie = 1, AdminPanelCookie = 2
        }
        public enum KeyName
        {
            Id, Name, Surname, Image, IsPersistent
        }
    }

css to make bootstrap navbar transparent

This works for 4.0.

<nav class="navbar navbar-expand-sm fixed-top navbar-light">
or
<nav class="navbar navbar-expand-lg fixed-top navbar-dark">

key item is fixed-top, otherwise, white or default page background is displayed even if there is a image top. navbar-light gives dark letters, navbar-dark shows light text.

DateDiff to output hours and minutes

No need to jump through hoops. Subtracting Start from End essentially gives you the timespan (combining Vignesh Kumar's and Carl Nitzsche's answers) :

SELECT *,
    --as a time object
    TotalHours = CONVERT(time, EndDate - StartDate),
    --as a formatted string
    TotalHoursText = CONVERT(varchar(20), EndDate - StartDate, 114)
FROM (
    --some test values (across days, but OP only cares about the time, not date)
    SELECT
        StartDate = CONVERT(datetime,'20090213 02:44:37.923'),
        EndDate   = CONVERT(datetime,'20090715 13:24:45.837')
) t

Ouput

StartDate               EndDate                 TotalHours       TotalHoursText
----------------------- ----------------------- ---------------- --------------------
2009-02-13 02:44:37.923 2009-07-15 13:24:45.837 10:40:07.9130000 10:40:07:913

See the full cast and convert options here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Simple search MySQL database using php

If you do mysqli_fetch_array(), you must put integer in $row index ex.($row[3]).If you read $row['id'] or $row['example'], you must use mysqli_fetch_assoc.

Using Java 8 to convert a list of objects into a string obtained from the toString() method

There is a collector joining in the API. It's a static method in Collectors.

list.stream().map(Object::toString).collect(Collectors.joining(","))

Not perfect because of the necessary call of toString, but works. Different delimiters are possible.

error: src refspec master does not match any

FWIW, ran into same error, but believe it came about due to the following sequence of events:

  • Remote Git repo was created with master branch.
  • Local clone was then created.
  • Remote Git repo was then modified to include a dev branch, which was defined as the default branch, in conjunction with permissions added to the master branch preventing changes without a pull request.
  • Code updates occurred in the local clone, ready to be pushed to the remote repo.

Then, when attempting to push changes from the local to the remote, received error "src refspec master does not match any", or when attempting to push to dev, "src refspec dev does not match any".

Because changes were pending in the local clone, I did not want to blast it and refresh. So, fixed the issue by renaming the local branch to dev...

$ git branch -m dev

...followed by the normal push of git push origin dev, which worked this time without throwing the aforementioned error.

MATLAB - multiple return values from a function?

Use the following in the function you will call and it will work just fine.

     [a b c] = yourfunction(optional)
     %your code
     a = 5;
     b = 7;
     c = 10;
     return
     end

This is a way to call the function both from another function and from the command terminal

     [aa bb cc] = yourfunction(optional);

The variables aa, bb and cc now hold the return variables.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Date formatting in WPF datagrid

first select datagrid and then go to properties find Datagrid_AutoGeneratingColumn and the double click And then use this code

   Datagrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
            {
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
                if (e.PropertyName == "Your column name")
                    (e.Column as DataGridTextColumn).Binding.StringFormat = "dd/MMMMMMMMM/yyyy";
            }

I try it it works on WPF

Mean of a column in a data frame, given the column's name

if your column contain any value that you want to neglect. it will help you

## da is data frame & Ozone is column name 

##for single column
mean(da$Ozone, na.rm = TRUE)  

##for all columns
colMeans(x=da, na.rm = TRUE)

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

Convert DateTime to long and also the other way around

There is a DateTime constructor that takes a long.

DateTime today = new DateTime(t); // where t represents long format of dateTime 

How to execute XPath one-liners from shell?

I've tried a couple of command line XPath utilities and when I realized I am spending too much time googling and figuring out how they work, so I wrote the simplest possible XPath parser in Python which did what I needed.

The script below shows the string value if the XPath expression evaluates to a string, or shows the entire XML subnode if the result is a node:

#!/usr/bin/env python
import sys
from lxml import etree

tree = etree.parse(sys.argv[1])
xpath = sys.argv[2]

for e in tree.xpath(xpath):

    if isinstance(e, str):
        print(e)
    else:
        print((e.text and e.text.strip()) or etree.tostring(e))

It uses lxml — a fast XML parser written in C which is not included in the standard python library. Install it with pip install lxml. On Linux/OSX might need prefixing with sudo.

Usage:

python xmlcat.py file.xml "//mynode"

lxml can also accept an URL as input:

python xmlcat.py http://example.com/file.xml "//mynode" 

Extract the url attribute under an enclosure node i.e. <enclosure url="http:...""..>):

python xmlcat.py xmlcat.py file.xml "//enclosure/@url"

Xpath in Google Chrome

As an unrelated side note: If by chance you want to run an XPath expression against the markup of a web page then you can do it straight from the Chrome devtools: right-click the page in Chrome > select Inspect, and then in the DevTools console paste your XPath expression as $x("//spam/eggs").

Get all authors on this page:

$x("//*[@class='user-details']/a/text()")

Addition for BigDecimal

BigDecimal no = new BigDecimal(10); //you can add like this also
no = no.add(new BigDecimal(10));
System.out.println(no);

20

querySelectorAll with multiple conditions

According to the documentation, just like with any css selector, you can specify as many conditions as you want, and they are treated as logical 'OR'.

This example returns a list of all div elements within the document with a class of either "note" or "alert":

var matches = document.querySelectorAll("div.note, div.alert");

source: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

Meanwhile to get the 'AND' functionality you can for example simply use a multiattribute selector, as jquery says:

https://api.jquery.com/multiple-attribute-selector/

ex. "input[id][name$='man']" specifies both id and name of the element and both conditions must be met. For classes it's as obvious as ".class1.class2" to require object of 2 classes.

All possible combinations of both are valid, so you can easily get equivalent of more sophisticated 'OR' and 'AND' expressions.

Regex to validate JSON

Here my regexp for validate string:

^\"([^\"\\]*|\\(["\\\/bfnrt]{1}|u[a-f0-9]{4}))*\"$

Was written usign original syntax diagramm.

How can I download HTML source in C#

basically:

using System.Net;
using System.Net.Http;  // in LINQPad, also add a reference to System.Net.Http.dll

WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";

string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
    source = reader.ReadToEnd();
}

Console.WriteLine(source);

Custom Authentication in ASP.Net-Core

From what I learned after several days of research, Here is the Guide for ASP .Net Core MVC 2.x Custom User Authentication

In Startup.cs :

Add below lines to ConfigureServices method :

public void ConfigureServices(IServiceCollection services)
{

services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme
).AddCookie(CookieAuthenticationDefaults.AuthenticationScheme,
    options =>
    {
        options.LoginPath = "/Account/Login";
        options.LogoutPath = "/Account/Logout";
    });

    services.AddMvc();

    // authentication 
    services.AddAuthentication(options =>
    {
       options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    });

    services.AddTransient(
        m => new UserManager(
            Configuration
                .GetValue<string>(
                    DEFAULT_CONNECTIONSTRING //this is a string constant
                )
            )
        );
     services.AddDistributedMemoryCache();
}

keep in mind that in above code we said that if any unauthenticated user requests an action which is annotated with [Authorize] , they well force redirect to /Account/Login url.

Add below lines to Configure method :

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
        app.UseDatabaseErrorPage();
    }
    else
    {
        app.UseExceptionHandler(ERROR_URL);
    }
     app.UseStaticFiles();
     app.UseAuthentication();
     app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: DEFAULT_ROUTING);
    });
}

Create your UserManager class that will also manage login and logout. it should look like below snippet (note that i'm using dapper):

public class UserManager
{
    string _connectionString;

    public UserManager(string connectionString)
    {
        _connectionString = connectionString;
    }

    public async void SignIn(HttpContext httpContext, UserDbModel user, bool isPersistent = false)
    {
        using (var con = new SqlConnection(_connectionString))
        {
            var queryString = "sp_user_login";
            var dbUserData = con.Query<UserDbModel>(
                queryString,
                new
                {
                    UserEmail = user.UserEmail,
                    UserPassword = user.UserPassword,
                    UserCellphone = user.UserCellphone
                },
                commandType: CommandType.StoredProcedure
            ).FirstOrDefault();

            ClaimsIdentity identity = new ClaimsIdentity(this.GetUserClaims(dbUserData), CookieAuthenticationDefaults.AuthenticationScheme);
            ClaimsPrincipal principal = new ClaimsPrincipal(identity);

            await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
        }
    }

    public async void SignOut(HttpContext httpContext)
    {
        await httpContext.SignOutAsync();
    }

    private IEnumerable<Claim> GetUserClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Name, user.UserFirstName));
        claims.Add(new Claim(ClaimTypes.Email, user.UserEmail));
        claims.AddRange(this.GetUserRoleClaims(user));
        return claims;
    }

    private IEnumerable<Claim> GetUserRoleClaims(UserDbModel user)
    {
        List<Claim> claims = new List<Claim>();

        claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id().ToString()));
        claims.Add(new Claim(ClaimTypes.Role, user.UserPermissionType.ToString()));
        return claims;
    }
}

Then maybe you have an AccountController which has a Login Action that should look like below :

public class AccountController : Controller
{
    UserManager _userManager;

    public AccountController(UserManager userManager)
    {
        _userManager = userManager;
    }

    [HttpPost]
    public IActionResult LogIn(LogInViewModel form)
    {
        if (!ModelState.IsValid)
            return View(form);
         try
        {
            //authenticate
            var user = new UserDbModel()
            {
                UserEmail = form.Email,
                UserCellphone = form.Cellphone,
                UserPassword = form.Password
            };
            _userManager.SignIn(this.HttpContext, user);
             return RedirectToAction("Search", "Home", null);
         }
         catch (Exception ex)
         {
            ModelState.AddModelError("summary", ex.Message);
            return View(form);
         }
    }
}

Now you are able to use [Authorize] annotation on any Action or Controller.

Feel free to comment any questions or bug's.

How To Launch Git Bash from DOS Command Line?

I prefer, putting git in environment variable and just calling

c:\Users\[myname]>sh
or 
c:\Users\[myname]>bash

Steps to create Environment variable (Win7)

  • From the desktop, right click the Computer icon.
  • Choose Properties from the context menu.
  • Click the Advanced system settings link.
  • Click Environment Variables.
  • In the section User variables, hit button NEW, put variable name as GIT_HOME, value as (folder-where-you-installed-git).

    • for me it is was c:\tools\git, others maybe have C:\Program Files\Git
  • find the PATH environment variable and select it. Click Edit. (If the PATH environment variable does not exist, click New).

  • In the Edit window, add a new value %GIT_HOME% and %GIT_HOME%\bin. Click OK. Close all remaining windows by clicking OK.
  • [Make sure you close the CMD which you want use for git]
  • open new Command prompt, and just type sh or bash or git-bash

How can I make a checkbox readonly? not disabled?

There is no property to make the checkbox readonly. But you can try this trick.

<input type="checkbox" onclick="return false" />

DEMO

How to use switch statement inside a React component?


function Notification({ text, status }) {
  return (
    <div>
      {(() => {
        switch (status) {
          case 'info':
            return <Info text={text} />;
          case 'warning':
            return <Warning text={text} />;
          case 'error':
            return <Error text={text} />;
          default:
            return null;
        }
      })()}
    </div>
  );
}

Spring Data JPA map the native query result to Non-Entity POJO

You can do something like

@NamedQuery(name="IssueDescriptor.findByIssueDescriptorId" ,

    query=" select new com.test.live.dto.IssuesDto (idc.id, dep.department, iss.issueName, 
               cat.issueCategory, idc.issueDescriptor, idc.description) 
            from Department dep 
            inner join dep.issues iss 
            inner join iss.category cat 
            inner join cat.issueDescriptor idc 
            where idc.id in(?1)")

And there must be Constructor like

public IssuesDto(long id, String department, String issueName, String issueCategory, String issueDescriptor,
            String description) {
        super();
        this.id = id;
        this.department = department;
        this.issueName = issueName;
        this.issueCategory = issueCategory;
        this.issueDescriptor = issueDescriptor;
        this.description = description;
    }

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

I had this problem as well.

I got it working with this:

.ui-dialog{
    display:inline-block;
}

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

Updating others' answers with the new syntax:

<li *ngFor="let obj of myArray">{{obj | json}}</li>

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

Iterate through 2 dimensional array

Consider it as an array of arrays and this will work for sure.

int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
                {15, 25, 35, 45},
                {27, 29, 37, 48},
                {32, 33, 39, 50, 51, 89},
              };


    for(int i=0; i<mat.length; i++) {
        for(int j=0; j<mat[i].length; j++) {
            System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
        }
    }

Show hide fragment in android

Try this:

MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.mapview);
mapFragment.getView().setVisibility(View.GONE);

How make background image on newsletter in outlook?

You can use it only in body tag or in tables. Something like this:

<table width="100%" background="YOUR_IMAGE_URL" style="STYLES YOU WANT (i.e. background-repeat)">

This worked for me.

GoogleMaps API KEY for testing

There seems no way to have google maps api key free without credit card. To test the functionality of google map you can use it while leaving the api key field "EMPTY". It will show a message saying "For Development Purpose Only". And that way you can test google map functionality without putting billing information for google map api key.

<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap" async defer></script>

Bootstrap 4 Change Hamburger Toggler Color

Use a font-awesome icon as the default icon of your navbar.

<span class="navbar-toggler-icon">   
    <i class="fas fa-bars" style="color:#fff; font-size:28px;"></i>
</span>

Or try this on old font-awesome versions:

<span class="navbar-toggler-icon">   
    <i class="fa fa-navicon" style="color:#fff; font-size:28px;"></i>
</span>

What is the difference between visibility:hidden and display:none?

There are a lot of detailed answers here, but I thought I should add this to address accessibility since there are implications.

display: none; and visibility: hidden; may not be read by all screen reader software. Keep in mind what visually-impaired users will experience.

The question also asks about synonyms. text-indent: -9999px; is one other that is roughly equivalent. The important difference with text-indent is that it will often be read by screen readers. It can be a bit of a bad experience as users can still tab to the link.

For accessibility, what I see used today is a combination of styles to hide an element while being visible to screen readers.

{
  clip: rect(1px, 1px, 1px, 1px);
  clip-path: inset(50%);
  height: 1px;
  width: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
}

A great practice is to create a "Skip to content" link to the anchor of the main body of content. Visually-impaired users probably don't want to listen to your full navigation tree on every single page. Make the link visually hidden. Users can just hit tab to access the link.

For more on accessibility and hidden content, see:

How to check if Thread finished execution

Use Thread.Join(TimeSpan.Zero) It will not block the caller and returns a value indicating whether the thread has completed its work. By the way, that is the standard way of testing all WaitHandle classes as well.

How to get the excel file name / path in VBA

If you need path only this is the most straightforward way:

PathOnly = ThisWorkbook.Path

Check table exist or not before create it in Oracle

-- checks for table in specfic schema:

declare n number(10);

begin
    Select count(*) into n  from SYS.All_All_Tables where owner = 'MYSCHEMA' and TABLE_NAME =  'EMPLOYEE';

   if (n = 0) then 
     execute immediate 
     'create table MYSCHEMA.EMPLOYEE ( ID NUMBER(3), NAME VARCHAR2(30) NOT NULL)';      
   end if;
end;

Restore the mysql database from .frm files

Yes! It is possible

Long approach but you can get all the data's using just .frm files. Of course you need other files in the mysql/data directory.

My Problem

One day my harddisk crashed and got the booting blue screen error. I try connecting with multiple machine and it didn't work. Since it is a booting error i was concered about the files. and i tryed with the secondary harddisk and try to recover the folders and files. I also backed up the full xampp folder c:/xampp just in case, Because I had no back of the recent databases i got really worried how to retrieve the database. we have lot of clients project management and personal doc in the database.

None of the method listed on the stackoverflow comment works, at-least for me. It took me 2 full days googling for the answer to get the data's from the .frm files. Came across multiple approaches from many people but everything was frustration and getting some error or another when implementing. If most of them get it working (based on their comment) then what am i missing.

Because i was so desperate I even reinstall windows which result in loosing all my softwares and tried again. But still the same error

THANKS to Dustin Davis

i found the solution in his blog and i managed to get it working exactly the same way he did. Let me give the credit to this guy, Dustin Davis (https://dustindavis.me/restoring-mysql-innodb-files-on-windows/). You could jump from here to his blog and try his method, pretty clear and easy to follow.

But there are something i discovered when trying his approach which he hasn't explained in his blog and i will try my best to explain how i did and what you need to look for.

Follow this exactly

IMPORTANT: Make sure you to install the same version of XAMPP. You cannot copy paste from older XAMPP to a new version. This will result in __config or __tracking errors.

How to check your XAMPP version

  1. Go to your xampp folder (your backed up xampp).
  2. Open the readme_en.txt file. which is in the root directory of the xampp.
  3. You should see the version on top. ###### ApacheFriends XAMPP Version X.X.XX ######

Files require to restore

xampp(old folder)/mysql/data/

ibdata1
ib_logfile0
ib_logfile1
<databasename>/*.frm
<databasename>/*.ibd

Step 1

  1. After installed the same version of xampp.
  2. Do not start the apache or myql

Step 2

  • Go to the mysql/data folder and replace the ibdata1, ib_logfile0, and ib_logfile1
  • Now copy paste your database folder from your old xampp backup to the newly installed xampp folder c:/xampp/mysql/data/ that contain .frm and .ibd files, If you are not sure try with one database.

Step 3

  • Go to c:/xampp/mysql/bin and look for my.cn.
  • Open the my.cn file and look for #skip-innodb and under that look for the line that says innodb_log_file_size=5M change it to 170M. innodb_log_file_size=170M. This is your log file size and if you are not sure just set it to 170

Step 4

  • Now open the file mysql_start.bat (Windows Batch file) that is in the c:/xampp/ directory.
  • Add –innodb_force_recovery=6 after the ... --console

    ....
    
    mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
    –innodb_force_recovery=6
    if errorlevel 1 goto error
    goto finish
    

Step 5

  • Now Start your Apache and Mysql.
  • Go to your phpmyadmin and check for your database and its tables. if you do not get any errors you are on the right track.
  • Stop the Apache and Mysql and copy paste the rest of the databases.

How to set editor theme in IntelliJ Idea

IntelliJ IDEA seems to have reorganized the configurations panel. Now one should go to Editor -> Color Scheme and click on the gears icon to import the theme they want from external .jar files.

MongoDB and "joins"

I came across lot of posts searching for the same - "Mongodb Joins" and alternatives or equivalents. So my answer would help many other who are like me. This is the answer I would be looking for.

I am using Mongoose with Express framework. There is a functionality called Population in place of joins.

As mentioned in Mongoose docs.

There are no joins in MongoDB but sometimes we still want references to documents in other collections. This is where population comes in.

This StackOverflow answer shows a simple example on how to use it.

Calendar date to yyyy-MM-dd format in java

A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

Java 8+

LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"

String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12

Prior to Java 8

You should be making use of the ThreeTen Backport

The following is maintained for historical purposes (as the original answer)

What you can do, is format the date.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"

System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"

These are actually the same date, represented differently.

How do I launch the Android emulator from the command line?

A launcher script which lists existing AVDs and lets you pick the one you want. Requires python3 (at least v3.4) and a valid environment variable ANDROID_HOME or ANDROID_SDK pointing to the Android SDK dir.

#!/usr/bin/env python3

import os
import subprocess
from pathlib import Path

android_emulator_dir: Path = Path(os.environ['ANDROID_HOME'] or os.environ['ANDROID_SDK']) / 'emulator'

if android_emulator_dir.exists():
    emulator_dir = android_emulator_dir.absolute()
    print(f'SDK emulator dir: {emulator_dir}', end='\n\n')

    proc = subprocess.Popen(['./emulator', '-list-avds'], stdout=subprocess.PIPE, cwd=emulator_dir, text=True)
    avds = {idx: avd_name.strip() for idx, avd_name in enumerate(proc.stdout, start=1)}

    print('\n'.join([f'{idx}: {avd_name}' for idx, avd_name in avds.items()]))

    avd_idx = input("\nType AVD index and press Enter... ")
    avd_name = avds.get(int(avd_idx))

    if avd_name:
        subprocess.Popen(['./emulator', '-avd', avd_name, '-no-boot-anim'], cwd=emulator_dir)
    else:
        print('Invalid AVD index')
else:
    print(f'Either $ANDROID_HOME or $ANDROID_SDK must be defined!')

AppleScript version (MacOS only)

osascript -e '
set avds to paragraphs of (do shell script "~/Library/Android/sdk/emulator/emulator -list-avds")
set avd to (choose from list avds with prompt "Please select an AVD to start" default items "None" OK button name {"Start"} cancel button name {"Cancel"})
do shell script "~/Library/Android/sdk/emulator/emulator -avd " & avd & " -no-boot-anim > /dev/null 2>&1 &"
'

The script above can also be run from the Script Editor.app or from Automator.app (the bit between the single quotes). Also you can use Script Editor to save it as a native macos app: select File on the menu, press and hold the ? (Option) key, select Save As and then select File Format: Application.

Printing column separated by comma using Awk command line

Try this awk

awk -F, '{$0=$3}1' file
column3
  • , Divide fields by ,
  • $0=$3 Set the line to only field 3
  • 1 Print all out. (explained here)

This could also be used:

awk -F, '{print $3}' file

AttributeError: 'DataFrame' object has no attribute

value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:

df['accepted'].value_counts()

It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using

df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()

Unknown version of Tomcat was specified in Eclipse

As soon as you provide the directory where Tomcat needs to be installed and click ok you can notice download and installation starts in the progress tab of Eclipse.

enter image description here

Let the process complete.The error will automatically disappear.

enter image description here

Note: It is not mandatory to name your folder CATALINA_HOME. I have tested this with windows. Cannot assert the same for Linux but IMO same rule should apply.

How can strip whitespaces in PHP's variable?

Sometimes you would need to delete consecutive white spaces. You can do it like this:

$str = "My   name    is";
$str = preg_replace('/\s\s+/', ' ', $str);

Output:

My name is

C# - Simplest way to remove first occurrence of a substring from another string

I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.

public static string Remove(this string source, string remove,  int firstN)
    {
        if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
        {
            return source;
        }
        int index = source.IndexOf(remove);
        return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);
    }

This does a bit of recursion which is always fun.

Here is a simple unit test as well:

   [TestMethod()]
    public void RemoveTwiceTest()
    {
        string source = "look up look up look it up";
        string remove = "look";
        int firstN = 2;
        string expected = " up  up look it up";
        string actual;
        actual = source.Remove(remove, firstN);
        Assert.AreEqual(expected, actual);

    }