Programs & Examples On #Bisect

ModuleNotFoundError: What does it mean __main__ is not a package?

If you have created directory and sub-directory, follow the steps below and please keep in mind all directory must have __init__.py to get it recognized as a directory.

  1. In your script, include import sys and sys.path, you will be able to see all the paths available to Python. You must be able to see your current working directory.

  2. Now import sub-directory and respective module that you want to use using: import subdir.subdir.modulename as abc and now you can use the methods in that module.

enter image description here

As an example, you can see in this screenshot I have one parent directory and two sub-directories and under second sub-directories I have the module CommonFunction. On the right my console shows that after execution of sys.path, I can see my working directory.

Style bottom Line in Android

I feel it is straightforward, without all this negative paddings or storks.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/main_bg_color"/>
    <item android:gravity="bottom">
        <shape android:shape="rectangle">
            <size android:height="5dp"/>
            <solid android:color="@color/bottom_bar_color"/>
        </shape>
    </item>
</layer-list>

Find which commit is currently checked out in Git

You have at least 5 different ways to view the commit you currently have checked out into your working copy during a git bisect session (note that options 1-4 will also work when you're not doing a bisect):

  1. git show.
  2. git log -1.
  3. Bash prompt.
  4. git status.
  5. git bisect visualize.

I'll explain each option in detail below.

Option 1: git show

As explained in this answer to the general question of how to determine which commit you currently have checked-out (not just during git bisect), you can use git show with the -s option to suppress patch output:

$ git show --oneline -s
a9874fd Merge branch 'epic-feature'

Option 2: git log -1

You can also simply do git log -1 to find out which commit you're currently on.

$ git log -1 --oneline
c1abcde Add feature-003

Option 3: Bash prompt

In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have c1abcde checked out:

# Prompt during a bisect
user ~ (c1abcde...)|BISECTING $

# Prompt at detached HEAD state 
user ~ (c1abcde...) $

Option 4: git status

Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running git status will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:

$ git status
# HEAD detached at c1abcde <== RIGHT HERE

Option 5: git bisect visualize

Finally, while you're doing a git bisect, you can also simply use git bisect visualize or its built-in alias git bisect view to launch gitk, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:

git bisect visualize 
git bisect view # shorter, means same thing

enter image description here

Binary search (bisection) in Python

Check out the examples on Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

def binary_search(a, key, imin=0, imax=None):
    if imax is None:
        # if max amount not set, get the total
        imax = len(a) - 1

    while imin <= imax:
        # calculate the midpoint
        mid = (imin + imax)//2
        midval = a[mid]

        # determine which subarray to search
        if midval < key:
            # change min index to search upper subarray
            imin = mid + 1
        elif midval > key:
            # change max index to search lower subarray
            imax = mid - 1
        else:
            # return index number 
            return mid
    raise ValueError

PHPMailer: SMTP Error: Could not connect to SMTP host

I had a similar issue and figured out that it was the openssl.cafile configuration directive in php.ini that needed to be set to allow verification of secure peers. You just set it to the location of a certificate authority file like the one you can get at http://curl.haxx.se/docs/caextract.html.

This directive is new as of PHP 5.6 so this caught me off guard when upgrading from PHP 5.5.

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

It's definitely an issue with some of the projects being built for x86 compatibility instead of any CPU. If I had to guess I would say that some of the references between your projects are probably referencing the dll's in some of the bin\debug folders instead of being project references.

When a project is compiled for x86 instead of 'Any CPU' the dll's go into the bin\x86\debug folder instead of bin\debug (which is probably where your references are looking).

But in any case, you should be using project references between your projects.

Laravel: Get Object From Collection By Attribute

You can use filter, like so:

$desired_object = $food->filter(function($item) {
    return $item->id == 24;
})->first();

filter will also return a Collection, but since you know there will be only one, you can call first on that Collection.

You don't need the filter anymore (or maybe ever, I don't know this is almost 4 years old). You can just use first:

$desired_object = $food->first(function($item) {
    return $item->id == 24;
});

Is there a native jQuery function to switch elements?

No need to use jquery for any major browser to swap elements at the moment. Native dom method, insertAdjacentElement does the trick no matter how they are located:

var el1 = $("el1");
var el2 = $("el2");
el1[0].insertAdjacentElement("afterend", el2[0]);

Keep only first n characters in a string?

Use the string.substring(from, to) API. In your case, use string.substring(0,8).

Matplotlib color according to class labels

A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:

arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)

Selenium using Python - Geckodriver executable needs to be in PATH

from webdriverdownloader import GeckoDriverDownloader # vs ChromeDriverDownloader vs OperaChromiumDriverDownloader
gdd = GeckoDriverDownloader()
gdd.download_and_install()
#gdd.download_and_install("v0.19.0")

This will get you the path to your gekodriver.exe on Windows.

from selenium import webdriver
driver = webdriver.Firefox(executable_path=r'C:\\Users\\username\\\bin\\geckodriver.exe')
driver.get('https://www.amazon.com/')

Center image using text-align center?

display: block with margin: 0 didn't work for me, neither wrapping with a text-align: center element.

This is my solution:

img.center {
    position: absolute;
    transform: translateX(-50%);
    left: 50%;
}

translateX is supported by most browsers

Best way to retrieve variable values from a text file?

You can treat your text file as a python module and load it dynamically using imp.load_source:

import imp
imp.load_source( name, pathname[, file]) 

Example:

// mydata.txt
var1 = 'hi'
var2 = 'how are you?'
var3 = { 1:'elem1', 2:'elem2' }
//...

// In your script file
def getVarFromFile(filename):
    import imp
    f = open(filename)
    global data
    data = imp.load_source('data', '', f)
    f.close()

# path to "config" file
getVarFromFile('c:/mydata.txt')
print data.var1
print data.var2
print data.var3
...

Make Iframe to fit 100% of container's remaining height

Here are a few modern approaches:


  • Approach 1 - Combination of viewport relative units / calc().

    The expression calc(100vh - 30px) represents the remaining height. Where 100vh is the height of the browser and the usage of calc() effectively displaces the height of the other element.

    Example Here

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .banner {_x000D_
        background: #f00;_x000D_
        height: 30px;_x000D_
    }_x000D_
    iframe {_x000D_
        display: block;_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        height: calc(100vh - 30px);_x000D_
        width: 100%;_x000D_
    }
    _x000D_
    <div class="banner"></div>_x000D_
    <iframe></iframe>
    _x000D_
    _x000D_
    _x000D_

    Support for calc() here; support for viewport relative units here.


  • Approach 2 - Flexbox approach

    Example Here

    Set the display of the common parent element to flex, along with flex-direction: column (assuming you want the elements to stack on top of each other). Then set flex-grow: 1 on the child iframe element in order for it to fill the remaining space.

    _x000D_
    _x000D_
    body {_x000D_
        margin: 0;_x000D_
    }_x000D_
    .parent {_x000D_
        display: flex;_x000D_
        flex-direction: column;_x000D_
        min-height: 100vh;_x000D_
    }_x000D_
    .parent .banner {_x000D_
        background: #f00;_x000D_
        width: 100%;_x000D_
        height: 30px;_x000D_
    }_x000D_
    .parent iframe {_x000D_
        background: #000;_x000D_
        border: none;_x000D_
        flex-grow: 1;_x000D_
    }
    _x000D_
    <div class="parent">_x000D_
        <div class="banner"></div>_x000D_
        <iframe></iframe>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Since this approach has less support1, I'd suggest going with the aforementioned approach.

1Though it seems to work in Chrome/FF, it doesn't work in IE (the first method works in all current browsers).

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

How do I wrap text in a pre tag?

You can either:

pre { white-space: normal; }

to maintain the monospace font but add word-wrap, or:

pre { overflow: auto; }

which will allow a fixed size with horizontal scrolling for long lines.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

The configuration I use in my parent level pom where I have separate unit and integration test phases.

I configure the following properties in the parent POM Properties

    <maven.surefire.report.plugin>2.19.1</maven.surefire.report.plugin>
    <jacoco.plugin.version>0.7.6.201602180812</jacoco.plugin.version>
    <jacoco.check.lineRatio>0.52</jacoco.check.lineRatio>
    <jacoco.check.branchRatio>0.40</jacoco.check.branchRatio>
    <jacoco.check.complexityMax>15</jacoco.check.complexityMax>
    <jacoco.skip>false</jacoco.skip>
    <jacoco.excludePattern/>
    <jacoco.destfile>${project.basedir}/../target/coverage-reports/jacoco.exec</jacoco.destfile>

    <sonar.language>java</sonar.language>
    <sonar.exclusions>**/generated-sources/**/*</sonar.exclusions>
    <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
    <sonar.coverage.exclusions>${jacoco.excludePattern}</sonar.coverage.exclusions>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/coverage-reports</sonar.jacoco.reportPath>

    <skip.surefire.tests>${skipTests}</skip.surefire.tests>
    <skip.failsafe.tests>${skipTests}</skip.failsafe.tests>

I place the plugin definitions under plugin management.

Note that I define a property for surefire (surefireArgLine) and failsafe (failsafeArgLine) arguments to allow jacoco to configure the javaagent to run with each test.

Under pluginManagement

  <build>
     <pluginManagment>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <fork>true</fork>
                    <meminitial>1024m</meminitial>
                    <maxmem>1024m</maxmem>
                    <compilerArgument>-g</compilerArgument>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>-Xmx2048m ${surefireArgLine}</argLine>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <excludes>
                        <exclude>**/*IT.java</exclude>
                    </excludes>
                    <skip>${skip.surefire.tests}</skip>
                </configuration>
            </plugin>
            <plugin>
                <!-- For integration test separation -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.19.1</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>${failsafeArgLine}</argLine>
                    <includes>
                        <include>**/*IT.java</include>
                    </includes>
                    <skip>${skip.failsafe.tests}</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <!-- Code Coverage -->
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco.plugin.version}</version>
                <configuration>
                    <haltOnFailure>true</haltOnFailure>
                    <excludes>
                        <exclude>**/*.mar</exclude>
                        <exclude>${jacoco.excludePattern}</exclude>
                    </excludes>
                    <rules>
                        <rule>
                            <element>BUNDLE</element>
                            <limits>
                                <limit>
                                    <counter>LINE</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.lineRatio}</minimum>
                                </limit>
                                <limit>
                                    <counter>BRANCH</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.branchRatio}</minimum>
                                </limit>
                            </limits>
                        </rule>
                        <rule>
                            <element>METHOD</element>
                            <limits>
                                <limit>
                                    <counter>COMPLEXITY</counter>
                                    <value>TOTALCOUNT</value>
                                    <maximum>${jacoco.check.complexityMax}</maximum>
                                </limit>
                            </limits>
                        </rule>
                    </rules>
                </configuration>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.surefire.tests}</skip>
                        </configuration>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>failsafeArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.failsafe.tests}</skip>
                        </configuration>
                    </execution>
                    <!-- Disabled until such time as code quality stops this tripping
                    <execution>
                        <id>default-check</id>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                        </configuration>
                    </execution>
                    -->
                </executions>
            </plugin>
            ...

And in the build section

 <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
        </plugin>

        <plugin>
            <!-- for unit test execution -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For integration test separation -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For code coverage -->
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
        </plugin>
        ....

And in the reporting section

    <reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-report-plugin</artifactId>
            <version>${maven.surefire.report.plugin}</version>
            <configuration>
                <showSuccess>false</showSuccess>
                <alwaysGenerateFailsafeReport>true</alwaysGenerateFailsafeReport>
                <alwaysGenerateSurefireReport>true</alwaysGenerateSurefireReport>
                <aggregate>true</aggregate>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.plugin.version}</version>
            <configuration>
                <excludes>
                    <exclude>**/*.mar</exclude>
                    <exclude>${jacoco.excludePattern}</exclude>
                </excludes>
            </configuration>
        </plugin>
     </plugins>
  </reporting>

Accessing dict keys like an attribute?

The easiest way is to define a class let's call it Namespace. which uses the object dict.update() on the dict. Then, the dict will be treated as an object.

class Namespace(object):
    '''
    helps referencing object in a dictionary as dict.key instead of dict['key']
    '''
    def __init__(self, adict):
        self.__dict__.update(adict)



Person = Namespace({'name': 'ahmed',
                     'age': 30}) #--> added for edge_cls


print(Person.name)

C# Form.Close vs Form.Dispose

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

SQL Server default character encoding

The default character encoding for a SQL Server database is iso_1, which is ISO 8859-1. Note that the character encoding depends on the data type of a column. You can get an idea of what character encodings are used for the columns in a database as well as the collations using this SQL:

select data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name, count(*) count
from information_schema.columns
group by data_type, character_set_catalog, character_set_schema, character_set_name, collation_catalog, collation_schema, collation_name;

If it's using the default, the character_set_name should be iso_1 for the char and varchar data types. Since nchar and nvarchar store Unicode data in UCS-2 format, the character_set_name for those data types is UNICODE.

Add leading zeroes to number in Java?

In case of your jdk version less than 1.5, following option can be used.

    int iTest = 2;
    StringBuffer sTest = new StringBuffer("000000"); //if the string size is 6
    sTest.append(String.valueOf(iTest));
    System.out.println(sTest.substring(sTest.length()-6, sTest.length()));

Array inside a JavaScript Object?

var obj = {
 webSiteName: 'StackOverFlow',
 find: 'anything',
 onDays: ['sun'     // Object "obj" contains array "onDays" 
            ,'mon',
            'tue',
            'wed',
            'thu',
            'fri',
            'sat',
             {name : "jack", age : 34},
              // array "onDays"contains array object "manyNames"
             {manyNames : ["Narayan", "Payal", "Suraj"]}, //                 
           ]
};

Regular expression replace in C#

You can do it this with two replace's

//let stw be "John Smith $100,000.00 M"

sb_trim = Regex.Replace(stw, @"\s+\$|\s+(?=\w+$)", ",");
//sb_trim becomes "John Smith,100,000.00,M"

sb_trim = Regex.Replace(sb_trim, @"(?<=\d),(?=\d)|[.]0+(?=,)", "");
//sb_trim becomes "John Smith,100000,M"

sw.WriteLine(sb_trim);

Disable LESS-CSS Overwriting calc()

Apart from using an escaped value as described in my other answer, it is also possible to fix this issue by enabling the Strict Math setting.

With strict math on, only maths that are inside unnecessary parentheses will be processed, so your code:

width: calc(100% - 200px);

Would work as expected with the strict math option enabled.

However, note that Strict Math is applied globally, not only inside calc(). That means, if you have:

font-size: 12px + 2px;

The math will no longer be processed by Less -- it will output font-size: 12px + 2px which is, obviously, invalid CSS. You'd have to wrap all maths that should be processed by Less in (previously unnecessary) parentheses:

font-size: (12px + 2px);

Strict Math is a nice option to consider when starting a new project, otherwise you'd possibly have to rewrite a good part of the code base. For the most common use cases, the escaped string approach described in the other answer is more suitable.

Simulate a click on 'a' element using javascript/jquery

Code snippet underneath!

Please take a look at these documentations and examples at MDN, and you will find your answer. This is the propper way to do it I would say.

Creating and triggering events

Dispatch Event (example)

Taken from the 'Dispatch Event (example)'-HTML-link (simulate click):

function simulateClick() {

  var evt = document.createEvent("MouseEvents");

  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);

  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);

  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

This is how I would do it (2017 ..) :

Simply using MouseEvent.

function simulateClick() {

    var evt = new MouseEvent("click");

    var cb = document.getElementById("checkbox");
    var canceled = !cb.dispatchEvent(evt);

    if (canceled) {
        // A handler called preventDefault
        console.log("canceled");
    } else {
        // None of the handlers called preventDefault
        console.log("not canceled");
    }
}

_x000D_
_x000D_
document.getElementById("button").onclick = evt => {_x000D_
    _x000D_
    simulateClick()_x000D_
}_x000D_
_x000D_
function simulateClick() {_x000D_
_x000D_
    var evt = new MouseEvent("click");_x000D_
_x000D_
    var cb = document.getElementById("checkbox");_x000D_
    var canceled = !cb.dispatchEvent(evt);_x000D_
_x000D_
    if (canceled) {_x000D_
        // A handler called preventDefault_x000D_
        console.log("canceled");_x000D_
    } else {_x000D_
        // None of the handlers called preventDefault_x000D_
        console.log("not canceled");_x000D_
    }_x000D_
}
_x000D_
<input type="checkbox" id="checkbox">_x000D_
<br>_x000D_
<br>_x000D_
<button id="button">Check it out, or not</button>
_x000D_
_x000D_
_x000D_

SQL Server 2008- Get table constraints

SELECT
    [oj].[name] [TableName],
    [ac].[name] [ColumnName],
    [dc].[name] [DefaultConstraintName],
    [dc].[definition]
FROM
    sys.default_constraints [dc],
    sys.all_objects [oj],
    sys.all_columns [ac]
WHERE
    (
        ([oj].[type] IN ('u')) AND
        ([oj].[object_id] = [dc].[parent_object_id]) AND
        ([oj].[object_id] = [ac].[object_id]) AND
        ([dc].[parent_column_id] = [ac].[column_id])
    )

jquery mobile background image

Try this. This should work:

<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
    data-theme="a">

What range of values can integer types store in C++

Other folks here will post links to data_sizes and precisions etc.
I'm going to tell you how to figure it out yourself.
Write a small app that will do the following.

unsigned int ui;
std::cout <<  sizeof(ui));

this will (depending on compiler and archicture) print 2, 4 or 8, saying 2 bytes long, 4 bytes long etc.

Lets assume it's 4.

You now want the maximum value 4 bytes can store, the max value for one byte is (in hex)0xFF. The max value of four bytes is 0x followed by 8 f's (one pair of f's for each byte, the 0x tells the compiler that the following string is a hex number). Now change your program to assign that value and print the result

unsigned int ui = 0xFFFFFFFF;
std::cout <<  ui;

Thats the max value an unsigned int can hold, shown in base 10 representation.

Now do that for long's, shorts and any other INTEGER value you're curious about.

NB: This approach will not work for floating point numbers (i.e. double or float).

Hope this helps

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

git switch branch without discarding local changes

You can use :

  1. git stash to save your work
  2. git checkout <your-branch>
  3. git stash apply or git stash pop to load your last work

Git stash extremely useful when you want temporarily save undone or messy work, while you want to doing something on another branch.

git -stash documentation

How can we programmatically detect which iOS version is device running on?

Best current version, without need to deal with numeric search within NSString is to define macros (See original answer: Check iPhone iOS Version)

Those macros do exist in github, see: https://github.com/carlj/CJAMacros/blob/master/CJAMacros/CJAMacros.h

Like this:

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

and use them like this:

if (SYSTEM_VERSION_LESS_THAN(@"5.0")) {
    // code here
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
    // code here
}

Outdated version below

to get OS version:

[[UIDevice currentDevice] systemVersion]

returns string, which can be turned into int/float via

-[NSString floatValue]
-[NSString intValue]

like this

Both values (floatValue, intValue) will be stripped due to its type, 5.0.1 will become 5.0 or 5 (float or int), for comparing precisely, you will have to separate it to array of INTs check accepted answer here: Check iPhone iOS Version

NSString *ver = [[UIDevice currentDevice] systemVersion];
int ver_int = [ver intValue];
float ver_float = [ver floatValue];

and compare like this

NSLog(@"System Version is %@",[[UIDevice currentDevice] systemVersion]);
NSString *ver = [[UIDevice currentDevice] systemVersion];
float ver_float = [ver floatValue];
if (ver_float < 5.0) return false;

For Swift 4.0 syntax

below example is just checking if the device is of iOS11 or greater version.

let systemVersion = UIDevice.current.systemVersion
if systemVersion.cgFloatValue >= 11.0 {
    //"for ios 11"
  }
else{
   //"ios below 11")
  }

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

How to convert IPython notebooks to PDF and HTML?

Also pass the --execute flag to generate the output cells

jupyter nbconvert --execute --to html notebook.ipynb
jupyter nbconvert --execute --to pdf notebook.ipynb

The best practice is to keep the output out of the notebook for version control, see: Using IPython notebooks under version control

But then, if you don't pass --execute, the output won't be present in the HTML, see also: How to run an .ipynb Jupyter Notebook from terminal?

For an HTML fragment without header: How to export an IPython notebook to HTML for a blog post?

Tested in Jupyter 4.4.0.

CSS to stop text wrapping under image

For those who want some background info, here's a short article explaining why overflow: hidden works. It has to do with the so-called block formatting context. This is part of W3C's spec (ie is not a hack) and is basically the region occupied by an element with a block-type flow.

Every time it is applied, overflow: hidden creates a new block formatting context. But it's not the only property capable of triggering that behaviour. Quoting a presentation by Fiona Chan from Sydney Web Apps Group:

  • float: left / right
  • overflow: hidden / auto / scroll
  • display: table-cell and any table-related values / inline-block
  • position: absolute / fixed

How to include file in a bash shell script

Above answers are correct, but if run script in other folder, there will be some problem.

For example, the a.sh and b.sh are in same folder, a include b with . ./b.sh to include.

When run script out of the folder, for example with xx/xx/xx/a.sh, file b.sh will not found: ./b.sh: No such file or directory.

I use

. $(dirname "$0")/b.sh

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How to extract elements from a list using indices in Python?

Bounds checked:

 [a[index] for index in (1,2,5,20) if 0 <= index < len(a)]
 # [11, 12, 15] 

How to convert An NSInteger to an int?

I'm not sure about the circumstances where you need to convert an NSInteger to an int.

NSInteger is just a typedef:

NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

You can use NSInteger any place you use an int without converting it.

QByteArray to QString

You can use:

QString::fromStdString(byteArray.toStdString())

How to wrap text in textview in Android

Try @Guykun's approach

android:layout_weight="1" android:ellipsize="none" android:maxLines="100" android:scrollHorizontally="false"

Also, make sure that parents width is not set to wrap content. This is the thing that I was missing.

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

Android - Adding at least one Activity with an ACTION-VIEW intent-filter after Updating SDK version 23

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.app"
tools:ignore="GoogleAppIndexingWarning">

You can remove the warning by adding xmlns:tools="http://schemas.android.com/tools" and tools:ignore="GoogleAppIndexingWarning" to the <manifest> tag.

Practical uses of git reset --soft?

SourceTree is a git GUI which has a pretty convenient interface for staging just the bits you want. It does not have anything remotely similar for amending a proper revision.

So git reset --soft HEAD~1 is much more useful than commit --amend in this scenario. I can undo the commit, get all the changes back into the staging area, and resume tweaking the staged bits using SourceTree.

Really, it seems to me that commit --amend is the more redundant command of the two, but git is git and does not shy away from similar commands that do slightly different things.

How to create war files

A war file is simply a jar file with a war extension, but what makes it work is how the contents is actually structured.

The J2EE/Java EE tutorial can be a start:

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/WebComponents3.html

And the Servlet specification contains the gory details:

http://java.sun.com/products/servlet/download.html

If you create a new web project in Eclipse (I am referring to the Java EE version), the structure is created for you and you can also tell it where your Appserver is installed and it will deploy and start the application for you.

Using the "Export->WAR file" option will let you save the war file.

how to replace an entire column on Pandas.DataFrame

For those that struggle with the "SettingWithCopy" warning, here's a workaround which may not be so efficient, but still gets the job done.

Suppose you with to overwrite column_1 and column_3, but retain column_2 and column_4

columns_to_overwrite = ["column_1", "column_3"]

First delete the columns that you intend to replace...

original_df.drop(labels=columns_to_overwrite, axis="columns", inplace=True)

... then re-insert the columns, but using the values that you intended to overwrite

original_df[columns_to_overwrite] = other_data_frame[columns_to_overwrite]

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {_x000D_
   key1: 'value1',_x000D_
   key2: 'value2',_x000D_
   key3: 'value3',_x000D_
   key4: 'value4'_x000D_
}_x000D_
var keys = Object.keys(obj);_x000D_
console.log('obj contains ' + keys.length + ' keys: '+  keys);
_x000D_
_x000D_
_x000D_

It's supported on most major browsers now.

How do I set the timeout for a JAX-WS webservice client?

Not sure if this will help in your context...

Can the soap object be cast as a BindingProvider ?

MyWebServiceSoap soap;
MyWebService service = new MyWebService("http://www.google.com");
soap = service.getMyWebServiceSoap();
// set timeouts here
((BindingProvider)soap).getRequestContext().put("com.sun.xml.internal.ws.request.timeout", 10000);
    soap.sendRequestToMyWebService();

On the other hand if you are wanting to set the timeout on the initialization of the MyWebService object then this will not help.

This worked for me when wanting to timeout the individual WebService calls.

What is the difference between Nexus and Maven?

Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

Details

Create a date time with month and day only, no year

How about creating a timer with the next date?

In your timer callback you create the timer for the following year? DateTime has always a year value. What you want to express is a recurring time specification. This is another type which you would need to create. DateTime is always represents a specific date and time but not a recurring date.

How does Java deal with multiple conditions inside a single IF statement

Please look up the difference between & and && in Java (the same applies to | and ||).

& and | are just logical operators, while && and || are conditional logical operators, which in your example means that

if(bool1 && bool2 && bool3) {

will skip bool2 and bool3 if bool1 is false, and

if(bool1 & bool2 & bool3) {

will evaluate all conditions regardless of their values.

For example, given:

boolean foo() {
    System.out.println("foo");
    return true;
}

if(foo() | foo()) will print foo twice, and if(foo() || foo()) - just once.

Login credentials not working with Gmail SMTP

I had same issue. And I fix it with creating an app-password for Email application on Mac. You can find it at my account -> Security -> Signing in to Google -> App passwords. below is the link for it. https://myaccount.google.com/apppasswords?utm_source=google-account&utm_medium=web

extracting days from a numpy.timedelta64 value

Use dt.days to obtain the days attribute as integers.

For eg:

In [14]: s = pd.Series(pd.timedelta_range(start='1 days', end='12 days', freq='3000T'))

In [15]: s
Out[15]: 
0    1 days 00:00:00
1    3 days 02:00:00
2    5 days 04:00:00
3    7 days 06:00:00
4    9 days 08:00:00
5   11 days 10:00:00
dtype: timedelta64[ns]

In [16]: s.dt.days
Out[16]: 
0     1
1     3
2     5
3     7
4     9
5    11
dtype: int64

More generally - You can use the .components property to access a reduced form of timedelta.

In [17]: s.dt.components
Out[17]: 
   days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
0     1      0        0        0             0             0            0
1     3      2        0        0             0             0            0
2     5      4        0        0             0             0            0
3     7      6        0        0             0             0            0
4     9      8        0        0             0             0            0
5    11     10        0        0             0             0            0

Now, to get the hours attribute:

In [23]: s.dt.components.hours
Out[23]: 
0     0
1     2
2     4
3     6
4     8
5    10
Name: hours, dtype: int64

The difference in months between dates in MySQL

You can also try this:

select MONTH(NOW())-MONTH(table_date) as 'Total Month Difference' from table_name;

OR

select MONTH(Newer_date)-MONTH(Older_date) as 'Total Month Difference' from table_Name;

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

.NET Core vs Mono

This is one of my favorite topics and the content here was just amazing. I was thinking if it would be worth while or effective to compare the methods available in Runtime vs. Mono. I hope I got my terms right, but I think you know what I mean. In order to have a somewhat better understanding of what each Runtime supports currently, would it make sense to compare the methods they provide? I realize implementations may vary, and I have not considered the Framework Class libraries or the slew of other libraries available in one environment vs. the other. I also realize someone might have already done this work even more efficiently. I would be most grateful if you would let me know so I can review it. I feel doing a diff between the outcome of such activity would be of value, and wanted to see how more experienced developers feel about it, and would they provide useful guidance. While back I was playing with reflection, and wrote some lines that traverse the .net directory, and list the assemblies.

How to detect shake event with android?

You can also take a look on library Seismic

public class Demo extends Activity implements ShakeDetector.Listener {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    ShakeDetector sd = new ShakeDetector(this);
    sd.start(sensorManager);

    TextView tv = new TextView(this);
    tv.setGravity(CENTER);
    tv.setText("Shake me, bro!");
    setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
  }

  @Override public void hearShake() {
    Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
  }
}

Finding even or odd ID values

dividend % divisor

Dividend is the numeric expression to divide. Dividend must be any expression of integer data type in sql server.

Divisor is the numeric expression to divide the dividend. Divisor must be expression of integer data type except in sql server.

SELECT 15 % 2

Output
1

Dividend = 15

Divisor = 2

Let's say you wanted to query

Query a list of CITY names from STATION with even ID numbers only.

Schema structure for STATION:

ID Number

CITY varchar

STATE varchar


select CITY from STATION as st where st.id % 2 = 0

Will fetch the even set of records 


In order to fetch the odd records with Id as odd number.

select CITY from STATION as st where st.id % 2 <> 0

% function reduces the value to either 0 or 1

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

you can use an external package if you cant upgrade to 4.5. One such is Ionic.Zip.dll from DotNetZipLib.

using Ionic.Zip;

you can download it here, its free. http://dotnetzip.codeplex.com/

Java: export to an .jar file in eclipse

FatJar can help you in this case.

In addition to the"Export as Jar" function which is included to Eclipse the Plug-In bundles all dependent JARs together into one executable jar.
The Plug-In adds the Entry "Build Fat Jar" to the Context-Menu of Java-projects

This is useful if your final exported jar includes other external jars.

If you have Ganymede, the Export Jar dialog is enough to export your resources from your project.

After Ganymede, you have:

Export Jar

How to establish a connection pool in JDBC?

Usually if you need a connection pool you are writing an application that runs in some managed environment, that is you are running inside an application server. If this is the case be sure to check what connection pooling facilities your application server providesbefore trying any other options.

The out-of-the box solution will be the best integrated with the rest of the application servers facilities. If however you are not running inside an application server I would recommend the Apache Commons DBCP Component. It is widely used and provides all the basic pooling functionality most applications require.

How do I get a list of all subdomains of a domain?

The hint (using axfr) only works if the NS you're querying (ns1.foo.bar in your example) is configured to allow AXFR requests from the IP you're using; this is unlikely, unless your IP is configured as a secondary for the domain in question.

Basically, there's no easy way to do it if you're not allowed to use axfr. This is intentional, so the only way around it would be via brute force (i.e. dig a.some_domain.com, dig b.some_domain.com, ...), which I can't recommend, as it could be viewed as a denial of service attack.

How do I get user IP address in django?

No More confusion In the recent versions of Django it is mentioned clearly that the Ip address of the client is available at

request.META.get("REMOTE_ADDR")

for more info check the Django Docs

Getting last month's date in php

If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months')); what? first date will always be 1 :D

How to execute a MySQL command from a shell script?

As stated before you can use -p to pass the password to the server.

But I recommend this:

mysql -h "hostaddress" -u "username" -p "database-name" < "sqlfile.sql"

Notice the password is not there. It would then prompt your for the password. I would THEN type it in. So that your password doesn't get logged into the servers command line history.

This is a basic security measure.

If security is not a concern, I would just temporarily remove the password from the database user. Then after the import - re-add it.

This way any other accounts you may have that share the same password would not be compromised.

It also appears that in your shell script you are not waiting/checking to see if the file you are trying to import actually exists. The perl script may not be finished yet.

What is difference between png8 and png24

While making image with fully transparent background in PNG-8, the outline of the image looks prominent with little white bits. But in PNG-24 the outline is gone and looks perfect. Transparency in PNG-24 is greater and cleaner than PNG-8.

PNG-8 contains 256 colors, while PNG-24 contains 16 million colors.

File size is almost double in PNG-24 than PNG-8.

Remove grid, background color, and top and right borders from ggplot2

The above options do not work for maps created with sf and geom_sf(). Hence, I want to add the relevant ndiscr parameter here. This will create a nice clean map showing only the features.

library(sf)
library(ggplot2)

ggplot() + 
  geom_sf(data = some_shp) + 
  theme_minimal() +                     # white background
  theme(axis.text = element_blank(),    # remove geographic coordinates
        axis.ticks = element_blank()) + # remove ticks
  coord_sf(ndiscr = 0)                  # remove grid in the background

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Your listener.ora is misconfigured. There is no orcl service.

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

Return multiple values to a method caller

From this article, you can use three options as posts above said.

KeyValuePair is quickest way.

out is at the second.

Tuple is the slowest.

Anyway, this is depend on what is the best for your scenario.

How do I set bold and italic on UILabel of iPhone/iPad?

Swift 3

Bold:

let bondFont = UIFont.boldSystemFont(ofSize:UIFont.labelFontSize)

Italic:

let italicFont = UIFont.italicSystemFont(ofSize:UIFont.labelFontSize)

How to get the path of a running JAR file?

Other answers seem to point to the code source which is Jar file location which is not a directory.

Use

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();

How to count days between two dates in PHP?

You can use date_diff to calculate the difference between two dates:

$date1 = date_create("2013-03-15");
$date2 = date_create("2013-12-12");
$diff =  date_diff($date1 , $date2);
echo  $diff->format("%R%a days");

read string from .resx file in C#

The Simplest Way to get value from resource file. Add Resource file in the project. Now get the string where you want to add like in my case it was text block(SilverLight). No need to add any namespace also.Its working fine in my case

txtStatus.Text = Constants.RefractionUpdateMessage;

Constants is my resource file name in the project.Here how my resource file look like

How to test valid UUID/GUID?

thanks to @usertatha with some modification

function isUUID ( uuid ) {
    let s = "" + uuid;

    s = s.match('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$');
    if (s === null) {
      return false;
    }
    return true;
}

How to download dependencies in gradle

This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy.

// There are a few dependencies added by one of the Scala plugins that this cannot reach.
task downloadDependencies {
  description "Pre-downloads *most* dependencies"
  doLast {
    configurations.getAsMap().each { name, config ->
      println "Retrieving dependencies for $name"
      try {
        config.files
      } catch (e) {
        project.logger.info e.message // some cannot be resolved, silentlyish skip them
      }
    }
  }
}

I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to reduce the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.

Eclipse will not open due to environment variables

First uninstall all java software like JRE 7 or JRE 6 or JDK ,then open the following path :

START > CONTROL PANEL > ADVANCED SETTING > ENVIRONMENT VARIABLE > SYSTEM VARIABLE > PATH

Then click on Edit button and paste the following text to Variable_Value and click OK.

C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft SQL Server\90\Tools\binn\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\

Now go to this url http://java.com/en/download/manual.jsp and click on Windows Offline and click on run and start again eclipse.

Enjoy it!

Find CRLF in Notepad++

On the Replace dialog, you want to set the search mode to "Extended". Normal or Regular Expression modes wont work.

Then just find "\r\n" (or just \n for unix files or just \r for mac format files), and set the replace to whatever you want.

How is the AND/OR operator represented as in Regular Expressions?

Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"

Bootstrap: wider input field

There is also a smaller one yet called "input-mini".

Java balanced expressions check {[()]}

public class StackProb {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    List<Boolean> list = new ArrayList<>();

    while (sc.hasNextLine()) {
        String s=sc.nextLine();
        if(!s.isEmpty()) {
            list.add(isBalanced(s));
            //System.out.println(isBalanced(s));
        }else {
            sc.close();
            break;
        }
    }

    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i) + " ");
    }

}

private static boolean isBalanced(String s) {
    boolean res = false;
    Stack<Character> stack = new Stack();
    int countA = 0;
    int countB = 0;
    for (int i = 0; i < s.length(); i++) {

        if(s.charAt(i)=='{' || s.charAt(i)=='(' || s.charAt(i)=='[') {

            stack.push(s.charAt(i));
            countA++;
        }


        if(s.charAt(i)=='}' || s.charAt(i)==')' || s.charAt(i)==']') {

            stack.push(s.charAt(i));
            countB++;
        }

        if(stack.firstElement()=='}' || stack.firstElement()==')' || stack.firstElement()==']') {
            countB++;
        }


    }
    if(countA==countB) {
        return true;
    }
    return false;

}

}

How to display JavaScript variables in a HTML page without document.write

there are different ways of doing this. one way would be to write a script retrieving a command. like so:

var name="kieran";
document.write=(name);

or we could use the default JavaScript way to print it.

var name="kieran";
document.getElementById("output").innerHTML=name;

and the html code would be: 

<p id="output"></p>

i hope this helped :)

Add column to SQL Server

Add new column to Table with default value.

ALTER TABLE NAME_OF_TABLE
ADD COLUMN_NAME datatype
DEFAULT DEFAULT_VALUE

Inserting values to SQLite table in Android

You'll find debugging errors like this a lot easier if you catch any errors thrown from the execSQL call. eg:

 try 
 {
      db.execSQL(Create_CashBook);  
 }
 catch (Exception e) 
 {
       Log.e("ERROR", e.toString());
 }

String length in bytes in JavaScript

Another very simple approach using Buffer (only for NodeJS):

Buffer.byteLength(string, 'utf8')

Buffer.from(string).length

Carriage return and Line feed... Are both required in C#?

It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.

Difference between try-catch and throw in java

try block contains set of statements where an exception can occur.

catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

// Java program to demonstrate working of throws, throw, try, catch and finally.

 public class MyExample { 
      
        static void myMethod() throws IllegalAccessException 
        { 
            System.out.println("Inside myMethod()."); 
            throw new IllegalAccessException("demo"); 
        } 
      
        // This is a caller function  
        public static void main(String args[]) 
        { 
            try { 
                myMethod(); 
            } 
            catch (IllegalAccessException e) { 
                System.out.println("exception caught in main method."); 
            }
            finally(){
                System.out.println("I am in final block.");
            } 
        } 
    } 

Output:

Inside myMethod().
exception caught in main method.
I am in final block.

What is the purpose of .PHONY in a Makefile?

Let's assume you have install target, which is a very common in makefiles. If you do not use .PHONY, and a file named install exists in the same directory as the Makefile, then make install will do nothing. This is because Make interprets the rule to mean "execute such-and-such recipe to create the file named install". Since the file is already there, and its dependencies didn't change, nothing will be done.

However if you make the install target PHONY, it will tell the make tool that the target is fictional, and that make should not expect it to create the actual file. Hence it will not check whether the install file exists, meaning: a) its behavior will not be altered if the file does exist and b) extra stat() will not be called.

Generally all targets in your Makefile which do not produce an output file with the same name as the target name should be PHONY. This typically includes all, install, clean, distclean, and so on.

Scroll to the top of the page using JavaScript?

<script>
$(function(){
   var scroll_pos=(0);          
   $('html, body').animate({scrollTop:(scroll_pos)}, '2000');
});
</script>

Edit:

$('html, body').animate({scrollTop:(scroll_pos)}, 2000);

Another way scroll with top and left margin:

window.scrollTo({ top: 100, left: 100, behavior: 'smooth' });

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

As it has been explained here, beside of multiple extensions that perform ad or script blocking you may aware that this may happen by file names as below:

Particularly in the AdBlock Plus the character string "-300x600" is causing the Failed to Load Resource ERR_BLOCKED_BY_CLIENT problem.

As shown in the picture, some of the images were blocked because of the '-300x600' pattern in their name, that particular text pattern matches an expression list pattern in the AdBlock Plus.

ERR_BLOCKED_BY_CLIENT problem

svn over HTTP proxy

when you use the svn:// URI it uses port 3690 and probably won't use http proxy

How do I specify "close existing connections" in sql script

try this C# code to drop your database

public static void DropDatabases(string dataBase) {

        string sql =  "ALTER DATABASE "  + dataBase + "SET SINGLE_USER WITH ROLLBACK IMMEDIATE" ;

        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["DBRestore"].ConnectionString))
        {
            connection.Open();
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
            sql = "DROP DATABASE " + dataBase;
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(sql, connection))
            {
                command.CommandType = CommandType.Text;
                command.CommandTimeout = 7200;
                command.ExecuteNonQuery();
            }
        }
    }

How do you set a JavaScript onclick event to a class with css

Here is my solution through CSS, It does not use any JavaScript at all

HTML:

<a href="#openModal">Open Modal</a>

<div id="openModal" class="modalDialog">
        <div>   <a href="#close" title="Close" class="close">X</a>

                <h2>Modal Box</h2>

            <p>This is a sample modal box that can be created using the powers of CSS3.</p>
            <p>You could do a lot of things here like have a pop-up ad that shows when your website loads, or create a login/register form for users.</p>
        </div>
    </div>

CSS:

.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 99999;
    opacity:0;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    pointer-events: none;
}
.modalDialog:target {
    opacity:1;
    pointer-events: auto;
}
.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}
.close {
    background: #606061;
    color: #FFFFFF;
    line-height: 25px;
    position: absolute;
    right: -12px;
    text-align: center;
    top: -10px;
    width: 24px;
    text-decoration: none;
    font-weight: bold;
    -webkit-border-radius: 12px;
    -moz-border-radius: 12px;
    border-radius: 12px;
    -moz-box-shadow: 1px 1px 3px #000;
    -webkit-box-shadow: 1px 1px 3px #000;
    box-shadow: 1px 1px 3px #000;
}
.close:hover {
    background: #00d9ff;
}

CSS alert No JavaScript Just pure HTML and CSS

I believe that it will do the trick for you as it has for me

Selecting element by data attribute with jQuery

Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:

  • pure/plain JS with querySelector (uses CSS-selectors):
    • select the first in DOM: document.querySelector('[data-answer="42"],[type="submit"]')
    • select all in DOM: document.querySelectorAll('[data-answer="42"],[type="submit"]')
  • pure/plain CSS
    • some specific tags: [data-answer="42"],[type="submit"]
    • all tags with an specific attribute: [data-answer] or input[type]

symfony2 : failed to write cache directory

For a GOOD and definite solution see the Setting up Permissions section in Installing and Configuring Symfony section :

Setting up Permissions

One common issue when installing Symfony is that the app/cache and app/logs directories must be writable both by the web server and the command line user. On a UNIX system, if your web server user is different from your command line user, you can try one of the following solutions.

  1. Use the same user for the CLI and the web server

In development environments, it is a common practice to use the same UNIX user for the CLI and the web server because it avoids any of these permissions issues when setting up new projects. This can be done by editing your web server configuration (e.g. commonly httpd.conf or apache2.conf for Apache) and setting its user to be the same as your CLI user (e.g. for Apache, update the User and Group values).

  1. Using ACL on a system that supports chmod +a

Many systems allow you to use the chmod +a command. Try this first, and if you get an error - try the next method. This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ rm -rf app/cache/*
$ rm -rf app/logs/*

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo chmod +a "$HTTPDUSER allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
$ sudo chmod +a "`whoami` allow delete,write,append,file_inherit,directory_inherit" app/cache app/logs
  1. Using ACL on a system that does not support chmod +a

Some systems don't support chmod +a, but do support another utility called setfacl. You may need to enable ACL support on your partition and install setfacl before using it (as is the case with Ubuntu). This uses a command to try to determine your web server user and set it as HTTPDUSER:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX app/cache app/logs

For Symfony 3 it would be:

$ HTTPDUSER=`ps aux | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`
$ sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs
$ sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX var/cache var/logs

If this doesn't work, try adding -n option.

  1. Without using ACL

If none of the previous methods work for you, change the umask so that the cache and log directories will be group-writable or world-writable (depending if the web server user and the command line user are in the same group or not). To achieve this, put the following line at the beginning of the app/console, web/app.php and web/app_dev.php files:

umask(0002); // This will let the permissions be 0775

// or

umask(0000); // This will let the permissions be 0777

Note that using the ACL is recommended when you have access to them on your server because changing the umask is not thread-safe.

http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup

source : Failed to write cache file "/var/www/myapp/app/cache/dev/classes.php" when clearing the cache

How to know installed Oracle Client is 32 bit or 64 bit?

Go to %ORACLE_HOME%\inventory\ContentsXML folder and open comps.xml file

Look for <DEP_LIST> on ~second screen.
If following lines have

  • PLAT="NT_AMD64" then this Oracle Home is 64 bit.
  • PLAT="NT_X86" then - 32 bit.

    You may have both 32-bit and 64-bit Oracle Homes installed.

  • Increment value in mysql update query

    "UPDATE member_profile SET points = points + 1 WHERE user_id = '".$userid."'"
    

    JSON to pandas DataFrame

    Optimization of the accepted answer:

    The accepted answer has some functioning problems, so I want to share my code that does not rely on urllib2:

    import requests
    from pandas import json_normalize
    url = 'https://www.energidataservice.dk/proxy/api/datastore_search?resource_id=nordpoolmarket&limit=5'
    
    response = requests.get(url)
    dictr = response.json()
    recs = dictr['result']['records']
    df = json_normalize(recs)
    print(df)
    

    Output:

            _id                    HourUTC               HourDK  ... ElbasAveragePriceEUR  ElbasMaxPriceEUR  ElbasMinPriceEUR
    0    264028  2019-01-01T00:00:00+00:00  2019-01-01T01:00:00  ...                  NaN               NaN               NaN
    1    138428  2017-09-03T15:00:00+00:00  2017-09-03T17:00:00  ...                33.28              33.4              32.0
    2    138429  2017-09-03T16:00:00+00:00  2017-09-03T18:00:00  ...                35.20              35.7              34.9
    3    138430  2017-09-03T17:00:00+00:00  2017-09-03T19:00:00  ...                37.50              37.8              37.3
    4    138431  2017-09-03T18:00:00+00:00  2017-09-03T20:00:00  ...                39.65              42.9              35.3
    ..      ...                        ...                  ...  ...                  ...               ...               ...
    995  139290  2017-10-09T13:00:00+00:00  2017-10-09T15:00:00  ...                38.40              38.4              38.4
    996  139291  2017-10-09T14:00:00+00:00  2017-10-09T16:00:00  ...                41.90              44.3              33.9
    997  139292  2017-10-09T15:00:00+00:00  2017-10-09T17:00:00  ...                46.26              49.5              41.4
    998  139293  2017-10-09T16:00:00+00:00  2017-10-09T18:00:00  ...                56.22              58.5              49.1
    999  139294  2017-10-09T17:00:00+00:00  2017-10-09T19:00:00  ...                56.71              65.4              42.2 
    

    PS: API is for Danish electricity prices

    Modify table: How to change 'Allow Nulls' attribute from not null to allow null

    For MySQL, MariaDB

    ALTER TABLE [table name] MODIFY COLUMN [column name] [data type] NULL
    

    Use MODIFY COLUMN instead of ALTER COLUMN.

    Iterating through directories with Python

    Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):

    from pathlib import Path
    
    rootdir = Path('C:/Users/sid/Desktop/test')
    # Return a list of regular files only, not directories
    file_list = [f for f in rootdir.glob('**/*') if f.is_file()]
    
    # For absolute paths instead of relative the current dir
    file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]
    

    Since Python 3.5, the glob module also supports recursive file finding:

    import os
    from glob import iglob
    
    rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
    # This will return absolute paths
    file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]
    

    The file_list from either of the above approaches can be iterated over without the need for a nested loop:

    for f in file_list:
        print(f) # Replace with desired operations
    

    Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource

    I used the header("Access-Control-Allow-Origin: *"); method but still received the CORS error. It turns out that the PHP script that was being requested had an error in it (I had forgotten to add a period (.) when concatenating two variables). Once I fixed that typo, it worked!

    So, It seems that the remote script being called cannot have errors within it.

    How do I show the number keyboard on an EditText in android?

    If you need fractional number, then this is the answer for you:

    android:inputType="numberDecimal"
    

    What's the best way to use R scripts on the command line (terminal)?

    You might want to use python's rpy2 module. However, the "right" way to do this is with R CMD BATCH. You can modify this to write to STDOUT, but the default is to write to a .Rout file. See example below:

    [ramanujan:~]$cat foo.R
    print(rnorm(10))
    [ramanujan:~]$R CMD BATCH foo.R
    [ramanujan:~]$cat foo.Rout
    
    R version 2.7.2 (2008-08-25)
    Copyright (C) 2008 The R Foundation for Statistical Computing
    ISBN 3-900051-07-0
    
    R is free software and comes with ABSOLUTELY NO WARRANTY.
    You are welcome to redistribute it under certain conditions.
    Type 'license()' or 'licence()' for distribution details.
    
    R is a collaborative project with many contributors.
    Type 'contributors()' for more information and
    'citation()' on how to cite R or R packages in publications.
    
    Type 'demo()' for some demos, 'help()' for on-line help, or
    'help.start()' for an HTML browser interface to help.
    Type 'q()' to quit R.
    
    [Previously saved workspace restored]
    
    
     ~/.Rprofile loaded.
    Welcome at  Fri Apr 17 13:33:17 2009
    > print(rnorm(10))
     [1]  1.5891276  1.1219071 -0.6110963  0.1579430 -0.3104579  1.0072677 -0.1303165  0.6998849  1.9918643 -1.2390156
    >
    
    Goodbye at  Fri Apr 17 13:33:17 2009
    > proc.time()
       user  system elapsed
      0.614   0.050   0.721
    

    Note: you'll want to try out the --vanilla and other options to remove all the startup cruft.

    Change background color for selected ListBox item

    You have to create a new template for item selection like this.

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Border
                    BorderThickness="{TemplateBinding Border.BorderThickness}"
                    Padding="{TemplateBinding Control.Padding}"
                    BorderBrush="{TemplateBinding Border.BorderBrush}"
                    Background="{TemplateBinding Panel.Background}"
                    SnapsToDevicePixels="True">
                    <ContentPresenter
                        Content="{TemplateBinding ContentControl.Content}"
                        ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                        HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}"
                        SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    

    Java Generics With a Class & an Interface - Together

    You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

    import java.util.List;
    interface A{}
    interface B{}
    public class Test<E extends B & A, T extends List<E>> {
        T t;
    }
    

    ThreeJS: Remove object from scene

    I started to save this as a function, and call it as needed for whatever reactions require it:

    function Remove(){
        while(scene.children.length > 0){ 
        scene.remove(scene.children[0]); 
    }
    }
    

    Now you can call the Remove(); function where appropriate.

    Is there an Eclipse plugin to run system shell in the Console?

    In Eclipse 3.7, I found a terminal view plugin that I installed through Eclipse Marketplace. Details are as follow:

    Local Terminal (Incubation) http://market.eclipsesource.com/yoxos/node/org.eclipse.tm.terminal.local.feature.group

    A terminal emulation for local shells and external tools. Requires CDT Core 7.0 or later. Works on Linux, Solaris and Mac. Includes Source.

    Side note, this terminal does not execute .bash_profile or .bashrc so you can do

    source ~/.bash_profile
    

    and (if this isn't sourced by `.bash_profile)

    source ~/.bashrc
    

    Update:

    This is actually was base for Terminal plug-in for Eclipse fork. Quote from http://alexruiz.developerblogs.com/?p=2428

    Uwe Stieber July 23, 2013 at 12:57 am

    Alex, why not aiming for rejoining your work with the original TM Terminal? I’ve checked and haven’t found any bugzilla asking for missing features or pointing out bugs. There had been changes to the original Terminal control, so I’m not sure if all of your original reasons to clone it are still true.

    Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

    I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)

    After creating Keystore with the same password as private key had the issue was resolved.

    Loop backwards using indices in Python?

    Why your code didn't work

    You code for i in range (100, 0) is fine, except

    the third parameter (step) is by default +1. So you have to specify 3rd parameter to range() as -1 to step backwards.

    for i in range(100, -1, -1):
        print(i)
    

    NOTE: This includes 100 & 0 in the output.

    There are multiple ways.

    Better Way

    For pythonic way, check PEP 0322.

    This is Python3 pythonic example to print from 100 to 0 (including 100 & 0).

    for i in reversed(range(101)):
        print(i)
    

    Duplicate keys in .NET dictionaries?

    The NameValueCollection supports multiple string values under one key (which is also a string), but it is the only example I am aware of.

    I tend to create constructs similar to the one in your example when I run into situations where I need that sort of functionality.

    Iterate through a C++ Vector using a 'for' loop

    Here is a simpler way to iterate and print values in vector.

    for(int x: A) // for integer x in vector A
        cout<< x <<" "; 
    

    All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

    I wrote the following to print a list of results to standard out based on available charsets. Note that it also tells you what line fails from a 0 based line number in case you are troubleshooting what character is causing issues.

    public static void testCharset(String fileName) {
        SortedMap<String, Charset> charsets = Charset.availableCharsets();
        for (String k : charsets.keySet()) {
            int line = 0;
            boolean success = true;
            try (BufferedReader b = Files.newBufferedReader(Paths.get(fileName),charsets.get(k))) {
                while (b.ready()) {
                    b.readLine();
                    line++;
                }
            } catch (IOException e) {
                success = false;
                System.out.println(k+" failed on line "+line);
            }
            if (success) 
                System.out.println("*************************  Successs "+k);
        }
    }
    

    Convert/cast an stdClass object to another class

    And yet another approach using the decorator pattern and PHPs magic getter & setters:

    // A simple StdClass object    
    $stdclass = new StdClass();
    $stdclass->foo = 'bar';
    
    // Decorator base class to inherit from
    class Decorator {
    
        protected $object = NULL;
    
        public function __construct($object)
        {
           $this->object = $object;  
        }
    
        public function __get($property_name)
        {
            return $this->object->$property_name;   
        }
    
        public function __set($property_name, $value)
        {
            $this->object->$property_name = $value;   
        }
    }
    
    class MyClass extends Decorator {}
    
    $myclass = new MyClass($stdclass)
    
    // Use the decorated object in any type-hinted function/method
    function test(MyClass $object) {
        echo $object->foo . '<br>';
        $object->foo = 'baz';
        echo $object->foo;   
    }
    
    test($myclass);
    

    How can I append a string to an existing field in MySQL?

    Update image field to add full URL, ignoring null fields:

    UPDATE test SET image = CONCAT('https://my-site.com/images/',image) WHERE image IS NOT NULL;
    

    Check array position for null/empty

    If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

    SomeClass* myArray[2];
    myArray[0] = new SomeClass();
    myArray[1] = NULL;
    
    if (myArray[0] != NULL) { // this will be executed }
    if (myArray[1] != NULL) { // this will NOT be executed }
    

    As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

    how to execute a scp command with the user name and password in one line

    Using sshpass works best. To just include your password in scp use the ' ':

    scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/
    

    How to identify server IP address in PHP

    I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.

    /** IIS IP Check **/
    if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
    if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }
    

    Floating elements within a div, floats outside of div. Why?

    Reason

    The problem is that floating elements are out-of-flow:

    An element is called out of flow if it is floated, absolutely positioned, or is the root element.

    Therefore, they don't impact surrounding elements as an in-flow element would.

    This is explained in 9.5 Floats:

    Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist. However, the current and subsequent line boxes created next to the float are shortened as necessary to make room for the margin box of the float.

    enter image description here

    _x000D_
    _x000D_
    html {_x000D_
      width: 550px;_x000D_
      border: 1px solid;_x000D_
    }_x000D_
    body {_x000D_
      font-family: sans-serif;_x000D_
      color: rgba(0,0,0,.15);_x000D_
    }_x000D_
    body:after {_x000D_
      content: '';_x000D_
      display: block;_x000D_
      clear: both;_x000D_
    }_x000D_
    div {_x000D_
      position: relative;_x000D_
    }_x000D_
    div:after {_x000D_
      font-size: 200%;_x000D_
      position: absolute;_x000D_
      left: 0;_x000D_
      right: 0;_x000D_
      top: 0;_x000D_
      text-align: center;_x000D_
    }_x000D_
    .block-sibling {_x000D_
      border: 3px solid green;_x000D_
    }_x000D_
    .block-sibling:after {_x000D_
      content: 'Block sibling';_x000D_
      color: green;_x000D_
    }_x000D_
    .float {_x000D_
      float: left;_x000D_
      border: 3px solid red;_x000D_
      height: 90px;_x000D_
      width: 150px;_x000D_
      z-index: 1;_x000D_
    }_x000D_
    .float:after {_x000D_
      content: 'Float';_x000D_
      color: red;_x000D_
    }
    _x000D_
    <div class="float"></div>_x000D_
    <div class="block-sibling">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur. Donec ut libero sed arcu vehicula ultricies a non tortor._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    This is also specified in 10.6 Calculating heights and margins. For "normal" blocks,

    Only children in the normal flow are taken into account (i.e., floating boxes and absolutely positioned boxes are ignored […])

    enter image description here

    _x000D_
    _x000D_
    html {_x000D_
      width: 550px;_x000D_
      border: 1px solid;_x000D_
    }_x000D_
    body {_x000D_
      font-family: sans-serif;_x000D_
      color: rgba(0,0,0,.15);_x000D_
    }_x000D_
    body:after {_x000D_
      content: '';_x000D_
      display: block;_x000D_
      clear: both;_x000D_
    }_x000D_
    div {_x000D_
      position: relative;_x000D_
    }_x000D_
    div:after {_x000D_
      font-size: 200%;_x000D_
      position: absolute;_x000D_
      left: 0;_x000D_
      right: 0;_x000D_
      top: 0;_x000D_
      text-align: center;_x000D_
    }_x000D_
    .block-parent {_x000D_
      border: 3px solid blue;_x000D_
    }_x000D_
    .block-parent:after {_x000D_
      content: 'Block parent';_x000D_
      color: blue;_x000D_
    }_x000D_
    .float {_x000D_
      float: left;_x000D_
      border: 3px solid red;_x000D_
      height: 130px;_x000D_
      width: 150px;_x000D_
    }_x000D_
    .float:after {_x000D_
      content: 'Float';_x000D_
      color: red;_x000D_
    }
    _x000D_
    <div class="block-parent">_x000D_
      <div class="float"></div>_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Hacky solution: clearance

    A way to solve the problem is forcing some in-flow element to be placed below all floats. Then, the height of the parent will grow to wrap that element (and thus the floats too).

    This can be achieved using the clear property:

    This property indicates which sides of an element's box(es) may not be adjacent to an earlier floating box.

    enter image description here

    _x000D_
    _x000D_
    html {_x000D_
      width: 550px;_x000D_
      border: 1px solid;_x000D_
    }_x000D_
    body {_x000D_
      font-family: sans-serif;_x000D_
      color: rgba(0,0,0,.15);_x000D_
    }_x000D_
    body:after {_x000D_
      content: '';_x000D_
      display: block;_x000D_
      clear: both;_x000D_
    }_x000D_
    div {_x000D_
      position: relative;_x000D_
    }_x000D_
    div:after {_x000D_
      font-size: 200%;_x000D_
      position: absolute;_x000D_
      left: 0;_x000D_
      right: 0;_x000D_
      top: 0;_x000D_
      text-align: center;_x000D_
    }_x000D_
    .block-parent {_x000D_
      border: 3px solid blue;_x000D_
    }_x000D_
    .block-parent:after {_x000D_
      content: 'Block parent';_x000D_
      color: blue;_x000D_
    }_x000D_
    .float {_x000D_
      float: left;_x000D_
      border: 3px solid red;_x000D_
      height: 84px;_x000D_
      width: 150px;_x000D_
    }_x000D_
    .float:after {_x000D_
      content: 'Float';_x000D_
      color: red;_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
      text-align: center;_x000D_
      height: 37px;_x000D_
      border: 3px dashed pink;_x000D_
    }_x000D_
    .clear:after {_x000D_
      position: static;_x000D_
      content: 'Block sibling with clearance';_x000D_
      color: pink;_x000D_
    }
    _x000D_
    <div class="block-parent">_x000D_
      <div class="float"></div>_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra._x000D_
      <div class="clear"></div>_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    So a solution is adding an empty element with clear: both as the last sibling of the floats

    <div style="clear: both"></div>
    

    However, that is not semantic. So better generate a pseudo-element at the end of the parent:

    .clearfix::after {
      clear: both;
      display: block;
    }
    

    There are multiple variants of this approach, e.g. using the deprecated single colon syntax :after to support old browsers, or using other block-level displays like display: table.

    Solution: BFC roots

    There is an exception to the problematic behavior defined at the beginning: if a block element establishes a Block Formatting Context (is a BFC root), then it will also wrap its floating contents.

    According to 10.6.7 'Auto' heights for block formatting context roots,

    If the element has any floating descendants whose bottom margin edge is below the element's bottom content edge, then the height is increased to include those edges.

    enter image description here

    _x000D_
    _x000D_
    html {_x000D_
      width: 550px;_x000D_
      border: 1px solid;_x000D_
    }_x000D_
    body {_x000D_
      font-family: sans-serif;_x000D_
      color: rgba(0,0,0,.15);_x000D_
    }_x000D_
    body:after {_x000D_
      content: '';_x000D_
      display: block;_x000D_
      clear: both;_x000D_
    }_x000D_
    div {_x000D_
      position: relative;_x000D_
    }_x000D_
    div:after {_x000D_
      font-size: 200%;_x000D_
      position: absolute;_x000D_
      left: 0;_x000D_
      right: 0;_x000D_
      top: 0;_x000D_
      text-align: center;_x000D_
    }_x000D_
    .block-parent {_x000D_
      border: 3px solid blue;_x000D_
    }_x000D_
    .block-parent.bfc-root:after {_x000D_
      content: 'BFC parent';_x000D_
      color: blue;_x000D_
    }_x000D_
    .float {_x000D_
      float: left;_x000D_
      border: 3px solid red;_x000D_
      height: 127px;_x000D_
      width: 150px;_x000D_
    }_x000D_
    .float:after {_x000D_
      content: 'Float';_x000D_
      color: red;_x000D_
    }_x000D_
    .bfc-root {_x000D_
      overflow: hidden;_x000D_
    }
    _x000D_
    <div class="block-parent bfc-root">_x000D_
      <div class="float"></div>_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    Additionally, as explained 9.5 Floats, BFC roots are also useful because of the following:

    The border box of a table, a block-level replaced element, or an element in the normal flow that establishes a new block formatting context […] must not overlap the margin box of any floats in the same block formatting context as the element itself.

    enter image description here

    _x000D_
    _x000D_
    html {_x000D_
      width: 550px;_x000D_
      border: 1px solid;_x000D_
    }_x000D_
    body {_x000D_
      font-family: sans-serif;_x000D_
      color: rgba(0,0,0,.15);_x000D_
    }_x000D_
    body:after {_x000D_
      content: '';_x000D_
      display: block;_x000D_
      clear: both;_x000D_
    }_x000D_
    div {_x000D_
      position: relative;_x000D_
    }_x000D_
    div:after {_x000D_
      font-size: 200%;_x000D_
      position: absolute;_x000D_
      left: 0;_x000D_
      right: 0;_x000D_
      top: 0;_x000D_
      text-align: center;_x000D_
    }_x000D_
    .block-sibling {_x000D_
      border: 3px solid green;_x000D_
    }_x000D_
    .block-sibling.bfc-root:after {_x000D_
      content: 'BFC sibling';_x000D_
      color: green;_x000D_
    }_x000D_
    .float {_x000D_
      float: left;_x000D_
      border: 3px solid red;_x000D_
      height: 90px;_x000D_
      width: 150px;_x000D_
      z-index: 1;_x000D_
    }_x000D_
    .float:after {_x000D_
      content: 'Float';_x000D_
      color: red;_x000D_
    }_x000D_
    .bfc-root {_x000D_
      overflow: hidden;_x000D_
    }
    _x000D_
    <div class="float"></div>_x000D_
    <div class="block-sibling bfc-root">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    A block formatting context is established by

    • Block boxes with overflow other than visible, e.g. hidden

      .bfc-root {
        overflow: hidden;
        /* display: block; */
      }
      
    • Block containers that are not block boxes: when display is set to inline-block, table-cell or table-caption.

      .bfc-root {
        display: inline-block;
      }
      
    • Floating elements: when float is set to left or right.

      .bfc-root {
        float: left;
      }
      
    • Absolutely positioned elements: when position is set to absolute or fixed.

      .bfc-root {
        position: absolute;
      }
      

    Note those may have undesired collateral effects, like clipping overflowing content, calculating auto widths with the shrink-to-fit algorithm, or becoming out-of-flow. So the problem is that it's not possible to have an in-flow block-level element with visible overflow that establishes a BFC.

    Display L3 addresses these issues:

    Created the flow and flow-root inner display types to better express flow layout display types and to create an explicit switch for making an element a BFC root. (This should eliminate the need for hacks like ::after { clear: both; } and overflow: hidden […])

    Sadly, there is no browser support yet. Eventually we may be able to use

    .bfc-root {
      display: flow-root;
    }
    

    How to check if a map contains a key in Go?

    better way here

    if _, ok := dict["foo"]; ok {
        //do something here
    }
    

    How can I generate a unique ID in Python?

    This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).

    import threading
    
    _uid = threading.local()
    def genuid():
        if getattr(_uid, "uid", None) is None:
            _uid.tid = threading.current_thread().ident
            _uid.uid = 0
        _uid.uid += 1
        return (_uid.tid, _uid.uid)
    

    It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).

    Hope that helps.

    Working with select using AngularJS's ng-options

    I hope the following will work for you.

    <select class="form-control"
            ng-model="selectedOption"
            ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
    </select>
    

    Why are primes important in cryptography?

    There are some good resources for ramping up on crypto. Here's one:

    From that page:

    In the most commonly used public-key cryptography system, invented by Ron Rivest, Adi Shamir, and Len Adleman in 1977, both the public and the private keys are derived from a pair of large prime numbers according to a relatively simple mathematical formula. In theory, it might be possible to derive the private key from the public key by working the formula backwards. But only the product of the large prime numbers is public, and factoring numbers of that size into primes is so hard that even the most powerful supercomputers in the world cant break an ordinary public key.

    Bruce Schneier's book Applied Cryptography is another. I highly recommend that book; it's fun reading.

    select2 - hiding the search box

    //readonly on all select2 input
    $(".select2-search input").prop("readonly", true);
    

    Detect when input has a 'readonly' attribute

    Check the current value of your "readonly" attribute, if it's "false" (a string) or empty (undefined or "") then it's not readonly.

    $('input').each(function() {
        var readonly = $(this).attr("readonly");
        if(readonly && readonly.toLowerCase()!=='false') { // this is readonly
            alert('this is a read only field');
        }
    });
    

    Installing mysql-python on Centos

    I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.

    For me it worked with the following command:

    # pip install mysql-python
    

    Note pre-requisites here:

    Install Python pip:

    # rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
    
    # yum -y update
    Reboot the machine (if kernel is also updated)
    
    # yum -y install python-pip
    

    Install Python devel packages:

    # yum install python-devel
    

    Install MySQL devel packages:

    # yum install mysql-devel
    

    How to detect the end of loading of UITableView

    In iOS7.0x the solution is a bit different. Here is what I came up with.

        - (void)tableView:(UITableView *)tableView 
          willDisplayCell:(UITableViewCell *)cell 
        forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        BOOL isFinishedLoadingTableView = [self isFinishedLoadingTableView:tableView  
                                                                 indexPath:indexPath];
        if (isFinishedLoadingTableView) {
            NSLog(@"end loading");
        }
    }
    
    - (BOOL)isFinishedLoadingTableView:(UITableView *)tableView 
                             indexPath:(NSIndexPath *)indexPath
    {
        // The reason we cannot just look for the last row is because 
        // in iOS7.0x the last row is updated before
        // looping through all the visible rows in ascending order 
        // including the last row again. Strange but true.
        NSArray * visibleRows = [tableView indexPathsForVisibleRows];   // did verify sorted ascending via logging
        NSIndexPath *lastVisibleCellIndexPath = [visibleRows lastObject];
        // For tableviews with multiple sections this will be more complicated.
        BOOL isPreviousCallForPreviousCell = 
                 self.previousDisplayedIndexPath.row + 1 == lastVisibleCellIndexPath.row;
        BOOL isLastCell = [indexPath isEqual:lastVisibleCellIndexPath];
        BOOL isFinishedLoadingTableView = isLastCell && isPreviousCallForPreviousCell;
        self.previousDisplayedIndexPath = indexPath;
        return isFinishedLoadingTableView;
    }
    

    Android emulator: could not get wglGetExtensionsStringARB error

    just change your JDK I installed the JDK of SUN not Oracle and it works for me....

    __FILE__, __LINE__, and __FUNCTION__ usage in C++

    I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.

    How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

    If you want this behaviour everywhere in your app and don't want to add anything to individual viewDidAppear etc. then you should create a subclass

    class QFNavigationController:UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate{
        override func viewDidLoad() {
            super.viewDidLoad()
            interactivePopGestureRecognizer?.delegate = self
            delegate = self
        }
    
        override func pushViewController(_ viewController: UIViewController, animated: Bool) {
            super.pushViewController(viewController, animated: animated)
            interactivePopGestureRecognizer?.isEnabled = false
        }
    
        func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
            interactivePopGestureRecognizer?.isEnabled = true
        }
    
        // IMPORTANT: without this if you attempt swipe on
        // first view controller you may be unable to push the next one
        func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
            return viewControllers.count > 1
        }
    
    }
    

    Now, whenever you use QFNavigationController you get the desired experience.

    How to draw polygons on an HTML5 canvas?

    In addition to @canvastag, use a while loop with shift I think is more concise:

    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    
    var poly = [5, 5, 100, 50, 50, 100, 10, 90];
    
    // copy array
    var shape = poly.slice(0);
    
    ctx.fillStyle = '#f00'
    ctx.beginPath();
    ctx.moveTo(shape.shift(), shape.shift());
    while(shape.length) {
      ctx.lineTo(shape.shift(), shape.shift());
    }
    ctx.closePath();
    ctx.fill();
    

    Are multi-line strings allowed in JSON?

    Write property value as a array of strings. Like example given over here https://gun.io/blog/multi-line-strings-in-json/. This will help.

    We can always use array of strings for multiline strings like following.

    {
        "singleLine": "Some singleline String",
        "multiline": ["Line one", "line Two", "Line Three"]
    } 
    

    And we can easily iterate array to display content in multi line fashion.

    Memory Allocation "Error: cannot allocate vector of size 75.1 Mb"

    I had the same warning using the raster package.

    > my_mask[my_mask[] != 1] <- NA
    Error: cannot allocate vector of size 5.4 Gb
    

    The solution is really simple and consist in increasing the storage capacity of R, here the code line:

    ##To know the current storage capacity
    > memory.limit()
    [1] 8103
    ## To increase the storage capacity
    > memory.limit(size=56000)
    [1] 56000    
    ## I did this to increase my storage capacity to 7GB
    

    Hopefully, this will help you to solve the problem Cheers

    How to rename a class and its corresponding file in Eclipse?

    You can rename classes or any file by hitting F2 on the filename in Eclipse. It will ask you if you want to update references. It's really as easy as that :)

    CodeIgniter: Unable to connect to your database server using the provided settings Error Message

    Extending @Valeh Hajiyev great and clear answer for mysqli driver tests:

    Debug your database connection using this script at the end of ./config/database.php:

    /* Your db config here */ 
    $db['default'] = array(
      // ...
      'dbdriver'     => 'mysqli',
      // ...
    );
    
    /* Connection test: */
    
    echo '<pre>';
    print_r($db['default']);
    echo '</pre>';
    
    echo 'Connecting to database: ' .$db['default']['database'];
    
    $mysqli_connection = new MySQLi($db['default']['hostname'],
                                    $db['default']['username'],
                                    $db['default']['password'], 
                                    $db['default']['database']);
    
    if ($mysqli_connection->connect_error) {
       echo "Not connected, error: " . $mysqli_connection->connect_error;
    }
    else {
       echo "Connected.";
    }
    die( 'file: ' .__FILE__ . ' Line: ' .__LINE__);
    

    Serialize Class containing Dictionary member

    I wanted a SerializableDictionary class that used xml attributes for key/value so I've adapted Paul Welter's class.

    This produces xml like:

    <Dictionary>
      <Item Key="Grass" Value="Green" />
      <Item Key="Snow" Value="White" />
      <Item Key="Sky" Value="Blue" />
    </Dictionary>"
    

    Code:

    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.Serialization;
    
    namespace DataTypes {
        [XmlRoot("Dictionary")]
        public class SerializableDictionary<TKey, TValue>
            : Dictionary<TKey, TValue>, IXmlSerializable {
            #region IXmlSerializable Members
            public System.Xml.Schema.XmlSchema GetSchema() {
                return null;
            }
    
            public void ReadXml(XmlReader reader) {
                XDocument doc = null;
                using (XmlReader subtreeReader = reader.ReadSubtree()) {
                    doc = XDocument.Load(subtreeReader);
                }
                XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
                foreach (XElement item in doc.Descendants(XName.Get("Item"))) {
                    using(XmlReader itemReader =  item.CreateReader()) {
                        var kvp = serializer.Deserialize(itemReader) as SerializableKeyValuePair<TKey, TValue>;
                        this.Add(kvp.Key, kvp.Value);
                    }
                }
                reader.ReadEndElement();
            }
    
            public void WriteXml(System.Xml.XmlWriter writer) {
                XmlSerializer serializer = new XmlSerializer(typeof(SerializableKeyValuePair<TKey, TValue>));
                XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                ns.Add("", "");
                foreach (TKey key in this.Keys) {
                    TValue value = this[key];
                    var kvp = new SerializableKeyValuePair<TKey, TValue>(key, value);
                    serializer.Serialize(writer, kvp, ns);
                }
            }
            #endregion
    
            [XmlRoot("Item")]
            public class SerializableKeyValuePair<TKey, TValue> {
                [XmlAttribute("Key")]
                public TKey Key;
    
                [XmlAttribute("Value")]
                public TValue Value;
    
                /// <summary>
                /// Default constructor
                /// </summary>
                public SerializableKeyValuePair() { }
            public SerializableKeyValuePair (TKey key, TValue value) {
                Key = key;
                Value = value;
            }
        }
    }
    }
    

    Unit Tests:

    using System.IO;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    
    namespace DataTypes {
        [TestClass]
        public class SerializableDictionaryTests {
            [TestMethod]
            public void TestStringStringDict() {
                var dict = new SerializableDictionary<string, string>();
                dict.Add("Grass", "Green");
                dict.Add("Snow", "White");
                dict.Add("Sky", "Blue");
                dict.Add("Tomato", "Red");
                dict.Add("Coal", "Black");
                dict.Add("Mud", "Brown");
    
                var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
                using (var stream = new MemoryStream()) {
                    // Load memory stream with this objects xml representation
                    XmlWriter xmlWriter = null;
                    try {
                        xmlWriter = XmlWriter.Create(stream);
                        serializer.Serialize(xmlWriter, dict);
                    } finally {
                        xmlWriter.Close();
                    }
    
                    // Rewind
                    stream.Seek(0, SeekOrigin.Begin);
    
                    XDocument doc = XDocument.Load(stream);
                    Assert.AreEqual("Dictionary", doc.Root.Name);
                    Assert.AreEqual(dict.Count, doc.Root.Descendants().Count());
    
                    // Rewind
                    stream.Seek(0, SeekOrigin.Begin);
                    var outDict = serializer.Deserialize(stream) as SerializableDictionary<string, string>;
                    Assert.AreEqual(dict["Grass"], outDict["Grass"]);
                    Assert.AreEqual(dict["Snow"], outDict["Snow"]);
                    Assert.AreEqual(dict["Sky"], outDict["Sky"]);
                }
            }
    
            [TestMethod]
            public void TestIntIntDict() {
                var dict = new SerializableDictionary<int, int>();
                dict.Add(4, 7);
                dict.Add(5, 9);
                dict.Add(7, 8);
    
                var serializer = new System.Xml.Serialization.XmlSerializer(dict.GetType());
                using (var stream = new MemoryStream()) {
                    // Load memory stream with this objects xml representation
                    XmlWriter xmlWriter = null;
                    try {
                        xmlWriter = XmlWriter.Create(stream);
                        serializer.Serialize(xmlWriter, dict);
                    } finally {
                        xmlWriter.Close();
                    }
    
                    // Rewind
                    stream.Seek(0, SeekOrigin.Begin);
    
                    XDocument doc = XDocument.Load(stream);
                    Assert.AreEqual("Dictionary", doc.Root.Name);
                    Assert.AreEqual(3, doc.Root.Descendants().Count());
    
                    // Rewind
                    stream.Seek(0, SeekOrigin.Begin);
                    var outDict = serializer.Deserialize(stream) as SerializableDictionary<int, int>;
                    Assert.AreEqual(dict[4], outDict[4]);
                    Assert.AreEqual(dict[5], outDict[5]);
                    Assert.AreEqual(dict[7], outDict[7]);
                }
            }
        }
    }
    

    Error when testing on iOS simulator: Couldn't register with the bootstrap server

    I was getting this error all the time until I stopped trusting the "Stop" button in the Run dialog box. Now that I always hit stop in the toolbar before trying to run, I have yet to encounter any zombie processes.

    How to add an item to a drop down list in ASP.NET?

    Try this, it will insert the list item at index 0;

    DropDownList1.Items.Insert(0, new ListItem("Add New", ""));
    

    What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

    The official way to detect .NET 3.0 is described here

    http://msdn.microsoft.com/en-us/library/aa480198.aspx

    Flawed, because it requires the caller to have registry access permissions.

    MSDN also mentions a technique for detecting .NET 3.5 by checking the User Agent string:

    http://msdn.microsoft.com/en-us/library/bb909885.aspx

    I think Microsoft should have done a better job than this.

    SQL Server "AFTER INSERT" trigger doesn't see the just-inserted row

    Your "trigger" is doing something that a "trigger" is not suppose to be doing. You can simple have your Sql Server Agent run

    DELETE FROM someTable
    WHERE ISNUMERIC(someField) = 1
    

    every 1 second or so. While you're at it, how about writing a nice little SP to stop the programming folk from inserting errors into your table. One good thing about SP's is that the parameters are type safe.

    Ajax request returns 200 OK, but an error event is fired instead of success

    See this. Its also similar problem. Working i tried.

    Dont remove dataType: 'JSON',

    Note: echo only JSON Formate in PHP file if you use only php echo your ajax code return 200

    List all environment variables from the command line

    You can use SET in cmd

    To show the current variable, just SET is enough

    To show certain variable such as 'PATH', use SET PATH.

    For help, type set /?.

    What does "The APR based Apache Tomcat Native library was not found" mean?

    I just went through this and configured it with the following:

    Ubuntu 16.04

    Tomcat 8.5.9

    Apache2.4.25

    APR 1.5.2

    Tomcat-native 1.2.10

    Java 8

    These are the steps i used based on the older posts here:

    Install package

    sudo apt-get update
    sudo apt-get install libtcnative-1
    

    Verify these packages are installed

    sudo apt-get install make 
    sudo apt-get install gcc
    sudo apt-get install openssl
    

    Install package

    sudo apt-get install libssl-dev

    Install and compile Apache APR

    cd /opt/tomcat/bin
    sudo wget http://apache.mirror.anlx.net//apr/apr-1.5.2.tar.gz
    sudo tar -xzvf apr-1.5.2.tar.gz
    cd apr-1.5.2
    sudo ./configure
    sudo make
    sudo make install
    

    verify installation

    cd /usr/local/apr/lib/
    ls 
    

    you should see the compiled file as

    libapr-1.la

    Download and install Tomcat Native source package

    cd /opt/tomcat/bin
    sudo wget https://archive.apache.org/dist/tomcat/tomcat-connectors/native/1.2.10/source/tomcat-native-1.2.10-src.tar.gz
    sudo tar -xzvf tomcat-native-1.2.10-src.tar.gz
    cd tomcat-native-1.2.10-src/native
    

    verify JAVA_HOME

    sudo pico ~/.bashrc
    export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
    source ~/.bashrc
    sudo ./configure --with-apr=/usr/local/apr --with-java-home=$JAVA_HOME
    sudo make
    sudo make install
    

    Edit the /opt/tomcat/bin/setenv.sh file with following line:

    sudo pico /opt/tomcat/bin/setenv.sh
    export LD_LIBRARY_PATH='$LD_LIBRARY_PATH:/usr/local/apr/lib'
    

    restart tomcat

    sudo service tomcat restart

    How do I configure PyCharm to run py.test tests?

    I'm using 2018.2

    I do Run -> Edit Configurations... Then click the + in the upper left of the modal dialog. Select "python tests" -> py.test Then I give it a name like "All test with py.test"

    I select Target: module name and put in the module where my tests are (that is 'tests' for me) or the module where all my code is if my tests are mixed in with my code. This was tripping me up.

    I set the Python interpreter.

    I set the working directory to the project directory.

    What does "use strict" do in JavaScript, and what is the reasoning behind it?

    My two cents:

    One of the goals of strict mode is to allow for faster debugging of issues. It helps the developers by throwing exception when certain wrong things occur that can cause silent & strange behaviour of your webpage. The moment we use use strict, the code will throw out errors which helps developer to fix it in advance.

    Few important things which I have learned after using use strict :

    Prevents Global Variable Declaration:

    var tree1Data = { name: 'Banana Tree',age: 100,leafCount: 100000};
    
    function Tree(typeOfTree) {
        var age;
        var leafCount;
    
        age = typeOfTree.age;
        leafCount = typeOfTree.leafCount;
        nameoftree = typeOfTree.name;
    };
    
    var tree1 = new Tree(tree1Data);
    console.log(window);
    

    Now,this code creates nameoftree in global scope which could be accessed using window.nameoftree. When we implement use strict the code would throw error.

    Uncaught ReferenceError: nameoftree is not defined

    Sample

    Eliminates with statement :

    with statements can't be minified using tools like uglify-js. They're also deprecated and removed from future JavaScript versions.

    Sample

    Prevents Duplicates :

    When we have duplicate property, it throws an exception

    Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode

    "use strict";
    var tree1Data = {
        name: 'Banana Tree',
        age: 100,
        leafCount: 100000,
        name:'Banana Tree'
    };
    

    There are few more but I need to gain more knowledge on that.

    Separation of business logic and data access in django

    An old question, but I'd like to offer my solution anyway. It's based on acceptance that model objects too require some additional functionality while it's awkward to place it within the models.py. Heavy business logic may be written separately depending on personal taste, but I at least like the model to do everything related to itself. This solution also supports those who like to have all the logic placed within models themselves.

    As such, I devised a hack that allows me to separate logic from model definitions and still get all the hinting from my IDE.

    The advantages should be obvious, but this lists a few that I have observed:

    • DB definitions remain just that - no logic "garbage" attached
    • Model-related logic is all placed neatly in one place
    • All the services (forms, REST, views) have a single access point to logic
    • Best of all: I did not have to rewrite any code once I realised that my models.py became too cluttered and had to separate the logic away. The separation is smooth and iterative: I could do a function at a time or entire class or the entire models.py.

    I have been using this with Python 3.4 and greater and Django 1.8 and greater.

    app/models.py

    ....
    from app.logic.user import UserLogic
    
    class User(models.Model, UserLogic):
        field1 = models.AnyField(....)
        ... field definitions ...
    

    app/logic/user.py

    if False:
        # This allows the IDE to know about the User model and its member fields
        from main.models import User
    
    class UserLogic(object):
        def logic_function(self: 'User'):
            ... code with hinting working normally ...
    

    The only thing I can't figure out is how to make my IDE (PyCharm in this case) recognise that UserLogic is actually User model. But since this is obviously a hack, I'm quite happy to accept the little nuisance of always specifying type for self parameter.

    Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

    Swift 5, update @Ankush's Alamofire Code to

         var fullUrl = "http://httpbin.org/post" // for example
    
               Alamofire.upload(multipartFormData: { (multipartFormData) in
                    multipartFormData.append( imagePathUrl! , withName: "photo")
                    multipartFormData.append( videoPathUrl!,  withName: "video")
                    multipartFormData.append(Constants.AuthKey.data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                    multipartFormData.append("16".data(using: .utf8, allowLossyConversion: false)!, withName: "idUserChallenge")
                    multipartFormData.append("111".data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                    multipartFormData.append("comment".data(using: .utf8, allowLossyConversion: false)!, withName: "comment")
                    multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "latitude")
                    multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "longitude")
                    multipartFormData.append("India".data(using: .utf8, allowLossyConversion: false)!, withName: "location")
    
                }, to: fullUrl, method: .post) { (encodingResult) in
                    switch encodingResult {
                    case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                        upload.responseJSON { (response) in   // do sth     }
                    case .failure(let encodingError):
                        ()
                    }
                }
    

    java.sql.SQLException: Exhausted Resultset

    If you reset the result set to the top, using rs.absolute(1) you won't get exhaused result set.

    while (rs.next) {
        System.out.println(rs.getString(1));
    }
    rs.absolute(1);
    System.out.println(rs.getString(1));
    

    You can also use rs.first() instead of rs.absolute(1), it does the same.

    SQL Server Management Studio missing

    I know this is an old question, but I've just had the same frustrating issue for a couple of hours and wanted to share my solution. In my case the option "Managements Tools" wasn't available in the installation menu either. It wasn't just greyed out as disabled or already installed, but instead just missing, it wasn't anywhere on the menu.

    So what finally worked for me was to use the Web Platform Installer 4.0, and check this for installation: Products > Database > "Sql Server 2008 R2 Management Objects". Once this is done, you can relaunch the installation and "Management Tools" will appear like previous answers stated.

    Note there could also be a "Sql Server 2012 Shared Management Objects", but I think this is for different purposes.

    Hope this saves someone the couple of hours I wasted into this.

    How to parse a JSON string to an array using Jackson

    The other answer is correct, but for completeness, here are other ways:

    List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
    SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);
    

    UIScrollView scroll to bottom programmatically

    While Matt solution seems correct to me you need to take in account also the collection view inset if there is one that has been set-up.

    The adapted code will be:

    CGSize csz = sv.contentSize;
    CGSize bsz = sv.bounds.size;
    NSInteger bottomInset = sv.contentInset.bottom;
    if (sv.contentOffset.y + bsz.height + bottomInset > csz.height) {
        [sv setContentOffset:CGPointMake(sv.contentOffset.x, 
                                         csz.height - bsz.height + bottomInset) 
                    animated:YES];
    }
    

    Changing the background color of a drop down list transparent in html

    You can actualy fake the transparency of option DOMElements with the following CSS:

    CSS

    option { 
        /* Whatever color  you want */
        background-color: #82caff;
    }
    

    See Demo

    The option tag does not support rgba colors yet.

    Error : Index was outside the bounds of the array.

    You have declared an array that can store 8 elements not 9.

    this.posStatus = new int[8]; 
    

    It means postStatus will contain 8 elements from index 0 to 7.

    How do DATETIME values work in SQLite?

    One of the powerful features of SQLite is allowing you to choose the storage type. Advantages/disadvantages of each of the three different possibilites:

    • ISO8601 string

      • String comparison gives valid results
      • Stores fraction seconds, up to three decimal digits
      • Needs more storage space
      • You will directly see its value when using a database browser
      • Need for parsing for other uses
      • "default current_timestamp" column modifier will store using this format
    • Real number

      • High precision regarding fraction seconds
      • Longest time range
    • Integer number

      • Lowest storage space
      • Quick operations
      • Small time range
      • Possible year 2038 problem

    If you need to compare different types or export to an external application, you're free to use SQLite's own datetime conversion functions as needed.

    How to change an input button image using CSS?

    This article about CSS image replacement for submit buttons could help.

    "Using this method you'll get a clickable image when style sheets are active, and a standard button when style sheets are off. The trick is to apply the image replace methods to a button tag and use it as the submit button, instead of using input.

    And since button borders are erased, it's also recommendable change the button cursor to the hand shaped one used for links, since this provides a visual tip to the users."

    The CSS code:

    #replacement-1 {
      width: 100px;
      height: 55px;
      margin: 0;
      padding: 0;
      border: 0;
      background: transparent url(image.gif) no-repeat center top;
      text-indent: -1000em;
      cursor: pointer; /* hand-shaped cursor */
      cursor: hand; /* for IE 5.x */
    }
    
    #replacement-2 {
      width: 100px;
      height: 55px;
      padding: 55px 0 0;
      margin: 0;
      border: 0;
      background: transparent url(image.gif) no-repeat center top;
      overflow: hidden;
      cursor: pointer; /* hand-shaped cursor */
      cursor: hand; /* for IE 5.x */
    }
    form>#replacement-2 { /* For non-IE browsers*/
      height: 0px;
    }
    

    How to completely DISABLE any MOUSE CLICK

    The easiest way to freeze the UI would be to make the AJAX call synchronous.

    Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.

    java.net.SocketException: Software caused connection abort: recv failed

    This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling shutdownInput and shutdownOutput to clear up the session.

    How to call Makefile from another Makefile?

    Instead of the -f of make you might want to use the -C <path> option. This first changes the to the path '<path>', and then calles make there.

    Example:

    clean:
      rm -f ./*~ ./gmon.out ./core $(SRC_DIR)/*~ $(OBJ_DIR)/*.o
      rm -f ../svn-commit.tmp~
      rm -f $(BIN_DIR)/$(PROJECT)
      $(MAKE) -C gtest-1.4.0/make clean
    

    What is the difference between prefix and postfix operators?

    Prefix:

    int a=0;
    
    int b=++a;          // b=1,a=1 
    

    before assignment the value of will be incremented.

    Postfix:

    int a=0;
    int b=a++;  // a=1,b=0 
    

    first assign the value of 'a' to 'b' then increment the value of 'a'

    Custom header to HttpClient request

    var request = new HttpRequestMessage {
        RequestUri = new Uri("[your request url string]"),
        Method = HttpMethod.Post,
        Headers = {
            { "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
            { HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
            { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
        },
        Content = new MultipartContent { // Just example of request sending multipart request
            new ObjectContent<[YOUR JSON OBJECT TYPE]>(
                new [YOUR JSON OBJECT TYPE INSTANCE](...){...}, 
                new JsonMediaTypeFormatter(), 
                "application/json"), // this will add 'Content-Type' header for the first part of request
            new ByteArrayContent([BINARY DATA]) {
                Headers = { // this will add headers for the second part of request
                    { "Content-Type", "application/Executable" },
                    { "Content-Disposition", "form-data; filename=\"test.pdf\"" },
                },
            },
        },
    };
    

    How to set a text box for inputing password in winforms?

    I know the perfect answer:

    1. double click on The password TextBox.
    2. write your textbox name like textbox2.
    3. write PasswordChar = '*';.
    4. I prefer going to windows character map and find a perfect hide like ?.

      example:TextBox2.PasswordChar = '?';
      

    How do I attach events to dynamic HTML elements with jQuery?

    I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.

    From http://api.jquery.com/live/

    As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().

    For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.

    See http://api.jquery.com/on/

    So instead of...

    $(".myclass").click( function() {
        // do something
    });
    

    You can write...

    $('body').on('click', 'a.myclass', function() {
        // do something
    });
    

    This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.

    The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:

    $('ul').on('click', 'li', function() {
        alert( $(this).text() );
    });
    

    As long as the ul tag exists this will work (no li elements need exist yet).

    When to use pthread_exit() and when to use pthread_join() in Linux?

    When pthread_exit() is called, the calling threads stack is no longer addressable as "active" memory for any other thread. The .data, .text and .bss parts of "static" memory allocations are still available to all other threads. Thus, if you need to pass some memory value into pthread_exit() for some other pthread_join() caller to see, it needs to be "available" for the thread calling pthread_join() to use. It should be allocated with malloc()/new, allocated on the pthread_join threads stack, 1) a stack value which the pthread_join caller passed to pthread_create or otherwise made available to the thread calling pthread_exit(), or 2) a static .bss allocated value.

    It's vital to understand how memory is managed between a threads stack, and values store in .data/.bss memory sections which are used to store process wide values.

    How to use a typescript enum value in an Angular2 ngSwitch statement

    If using the 'typetable reference' approach (from @Carl G) and you're using multiple type tables you might want to consider this way :

    export default class AppComponent {
    
      // Store a reference to the enums (must be public for --AOT to work)
      public TT = { 
           CellType: CellType, 
           CatType: CatType, 
           DogType: DogType 
      };
    
      ...
    
      dog = DogType.GoldenRetriever; 
    

    Then access in your html file with

    {{ TT.DogType[dog] }}   => "GoldenRetriever"
    

    I favor this approach as it makes it clear you're referring to a typetable, and also avoids unnecessary pollution of your component file.

    You can also put a global TT somewhere and add enums to it as needed (if you want this you may as well make a service as shown by @VincentSels answer). If you have many many typetables this may become cumbersome.

    Also you always rename them in your declaration to get a shorter name.

    Checkout remote branch using git svn

    Standard Subversion layout

    Create a git clone of that includes your Subversion trunk, tags, and branches with

    git svn clone http://svn.example.com/project -T trunk -b branches -t tags

    The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

    git svn clone http://svn.example.com/project --stdlayout

    Make your git repository ignore everything the subversion repo does:

    git svn show-ignore >> .git/info/exclude

    You should now be able to see all the Subversion branches on the git side:

    git branch -r

    Say the name of the branch in Subversion is waldo. On the git side, you'd run

    git checkout -b waldo-svn remotes/waldo

    The -svn suffix is to avoid warnings of the form

    warning: refname 'waldo' is ambiguous.

    To update the git branch waldo-svn, run

    git checkout waldo-svn
    git svn rebase

    Starting from a trunk-only checkout

    To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

    [svn-remote "svn-mybranch"]
            url = http://svn.example.com/project/branches/mybranch
            fetch = :refs/remotes/mybranch

    You'll need to develop the habit of running

    git svn fetch --fetch-all

    to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

    git checkout -b mybranch-svn remotes/mybranch

    For the branches from which you intend to git svn dcommit, keep their histories linear!


    Further information

    You may also be interested in reading an answer to a related question.

    CMAKE_MAKE_PROGRAM not found

    Previous answers suggested (re)installing or configuring CMake, they all did not help.

    Previously MinGW's compilation of Make used the filename mingw32-make.exe and now it is make.exe. Most suggested ways to configure CMake to use the other file dont work.

    Just copy make.exe and rename the copy mingw32-make.exe.

    Getting data from selected datagridview row and which event?

    Simple solution would be as below. This is improvement of solution from vale.

    private void dgMapTable_SelectionChanged(object sender, EventArgs e) 
    {
        int active_map=0;
        if(dgMapTable.SelectedRows.Count>0)
            active_map = dgMapTable.SelectedRows[0].Index;
        // User code if required Process_ROW(active_map);
    }
    

    Note for other reader, for above code to work FullRowSelect selection mode for datagridview should be used. You may extend this to give message if more than two rows selected.

    How to install Ruby 2.1.4 on Ubuntu 14.04

    Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.

    To install RVM type into terminal:

    \curl -sSL https://get.rvm.io | bash -s stable
    

    And let it work. After that you will have RVM along with Ruby installed.

    Source: RVM Site

    Can I check if Bootstrap Modal Shown / Hidden?

    Use hasClass('in'). It will return true if modal is in OPEN state.

    E.g:

    if($('.modal').hasClass('in')){
       //Do something here
    }
    

    How to center text vertically with a large font-awesome icon?

    I just had to do this myself, you need to do it the other way around.

    • do not play with the vertical-align of your text
    • play with the vertical align of the font-awesome icon
    <div>
      <span class="icon icon-2x icon-camera" style=" vertical-align: middle;"></span>
      <span class="my-text">hello world</span>
    </div>
    

    Of course you could not use inline styles and target it with your own css class. But this works in a copy paste fashion.

    See here: Vertical alignment of text and icon in button

    If it were up to me however, I would not use the icon-2x. And simply specify the font-size myself, as in the following

    <div class='my-fancy-container'>
        <span class='my-icon icon-file-text'></span>
        <span class='my-text'>Hello World</span>
    </div>
    
    .my-icon {
        vertical-align: middle;
        font-size: 40px;
    }
    
    .my-text {
        font-family: "Courier-new";
    }
    
    .my-fancy-container {
        border: 1px solid #ccc;
        border-radius: 6px;
        display: inline-block;
        margin: 60px;
        padding: 10px;
    }
    

    for a working example, please see JsFiddle

    Difference between h:button and h:commandButton

    This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

    h:commandButton vs h:button

    What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

    The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

    There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

    First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

    The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

    Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

    Angular js init ng-model from default values

    This one is a more generic version of the ideas mentioned above... It simply checks whether there is any value in the model, and if not, it sets the value to the model.

    JS:

    function defaultValueDirective() {
        return {
            restrict: 'A',
            controller: [
                '$scope', '$attrs', '$parse',
                function ($scope, $attrs, $parse) {
                    var getter = $parse($attrs.ngModel);
                    var setter = getter.assign;
                    var value = getter();
                    if (value === undefined || value === null) {
                        var defaultValueGetter = $parse($attrs.defaultValue);
                        setter($scope, defaultValueGetter());
                    }
                }
            ]
        }
    }
    

    HTML (usage example):

    <select class="form-control"
            ng-options="v for (i, v) in compressionMethods"
            ng-model="action.parameters.Method"
            default-value="'LZMA2'"></select>
    

    What is the 'pythonic' equivalent to the 'fold' function from functional programming?

    Haskell

    foldl (+) 0 [1,2,3,4,5]

    Python

    reduce(lambda a,b: a+b, [1,2,3,4,5], 0)

    Obviously, that is a trivial example to illustrate a point. In Python you would just do sum([1,2,3,4,5]) and even Haskell purists would generally prefer sum [1,2,3,4,5].

    For non-trivial scenarios when there is no obvious convenience function, the idiomatic pythonic approach is to explicitly write out the for loop and use mutable variable assignment instead of using reduce or a fold.

    That is not at all the functional style, but that is the "pythonic" way. Python is not designed for functional purists. See how Python favors exceptions for flow control to see how non-functional idiomatic python is.

    Display List in a View MVC

    You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

    You have to pass following model

    var model = new List<Teams>();
    
    model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
    model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
    return View(model);
    

    ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

    If you are on Public Network, Firewall will block all incoming connections by default. check your firewall settings or use private network to SSL

    Error including image in Latex

    I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

    \includegraphics[height=60mm, width=100mm]{number2.png}
    

    works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

    Incidentally, you can change this in TexShop from the "Typeset" menu.

    Hope this helps.

    Connect multiple devices to one device via Bluetooth

    I don't think it's possible with bluetooth, but you could try looking into WiFi Peer-to-Peer,
    which allows one-to-many connections.

    Determining if Swift dictionary contains key and obtaining any of its values

    My solution for a cache implementation that stores optional NSAttributedString:

    public static var attributedMessageTextCache    = [String: NSAttributedString?]()
    
        if attributedMessageTextCache.index(forKey: "key") != nil
        {
            if let attributedMessageText = TextChatCache.attributedMessageTextCache["key"]
            {
                return attributedMessageText
            }
            return nil
        }
    
        TextChatCache.attributedMessageTextCache["key"] = .some(.none)
        return nil
    

    How to debug in Django, the good way?

    There are a bunch of ways to do it, but the most straightforward is to simply use the Python debugger. Just add following line in to a Django view function:

    import pdb; pdb.set_trace()
    

    or

    breakpoint()  #from Python3.7
    

    If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.

    However there are other options (I am not recommending them):

    * return HttpResponse({variable to inspect})
    
    * print {variable to inspect}
    
    * raise Exception({variable to inspect})
    

    But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at IPDB that uses ipython for debugging.

    Some more useful extension to pdb are

    pdb++, suggested by Antash.

    pudb, suggested by PatDuJour.

    Using the Python debugger in Django, suggested by Seafangs.

    How to delete last character from a string using jQuery?

    This page comes first when you search on Google "remove last character jquery"

    Although all previous answers are correct, somehow did not helped me to find what I wanted in a quick and easy way.

    I feel something is missing. Apologies if i'm duplicating

    jQuery

    $('selector').each(function(){ 
      var text = $(this).html();
      text = text.substring(0, text.length-1);
      $(this).html(text);
    });
    

    or

    $('selector').each(function(){ 
      var text = $(this).html();
      text = text.slice(0,-1);
      $(this).html(text);
    })
    

    How to open a folder in Windows Explorer from VBA?

    Here is some more cool knowledge to go with this:

    I had a situation where I needed to be able to find folders based on a bit of criteria in the record and then open the folder(s) that were found. While doing work on finding a solution I created a small database that asks for a search starting folder gives a place for 4 pieces of criteria and then allows the user to do criteria matching that opens the 4 (or more) possible folders that match the entered criteria.

    Here is the whole code on the form:

    Option Compare Database
    Option Explicit
    
    Private Sub cmdChooseFolder_Click()
    
        Dim inputFileDialog As FileDialog
        Dim folderChosenPath As Variant
    
        If MsgBox("Clear List?", vbYesNo, "Clear List") = vbYes Then DoCmd.RunSQL "DELETE * FROM tblFileList"
        Me.sfrmFolderList.Requery
    
        Set inputFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    
        With inputFileDialog
            .Title = "Select Folder to Start with"
            .AllowMultiSelect = False
            If .Show = False Then Exit Sub
            folderChosenPath = .SelectedItems(1)
        End With
    
        Me.txtStartPath = folderChosenPath
    
        Call subListFolders(Me.txtStartPath, 1)
    
    End Sub
    Private Sub cmdFindFolderPiece_Click()
    
        Dim strCriteria As String
        Dim varCriteria As Variant
        Dim varIndex As Variant
        Dim intIndex As Integer
    
        varCriteria = Array(Nz(Me.txtSerial, "Null"), Nz(Me.txtCustomerOrder, "Null"), Nz(Me.txtAXProject, "Null"), Nz(Me.txtWorkOrder, "Null"))
        intIndex = 0
    
        For Each varIndex In varCriteria
            strCriteria = varCriteria(intIndex)
            If strCriteria <> "Null" Then
                Call fnFindFoldersWithCriteria(TrailingSlash(Me.txtStartPath), strCriteria, 1)
            End If
            intIndex = intIndex + 1
        Next varIndex
    
        Set varIndex = Nothing
        Set varCriteria = Nothing
        strCriteria = ""
    
    End Sub
    Private Function fnFindFoldersWithCriteria(ByVal strStartPath As String, ByVal strCriteria As String, intCounter As Integer)
    
        Dim fso As New FileSystemObject
        Dim fldrStartFolder As Folder
        Dim subfldrInStart As Folder
        Dim subfldrInSubFolder As Folder
        Dim subfldrInSubSubFolder As String
        Dim strActionLog As String
    
        Set fldrStartFolder = fso.GetFolder(strStartPath)
    
    '    Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(fldrStartFolder.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
    
        If fnCompareCriteriaWithFolderName(fldrStartFolder.Name, strCriteria) Then
    '        Debug.Print "Found and Opening: " & fldrStartFolder.Name & "Because of: " & strCriteria
            Shell "EXPLORER.EXE" & " " & Chr(34) & fldrStartFolder.Path & Chr(34), vbNormalFocus
        Else
            For Each subfldrInStart In fldrStartFolder.SubFolders
    
                intCounter = intCounter + 1
    
                Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(subfldrInStart.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
    
                If fnCompareCriteriaWithFolderName(subfldrInStart.Name, strCriteria) Then
    '                Debug.Print "Found and Opening: " & subfldrInStart.Name & "Because of: " & strCriteria
                    Shell "EXPLORER.EXE" & " " & Chr(34) & subfldrInStart.Path & Chr(34), vbNormalFocus
                Else
                    Call fnFindFoldersWithCriteria(subfldrInStart, strCriteria, intCounter)
                End If
                Me.txtProcessed = intCounter
                Me.txtProcessed.Requery
            Next
        End If
    
        Set fldrStartFolder = Nothing
        Set subfldrInStart = Nothing
        Set subfldrInSubFolder = Nothing
        Set fso = Nothing
    
    End Function
    Private Function fnCompareCriteriaWithFolderName(strFolderName As String, strCriteria As String) As Boolean
    
        fnCompareCriteriaWithFolderName = False
    
        fnCompareCriteriaWithFolderName = InStr(1, Replace(strFolderName, " ", "", 1, , vbTextCompare), Replace(strCriteria, " ", "", 1, , vbTextCompare), vbTextCompare) > 0
    
    End Function
    
    Private Sub subListFolders(ByVal strFolders As String, intCounter As Integer)
        Dim dbs As Database
        Dim fso As New FileSystemObject
        Dim fldFolders As Folder
        Dim fldr As Folder
        Dim subfldr As Folder
        Dim sfldFolders As String
        Dim strSQL As String
    
        Set fldFolders = fso.GetFolder(TrailingSlash(strFolders))
        Set dbs = CurrentDb
    
        strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldFolders.Path & Chr(34) & ", " & Chr(34) & fldFolders.Name & Chr(34) & ", '" & fldFolders.Size & "')"
        dbs.Execute strSQL
    
        For Each fldr In fldFolders.SubFolders
            intCounter = intCounter + 1
            strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldr.Path & Chr(34) & ", " & Chr(34) & fldr.Name & Chr(34) & ", '" & fldr.Size & "')"
            dbs.Execute strSQL
            For Each subfldr In fldr.SubFolders
                intCounter = intCounter + 1
                sfldFolders = subfldr.Path
                Call subListFolders(sfldFolders, intCounter)
                Me.sfrmFolderList.Requery
            Next
            Me.txtListed = intCounter
            Me.txtListed.Requery
        Next
    
        Set fldFolders = Nothing
        Set fldr = Nothing
        Set subfldr = Nothing
        Set dbs = Nothing
    
    End Sub
    
    Private Function TrailingSlash(varIn As Variant) As String
        If Len(varIn) > 0& Then
            If Right(varIn, 1&) = "\" Then
                TrailingSlash = varIn
            Else
                TrailingSlash = varIn & "\"
            End If
        End If
    End Function
    

    The form has a subform based on the table, the form has 4 text boxes for the criteria, 2 buttons leading to the click procedures and 1 other text box to store the string for the start folder. There are 2 text boxes that are used to show the number of folders listed and the number processed when searching them for the criteria.

    If I had the Rep I would post a picture... :/

    I have some other things I wanted to add to this code but haven't had the chance yet. I want to have a way to store the ones that worked in another table or get the user to mark them as good to store.

    I can not claim full credit for all the code, I cobbled some of it together from stuff I found all around, even in other posts on stackoverflow.

    I really like the idea of posting questions here and then answering them yourself because as the linked article says, it makes it easy to find the answer for later reference.

    When I finish the other parts I want to add I will post the code for that too. :)

    How can I use Html.Action?

    You should look at the documentation for the Action method; it's explained well. For your case, this should work:

    @Html.Action("GetOptions", new { pk="00", rk="00" });
    

    The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

    @Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });
    

    Cannot open include file with Visual Studio

    By default, Visual Studio searches for headers in the folder where your project is ($ProjectDir) and in the default standard libraries directories. If you need to include something that is not placed in your project directory, you need to add the path to the folder to include:

    Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories add the path to your .h file.

    You can, also, as suggested by Chris Olen, add the path to VC++ Directories field.

    Set Matplotlib colorbar size to match graph

    You can do this easily with a matplotlib AxisDivider.

    The example from the linked page also works without using subplots:

    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import numpy as np
    
    plt.figure()
    ax = plt.gca()
    im = ax.imshow(np.arange(100).reshape((10,10)))
    
    # create an axes on the right side of ax. The width of cax will be 5%
    # of ax and the padding between cax and ax will be fixed at 0.05 inch.
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    
    plt.colorbar(im, cax=cax)
    

    enter image description here

    Cast Int to enum in Java

    This not something that is usually done, so I would reconsider. But having said that, the fundamental operations are: int --> enum using EnumType.values()[intNum], and enum --> int using enumInst.ordinal().

    However, since any implementation of values() has no choice but to give you a copy of the array (java arrays are never read-only), you would be better served using an EnumMap to cache the enum --> int mapping.

    No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

    Doesn't look like you got an answer but this problem can also creep up if you're passing null ID's into your JPA Predicate.

    For instance.

    If I did a query on Cats to get back a list. Which returns 3 results.

    List catList;

    I then iterate over that List of cats and store a foriegn key of cat perhaps leashTypeId in another list.

    List<Integer> leashTypeIds= new ArrayList<>();
    
    for(Cats c : catList){
        leashTypeIds.add(c.getLeashTypeId);
    }
    
    jpaController().findLeashes(leashTypeIds);
    

    If any of the Cats in catList have a null leashTypeId it will throw this error when you try to query your DB.

    (Just realized I am posting on a 5 year old thread, perhaps someone will find this useful)

    Round to 5 (or other number) in Python

    Use:

    >>> def round_to_nearest(n, m):
            r = n % m
            return n + m - r if r + r >= m else n - r
    

    It does not use multiplication and will not convert from/to floats.

    Rounding to the nearest multiple of 10:

    >>> for n in range(-21, 30, 3): print('{:3d}  =>  {:3d}'.format(n, round_to_nearest(n, 10)))
    -21  =>  -20
    -18  =>  -20
    -15  =>  -10
    -12  =>  -10
     -9  =>  -10
     -6  =>  -10
     -3  =>    0
      0  =>    0
      3  =>    0
      6  =>   10
      9  =>   10
     12  =>   10
     15  =>   20
     18  =>   20
     21  =>   20
     24  =>   20
     27  =>   30
    

    As you can see, it works for both negative and positive numbers. Ties (e.g. -15 and 15) will always be rounded upwards.

    A similar example that rounds to the nearest multiple of 5, demonstrating that it also behaves as expected for a different "base":

    >>> for n in range(-21, 30, 3): print('{:3d}  =>  {:3d}'.format(n, round_to_nearest(n, 5)))
    -21  =>  -20
    -18  =>  -20
    -15  =>  -15
    -12  =>  -10
     -9  =>  -10
     -6  =>   -5
     -3  =>   -5
      0  =>    0
      3  =>    5
      6  =>    5
      9  =>   10
     12  =>   10
     15  =>   15
     18  =>   20
     21  =>   20
     24  =>   25
     27  =>   25
    

    Is there a format code shortcut for Visual Studio?

    Change these shortcuts in Visual Studio

    Tools ? Options ? Environment ? Keyboard
    

    and then change the command

    "Edit.FormatDocument" or "Edit.FormatSelection"
    

    assign the same shortcut alt + shift +f as in visual studio code in order to not remember another one and confuse between each other.

    Recyclerview and handling different type of row inflation

    The trick is to create subclasses of ViewHolder and then cast them.

    public class GroupViewHolder extends RecyclerView.ViewHolder {
        TextView mTitle;
        TextView mContent;
        public GroupViewHolder(View itemView) {
            super (itemView);
            // init views...
        }
    }
    
    public class ImageViewHolder extends RecyclerView.ViewHolder {
        ImageView mImage;
        public ImageViewHolder(View itemView) {
            super (itemView);
            // init views...
        }
    }
    
    private static final int TYPE_IMAGE = 1;
    private static final int TYPE_GROUP = 2;  
    

    And then, at runtime do something like this:

    @Override
    public int getItemViewType(int position) {
        // here your custom logic to choose the view type
        return position == 0 ? TYPE_IMAGE : TYPE_GROUP;
    }
    
    @Override
    public void onBindViewHolder (ViewHolder viewHolder, int i) {
    
        switch (viewHolder.getItemViewType()) {
    
            case TYPE_IMAGE:
                ImageViewHolder imageViewHolder = (ImageViewHolder) viewHolder;
                imageViewHolder.mImage.setImageResource(...);
                break;
    
            case TYPE_GROUP:
                GroupViewHolder groupViewHolder = (GroupViewHolder) viewHolder;
                groupViewHolder.mContent.setText(...)
                groupViewHolder.mTitle.setText(...);
                break;
        }
    }
    

    Hope it helps.

    How to print to console using swift playground?

    As of Xcode 7.0.1 println is change to print. Look at the image. there are lot more we can print out. enter image description here

    Setting environment variables in Linux using Bash

    export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR".

    Failed to Connect to MySQL at localhost:3306 with user root

    MySQL default port is 3306 but it may be unavailable for some reasons, try to restart your machine. Also sesrch for your MySQL configuration file (should be called "my.cnf") and check if the used port is 3306 or 3307, if is 3307 you can change it to 3306 and then reboot your MySQL server.

    How to Uninstall RVM?

    It’s easy; just do the following:

    rvm implode
    

    or

    rm -rf ~/.rvm
    

    And don’t forget to remove the script calls in the following files:

    • ~/.bashrc
    • ~/.bash_profile
    • ~/.profile

    And maybe others depending on whatever shell you’re using.

    XPath selecting a node with some attribute value equals to some other node's attribute value

    This XPath is specific to the code snippet you've provided. To select <child> with id as #grand you can write //child[@id='#grand'].

    To get age //child[@id='#grand']/@age

    Hope this helps

    How to trigger Jenkins builds remotely and to pass parameters

    When we have to send multiple trigger parameters to jenkins job, the following commands works.

    curl -X POST -i -u "auto_user":"xxxauthentication_tokenxxx" "JENKINS_URL/view/tests/job/helloworld/buildWithParameters?param1=162&param2=store"
    

    Change line width of lines in matplotlib pyplot legend

    @ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

    Method 1

    import numpy as np
    import matplotlib.pyplot as plt
    
    # make some data
    x = np.linspace(0, 2*np.pi)
    
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    # plot sin(x) and cos(x)
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    ax.plot(x, y1, c='b', label='y1')
    ax.plot(x, y2, c='r', label='y2')
    
    leg = plt.legend()
    # get the individual lines inside legend and set line width
    for line in leg.get_lines():
        line.set_linewidth(4)
    # get label texts inside legend and set font size
    for text in leg.get_texts():
        text.set_fontsize('x-large')
    
    plt.savefig('leg_example')
    plt.show()
    

    Method 2

    import numpy as np
    import matplotlib.pyplot as plt
    
    # make some data
    x = np.linspace(0, 2*np.pi)
    
    y1 = np.sin(x)
    y2 = np.cos(x)
    
    # plot sin(x) and cos(x)
    fig = plt.figure()
    ax  = fig.add_subplot(111)
    ax.plot(x, y1, c='b', label='y1')
    ax.plot(x, y2, c='r', label='y2')
    
    leg = plt.legend()
    # get the lines and texts inside legend box
    leg_lines = leg.get_lines()
    leg_texts = leg.get_texts()
    # bulk-set the properties of all lines and texts
    plt.setp(leg_lines, linewidth=4)
    plt.setp(leg_texts, fontsize='x-large')
    plt.savefig('leg_example')
    plt.show()
    

    The above two methods produce the same output image:

    output image

    How is length implemented in Java Arrays?

    According to the Java Language Specification (specifically §10.7 Array Members) it is a field:

    • The public final field length, which contains the number of components of the array (length may be positive or zero).

    Internally the value is probably stored somewhere in the object header, but that is an implementation detail and depends on the concrete JVM implementation.

    The HotSpot VM (the one in the popular Oracle (formerly Sun) JRE/JDK) stores the size in the object-header:

    [...] arrays have a third header field, for the array size.

    How to Calculate Execution Time of a Code Snippet in C++

    I created a simple utility for measuring performance of blocks of code, using the chrono library's high_resolution_clock: https://github.com/nfergu/codetimer.

    Timings can be recorded against different keys, and an aggregated view of the timings for each key can be displayed.

    Usage is as follows:

    #include <chrono>
    #include <iostream>
    #include "codetimer.h"
    
    int main () {
        auto start = std::chrono::high_resolution_clock::now();
        // some code here
        CodeTimer::record("mykey", start);
        CodeTimer::printStats();
        return 0;
    }
    

    Find the least number of coins required that can make any change from 1 to 99 cents

    This the code in c# to find the solution.

    public struct CoinCount
    {
        public int coinValue;
        public int noOfCoins;
    }
    
    /// <summary>
    /// Find and returns the no of coins in each coins in coinSet
    /// </summary>
    /// <param name="coinSet">sorted coins value in assending order</param>
    /// <returns></returns>
    public CoinCount[] FindCoinsCountFor1to99Collection(int[] coinSet)
    {
        // Add extra coin value 100 in the coin set. Since it need to find the collection upto 99.
        CoinCount[] result = new CoinCount[coinSet.Length];
        List<int> coinValues = new List<int>();
        coinValues.AddRange(coinSet);
        coinValues.Add(100);
    
        // Selected coin total values
        int totalCount = 0;
        for (int i = 0; i < coinValues.Count - 1; i++)
        {
            int count = 0;
            if (totalCount <= coinValues[i])
            {
                // Find the coins count
                int remainValue = coinValues[i + 1] - totalCount;
                count = (int)Math.Ceiling((remainValue * 1.0) / coinValues[i]);
            }
            else
            {
                if (totalCount <= coinValues[i + 1])
                    count = 1;
                else
                    count = 0;
            }
            result[i] = new CoinCount() { coinValue =  coinValues[i], noOfCoins = count };
            totalCount += coinValues[i] * count;
        }
        return result;
    }
    

    Oracle select most recent date record

    Assuming staff_id + date form a uk, this is another method:

    SELECT STAFF_ID, SITE_ID, PAY_LEVEL
      FROM TABLE t
      WHERE END_ENROLLMENT_DATE is null
        AND DATE = (SELECT MAX(DATE)
                      FROM TABLE
                      WHERE staff_id = t.staff_id
                        AND DATE <= SYSDATE)
    

    Converting Dictionary to List?

    Converting from dict to list is made easy in Python. Three examples:

    >> d = {'a': 'Arthur', 'b': 'Belling'}
    
    >> d.items()
    [('a', 'Arthur'), ('b', 'Belling')]
    
    >> d.keys()
    ['a', 'b']
    
    >> d.values()
    ['Arthur', 'Belling']
    

    How to check if a service is running via batch file and start it, if it is not running?

    Related with the answer by @DanielSerrano, I've been recently bit by localization of the sc.exe command, namely in Spanish. My proposal is to pin-point the line and token which holds numerical service state and interpret it, which should be much more robust:

    @echo off
    
    rem TODO: change to the desired service name
    set TARGET_SERVICE=w32time
    
    set SERVICE_STATE=
    rem Surgically target third line, as some locales (such as Spanish) translated the utility's output
    for /F "skip=3 tokens=3" %%i in ('""%windir%\system32\sc.exe" query "%TARGET_SERVICE%" 2>nul"') do (
      if not defined SERVICE_STATE set SERVICE_STATE=%%i
    )
    rem Process result
    if not defined SERVICE_STATE (
      echo ERROR: could not obtain service state!
    ) else (
      rem NOTE: values correspond to "SERVICE_STATUS.dwCurrentState"
      rem https://msdn.microsoft.com/en-us/library/windows/desktop/ms685996(v=vs.85).aspx
      if not %SERVICE_STATE%==4 (
        echo WARNING: service is not running
        rem TODO: perform desired operation
        rem net start "%TARGET_SERVICE%"
      ) else (
        echo INFORMATION: service is running
      )
    )
    

    Tested with:

    • Windows XP (32-bit) English
    • Windows 10 (32-bit) Spanish
    • Windows 10 (64-bit) English

    CSS Calc Viewport Units Workaround?

    <div>It's working fine.....</div>
    
    div
    {
         height: calc(100vh - 8vw);
        background: #000;
        overflow:visible;
        color: red;
    }
    

    Check here this css code right now support All browser without Opera

    just check this

    Live

    see Live preview by jsfiddle

    See Live preview by codepen.io

    How do you check current view controller class in Swift?

    I had to find the current viewController in AppDelegate. I used this

    //at top of class
    var window:UIWindow?
    
    // inside my method/function
    if let viewControllers = window?.rootViewController?.childViewControllers {
        for viewController in viewControllers {
            if viewController.isKindOfClass(MyViewControllerClass) {
                println("Found it!!!")
                }
            }
        }
    

    How to convert Blob to String and String to Blob in java

    Use this to convert String to Blob. Where connection is the connection to db object.

        String strContent = s;
        byte[] byteConent = strContent.getBytes();
        Blob blob = connection.createBlob();//Where connection is the connection to db object. 
        blob.setBytes(1, byteContent);