Programs & Examples On #Sqljdbc

Microsoft JDBC Driver for SQL Server

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

Microsoft recently open sourced their jdbc driver.

You can now find the driver on maven central:

<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre8</version>
</dependency>

or for java 7:

<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>6.1.0.jre7</version>
</dependency>

Java program to connect to Sql Server and running the sample query From Eclipse

you forgotten to add the sqlserver.jar in eclipse external library follow the process to add jar files

  1. Right click on your project.
  2. click buildpath
  3. click configure bulid path
  4. click add external jar and then give the path of jar

dll missing in JDBC

If its the case of the dll file missing you can download the dll file from this link http://en.osdn.jp/projects/sfnet_dose-grok/downloads/sqljdbc_auth.dll/

else you need to provide the username and password of the db you are trying to connect, and make the authentication as false

error: package javax.servlet does not exist

The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.

The servlet-api jar is best left up to the server to manage see here for detail

With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be

<dependency>
    <groupId>org.jboss.spec.javax.servlet</groupId>
    <artifactId>jboss-servlet-api_3.1_spec</artifactId>
    <scope>provided</scope>
</dependency>

So becareful to check how your container has provided the servlet implementation.

no sqljdbc_auth in java.library.path

For easy fix follow these steps:

  1. goto: https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated
  2. Download the JDBC file and extract to your preferred location
  3. open the auth folder matching your OS x64 or x86
  4. copy sqljdbc_auth.dll file
  5. paste in: C:\Program Files\Java\jdk_version\bin
  6. restart either eclipse or netbeans

java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver

For someone looking to solve same by using maven. Add below dependency in POM:

<dependency>
    <groupId>com.microsoft.sqlserver</groupId>
    <artifactId>mssql-jdbc</artifactId>
    <version>7.0.0.jre8</version>
</dependency>

And use below code for connection:

String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=master;user=sa;password=your_password";

try {
    System.out.print("Connecting to SQL Server ... ");
    try (Connection connection = DriverManager.getConnection(connectionUrl))        {
        System.out.println("Done.");
    }
} catch (Exception e) {
    System.out.println();
    e.printStackTrace();
}

Look for this link for other CRUD type of queries.

How to make Java work with SQL Server?

For anyone still googling this, go to \blackboard\config\tomcat\conf and in wrapper.conf put an extra line in wrapper.java.classpath pointing to the sqljdbc4.jar and then update the wrapper.conf.bb as well

Then restart the blackboard services and tomcat and it should work

It won't work by simply setting your java classpath, you have to set it up in the blackboard config files to point to your jar file with the jdbc library

How can I use the MS JDBC driver with MS SQL Server 2008 Express?

You can try the following. Works fine in my case:

  1. Download the current jTDS JDBC Driver
  2. Put jtds-x.x.x.jar in your classpath.
  3. Copy ntlmauth.dll to windows/system32. Choose the dll based on your hardware x86,x64...
  4. The connection url is: 'jdbc:jtds:sqlserver://localhost:1433/YourDB' , you don't have to provide username and password.

Hope that helps.

JQuery show and hide div on mouse click (animate)

That .toggle() method was removed from jQuery in version 1.9. You can do this instead:

$(document).ready(function() {
    $('#showmenu').click(function() {
            $('.menu').slideToggle("fast");
    });
});

Demo: http://jsfiddle.net/APA2S/1/

...but as with the code in your question that would slide up or down. To slide left or right you can do the following:

$(document).ready(function() {
    $('#showmenu').click(function() {
         $('.menu').toggle("slide");
    });
});

Demo: http://jsfiddle.net/APA2S/2/

Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.

java get file size efficiently

All the test cases in this post are flawed as they access the same file for each method tested. So disk caching kicks in which tests 2 and 3 benefit from. To prove my point I took test case provided by GHAD and changed the order of enumeration and below are the results.

Looking at result I think File.length() is the winner really.

Order of test is the order of output. You can even see the time taken on my machine varied between executions but File.Length() when not first, and incurring first disk access won.

---
LENGTH sum: 1163351, per Iteration: 4653.404
CHANNEL sum: 1094598, per Iteration: 4378.392
URL sum: 739691, per Iteration: 2958.764

---
CHANNEL sum: 845804, per Iteration: 3383.216
URL sum: 531334, per Iteration: 2125.336
LENGTH sum: 318413, per Iteration: 1273.652

--- 
URL sum: 137368, per Iteration: 549.472
LENGTH sum: 18677, per Iteration: 74.708
CHANNEL sum: 142125, per Iteration: 568.5

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

The only things that work for for moving to the beginning and end of line are

?? "SEND ESC SEQ" OH - to move to the beginning of line
?? "SEND ESC SEQ" OF - to move to the end of line

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

How can I remove the last character of a string in python?

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'

how to properly display an iFrame in mobile safari

Sharon's method worked for me, however when a link in the iframe is followed and then the browser back button is pressed, the cached version of the page is loaded and the iframe is no longer scrollable. To overcome this I used some code to refresh the page as follows:

if ('ontouchstart' in document.documentElement)
     {
        document.getElementById('Scrolling').src = document.getElementById('SCrolling').src;
    }

How to add a WiX custom action that happens only on uninstall (via MSI)?

You can do this with a custom action. You can add a refrence to your custom action under <InstallExecuteSequence>:

<InstallExecuteSequence>
...
  <Custom Action="FileCleaner" After='InstallFinalize'>
          Installed AND NOT UPGRADINGPRODUCTCODE</Custom>

Then you will also have to define your Action under <Product>:

<Product> 
...
  <CustomAction Id='FileCleaner' BinaryKey='FileCleanerEXE' 
                ExeCommand='' Return='asyncNoWait'  />

Where FileCleanerEXE is a binary (in my case a little c++ program that does the custom action) which is also defined under <Product>:

<Product> 
...
  <Binary Id="FileCleanerEXE" SourceFile="path\to\fileCleaner.exe" />

The real trick to this is the Installed AND NOT UPGRADINGPRODUCTCODE condition on the Custom Action, with out that your action will get run on every upgrade (since an upgrade is really an uninstall then reinstall). Which if you are deleting files is probably not want you want during upgrading.

On a side note: I recommend going through the trouble of using something like C++ program to do the action, instead of a batch script because of the power and control it provides -- and you can prevent the "cmd prompt" window from flashing while your installer runs.

Maven: How to include jars, which are not available in reps into a J2EE project?

Create a repository folder under your project. Let's take

${project.basedir}/src/main/resources/repo

Then, install your custom jar to this repo:

mvn install:install-file -Dfile=[FILE_PATH] \
-DgroupId=[GROUP] -DartifactId=[ARTIFACT] -Dversion=[VERS] \ 
-Dpackaging=jar -DlocalRepositoryPath=[REPO_DIR]

Lastly, add the following repo and dependency definitions to the projects pom.xml:

<repositories>
    <repository>
        <id>project-repo</id>
        <url>file://${project.basedir}/src/main/resources/repo</url>
    </repository>
</repositories>

<dependencies>    
    <dependency>
        <groupId>[GROUP]</groupId>
        <artifactId>[ARTIFACT]</artifactId>
        <version>[VERS]</version>
    </dependency>
</dependencies>

How to change pivot table data source in Excel?

Be a bit wary of any solution that doesn't involve re-creating the PivotTable from scratch. It is possible for your pivot fields' option names to get out of sync with the values they present to the database.

For example, in one workbook I'm dealing with involving demographic data, if you try to select the "20-24" age band option, Excel actually presents you with the figures for ages 25-29. It doesn't tell you it's doing this, of course.

See below for a programmatic (VBA) approach to the problem that solves this issue among others. I think it's fairly complete/robust, but I don't use PivotTables much so would appreciate feedback.

Sub SwapSources()

strOldSource = "2010 Data"
strNewSource = "2009 Data"

Dim tmpArrOut

For Each wsh In ThisWorkbook.Worksheets
    For Each pvt In wsh.PivotTables
        tmpArrIn = pvt.SourceData
        ' row 1 of SourceData is the connection string.
        ' rows 2+ are the SQL code broken down into 255-byte chunks.
        ' we need to concatenate rows 2+, replace, and then split them up again

        strSource1 = tmpArrIn(LBound(tmpArrIn))
        strSource2 = ""
        For ii = LBound(tmpArrIn) + 1 To UBound(tmpArrIn)
            strSource2 = strSource2 & tmpArrIn(ii)
        Next ii

        strSource1 = Replace(strSource1, strOldSource, strNewSource)
        strSource2 = Replace(strSource2, strOldSource, strNewSource)

        ReDim tmpArrOut(1 To Int(Len(strSource2) / 255) + 2)
        tmpArrOut(LBound(tmpArrOut)) = strSource1
        For ii = LBound(tmpArrOut) + 1 To UBound(tmpArrOut)
            tmpArrOut(ii) = Mid(strSource2, 255 * (ii - 2) + 1, 255)
        Next ii

        ' if the replacement SQL is invalid, the PivotTable object will throw an error
        Err.Clear
        On Error Resume Next
            pvt.SourceData = tmpArrOut
        On Error GoTo 0
        If Err.Number <> 0 Then
            MsgBox "Problems changing SQL for table " & wsh.Name & "!" & pvt.Name
            pvt.SourceData = tmpArrIn ' revert
        ElseIf pvt.RefreshTable <> True Then
            MsgBox "Problems refreshing table " & wsh.Name & "!" & pvt.Name
        Else
            ' table is now refreshed
            ' need to ensure that the "display name" for each pivot option matches
            ' the actual value that will be fed to the database.  It is possible for
            ' these to get out of sync.
            For Each pvf In pvt.PivotFields
                'pvf.Name = pvf.SourceName
                If Not IsError(pvf.SourceName) Then ' a broken field may have no SourceName
                    mismatches = 0
                    For Each pvi In pvf.PivotItems
                        If pvi.Name <> pvi.SourceName Then
                            mismatches = mismatches + 1
                            pvi.Name = "_mismatch" & CStr(mismatches)
                        End If
                    Next pvi
                    If mismatches > 0 Then
                        For Each pvi In pvf.PivotItems
                            If pvi.Name <> pvi.SourceName Then
                                pvi.Name = pvi.SourceName
                            End If
                        Next
                    End If
                End If
            Next pvf
        End If
    Next pvt
Next wsh

End Sub

How do I capture SIGINT in Python?

Yet Another Snippet

Referred main as the main function and exit_gracefully as the CTRL + c handler

if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        pass
    finally:
        exit_gracefully()

The project cannot be built until the build path errors are resolved.

just check if any unnecessary Jars are added in your library or not. if yes, then simply remove that jars from your library and clean your project once. Its worked for me.

"Access is denied" JavaScript error when trying to access the document object of a programmatically-created <iframe> (IE-only)

well i actually have a very similar problem, but with a twist... say the top level site is a.foo.com - now i set document domain to a.foo.com

then in the iframe that i create / own,i also set it too a.foo.com

note that i cant set them too foo.com b/c there is another iframe in the page pointed to b.a.foo.com (which again uses a.foo.com but i cant change the script code there)

youll note that im essentially setting document.domain to what it already would be anyway...but i have to do that to access the other iframe i mentioned from b.a.foo.com

inside my frame, after i set the domain, eventhough all iframes have the same setting, i still get an error when reaching up into the parent in IE 6/7

there are other things that r really bizaree

in the outside / top level, if i wait for its onload event, and set a timer, eventually i can reach down into the frame i need to access....but i can never reach from bottom up... and i really need to be able to

also if i set everything to be foo.com (which as i said i cannot do) IT WORKS! but for some reason, when using the same value as location.host....it doesnt and its freaking killing me.....

java: run a function after a specific number of seconds

ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.

Timer also has this ability but opens several thread even if used only once.

Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // The while is just to ignore interruption.
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

Test:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

Pandas - How to flatten a hierarchical index in columns

The easiest and most intuitive solution for me was to combine the column names using get_level_values. This prevents duplicate column names when you do more than one aggregation on the same column:

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
df.columns = level_one + level_two

If you want a separator between columns, you can do this. This will return the same thing as Seiji Armstrong's comment on the accepted answer that only includes underscores for columns with values in both index levels:

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
column_separator = ['_' if x != '' else '' for x in level_two]
df.columns = level_one + column_separator + level_two

I know this does the same thing as Andy Hayden's great answer above, but I think it is a bit more intuitive this way and is easier to remember (so I don't have to keep referring to this thread), especially for novice pandas users.

This method is also more extensible in the case where you may have 3 column levels.

level_one = df.columns.get_level_values(0).astype(str)
level_two = df.columns.get_level_values(1).astype(str)
level_three = df.columns.get_level_values(2).astype(str)
df.columns = level_one + level_two + level_three

Java 8, Streams to find the duplicate elements

An O(n) way would be as below:

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 4, 4);
Set<Integer> duplicatedNumbersRemovedSet = new HashSet<>();
Set<Integer> duplicatedNumbersSet = numbers.stream().filter(n -> !duplicatedNumbersRemovedSet.add(n)).collect(Collectors.toSet());

The space complexity would go double in this approach, but that space is not a waste; in-fact, we now have the duplicated alone only as a Set as well as another Set with all the duplicates removed too.

How to add a single item to a Pandas Series

Adding to joquin's answer the following form might be a bit cleaner (at least nicer to read):

x = p.Series()
N = 4
for i in xrange(N):
   x[i] = i**2

which would produce the same output

also, a bit less orthodox but if you wanted to simply add a single element to the end:

x=p.Series()
value_to_append=5
x[len(x)]=value_to_append

What is a Python egg?

The .egg file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe. But note that for pure Python, the .egg file is completely cross-platform.

The .egg file itself is essentially a .zip file. If you change the extension to “zip”, you can see that it will have folders inside the archive.

Also, if you have an .egg file, you can install it as a package using easy_install

Example: To create an .egg file for a directory say mymath which itself may have several python scripts, do the following step:

# setup.py
from setuptools import setup, find_packages
setup(
    name = "mymath",
    version = "0.1",
    packages = find_packages()
    )

Then, from the terminal do:

 $ python setup.py bdist_egg

This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg file, mymath-0.1-py3.5.egg with your default python (installation) version number(mine here: 3.5)

Source: Python library blog

Post order traversal of binary tree without recursion

So you can use one stack to do a post order traversal.

private void PostOrderTraversal(Node pos) {
    Stack<Node> stack = new Stack<Node>();
    do {
        if (pos==null && (pos=stack.peek().right)==null) {
            for (visit(stack.peek()); stack.pop()==(stack.isEmpty()?null:stack.peek().right); visit(stack.peek())) {}
        } else if(pos!=null) {
            stack.push(pos);
            pos=pos.left;
        }
    } while (!stack.isEmpty());
}

Column name or number of supplied values does not match table definition

The computed columns make the problem. Do not use SELECT *. You must specify each fields after SELECT except computed fields

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

How to determine if object is in array

Use something like this:

function containsObject(obj, list) {
    var i;
    for (i = 0; i < list.length; i++) {
        if (list[i] === obj) {
            return true;
        }
    }

    return false;
}

In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:

function containsObject(obj, list) {
    var x;
    for (x in list) {
        if (list.hasOwnProperty(x) && list[x] === obj) {
            return true;
        }
    }

    return false;
}

This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.

How to convert enum names to string in c

A function like that without validating the enum is a trifle dangerous. I suggest using a switch statement. Another advantage is that this can be used for enums that have defined values, for example for flags where the values are 1,2,4,8,16 etc.

Also put all your enum strings together in one array:-

static const char * allEnums[] = {
    "Undefined",
    "apple",
    "orange"
    /* etc */
};

define the indices in a header file:-

#define ID_undefined       0
#define ID_fruit_apple     1
#define ID_fruit_orange    2
/* etc */

Doing this makes it easier to produce different versions, for example if you want to make international versions of your program with other languages.

Using a macro, also in the header file:-

#define CASE(type,val) case val: index = ID_##type##_##val; break;

Make a function with a switch statement, this should return a const char * because the strings static consts:-

const char * FruitString(enum fruit e){

    unsigned int index;

    switch(e){
        CASE(fruit, apple)
        CASE(fruit, orange)
        CASE(fruit, banana)
        /* etc */
        default: index = ID_undefined;
    }
    return allEnums[index];
}

If programming with Windows then the ID_ values can be resource values.

(If using C++ then all the functions can have the same name.

string EnumToString(fruit e);

)

What is the best way to parse html in C#?

Html Agility Pack

This is an agile HTML parser that builds a read/write DOM and supports plain XPATH or XSLT (you actually don't HAVE to understand XPATH nor XSLT to use it, don't worry...). It is a .NET code library that allows you to parse "out of the web" HTML files. The parser is very tolerant with "real world" malformed HTML. The object model is very similar to what proposes System.Xml, but for HTML documents (or streams).

Get Maven artifact version at runtime

I am using maven-assembly-plugin for my maven packaging. The usage of Apache Maven Archiver in Joachim Sauer's answer could also work:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
        <archive>
            <manifest>
                <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
            </manifest>
        </archive>
    </configuration>
    <executions>
        <execution .../>
    </executions>
</plugin>

Because archiever is one of maven shared components, it could be used by multiple maven building plugins, which could also have conflict if two or more plugins introduced, including archive configuration inside.

How to beautify JSON in Python?

alias jsonp='pbpaste | python -m json.tool'

This will pretty print JSON that's on the clipboard in OSX. Just Copy it then call the alias from a Bash prompt.

How do I split a string into an array of characters?

You can split on an empty string:

var chars = "overpopulation".split('');

If you just want to access a string in an array-like fashion, you can do that without split:

var s = "overpopulation";
for (var i = 0; i < s.length; i++) {
    console.log(s.charAt(i));
}

You can also access each character with its index using normal array syntax. Note, however, that strings are immutable, which means you can't set the value of a character using this method, and that it isn't supported by IE7 (if that still matters to you).

var s = "overpopulation";

console.log(s[3]); // logs 'r'

Write HTML string in JSON

One way is to replace the double quotes in the HTML with single quotes but using double quotes has become the standard convention for attribute values in HTML.

The better option is to escape the double quotes in json and other characters that need to be escaped.

You can get some more details about escaping here: Where can I find a list of escape characters required for my JSON ajax return type?

Split comma separated column data into additional columns

If the number of fields in the CSV is constant then you could do something like this:

select a[1], a[2], a[3], a[4]
from (
    select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)

For example:

=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
 a | a | a | a 
---+---+---+---
 a | b | c | d
(1 row)

If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:

select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table

and then build the appropriate a[1], a[2], ..., a[M] column list for your query. So if the above gave you a max of 6, you'd use this:

select a[1], a[2], a[3], a[4], a[5], a[6]
from (
    select regexp_split_to_array(csv, ',')
    from your_table
) as dt(a)

You could combine those two queries into a function if you wanted.

For example, give this data (that's a NULL in the last row):

=> select * from csvs;
     csv     
-------------
 1,2,3
 1,2,3,4
 1,2,3,4,5,6

(4 rows)

=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
 max 
-----
   6
(1 row)

=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
 a | a | a | a | a | a 
---+---+---+---+---+---
 1 | 2 | 3 |   |   | 
 1 | 2 | 3 | 4 |   | 
 1 | 2 | 3 | 4 | 5 | 6
   |   |   |   |   | 
(4 rows)

Since your delimiter is a simple fixed string, you could also use string_to_array instead of regexp_split_to_array:

select ...
from (
    select string_to_array(csv, ',')
    from csvs
) as dt(a);

Thanks to Michael for the reminder about this function.

You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.

VBScript -- Using error handling

I'm exceptionally new to VBScript, so this may not be considered best practice or there may be a reason it shouldn't be done this that way I'm not yet aware of, but this is the solution I came up with to trim down the amount of error logging code in my main code block.

Dim oConn, connStr
Set oConn = Server.CreateObject("ADODB.Connection")
connStr = "Provider=SQLOLEDB;Server=XX;UID=XX;PWD=XX;Databse=XX"

ON ERROR RESUME NEXT

oConn.Open connStr
If err.Number <> 0 Then : showError() : End If


Sub ShowError()

    'You could write the error details to the console...
    errDetail = "<script>" & _
    "console.log('Description: " & err.Description & "');" & _
    "console.log('Error number: " & err.Number & "');" & _
    "console.log('Error source: " & err.Source & "');" & _
    "</script>"

    Response.Write(errDetail)       

    '...you could display the error info directly in the page...
    Response.Write("Error Description: " & err.Description)
    Response.Write("Error Source: " & err.Source)
    Response.Write("Error Number: " & err.Number)

    '...or you could execute additional code when an error is thrown...
    'Insert error handling code here

    err.clear
End Sub

Git Clone from GitHub over https with two-factor authentication

As per @Nitsew's answer, Create your personal access token and use your token as your username and enter with blank password.

Later you won't need any credentials to access all your private repo(s).

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

Use Collections.synchronizedList().

Ex:

Collections.synchronizedList(new ArrayList<YourClassNameHere>())

How to open new browser window on button click event?

You can use some code like this, you can adjust a height and width as per your need

    protected void button_Click(object sender, EventArgs e)
    {
        // open a pop up window at the center of the page.
        ScriptManager.RegisterStartupScript(this, typeof(string), "OPEN_WINDOW", "var Mleft = (screen.width/2)-(760/2);var Mtop = (screen.height/2)-(700/2);window.open( 'your_page.aspx', null, 'height=700,width=760,status=yes,toolbar=no,scrollbars=yes,menubar=no,location=no,top=\'+Mtop+\', left=\'+Mleft+\'' );", true);
    }

How to convert seconds to HH:mm:ss in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:

_x000D_
_x000D_
const secs = 456;_x000D_
_x000D_
const formatted = moment.utc(secs*1000).format('HH:mm:ss');_x000D_
_x000D_
document.write(formatted);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

Wrap with and make invisible. Work in Chrome, Safari && FF.

_x000D_
_x000D_
label { _x000D_
  padding: 5px;_x000D_
  background: silver;_x000D_
}_x000D_
label > input[type=file] {_x000D_
    display: none;_x000D_
}
_x000D_
<label>_x000D_
  <input type="file">_x000D_
  select file_x000D_
</label>
_x000D_
_x000D_
_x000D_

How to clear https proxy setting of NPM?

Running npm version 2.10.1 in windows 7, I used:

npm config delete proxy
npm config delete https-proxy

How to align the text middle of BUTTON

Sometime it is fixed by the Padding .. if you can play with that, then, it should fix your problem

<style type=text/css>

YourbuttonByID {Padding: 20px 80px; "for example" padding-left:50px; 
 padding-right:30px "to fix the text in the middle 
 without interfering with the text itself"}

</style>

It worked for me

How can I search Git branches for a file or directory?

git log + git branch will find it for you:

% git log --all -- somefile

commit 55d2069a092e07c56a6b4d321509ba7620664c63
Author: Dustin Sallings <[email protected]>
Date:   Tue Dec 16 14:16:22 2008 -0800

    added somefile


% git branch -a --contains 55d2069
  otherbranch

Supports globbing, too:

% git log --all -- '**/my_file.png'

The single quotes are necessary (at least if using the Bash shell) so the shell passes the glob pattern to git unchanged, instead of expanding it (just like with Unix find).

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

If you have copied & Pasted files from an old backup folder to new then its simple. Just copy the old ibdata1 into your new one. You can find it from \xampp\mysql\data

Maximum length of HTTP GET request

You are asking two separate questions here:

What's the maximum length of an HTTP GET request?

As already mentioned, HTTP itself doesn't impose any hard-coded limit on request length; but browsers have limits ranging on the 2 KB - 8 KB (255 bytes if we count very old browsers).

Is there a response error defined that the server can/should return if it receives a GET request exceeds this length?

That's the one nobody has answered.

HTTP 1.1 defines status code 414 Request-URI Too Long for the cases where a server-defined limit is reached. You can see further details on RFC 2616.

For the case of client-defined limits, there isn't any sense on the server returning something, because the server won't receive the request at all.

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

In the case of a non blocking socket that has no data available, recv will throw the socket.error exception and the value of the exception will have the errno of either EAGAIN or EWOULDBLOCK. Example:

import sys
import socket
import fcntl, os
import errno
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

while True:
    try:
        msg = s.recv(4096)
    except socket.error, e:
        err = e.args[0]
        if err == errno.EAGAIN or err == errno.EWOULDBLOCK:
            sleep(1)
            print 'No data available'
            continue
        else:
            # a "real" error occurred
            print e
            sys.exit(1)
    else:
        # got a message, do something :)

The situation is a little different in the case where you've enabled non-blocking behavior via a time out with socket.settimeout(n) or socket.setblocking(False). In this case a socket.error is stil raised, but in the case of a time out, the accompanying value of the exception is always a string set to 'timed out'. So, to handle this case you can do:

import sys
import socket
from time import sleep

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',9999))
s.settimeout(2)

while True:
    try:
        msg = s.recv(4096)
    except socket.timeout, e:
        err = e.args[0]
        # this next if/else is a bit redundant, but illustrates how the
        # timeout exception is setup
        if err == 'timed out':
            sleep(1)
            print 'recv timed out, retry later'
            continue
        else:
            print e
            sys.exit(1)
    except socket.error, e:
        # Something else happened, handle error, exit, etc.
        print e
        sys.exit(1)
    else:
        if len(msg) == 0:
            print 'orderly shutdown on server end'
            sys.exit(0)
        else:
            # got a message do something :)

As indicated in the comments, this is also a more portable solution since it doesn't depend on OS specific functionality to put the socket into non-blockng mode.

See recv(2) and python socket for more details.

How to share data between different threads In C# using AOP?

You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.

Read up on the lock statement.

lock

EDIT

Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.

public class Queue<T>
{
    /// <summary>Used as a lock target to ensure thread safety.</summary>
    private readonly Locker _Locker = new Locker();

    private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();

    /// <summary></summary>
    public void Enqueue(T item)
    {
        lock (_Locker)
        {
            _Queue.Enqueue(item);
        }
    }

    /// <summary>Enqueues a collection of items into this queue.</summary>
    public virtual void EnqueueRange(IEnumerable<T> items)
    {
        lock (_Locker)
        {
            if (items == null)
            {
                return;
            }

            foreach (T item in items)
            {
                _Queue.Enqueue(item);
            }
        }
    }

    /// <summary></summary>
    public T Dequeue()
    {
        lock (_Locker)
        {
            return _Queue.Dequeue();
        }
    }

    /// <summary></summary>
    public void Clear()
    {
        lock (_Locker)
        {
            _Queue.Clear();
        }
    }

    /// <summary></summary>
    public Int32 Count
    {
        get
        {
            lock (_Locker)
            {
                return _Queue.Count;
            }
        }
    }

    /// <summary></summary>
    public Boolean TryDequeue(out T item)
    {
        lock (_Locker)
        {
            if (_Queue.Count > 0)
            {
                item = _Queue.Dequeue();
                return true;
            }
            else
            {
                item = default(T);
                return false;
            }
        }
    }
}

EDIT 2

I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.

public class WorkState
{
    private readonly Object _Lock = new Object();
    private Int32 _State;

    public Int32 GetState()
    {
        lock (_Lock)
        {
            return _State;
        }
    }

    public void UpdateState()
    {
        lock (_Lock)
        {
            _State++;   
        }   
    }
}

public class Worker
{
    private readonly WorkState _State;
    private readonly Thread _Thread;
    private volatile Boolean _KeepWorking;

    public Worker(WorkState state)
    {
        _State = state;
        _Thread = new Thread(DoWork);
        _KeepWorking = true;                
    }

    public void DoWork()
    {
        while (_KeepWorking)
        {
            _State.UpdateState();                   
        }
    }

    public void StartWorking()
    {
        _Thread.Start();
    }

    public void StopWorking()
    {
        _KeepWorking = false;
    }
}



private void Execute()
{
    WorkState state = new WorkState();
    Worker worker = new Worker(state);

    worker.StartWorking();

    while (true)
    {
        if (state.GetState() > 100)
        {
            worker.StopWorking();
            break;
        }
    }                   
}

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
    param(
        [Parameter(Mandatory=$true)][string]$computername,
        [Parameter(Mandatory=$false)][string]$arg2,
        [Parameter(Mandatory=$false)][string]$domain
    )
    if(!($domain)){
        $domain = 'domain1'
    }
    write-host $domain
    if($arg2){
        write-host "arg2 present... executing script block"
    }
    else{
        write-host "arg2 missing... exiting or whatever"
    }
}

How to compare files from two different branches?

git diff can show you the difference between two commits:

git diff mybranch master -- myfile.cs

Or, equivalently:

git diff mybranch..master -- myfile.cs

Note you must specify the relative path to the file. So if the file were in the src directory, you'd say src/myfile.cs instead of myfile.cs.

Using the latter syntax, if either side is HEAD it may be omitted (e.g. master.. compares master to HEAD).

You may also be interested in mybranch...master (from git diff docs):

This form is to view the changes on the branch containing and up to the second <commit>, starting at a common ancestor of both <commit>. git diff A...B is equivalent to git diff $(git-merge-base A B) B.

In other words, this will give a diff of changes in master since it diverged from mybranch (but without new changes since then in mybranch).


In all cases, the -- separator before the file name indicates the end of command line flags. This is optional unless Git will get confused if the argument refers to a commit or a file, but including it is not a bad habit to get into. See https://stackoverflow.com/a/13321491/54249 for a few examples.


The same arguments can be passed to git difftool if you have one configured.

Is there a Google Keep API?

I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.

Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.

https://developers.google.com/google-apps/tasks/

Ant error when trying to build file, can't find tools.jar?

Using suggestions from answers on this page and this other one (ANT_HOME is set incorrectly or ant could not be located), the ultimate fix was the following:

  1. Adding a ANT_HOME environment variable that points to the ROOT directory of your Apache ant directory location. (Not the bin sub-dir!)

  2. Adding a JAVA_HOME environment variable that points to the ROOT directory of your Java JDK (or SDK) directory location. (NOT your JRE and not the bin sub-dir!)

  3. Appended %ANT_HOME%\bin;%JAVA_HOME%\bin to the PATH environment variable.

  4. Make sure you close any command window(s) that were open prior to the changes above. Only command windows opened after the changes will have the updated environment variables.

How do I POST a x-www-form-urlencoded request using Fetch?

You can use react-native-easy-app that is easier to send http request and formulate interception request.

import { XHttp } from 'react-native-easy-app';

* Synchronous request
const params = {name:'rufeng',age:20}
const response = await XHttp().url(url).param(params).formEncoded().execute('GET');
const {success, json, message, status} = response;


* Asynchronous requests
XHttp().url(url).param(params).formEncoded().get((success, json, message, status)=>{
    if (success){
       this.setState({content: JSON.stringify(json)});
    } else {
       showToast(msg);
    }
});

Checking whether a variable is an integer or not

The simplest way is:

if n==int(n):
    --do something--    

Where n is the variable

Is it possible to style a mouseover on an image map using CSS?

CSS Only:

Thinking about it on my way to the supermarket, you could of course also skip the entire image map idea, and make use of :hover on the elements on top of the image (changed the divs to a-blocks). Which makes things hell of a lot simpler, no jQuery needed...

Short explanation:

  • Image is in the bottom
  • 2 x a with display:block and absolute positioning + opacity:0
  • Set opacity to 0.2 on hover

Example:

_x000D_
_x000D_
.area {_x000D_
    background:#fff;_x000D_
    display:block;_x000D_
    height:475px;_x000D_
    opacity:0;_x000D_
    position:absolute;_x000D_
    width:320px;_x000D_
}_x000D_
#area2 {_x000D_
    left:320px;_x000D_
}_x000D_
#area1:hover, #area2:hover {_x000D_
    opacity:0.2;_x000D_
}
_x000D_
<a id="area1" class="area" href="#"></a>_x000D_
<a id="area2" class="area" href="#"></a>_x000D_
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Saimiri_sciureus-1_Luc_Viatour.jpg/640px-Saimiri_sciureus-1_Luc_Viatour.jpg" width="640" height="475" />
_x000D_
_x000D_
_x000D_

Original Answer using jQuery

I just created something similar with jQuery, I don't think it can be done with CSS only.

Short explanation:

  • Image is in the bottom
  • Divs with rollover (image or color) with absolute positioning + display:none
  • Transparent gif with the actual #map is on top (absolute position) (to prevent call to mouseout when the rollovers appear)
  • jQuery is used to show/hide the divs

_x000D_
_x000D_
    $(document).ready(function() {_x000D_
        if($('#location-map')) {_x000D_
            $('#location-map area').each(function() {_x000D_
                var id = $(this).attr('id');_x000D_
                $(this).mouseover(function() {_x000D_
                    $('#overlay'+id).show();_x000D_
                    _x000D_
                });_x000D_
                _x000D_
                $(this).mouseout(function() {_x000D_
                    var id = $(this).attr('id');_x000D_
                    $('#overlay'+id).hide();_x000D_
                });_x000D_
            _x000D_
            });_x000D_
        }_x000D_
    });
_x000D_
body,html {_x000D_
    margin:0;_x000D_
}_x000D_
#emptygif {_x000D_
    position:absolute;_x000D_
    z-index:200;_x000D_
}_x000D_
#overlayr1 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}_x000D_
#overlayr2 {_x000D_
    position:absolute;_x000D_
    background:#fff;_x000D_
    opacity:0.2;_x000D_
    width:300px;_x000D_
    height:160px;_x000D_
    top:160px;_x000D_
    z-index:100;_x000D_
    display:none;_x000D_
}
_x000D_
<img src="http://www.tfo.be/jobs/axa/premiumplus/img/empty.gif" width="300" height="350" border="0" usemap="#location-map" id="emptygif" />_x000D_
<div id="overlayr1">&nbsp;</div>_x000D_
<div id="overlayr2">&nbsp;</div>_x000D_
<img src="http://2.bp.blogspot.com/_nP6ESfPiKIw/SlOGugKqaoI/AAAAAAAAACs/6jnPl85TYDg/s1600-R/monkey300.jpg" width="300" height="350" border="0" />_x000D_
<map name="location-map" id="location-map">_x000D_
  <area shape="rect" coords="0,0,300,160" href="#" id="r1" />_x000D_
  <area shape="rect" coords="0,161,300,350" href="#" id="r2"/>_x000D_
</map>
_x000D_
_x000D_
_x000D_

Hope it helps..

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

Find location of a removable SD card

Environment.getExternalStorageState() returns path to internal SD mount point like "/mnt/sdcard"

No, Environment.getExternalStorageDirectory() refers to whatever the device manufacturer considered to be "external storage". On some devices, this is removable media, like an SD card. On some devices, this is a portion of on-device flash. Here, "external storage" means "the stuff accessible via USB Mass Storage mode when mounted on a host machine", at least for Android 1.x and 2.x.

But the question is about external SD. How to get a path like "/mnt/sdcard/external_sd" (it may differ from device to device)?

Android has no concept of "external SD", aside from external storage, as described above.

If a device manufacturer has elected to have external storage be on-board flash and also has an SD card, you will need to contact that manufacturer to determine whether or not you can use the SD card (not guaranteed) and what the rules are for using it, such as what path to use for it.


UPDATE

Two recent things of note:

First, on Android 4.4+, you do not have write access to removable media (e.g., "external SD"), except for any locations on that media that might be returned by getExternalFilesDirs() and getExternalCacheDirs(). See Dave Smith's excellent analysis of this, particularly if you want the low-level details.

Second, lest anyone quibble on whether or not removable media access is otherwise part of the Android SDK, here is Dianne Hackborn's assessment:

...keep in mind: until Android 4.4, the official Android platform has not supported SD cards at all except for two special cases: the old school storage layout where external storage is an SD card (which is still supported by the platform today), and a small feature added to Android 3.0 where it would scan additional SD cards and add them to the media provider and give apps read-only access to their files (which is also still supported in the platform today).

Android 4.4 is the first release of the platform that has actually allowed applications to use SD cards for storage. Any access to them prior to that was through private, unsupported APIs. We now have a quite rich API in the platform that allows applications to make use of SD cards in a supported way, in better ways than they have been able to before: they can make free use of their app-specific storage area without requiring any permissions in the app, and can access any other files on the SD card as long as they go through the file picker, again without needing any special permissions.

In C++ check if std::vector<string> contains a certain value

You can use std::find as follows:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

To be able to use std::find: include <algorithm>.

psql - save results of command to a file

I assume that there exist some internal psql command for this, but you could also run the script command from util-linux-ng package:

DESCRIPTION Script makes a typescript of everything printed on your terminal.

How to update Xcode from command line

I was facing the same problem, resolved it by using the following command.

sudo xcode-select -s /Library/Developer/CommandLineTools

After running the above command then xcode-select -p command showed the following.

/Library/Developer/CommandLineTools

Checkout Jenkins Pipeline Git SCM with credentials?

You can use the following in a pipeline:

git branch: 'master',
    credentialsId: '12345-1234-4696-af25-123455',
    url: 'ssh://[email protected]:company/repo.git'

If you're using the ssh url then your credentials must be username + private key. If you're using the https clone url instead of the ssh one, then your credentials should be username + password.

How to pass arguments to a Button command in Tkinter?

The reason it invokes the method immediately and pressing the button does nothing is that action(somenumber) is evaluated and its return value is attributed as the command for the button. So if action prints something to tell you it has run and returns None, you just run action to evaluate its return value and given None as the command for the button.

To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:

import Tkinter as Tk

frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
frame.grid(row=2,column=2)
frame.pack(fill=Tk.X, padx=5, pady=5)
def action():
    global output
    global variable
    output.insert(Tk.END,variable.get())
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
variable = Tk.Entry(master=frame)
variable.pack()
output = Tk.Text(master=frame)
output.pack()

if __name__ == '__main__':
    Tk.mainloop()

What I would do is make a class whose objects would contain every variable required and methods to change those as needed:

import Tkinter as Tk
class Window:
    def __init__(self):
        self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
        self.frame.grid(row=2,column=2)
        self.frame.pack(fill=Tk.X, padx=5, pady=5)

        self.button = Tk.Button(master=self.frame, text='press', command=self.action)
        self.button.pack()

        self.variable = Tk.Entry(master=self.frame)
        self.variable.pack()

        self.output = Tk.Text(master=self.frame)
        self.output.pack()

    def action(self):
        self.output.insert(Tk.END,self.variable.get())

if __name__ == '__main__':
    window = Window()
    Tk.mainloop()

Google Play Services Missing in Emulator (Android 4.4.2)

You will not able to test the app using the Google-Play-Service library in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.

https://stackoverflow.com/a/11213598/1405008

Refer the above answer to install Google play service on your emulator.

XPath to get all child nodes (elements, comments, and text) without parent

Use this XPath expression:

/*/*/X/node()

This selects any node (element, text node, comment or processing instruction) that is a child of any X element that is a grand-child of the top element of the XML document.

To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes"/>
 <xsl:template match="/">
  <xsl:copy-of select="/*/*/X/node()"/>
 </xsl:template>
</xsl:stylesheet>

and it produces exactly the wanted, correct result:

   First Text Node #1            
    <y> Y can Have Child Nodes #                
        <child> deep to it </child>
    </y>            Second Text Node #2 
    <z />

Explanation:

  1. As defined in the W3 XPath 1.0 Spec, "child::node() selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.

  2. node() is an abbreviation of child::node() (because child:: is the primary axis and is used when no axis is explicitly specified).

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

Try to use:

pattern="(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/\d{4}"

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

How to pass parameters using ui-sref in ui-router to controller

I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would be the controller:

.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    //..
    var foo = $stateParams.foo; //getting fooVal
    var bar = $stateParams.bar; //getting barVal
    //..
    $scope.state = $state.current
    $scope.params = $stateParams; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These two links will correctly pass arguments into the controller:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">

Also, the controller does consume $stateParams instead of $stateParam.

Link to doc:

You can check it here

params : {}

There is also new, more granular setting params : {}. As we've already seen, we can declare parameters as part of url. But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url:

.state('other', {
    url: '/other/:foo?bar',
    params: { 
        // here we define default value for foo
        // we also set squash to false, to force injecting
        // even the default value into url
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        // this parameter is now array
        // we can pass more items, and expect them as []
        bar : { 
          array : true,
        },
        // this param is not part of url
        // it could be passed with $state.go or ui-sref 
        hiddenParam: 'YES',
      },
    ...

Settings available for params are described in the documentation of the $stateProvider

Below is just an extract

  • value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
  • array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
  • squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.

We can call these params this way:

// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here

phonegap open link in browser

There are 2 different ways to open URL in android and iphone.

FOR IOS use following code.

window.open("http://google.com", '_system');

and for android OS use following code.

navigator.app.loadUrl("http://google.com", {openExternal : true});

What is the difference between float and double?

Floats have less precision than doubles. Although you already know, read What WE Should Know About Floating-Point Arithmetic for better understanding.

Web scraping with Java

Look at an HTML parser such as TagSoup, HTMLCleaner or NekoHTML.

"Could not find a version that satisfies the requirement opencv-python"

Install it by using this command:

pip install opencv-contrib-python

how to call an ASP.NET c# method using javascript

The Jayrock RPC library is a great tool for doing this in a nice familliar way for C# developers. It allows you to create a .NET class with the methods you require, and add this class as a script (in a roundabout way) to your page. You can then create a js object of your type and call methods as you would any other object.

It essentially hides away ajax implementation and presents RPC in a familliar format. Mind you the best option really is to use ASP.NET MVC and use jQuery ajax calls to action methods - much more concise and less messing about!

Checking for empty result (php, pdo, mysql)

One more approach to consider:

When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.

$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
    // non-repetitive markup code here
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

How can I get the number of records affected by a stored procedure?

WARNING: @@ROWCOUNT may return bogus data if the table being altered has triggers attached to it!

The @@ROWCOUNT will return the number of records affected by the TRIGGER, not the actual statement!

Deciding between HttpClient and WebClient

I have benchmark between HttpClient, WebClient, HttpWebResponse then call Rest Web Api

and result Call Rest Web Api Benchmark

---------------------Stage 1  ---- 10 Request

{00:00:17.2232544} ====>HttpClinet
{00:00:04.3108986} ====>WebRequest
{00:00:04.5436889} ====>WebClient

---------------------Stage 1  ---- 10 Request--Small Size
{00:00:17.2232544}====>HttpClinet
{00:00:04.3108986}====>WebRequest
{00:00:04.5436889}====>WebClient

---------------------Stage 3  ---- 10 sync Request--Small Size
{00:00:15.3047502}====>HttpClinet
{00:00:03.5505249}====>WebRequest
{00:00:04.0761359}====>WebClient

---------------------Stage 4  ---- 100 sync Request--Small Size
{00:03:23.6268086}====>HttpClinet
{00:00:47.1406632}====>WebRequest
{00:01:01.2319499}====>WebClient

---------------------Stage 5  ---- 10 sync Request--Max Size

{00:00:58.1804677}====>HttpClinet    
{00:00:58.0710444}====>WebRequest    
{00:00:38.4170938}====>WebClient
    
---------------------Stage 6  ---- 10 sync Request--Max Size

{00:01:04.9964278}====>HttpClinet    
{00:00:59.1429764}====>WebRequest    
{00:00:32.0584836}====>WebClient

_____ WebClient Is faster ()

var stopWatch = new Stopwatch();
        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {
            CallGetHttpClient();
            CallPostHttpClient();
        }

        stopWatch.Stop();

        var httpClientValue = stopWatch.Elapsed;

        stopWatch = new Stopwatch();

        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {
            CallGetWebRequest();
            CallPostWebRequest();
        }

        stopWatch.Stop();

        var webRequesttValue = stopWatch.Elapsed;


        stopWatch = new Stopwatch();

        stopWatch.Start();
        for (var i = 0; i < 10; ++i)
        {

            CallGetWebClient();
            CallPostWebClient();

        }

        stopWatch.Stop();

        var webClientValue = stopWatch.Elapsed;

//-------------------------Functions

private void CallPostHttpClient()
    {
        var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
        var responseTask = httpClient.PostAsync("PostJson", null);
        responseTask.Wait();

        var result = responseTask.Result;
        var readTask = result.Content.ReadAsStringAsync().Result;

    }
    private void CallGetHttpClient()
    {
        var httpClient = new HttpClient();
        httpClient.BaseAddress = new Uri("https://localhost:44354/api/test/");
        var responseTask = httpClient.GetAsync("getjson");
        responseTask.Wait();

        var result = responseTask.Result;
        var readTask = result.Content.ReadAsStringAsync().Result;

    }
    private string CallGetWebRequest()
    {
        var request = (HttpWebRequest)WebRequest.Create("https://localhost:44354/api/test/getjson");

        request.Method = "GET";
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

        var content = string.Empty;

        using (var response = (HttpWebResponse)request.GetResponse())
        {
            using (var stream = response.GetResponseStream())
            {
                using (var sr = new StreamReader(stream))
                {
                    content = sr.ReadToEnd();
                }
            }
        }

        return content;
    }
    private string CallPostWebRequest()
    {

        var apiUrl = "https://localhost:44354/api/test/PostJson";


        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(apiUrl));
        httpRequest.ContentType = "application/json";
        httpRequest.Method = "POST";
        httpRequest.ContentLength = 0;

        using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            using (Stream stream = httpResponse.GetResponseStream())
            {
                var json = new StreamReader(stream).ReadToEnd();
                return json;
            }
        }

        return "";
    }

    private string CallGetWebClient()
    {
        string apiUrl = "https://localhost:44354/api/test/getjson";


        var client = new WebClient();

        client.Headers["Content-type"] = "application/json";

        client.Encoding = Encoding.UTF8;

        var json = client.DownloadString(apiUrl);


        return json;
    }

    private string CallPostWebClient()
    {
        string apiUrl = "https://localhost:44354/api/test/PostJson";


        var client = new WebClient();

        client.Headers["Content-type"] = "application/json";

        client.Encoding = Encoding.UTF8;

        var json = client.UploadString(apiUrl, "");


        return json;
    }

REST HTTP status codes for failed validation or invalid duplicate

I recommend status code 422, "Unprocessable Entity".

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

How do you use variables in a simple PostgreSQL script?

Complete answer is located in the official PostgreSQL documentation.

You can use new PG9.0 anonymous code block feature (http://www.postgresql.org/docs/9.1/static/sql-do.html )

DO $$
DECLARE v_List TEXT;
BEGIN
  v_List := 'foobar' ;
  SELECT *
  FROM   dbo.PubLists
  WHERE  Name = v_List;
  -- ...
END $$;

Also you can get the last insert id:

DO $$
DECLARE lastid bigint;
BEGIN
  INSERT INTO test (name) VALUES ('Test Name') 
  RETURNING id INTO lastid;

  SELECT * FROM test WHERE id = lastid;
END $$;

Why doesn't importing java.util.* include Arrays and Lists?

The difference between

import java.util.*;

and

import java.util.*;
import java.util.List;
import java.util.Arrays;

becomes apparent when the code refers to some other List or Arrays (for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays will be used.

Insert PHP code In WordPress Page and Post

When I was trying to accomplish something very similar, I ended up doing something along these lines:

wp-content/themes/resources/functions.php

add_action('init', 'my_php_function');
function my_php_function() {
    if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
        // add desired php code here
    }
}

Java get last element of a collection

Well one solution could be:

list.get(list.size()-1)

Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

The URI depends on the version of JSTL you are using. For Version 1.0 use:

http://java.sun.com/jstl/core

and for 1.1 (and later), you need to use:

http://java.sun.com/jsp/jstl/core

How to create a HTTP server in Android?

You can try Restlet edition for android:

The source can be downloaded from Restlet website:

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

Apple Link

Below is the information about screen sizes. These details are taken from the apple website

Below is the information

Commit empty folder structure (with git)

This is easy.

tell .gitignore to ignore everything except .gitignore and the folders you want to keep. Put .gitignore into folders that you want to keep in the repo.

Contents of the top-most .gitignore:

# ignore everything except .gitignore and folders that I care about:
*
!images*
!.gitignore

In the nested images folder this is your .gitignore:

# ignore everything except .gitignore
*
!.gitignore

Note, you must spell out in the .gitignore the names of the folders you don't want to be ignored in the folder where that .gitignore is located. Otherwise they are, obviously, ignored.

Your folders in the repo will, obviously, NOT be empty, as each one will have .gitignore in it, but that part can be ignored, right. :)

How to do this in Laravel, subquery where in

Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres

Here's an example of what you're trying to achieve:

DB::table('users')
    ->whereIn('id', function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id = users.id
)

List<Object> and List<?>

To answer your second question, yes, you can cast the List<?> as a List<Object> or a List<T> of any type, since the ? (Wildcard) parameter indicates that the list contains a homogenous collection of an any Object. However, there's no way to know at compile what the type is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>.

Here's how you would make the cast:

List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;

In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object. Let's pretend that we're trying to cast this as a List<Integer> when it actually contains a collection of Strings.

// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;

// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);

Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass() on it to determine its type.

Class objectClass = wildcardList.get(0).getClass();

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

None of these worked for me. I did find the solution in another stackoverflow question. I'll add it here for easy reference:

You need to make a reference, so it will be copied in den application path. Because later it will be referenced in runtime. So you don't need to copy any files.

private volatile Type _dependency;

public MyClass()
{
    _dependency = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
}

How do I tidy up an HTML file's indentation in VI?

None of the answers worked for me because all my HTML was in a single line.

Basically you need first to break each line with the following command that substitutes >< with the same characters but with a line break in the middle.

:%s/></>\r</g

Then the command

gg=G

will indent the file.

How do I check if file exists in Makefile so I can delete it?

One line solution:

   [ -f ./myfile ] && echo exists

One line solution with error action:

   [ -f ./myfile ] && echo exists || echo not exists

Example used in my make clean directives:

clean:
    @[ -f ./myfile ] && rm myfile || true

And make clean works without error messages!

Sending multipart/formdata with jQuery.ajax

If your form is defined in your HTML, it is easier to pass the form into the constructor than it is to iterate and add images.

$('#my-form').submit( function(e) {
    e.preventDefault();

    var data = new FormData(this); // <-- 'this' is your form element

    $.ajax({
            url: '/my_URL/',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',     
            success: function(data){
            ...

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

How to use XPath preceding-sibling correctly

I also like to build locators from up to bottom like:

//div[contains(@class,'btn-group')][./button[contains(.,'Arcade Reader')]]/button[@name='settings']

It's pretty simple, as we just search btn-group with button[contains(.,'Arcade Reader')] and get it's button[@name='settings']

That's just another option to build xPath locators

What is the profit of searching wrapper element: you can return it by method (example in java) and just build selenium constructions like:

getGroupByName("Arcade Reader").find("button[name='settings']");
getGroupByName("Arcade Reader").find("button[name='delete']");

or even simplify more

getGroupButton("Arcade Reader", "delete").click();

Create a .csv file with values from a Python list

For another approach, you can use DataFrame in pandas: And it can easily dump the data to csv just like the code below:

import pandas
df = pandas.DataFrame(data={"col1": list_1, "col2": list_2})
df.to_csv("./file.csv", sep=',',index=False)

START_STICKY and START_NOT_STICKY

Both codes are only relevant when the phone runs out of memory and kills the service before it finishes executing. START_STICKY tells the OS to recreate the service after it has enough memory and call onStartCommand() again with a null intent. START_NOT_STICKY tells the OS to not bother recreating the service again. There is also a third code START_REDELIVER_INTENT that tells the OS to recreate the service and redeliver the same intent to onStartCommand().

This article by Dianne Hackborn explained the background of this a lot better than the official documentation.

Source: http://android-developers.blogspot.com.au/2010/02/service-api-changes-starting-with.html

The key part here is a new result code returned by the function, telling the system what it should do with the service if its process is killed while it is running:

START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.

START_NOT_STICKY says that, after returning from onStartCreated(), if the process is killed with no remaining start commands to deliver, then the service will be stopped instead of restarted. This makes a lot more sense for services that are intended to only run while executing commands sent to them. For example, a service may be started every 15 minutes from an alarm to poll some network state. If it gets killed while doing that work, it would be best to just let it be stopped and get started the next time the alarm fires.

START_REDELIVER_INTENT is like START_NOT_STICKY, except if the service's process is killed before it calls stopSelf() for a given intent, that intent will be re-delivered to it until it completes (unless after some number of more tries it still can't complete, at which point the system gives up). This is useful for services that are receiving commands of work to do, and want to make sure they do eventually complete the work for each command sent.

What does 'corrupted double-linked list' mean

This might be caused due to different reasons, some user have mentioned other possibilities and I add my case:

I got this error when using multi-threading (both std::pthread and std::thread) and the error occurred because I forgot to lock a variable which multi threads may change at the same time. this error comes randomly in some runs but not all because ... you know accident between to threads is random.

That variable in my case was a global std::vector which I tried to push_back() something into it in a function called by threads.. and then I used a std::mutex and never got this error again.

may help some

Arguments to main in C

Siamore, I keep seeing everyone using the command line to compile programs. I use x11 terminal from ide via code::blocks, a gnu gcc compiler on my linux box. I have never compiled a program from command line. So Siamore, if I want the programs name to be cp, do I initialize argv[0]="cp"; Cp being a string literal. And anything going to stdout goes on the command line??? The example you gave me Siamore I understood! Even though the string you entered was a few words long, it was still only one arg. Because it was encased in double quotations. So arg[0], the prog name, is actually your string literal with a new line character?? So I understand why you use if(argc!=3) print error. Because the prog name = argv[0] and there are 2 more args after that, and anymore an error has occured. What other reason would I use that? I really think that my lack of understanding about how to compile from the command line or terminal is my reason for lack understanding in this area!! Siamore, you have helped me understand cla's much better! Still don't fully understand but I am not oblivious to the concept. I'm gonna learn to compile from the terminal then re-read what you wrote. I bet, then I will fully understand! With a little more help from you lol

<> Code that I have not written myself, but from my book.

#include <stdio.h>

int main(int argc, char *argv[])
{
    int i;

    printf("The following arguments were passed to main(): ");
    for(i=1; i<argc; i++) printf("%s ", argv[i]);
    printf("\n");

    return 0;
} 

This is the output:

anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hey man
The follow arguments were passed to main(): hey man
anthony@anthony:~\Documents/C_Programming/CLA$ ./CLA hi how are you doing?
The follow arguments were passed to main(): hi how are you doing?

So argv is a table of string literals, and argc is the number of them. Now argv[0] is the name of the program. So if I type ./CLA to run the program ./CLA is argv[0]. The above program sets the command line to take an infinite amount of arguments. I can set them to only take 3 or 4 if I wanted. Like one or your examples showed, Siamore... if(argc!=3) printf("Some error goes here"); Thank you Siamore, couldn't have done it without you! thanks to the rest of the post for their time and effort also!

PS in case there is a problem like this in the future...you never know lol the problem was because I was using the IDE AKA Code::Blocks. If I were to run that program above it would print the path/directory of the program. Example: ~/Documents/C/CLA.c it has to be ran from the terminal and compiled using the command line. gcc -o CLA main.c and you must be in the directory of the file.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

I just ran into a similar issue when I tried to commit to a newly created repo with a "." in it's name. I've seen several others have different issues with putting a "." in the repo name.

I just re-created the repo and

replaced "." with "-"

There may be other ways to resolve this, but this was a quick fix for me since it was a new repo.

How can I give an imageview click effect like a button on Android?

Here is my code. The idea is that ImageView gets color filter when user touches it, and color filter is removed when user stops touching it.

Martin Booka Weser, András, Ah Lam, altosh, solution doesn't work when ImageView has also onClickEvent. worawee.s and kcoppock (with ImageButton) solution requires background, which has no sense when ImageView is not transparent.

This one is extension of AZ_ idea about color filter.

class PressedEffectStateListDrawable extends StateListDrawable {

    private int selectionColor;

    public PressedEffectStateListDrawable(Drawable drawable, int selectionColor) {
        super();
        this.selectionColor = selectionColor;
        addState(new int[] { android.R.attr.state_pressed }, drawable);
        addState(new int[] {}, drawable);
    }

    @Override
    protected boolean onStateChange(int[] states) {
        boolean isStatePressedInArray = false;
        for (int state : states) {
            if (state == android.R.attr.state_pressed) {
                isStatePressedInArray = true;
            }
        }
        if (isStatePressedInArray) {
            super.setColorFilter(selectionColor, PorterDuff.Mode.MULTIPLY);
        } else {
            super.clearColorFilter();
        }
        return super.onStateChange(states);
    }

    @Override
    public boolean isStateful() {
        return true;
    }
}

usage:

Drawable drawable = new FastBitmapDrawable(bm);
imageView.setImageDrawable(new PressedEffectStateListDrawable(drawable, 0xFF33b5e5));

How to check a channel is closed or not without reading it?

Well, you can use default branch to detect it, for a closed channel will be selected, for example: the following code will select default, channel, channel, the first select is not blocked.

func main() {
    ch := make(chan int)

    go func() {
        select {
        case <-ch:
            log.Printf("1.channel")
        default:
            log.Printf("1.default")
        }
        select {
        case <-ch:
            log.Printf("2.channel")
        }
        close(ch)
        select {
        case <-ch:
            log.Printf("3.channel")
        default:
            log.Printf("3.default")
        }
    }()
    time.Sleep(time.Second)
    ch <- 1
    time.Sleep(time.Second)
}

Prints

2018/05/24 08:00:00 1.default
2018/05/24 08:00:01 2.channel
2018/05/24 08:00:01 3.channel

Paritition array into N chunks with Numpy

I believe that you're looking for numpy.split or possibly numpy.array_split if the number of sections doesn't need to divide the size of the array properly.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

How to delete Project from Google Developers Console

  1. Click "Utilities and more" near the upper right corner of the screen after choosing your project three-dotted icon
  2. Choose "Project settings" from the drop down of the "Utilities and more" icon.

Now you may see trash icon and DELETE PROJECT button.

HTML5 Pre-resize images before uploading

You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.

It has builtin resize functions, but you can provide your own if you want.

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

What is the difference between & and && in Java?

all answers are great, and it seems that no more answer is needed but I just wonted to point out something about && operator called dependent condition

In expressions using operator &&, a condition—we’ll call this the dependent condition—may require another condition to be true for the evaluation of the dependent condition to be meaningful.

In this case, the dependent condition should be placed after the && operator to prevent errors.

Consider the expression (i != 0) && (10 / i == 2). The dependent condition (10 / i == 2) must appear after the && operator to prevent the possibility of division by zero.

another example (myObject != null) && (myObject.getValue() == somevaluse)

and another thing: && and || are called short-circuit evaluation because the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression

References: Java™ How To Program (Early Objects), Tenth Edition

How to make unicode string with python3

What's new in Python 3.0 says:

All text is Unicode; however encoded Unicode is represented as binary data

If you want to ensure you are outputting utf-8, here's an example from this page on unicode in 3.0:

b'\x80abc'.decode("utf-8", "strict")

Update MySQL using HTML Form and PHP

Your sql is incorrect.

$sql = mysql_query("UPDATE anstalld....

only

$sql = "UPDATE anstalld...

PHP write file from input to txt

A possible solution:

<?php
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

You were closing the script before close de file.

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

How to change the remote a branch is tracking?

I've found @critikaster's post helpful, except that I had to perform these commands with GIT 2.21:

$ git remote set-url origin https://some_url/some_repo
$ git push --set-upstream origin master

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

Format number to always show 2 decimal places

parseInt(number * 100) / 100; worked for me.

How can I increase a scrollbar's width using CSS?

This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:

::-webkit-scrollbar {
    width: 2em;
    height: 2em
}
::-webkit-scrollbar-button {
    background: #ccc
}
::-webkit-scrollbar-track-piece {
    background: #888
}
::-webkit-scrollbar-thumb {
    background: #eee
}?

JSFiddle Demo


References:

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

I just ran into this issue when diffing my branch with master. Git returned one 'mode' error when I expected my branch to be identical to master. I fixed by deleting the file and then merging master in again.

First I ran the diff:

git checkout my-branch
git diff master

This returned:

diff --git a/bin/script.sh b/bin/script.sh
old mode 100755
new mode 100644

I then ran the following to fix:

rm bin/script.sh
git merge -X theirs master

After this, git diff returned no differences between my-branch and master.

MySQL SELECT LIKE or REGEXP to match multiple words in one record

You can just replace each space with %

SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%2100%'

Excel 2007 - Compare 2 columns, find matching values

You could fill the C Column with variations on the following formula:

=IF(ISERROR(MATCH(A1,$B:$B,0)),"",A1)

Then C would only contain values that were in A and C.

Random number in range [min - max] using PHP

rand(1,20)

Docs for PHP's rand function are here:

http://php.net/manual/en/function.rand.php

Use the srand() function to set the random number generator's seed value.

Why can't I reference my class library?

I faced this problem, and I solved it by closing visual studio, reopening visual studio, cleaning and rebuilding the solution. This worked for me.

How to print to console when using Qt

Go the Project's Properties -> Linker-> System -> SubSystem, then set it to Console(/S).

Sequelize.js delete query?

In new version, you can try something like this

function (req,res) {    
        model.destroy({
            where: {
                id: req.params.id
            }
        })
        .then(function (deletedRecord) {
            if(deletedRecord === 1){
                res.status(200).json({message:"Deleted successfully"});          
            }
            else
            {
                res.status(404).json({message:"record not found"})
            }
        })
        .catch(function (error){
            res.status(500).json(error);
        });

How can I programmatically check whether a keyboard is present in iOS app?

You can iteratively check all textviews, textfields, and labels in the subviews of a parent view to see if any are the first responder with something like this:

-(BOOL)isKeyboardActiveInView:(UIView *)view {
    for (UIView *anyView in [view subviews]) {
        if ([anyView isKindOfClass:[UITextField class]]) {
            if (((UITextField *)anyView).isFirstResponder) {
                return YES;
            }
        } else if ([anyView isKindOfClass:[UILabel class]]) {
            if (((UILabel *)anyView).isFirstResponder) {
                return YES;
            }
        } else if ([anyView isKindOfClass:[UITextView class]]) {
            if (((UITextView *)anyView).isFirstResponder) {
                return YES;
            }
        } else {
            if ([self isKeyboardActiveInView:anyView]) {
                return YES;
            }
        }
    }
    return NO;
}

Android Dialog: Removing title bar

create new style in styles.xml

<style name="myDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

then add this to your manifest:

 <activity android:name=".youractivity" android:theme="@style/myDialog"></activity>

How do I query for all dates greater than a certain date in SQL Server?

select *  
from dbo.March2010 A 
where A.Date >= Convert(datetime, '2010-04-01' )

In your query, 2010-4-01 is treated as a mathematical expression, so in essence it read

select *  
from dbo.March2010 A 
where A.Date >= 2005; 

(2010 minus 4 minus 1 is 2005 Converting it to a proper datetime, and using single quotes will fix this issue.)

Technically, the parser might allow you to get away with

select *  
from dbo.March2010 A 
where A.Date >= '2010-04-01'

it will do the conversion for you, but in my opinion it is less readable than explicitly converting to a DateTime for the maintenance programmer that will come after you.

MySQL SELECT last few days?

SELECT DATEDIFF(NOW(),pickup_date) AS noofday 
FROM cir_order 
WHERE DATEDIFF(NOW(),pickup_date)>2;

or

SELECT * 
FROM cir_order 
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )

Rendering a template variable as HTML

No need to use the filter or tag in template. Just use format_html() to translate variable to html and Django will automatically turn escape off for you variable.

format_html("<h1>Hello</h1>")

Check out here https://docs.djangoproject.com/en/3.0/ref/utils/#django.utils.html.format_html

Read the package name of an Android APK

Based on @hackbod answer ... but related to windows.

aapt command is located on Android\SDK\build-tools\version. If you need more info about what is appt command (Android Asset Packaging Tool) read this https://stackoverflow.com/a/28234956/812915

The dump sub-command of aapt is used to display the values of individual elements or parts of a package:

aapt dump badging <path-to-apk>

If you want see only the line with package: name info, use findstr

aapt dump badging <path-to-apk> | findstr -n "package: name" | findstr "1:"

Hope it help other windows user!

phpinfo() is not working on my CentOS server

Try to create a php.ini file in root and write the following command in and save it.

disable_functions =

Using this code will enable the phpinfo() function for you if it is disabled by the global PHP configuration.

What is the difference between origin and upstream on GitHub?

In a nutshell answer.

  • origin: the fork
  • upstream: the forked

What size should apple-touch-icon.png be for iPad and iPhone?

Yes. If the size does not match, the system will rescale it. But it's better to make 2 versions of the icons.

  • iPad — 72x72.
  • iPhone (=4) — 114x114.
  • iPhone =3GS — 57x57 — If possible.

You could differentiate iPad and iPhone by the user agent on your server. If you don't want to write script on server, you could also change the icon with Javascript by

<link ref="apple-touch-icon" href="iPhone_version.png" />
...

if (... iPad test ...) {
  $('link[rel="apple-touch-icon"]').href = 'iPad_version.png'; // assuming jQuery
}

This works because the icon is queried only when you add the web clip.

(There's no public way to differentiate iPhone =4 from iPhone =3GS in Javascript yet.)

Save current directory in variable using Bash?

Similar to solution of mark with some checking of variables. Also I prefer not to use $variable but rather the same string I saved it under

save your folder/directory using save dir sdir myproject and go back to that folder using goto dir gdir myproject

in addition checkout the workings of native pushd and popd they will save the current folder and this is handy for going back and forth. In this case you can also use popd after gdir myproject and go back again

# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle

function sdir {
    [[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
    [[ ! -z "$1" ]] && cd "${!1}";
}

another handy trick is to combine the two pushd/popd and sdir and gdir wher you replace the cd in the goto dir function in pushd. This enables you to also fly back to your previous folder when making the jump to the saved folder.

# Save the current folder using sdir yourhandle to a variable you can later access the same folder fast using gdir yourhandle

function sdir {
    [[ ! -z "$1" ]] && export __d__$1="`pwd`";
}
function gdir {
    [[ ! -z "$1" ]] && pushd "${!1}";
}

Sending images using Http Post

I'm going to assume that you know the path and filename of the image that you want to upload. Add this string to your NameValuePair using image as the key-name.

Sending images can be done using the HttpComponents libraries. Download the latest HttpClient (currently 4.0.1) binary with dependencies package and copy apache-mime4j-0.6.jar and httpmime-4.0.1.jar to your project and add them to your Java build path.

You will need to add the following imports to your class.

import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

Now you can create a MultipartEntity to attach an image to your POST request. The following code shows an example of how to do this:

public void post(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for(int index=0; index < nameValuePairs.size(); index++) {
            if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
                // If the key equals to "image", we use FileBody to transfer the data
                entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File (nameValuePairs.get(index).getValue())));
            } else {
                // Normal string data
                entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
            }
        }

        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost, localContext);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

I hope this helps you a bit in the right direction.

How to push elements in JSON from javascript array

You can directly access BODY.values:

for (var ln = 0; ln < names.length; ln++) {
  var item1 = {
    "person": {
      "_path": "/people/"+names[ln],
    },
  };

  BODY.values.push(item1);
}

Location of my.cnf file on macOS

For mysql 8.0.19, I finally found the my.cnf here: /usr/local/opt/mysql/.bottle/etc I copied it to /usr/local/opt/mysql/ and modified it. Then I restart the mysql service, it works.

Read text file into string array (and write)

Cannot update first answer.
Anyway, after Go1 release, there are some breaking changes, so I updated as shown below:

package main

import (
    "os"
    "bufio"
    "bytes"
    "io"
    "fmt"
    "strings"
)

// Read a whole file into the memory and store it as array of lines
func readLines(path string) (lines []string, err error) {
    var (
        file *os.File
        part []byte
        prefix bool
    )
    if file, err = os.Open(path); err != nil {
        return
    }
    defer file.Close()

    reader := bufio.NewReader(file)
    buffer := bytes.NewBuffer(make([]byte, 0))
    for {
        if part, prefix, err = reader.ReadLine(); err != nil {
            break
        }
        buffer.Write(part)
        if !prefix {
            lines = append(lines, buffer.String())
            buffer.Reset()
        }
    }
    if err == io.EOF {
        err = nil
    }
    return
}

func writeLines(lines []string, path string) (err error) {
    var (
        file *os.File
    )

    if file, err = os.Create(path); err != nil {
        return
    }
    defer file.Close()

    //writer := bufio.NewWriter(file)
    for _,item := range lines {
        //fmt.Println(item)
        _, err := file.WriteString(strings.TrimSpace(item) + "\n"); 
        //file.Write([]byte(item)); 
        if err != nil {
            //fmt.Println("debug")
            fmt.Println(err)
            break
        }
    }
    /*content := strings.Join(lines, "\n")
    _, err = writer.WriteString(content)*/
    return
}

func main() {
    lines, err := readLines("foo.txt")
    if err != nil {
        fmt.Println("Error: %s\n", err)
        return
    }
    for _, line := range lines {
        fmt.Println(line)
    }
    //array := []string{"7.0", "8.5", "9.1"}
    err = writeLines(lines, "foo2.txt")
    fmt.Println(err)
}

How to delete an app from iTunesConnect / App Store Connect

As per 2018 in App Store Connect. We can delete/remove application with following stats.

enter image description here

App Store Connect details for Remove an app

So, from now onwards we can delete our test applications too from app store connect.

enter image description here

Compiling and Running Java Code in Sublime Text 2

By following the steps below, you will have 2 Build Systems in sublime - "JavaC" and "JavaC_Input".

"JavaC" would let you run code that doesn't require user input and display the results in sublime's terminal simulator, which is convenient and nice-looking. "JavaC_Input" lets you run code that requires user input in a separate terminal window, it's able to accept user input. You can also run non-input-requiring code in this build system, so if you don't mind the pop-up, you can just stick with this build system and don't switch. You switch between build systems from Tools -> Build System. And you compile&run code using ctrl+b.

Here are the steps to achieve this:

(note: Make sure you already have the basic setup of the java system: install JDK and set up correct CLASSPATH and PATH, I won't elaborate on this)

"JavaC" build system setup

1, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec.bat".

@ECHO OFF
cd %~dp1
javac %~nx1
java %~n1

2, Then edit C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\JavaC.sublime-build (if there isn't any, create one), the contents will be

{
   "cmd": ["javacexec.bat", "$file"],
   "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
   "selector": "source.java"
}

"JavaC_Input" build system setup

1, Install Cygwin [http://www.cygwin.com/]

2, Go to C:\Users\your_user_name\AppData\Roaming\Sublime Text 2\Packages\Java\, then create a file called "JavaC_Input.sublime-build" with the following content

{
"cmd": ["javacexec_input.bat", "$file"],
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java"
}

3, Make a bat file with the following code, and save it under C:\Program Files\Java\jdk*\bin\ to keep everything together. Name the file "javacexec_input.bat".

@echo off
javac  -Xlint:unchecked %~n1.java 
start cmd /k java -ea %~n1

Using Service to run background and create notification

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

scp or sftp copy multiple files with single command

In my case, I am restricted to only using the sftp command.
So, I had to use a batchfile with sftp. I created a script such as the following. This assumes you are working in the /tmp directory, and you want to put the files in the destdir_on_remote_system on the remote system. This also only works with a noninteractive login. You need to set up public/private keys so you can login without entering a password. Change as needed.

#!/bin/bash

cd /tmp
# start script with list of files to transfer
ls -1 fileset1* > batchfile1
ls -1 fileset2* >> batchfile1

sed -i -e 's/^/put /' batchfile1
echo "cd destdir_on_remote_system" > batchfile
cat batchfile1 >> batchfile
rm batchfile1

sftp -b batchfile user@host

Testing the type of a DOM element in JavaScript

if (element.nodeName == "A") {
 ...
} else if (element.nodeName == "TD") {
 ...
}

Dynamically load a JavaScript file

Here is some example code I've found... does anyone have a better way?

  function include(url)
  {
    var s = document.createElement("script");
    s.setAttribute("type", "text/javascript");
    s.setAttribute("src", url);
    var nodes = document.getElementsByTagName("*");
    var node = nodes[nodes.length -1].parentNode;
    node.appendChild(s);
  }

How do I iterate through each element in an n-dimensional matrix in MATLAB?

As pointed out in a few other answers, you can iterate over all elements in a matrix A (of any dimension) using a linear index from 1 to numel(A) in a single for loop. There are also a couple of functions you can use: arrayfun and cellfun.

Let's first assume you have a function that you want to apply to each element of A (called my_func). You first create a function handle to this function:

fcn = @my_func;

If A is a matrix (of type double, single, etc.) of arbitrary dimension, you can use arrayfun to apply my_func to each element:

outArgs = arrayfun(fcn, A);

If A is a cell array of arbitrary dimension, you can use cellfun to apply my_func to each cell:

outArgs = cellfun(fcn, A);

The function my_func has to accept A as an input. If there are any outputs from my_func, these are placed in outArgs, which will be the same size/dimension as A.

One caveat on outputs... if my_func returns outputs of different sizes and types when it operates on different elements of A, then outArgs will have to be made into a cell array. This is done by calling either arrayfun or cellfun with an additional parameter/value pair:

outArgs = arrayfun(fcn, A, 'UniformOutput', false);
outArgs = cellfun(fcn, A, 'UniformOutput', false);

How to extract custom header value in Web API message handler?

Try something like this:

IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();

There's also a TryGetValues method on Headers you can use if you're not always guaranteed to have access to the header.

Illegal Escape Character "\"

You can use:

\\

That's ok, for example:

if (invName.substring(j,k).equals("\\")) {
    copyf=invName.substring(0,j);
}

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

Just try this:

Bitmap bitmap = BitmapFactory.decodeFile("/path/images/image.jpg");
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /* Ignored for PNGs */, blob);
byte[] bitmapdata = blob.toByteArray();

If bitmapdata is the byte array then getting Bitmap is done like this:

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

Returns the decoded Bitmap, or null if the image could not be decoded.

Slicing a dictionary

Use a set to intersect on the dict.viewkeys() dictionary view:

l = {1, 5}
{key: d[key] for key in d.viewkeys() & l}

This is Python 2 syntax, in Python 3 use d.keys().

This still uses a loop, but at least the dictionary comprehension is a lot more readable. Using set intersections is very efficient, even if d or l is large.

Demo:

>>> d = {1:2, 3:4, 5:6, 7:8}
>>> l = {1, 5}
>>> {key: d[key] for key in d.viewkeys() & l}
{1: 2, 5: 6}

Detect Route Change with react-router

You can make use of history.listen() function when trying to detect the route change. Considering you are using react-router v4, wrap your component with withRouter HOC to get access to the history prop.

history.listen() returns an unlisten function. You'd use this to unregister from listening.

You can configure your routes like

index.js

ReactDOM.render(
      <BrowserRouter>
            <AppContainer>
                   <Route exact path="/" Component={...} />
                   <Route exact path="/Home" Component={...} />
           </AppContainer>
        </BrowserRouter>,
  document.getElementById('root')
);

and then in AppContainer.js

class App extends Component {
  
  componentWillMount() {
    this.unlisten = this.props.history.listen((location, action) => {
      console.log("on route change");
    });
  }
  componentWillUnmount() {
      this.unlisten();
  }
  render() {
     return (
         <div>{this.props.children}</div>
      );
  }
}
export default withRouter(App);

From the history docs:

You can listen for changes to the current location using history.listen:

history.listen((location, action) => {
      console.log(`The current URL is ${location.pathname}${location.search}${location.hash}`)
  console.log(`The last navigation action was ${action}`)
})

The location object implements a subset of the window.location interface, including:

**location.pathname** - The path of the URL
**location.search** - The URL query string
**location.hash** - The URL hash fragment

Locations may also have the following properties:

location.state - Some extra state for this location that does not reside in the URL (supported in createBrowserHistory and createMemoryHistory)

location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)

The action is one of PUSH, REPLACE, or POP depending on how the user got to the current URL.

When you are using react-router v3 you can make use of history.listen() from history package as mentioned above or you can also make use browserHistory.listen()

You can configure and use your routes like

import {browserHistory} from 'react-router';

class App extends React.Component {

    componentDidMount() {
          this.unlisten = browserHistory.listen( location =>  {
                console.log('route changes');
                
           });
      
    }
    componentWillUnmount() {
        this.unlisten();
     
    }
    render() {
        return (
               <Route path="/" onChange={yourHandler} component={AppContainer}>
                   <IndexRoute component={StaticContainer}  />
                   <Route path="/a" component={ContainerA}  />
                   <Route path="/b" component={ContainerB}  />
            </Route>
        )
    }
} 

Setting font on NSAttributedString on UITextView disregards line spacing

Attributed String Programming Guide:

UIFont *font = [UIFont fontWithName:@"Palatino-Roman" size:14.0];
NSDictionary *attrsDictionary = [NSDictionary dictionaryWithObject:font
                                forKey:NSFontAttributeName];
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"strigil" attributes:attrsDictionary];

Update: I tried to use addAttribute: method in my own app, but it seemed to be not working on the iOS 6 Simulator:

NSLog(@"%@", textView.attributedText);

The log seems to show correctly added attributes, but the view on iOS simulator was not display with attributes.

Using 'sudo apt-get install build-essentials'

I know this has been answered, but I had the same question and this is what I needed to do to resolve it. During installation, I had not added a network mirror, so I had to add information about where a repo was on the internet. To do this, I ran:

sudo vi /etc/apt/sources.list

and added the following lines:

deb http://ftp.debian.org/debian wheezy main
deb-src http://ftp.debian.org/debian wheezy main

If you need to do this, you may need to replace "wheezy" with the version of debian you're running. Afterwards, run:

sudo apt-get update
sudo apt-get install build-essential

Hopefully this will help someone who had the same problem that I did.

Filtering Sharepoint Lists on a "Now" or "Today"

Have you tried this: create a Computed column, called 'Expiry', with a formula that amounts to '[Created] + 7 days'. Then use the computed column in your View's filter. Let us know whether this worked or what problems this poses!

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

I believe fcntl() is a POSIX function. Where as ioctl() is a standard UNIX thing. Here is a list of POSIX io. ioctl() is a very kernel/driver/OS specific thing, but i am sure what you use works on most flavors of Unix. some other ioctl() stuff might only work on certain OS or even certain revs of it's kernel.

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

Static Block in Java

It's a static initializer. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference).

It can be thought of as a "class constructor".

Note that there are also instance initializers, which look the same, except that they don't have the static keyword. Those are run in addition to the code in the constructor when a new instance of the object is created.

What is a user agent stylesheet?

A user agent style sheet is a ”default style sheet” provided by the browser (e.g., Chrome, Firefox, Edge, etc.) in order to present the page in a way that satisfies ”general presentation expectations.” For example, a default style sheet would provide base styles for things like font size, borders, and spacing between elements. It is common to employ a reset style sheet to deal with inconsistencies amongst browsers.

From the specification...

A user agent's default style sheet should present the elements of the document language in ways that satisfy general presentation expectations for the document language. ~ The Cascade.

For more information about user agents in general, see user agent.

How to convert QString to int?

On the comments:

sscanf(Abcd, "%f %s", &f,&s);

Gives an Error.

This is the right way:

sscanf(Abcd, "%f %s", &f,qPrintable(s));

How to prevent sticky hover effects for buttons on touch devices

I was going to post my own solution, but checking if someone already posted it, I found that @Rodney almost did it. However, he missed it one last crucial that made it uniseful, at least in my case. I mean, I too took the same .fakeHover class addition / removing via mouseenter and mouseleave event detection, but that alone, per se, acts almost exactly like "genuine" :hover. I mean: when you tap on a element in your table, it won't detect that you have "leaved" it - thus keeping the "fakehover" state.

What I did was simply to listen on click, too, so when I "tap" the button, I manually fire a mouseleave.

Si this is my final code:

.fakeHover {
    background-color: blue;
}


$(document).on('mouseenter', 'button.myButton',function(){
    $(this).addClass('fakeHover');
});

$(document).on('mouseleave', 'button.myButton',function(){
    $(this).removeClass('fakeHover');
});

$(document).on('button.myButton, 'click', function(){
    $(this).mouseleave();
});

This way you keep your usual hover functionality when using a mouse when simply "hovering" on your buttons. Well, almost all of it: the only drawback somehow is that, after clicking on the button with the mouse, it wont be in hover state. Much like if you clicked and quickly took the pointer out of the button. But in my case I can live with that.

Reading json files in C++

You can use c++ boost::property_tree::ptree for parsing json data. here is the example for your json data. this would be more easy if you shift name inside each child nodes

#include <iostream>                                                             
#include <string>                                                               
#include <tuple>                                                                

#include <boost/property_tree/ptree.hpp>                                        
#include <boost/property_tree/json_parser.hpp> 
 int main () {

    namespace pt = boost::property_tree;                                        
    pt::ptree loadPtreeRoot;                                                    

    pt::read_json("example.json", loadPtreeRoot);                               
    std::vector<std::tuple<std::string, std::string, std::string>> people;      

    pt::ptree temp ;                                                            
    pt::ptree tage ;                                                            
    pt::ptree tprofession ;                                                     

    std::string age ;                                                           
    std::string profession ;                                                    
    //Get first child                                                           
    temp = loadPtreeRoot.get_child("Anna");                                     
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession =  tprofession.get_value<std::string>();                         
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Anna", age, profession));                 

    //Get Second child                                                          
    temp = loadPtreeRoot.get_child("Ben");                                      
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession  =  tprofession.get_value<std::string>();                        
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Ben", age, profession));                  

    for (const auto& tmppeople: people) {                                       
        std::cout << "Child[" << std::get<0>(tmppeople) << "] = " << "  age : " 
        << std::get<1>(tmppeople) << "\n    profession : " << std::get<2>(tmppeople) << "\n";
    }  
}

Change some value inside the List<T>

How about list.Find(x => x.Name == "height").Value = 20; This works fine. I know its an old post, but just wondered why hasn't anyone suggested this? Is there a drawback in this code?

Replace all whitespace characters

I've used the "slugify" method from underscore.string and it worked like a charm:

https://github.com/epeli/underscore.string#slugifystring--string

The cool thing is that you can really just import this method, don't need to import the entire library.

Initialize static variables in C++ class?

Optionally, move all your constants to .cpp file without declaration in .h file. Use anonymous namespace to make them invisible beyond the cpp module.

// MyClass.cpp

#include "MyClass.h"

// anonymous namespace
namespace
{
    string RE_ANY = "([^\\n]*)";
    string RE_ANY_RELUCTANT = "([^\\n]*?)";
}

// member function (static or not)
bool MyClass::foo()
{
    // logic that uses constants
    return RE_ANY_RELUCTANT.size() > 0;
}

Can typescript export a function?

In my case I'm doing it like this:

 module SayHi {
    export default () => { console.log("Hi"); }
 }
 new SayHi();

How do I pass a method as a parameter in Python

Not exactly what you want, but a related useful tool is getattr(), to use method's name as a parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

How to automate browsing using python?

You can also take a look at mechanize. Its meant to handle "stateful programmatic web browsing" (as per their site).

How do you read scanf until EOF in C?

Your code loops until it reads a single word, then exits. So if you give it multiple words it will read the first and exit, while if you give it an empty input, it will loop forever. In any case, it will only print random garbage from uninitialized memory. This is apparently not what you want, but what do you want? If you just want to read and print the first word (if it exists), use if:

if (scanf("%15s", word) == 1)
    printf("%s\n", word);

If you want to loop as long as you can read a word, use while:

while (scanf("%15s", word) == 1)
    printf("%s\n", word);

Also, as others have noted, you need to give the word array a size that is big enough for your scanf:

char word[16];

Others have suggested testing for EOF instead of checking how many items scanf matched. That's fine for this case, where scanf can't fail to match unless there's an EOF, but is not so good in other cases (such as trying to read integers), where scanf might match nothing without reaching EOF (if the input isn't a number) and return 0.

edit

Looks like you changed your question to match my code which works fine when I run it -- loops reading words until EOF is reached and then exits. So something else is going on with your code, perhaps related to how you are feeding it input as suggested by David

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

PreparedStatement with Statement.RETURN_GENERATED_KEYS

private void alarmEventInsert(DriveDetail driveDetail, String vehicleRegNo, int organizationId) {

    final String ALARM_EVENT_INS_SQL = "INSERT INTO alarm_event (event_code,param1,param2,org_id,created_time) VALUES (?,?,?,?,?)";
    CachedConnection conn = JDatabaseManager.getConnection();
    PreparedStatement ps = null;
    ResultSet generatedKeys = null;
    try {
        ps = conn.prepareStatement(ALARM_EVENT_INS_SQL, ps.RETURN_GENERATED_KEYS);
        ps.setInt(1, driveDetail.getEventCode());
        ps.setString(2, vehicleRegNo);
        ps.setString(3, null);
        ps.setInt(4, organizationId);
        ps.setString(5, driveDetail.getCreateTime());
        ps.execute();
        generatedKeys = ps.getGeneratedKeys();
        if (generatedKeys.next()) {
            driveDetail.setStopDuration(generatedKeys.getInt(1));
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("Error inserting into alarm_event : {}", e
                .getMessage());
        logger.info(ps.toString());
    } finally {
        if (ps != null) {
            try {

                if (ps != null)
                    ps.close();
            } catch (SQLException e) {
                logger.error("Error closing prepared statements : {}", e
                        .getMessage());
            }
        }
    }
    JDatabaseManager.freeConnection(conn);
}

How do I make a LinearLayout scrollable?

try this below code

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.example.blah"
    >

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:background="#000044"
            android:orientation="vertical">
            <TextView
                android:id="@+id/title"
                android:text="@string/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editTitle"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/description"
                android:text="@string/description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editDescription"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/location"
                android:text="@string/location"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editLocation"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/startTime"
                android:text="@string/startTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <DatePicker
                android:id="@+id/DatePicker01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TimePicker
                android:id="@+id/TimePicker01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/endTime"
                android:text="@string/endTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <DatePicker
                android:id="@+id/DatePicker02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TimePicker
                android:id="@+id/TimePicker02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/buttonCreate"
                android:text="Create"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout></ScrollView></RelativeLayout>

HTML meta tag for content language

Google recommends to use hreflang, read more info

Examples:

<link rel="alternate" href="http://example.com/en-ie" hreflang="en-ie" />
<link rel="alternate" href="http://example.com/en-ca" hreflang="en-ca" />
<link rel="alternate" href="http://example.com/en-au" hreflang="en-au" />
<link rel="alternate" href="http://example.com/en" hreflang="en" />

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Get all parameters from JSP page

<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
    if(parameter.toLowerCase().startsWith("question")) {
        String[] values = parameters.get(parameter);
        //your code here
    }
}

Read a file in Node.js

Run this code, it will fetch data from file and display in console

function fileread(filename)
{            
   var contents= fs.readFileSync(filename);
   return contents;
}        
var fs =require("fs");  // file system        
var data= fileread("abc.txt");
//module.exports.say =say;
//data.say();
console.log(data.toString());

How do I make a list of data frames?

This isn't related to your question, but you want to use = and not <- within the function call. If you use <-, you'll end up creating variables y1 and y2 in whatever environment you're working in:

d1 <- data.frame(y1 <- c(1, 2, 3), y2 <- c(4, 5, 6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6

This won't have the seemingly desired effect of creating column names in the data frame:

d1
#   y1....c.1..2..3. y2....c.4..5..6.
# 1                1                4
# 2                2                5
# 3                3                6

The = operator, on the other hand, will associate your vectors with arguments to data.frame.

As for your question, making a list of data frames is easy:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))
d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))
my.list <- list(d1, d2)

You access the data frames just like you would access any other list element:

my.list[[1]]
#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

How do I set a path in Visual Studio?

Set the PATH variable, like you're doing. If you're running the program from the IDE, you can modify environment variables by adjusting the Debugging options in the project properties.

If the DLLs are named such that you don't need different paths for the different configuration types, you can add the path to the system PATH variable or to Visual Studio's global one in Tools | Options.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

How to disable "prevent this page from creating additional dialogs"?

I know everybody is ethically against this, but I understand there are reasons of practical joking where this is desired. I think Chrome took a solid stance on this by enforcing a mandatory one second separation time between alert messages. This gives the visitor just enough time to close the page or refresh if they're stuck on an annoying prank site.

So to answer your question, it's all a matter of timing. If you alert more than once per second, Chrome will create that checkbox. Here's a simple example of a workaround:

var countdown = 99;
function annoy(){
    if(countdown>0){
        alert(countdown+" bottles of beer on the wall, "+countdown+" bottles of beer! Take one down, pass it around, "+(countdown-1)+" bottles of beer on the wall!");
        countdown--;

        // Time must always be 1000 milliseconds, 999 or less causes the checkbox to appear
        setTimeout(function(){
            annoy();
        }, 1000);
    }
}

// Don't alert right away or Chrome will catch you
setTimeout(function(){
    annoy();
}, 1000);

A cycle was detected in the build path of project xxx - Build Path Problem

Mark circular dependencies as "Warning" in Eclipse tool to avoid "A CYCLE WAS DETECTED IN THE BUILD PATH" error.

In Eclipse go to:

Windows -> Preferences -> Java-> Compiler -> Building -> Circular Dependencies

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case the project Build Settings contained some to non-existing directories for Framework Search Paths and Library Search Paths.

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

best OCR (Optical character recognition) example in android

Like you I also faced many problems implementing OCR in Android, but after much Googling I found the solution, and it surely is the best example of OCR.

Let me explain using step-by-step guidance.

First, download the source code from https://github.com/rmtheis/tess-two.

Import all three projects. After importing you will get an error. To solve the error you have to create a res folder in the tess-two project

enter image description here

First, just create res folder in tess-two by tess-two->RightClick->new Folder->Name it "res"

After doing this in all three project the error should be gone.

Now download the source code from https://github.com/rmtheis/android-ocr, here you will get best example.

Now you just need to import it into your workspace, but first you have to download android-ndk from this site:

http://developer.android.com/tools/sdk/ndk/index.html i have windows 7 - 32 bit PC so I have download http://dl.google.com/android/ndk/android-ndk-r9-windows-x86.zip this file

Now extract it suppose I have extract it into E:\Software\android-ndk-r9 so I will set this path on Environment Variable

Right Click on MyComputer->Property->Advance-System-Settings->Advance->Environment Variable-> find PATH on second below Box and set like path like below picture

enter image description here

done it

Now open cmd and go to on D:\Android Workspace\tess-two like below

enter image description here

If you have successfully set up environment variable of NDK then just type ndk-build just like above picture than enter you will not get any kind of error and all file will be compiled successfully:

Now download other source code also from https://github.com/rmtheis/tess-two , and extract and import it and give it name OCRTest, like in my PC which is in D:\Android Workspace\OCRTest

enter image description here

Import test-two in this and run OCRTest and run it; you will get the best example of OCR.

How to set input type date's default value to today?

There is no default method within HTML itself to insert todays date into the input field. However, like any other input field it will accept a value.

You can use PHP to fetch todays date and input it into the value field of the form element.

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";

    // Send to the browser the input field with the value set with the date string
    echo "<input type='date' value='$date_string' />";
?>

The value field accepts the format YYYY-MM-DD as an input so simply by creating a variable $date_string in the same format that the input value accepts and fill it with the year, month and day fetched from todays date and voilá! You have yourself a preselected date!

Hope this helps :)

Edit:

If you would like to have the input field nested within HTML rather than PHP you could do the following.

<?php
    // Fetch the year, month and day
    $year = date(Y);
    $month = date(m);
    $day = date(d);

    // Merge them into a string accepted by the input field
    $date_string = "$year-$month-$day";
?>
<html>
    <head>...</head>
    <body>
        <form>
            <input type="date" value="<?php print($date_string); ?>" />
        </form>
    </body>
</html>

I realise this question was asked a while back (2 years ago) but it still took me a while to find a definite answer out on the internet, so this goes to serve anyone who is looking for the answer whenever it may be and hope it helps everyone greatly :)

Another Edit:

Almost forgot, something thats been a royal pain for me in the past is always forgetting to set the default timezone whenever making a script in PHP that makes use of the date() function.

The syntax is date_default_timezone_set(...);. Documentation can be found here at PHP.net and the list of supported timezones to insert into the function can be found here. This was always annoying since I am in Australia, everything is always pushed back 10 hours if I didn't set this properly as it defaults to UTC+0000 where I need UTC+1000 so just be cautious :)

How to truncate text in Angular2?

Truncate Pipe with optional params:

  • limit - string max length
  • completeWords - Flag to truncate at the nearest complete word, instead of character
  • ellipsis - appended trailing suffix

-

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
    if (completeWords) {
      limit = value.substr(0, limit).lastIndexOf(' ');
    }
    return value.length > limit ? value.substr(0, limit) + ellipsis : value;
  }
}

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

Usage

Example String:

public longStr = 'A really long string that needs to be truncated';

Markup:

  <h1>{{longStr | truncate }}</h1> 
  <!-- Outputs: A really long string that... -->

  <h1>{{longStr | truncate : 12 }}</h1> 
  <!-- Outputs: A really lon... -->

  <h1>{{longStr | truncate : 12 : true }}</h1> 
  <!-- Outputs: A really... -->

  <h1>{{longStr | truncate : 12 : false : '***' }}</h1> 
  <!-- Outputs: A really lon*** -->

How to increase size of DOSBox window?

Here's how to change the dosbox.conf file in Linux to increase the size of the window. I actually DID what follows, so I can say it works (in 32-bit PCLinuxOS fullmontyKDE, anyway). The question's answer is in the .conf file itself.

You find this file in Linux at /home/(username)/.dosbox . In Konqueror or Dolphin, you must first check 'Hidden files' or you won't see the folder. Open it with KWrite superuser or your fav editor.

  1. Save the file with another name like 'dosbox-0.74original.conf' to preserve the original file in case you need to restore it.
  2. Search on 'resolution' and carefully read what the conf file says about changing it. There are essentially two variables: resolution and output. You want to leave fullresolution alone for now. Your question was about WINDOW, not full. So look for windowresolution, see what the comments in conf file say you can do. The best suggestion is to use a bigger-window resolution like 900x800 (which is what I used on a 1366x768 screen), but NOT the actual resolution of your machine (which would make the window fullscreen, and you said you didn't want that). Be specific, replacing the 'windowresolution=original' with 'windowresolution=900x800' or other dimensions. On my screen, that doubled the window size just as it does with the max Font tab in Windows Properties (for the exe file; as you'll see below the ==== marks, 32-bit Windows doesn't need Dosbox).

Then, search on 'output', and as the instruction in the conf file warns, if and only if you have 'hardware scaling', change the default 'output=surface' to something else; he then lists the optional other settings. I changed it to 'output=overlay'. There's one other setting to test: aspect. Search the file for 'aspect', and change the 'false' to 'true' if you want an even bigger window. When I did this, the window took up over half of the screen. With 'false' left alone, I had a somewhat smaller window (I use widescreen monitors, whether laptop or desktop, maybe that's why).

So after you've made the changes, save the file with the original name of dosbox-0.74.conf . Then, type dosbox at the command line or create a Launcher (in KDE, this is a right click on the desktop) with the command dosbox. You still have to go through the mount command (i.e., mount c~ c:\123 if that's the location and file you'll execute). I'm sure there's a way to make a script, but haven't yet learned how to do that.

how to check for null with a ng-if values in a view with angularjs?

Here is a simple example that I tried to explain.

<div>
    <div *ngIf="product">     <!--If "product" exists-->
      <h2>Product Details</h2><hr>
      <h4>Name: {{ product.name }}</h4>
      <h5>Price: {{ product.price | currency }}</h5>
      <p> Description: {{ product.description }}</p>
    </div>

    <div *ngIf="!product">     <!--If "product" not exists-->
       *Product not found
    </div>
</div>

Prompt for user input in PowerShell

As an alternative, you could add it as a script parameter for input as part of script execution

 param(
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value1,
      [Parameter(Mandatory = $True,valueFromPipeline=$true)][String] $value2
      )

Setting PHPMyAdmin Language

At the first site is a dropdown field to select the language of phpmyadmin.

In the config.inc.php you can set:

$cfg['Lang'] = '';

More details you can find in the documentation: http://www.phpmyadmin.net/documentation/

Round integers to the nearest 10

round() can take ints and negative numbers for places, which round to the left of the decimal. The return value is still a float, but a simple cast fixes that:

>>> int(round(5678,-1))
5680
>>> int(round(5678,-2))
5700
>>> int(round(5678,-3))
6000

How to vertically align into the center of the content of a div with defined width/height?

I would say to add a paragraph with a period in it and style it like so:

<p class="center">.</p>

<style>
.center {font-size: 0px; margin-bottom: anyPercentage%;}
</style>

You may need to toy around with the percentages to get it right

Check empty string in Swift?

Check check for only spaces and newlines characters in text

extension String
{
    var  isBlank:Bool {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
    }
}

using

if text.isBlank
{
  //text is blank do smth
}

I need to round a float to two decimal places in Java

If you're looking for currency formatting (which you didn't specify, but it seems that is what you're looking for) try the NumberFormat class. It's very simple:

double d = 2.3d;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String output = formatter.format(d);

Which will output (depending on locale):

$2.30

Also, if currency isn't required (just the exact two decimal places) you can use this instead:

NumberFormat formatter = NumberFormat.getNumberInstance();
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String output = formatter.format(d);

Which will output 2.30

How to clear APC cache entries?

My work-around for Symfony build having loot of instances at the same server:

Step 1. Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2. On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2. Run app.

What is the purpose of .PHONY in a Makefile?

There's also one important tricky treat of ".PHONY" - when a physical target depends on phony target that depends on another physical target:

TARGET1 -> PHONY_FORWARDER1 -> PHONY_FORWARDER2 -> TARGET2

You'd simply expect that if you updated TARGET2, then TARGET1 should be considered stale against TARGET1, so TARGET1 should be rebuild. And it really works this way.

The tricky part is when TARGET2 isn't stale against TARGET1 - in which case you should expect that TARGET1 shouldn't be rebuild.

This surprisingly doesn't work because: the phony target was run anyway (as phony targets normally do), which means that the phony target was considered updated. And because of that TARGET1 is considered stale against the phony target.

Consider:

all: fileall

fileall: file2 filefwd
    echo file2 file1 >fileall


file2: file2.src
    echo file2.src >file2

file1: file1.src
    echo file1.src >file1
    echo file1.src >>file1

.PHONY: filefwd
.PHONY: filefwd2

filefwd: filefwd2

filefwd2: file1
    @echo "Produced target file1"


prepare:
    echo "Some text 1" >> file1.src
    echo "Some text 2" >> file2.src

You can play around with this:

  • first do 'make prepare' to prepare the "source files"
  • play around with that by touching particular files to see them updated

You can see that fileall depends on file1 indirectly through a phony target - but it always gets rebuilt due to this dependency. If you change the dependency in fileall from filefwd to file, now fileall does not get rebuilt every time, but only when any of dependent targets is stale against it as a file.

Which characters are valid in CSS class names/selectors?

For those looking for a workaround, you can use an attribute selector, for instance, if your class begins with a number. Change:

.000000-8{background:url(../../images/common/000000-0.8.png);} /* DOESN'T WORK!! */

to this:

[class="000000-8"]{background:url(../../images/common/000000-0.8.png);} /* WORKS :) */

Also, if there are multiple classes, you will need to specify them in selector I think.

Sources:

  1. https://benfrain.com/when-and-where-you-can-use-numbers-in-id-and-class-names/
  2. Is there a workaround to make CSS classes with names that start with numbers valid?

Remove gutter space for a specific div only

Example 4 columns of span3. For other span widths use new width = old width + gutter size. Use media queries to make it responsive.

css:

    <style type="text/css">
    @media (min-width: 1200px) 
    {   
        .nogutter .span3
        {
            margin-left: 0px; width:300px;
        }   
    }
    @media (min-width: 980px) and (max-width: 1199px) 
    { 
        .nogutter .span3
        {
            margin-left: 0px; width:240px;
        }   
    }
    @media (min-width: 768px) and (max-width: 979px) 
    { 
        .nogutter .span3
        {   
            margin-left: 0px; width:186px;
        }   
    }
    </style>

html:

<div class="container">
<div class="row">
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
</div>
<br>
<div class="row nogutter">
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
  <div class="span3" style="background-color:red;">...</div>
</div> 
</div>

update: or split a span12 div in 100/numberofcolumns % width parts floating left:

<div class="row">
  <div class="span12">
    <div style="background-color:green;width:25%;float:left;">...</div>
  <div style="background-color:yellow;width:25%;float:left;">...</div>
  <div style="background-color:red;width:25%;float:left;">...</div>
  <div style="background-color:blue;width:25%;float:left;">...</div>
  </div>
</div>  

For both solutions see: http://bootply.com/61557

Where can I find the TypeScript version installed in Visual Studio?

As far as I understand VS has nothing to do with TS installed by NPM. (You may notice after you install TS using NPM, there is no tsc.exe file). VS targets only tsc.exe installed by TS for VS extension, which installes TS to c:\Program Files (x86)\Microsoft SDKs\TypeScript\X.Y. You may have multiple folders under c:\Program Files (x86)\Microsoft SDKs\TypeScript. Set TypeScriptToolsVersion to the highest version installed. In my case I had folders "1.0", "1.7", "1.8", so I set TypeScriptToolsVersion = 1.8, and if you run tsc - v inside that folder you will get 1.8.3 or something, however, when u run tsc outside that folder, it will use PATH variable pointing to TS version installed by NPM, which is in my case 1.8.10. I believe TS for VS will always be a little behind the latest version of TS you install using NPM. But as far as I understand, VS doesnt know anything about TS installed by NPM, it only targets whateve versions installed by TS for VS extensions, and the version specified in TypeScriptToolsVersion in your project file.

How can I compare a date and a datetime in Python?

I am trying to compare date which are in string format like '20110930'

benchMark = datetime.datetime.strptime('20110701', "%Y%m%d") 

actualDate = datetime.datetime.strptime('20110930', "%Y%m%d")

if actualDate.date() < benchMark.date():
    print True

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

Angular 2 Scroll to bottom (Chat style)

const element = document.getElementById('box');
element.scrollIntoView({ behavior: 'smooth', block: 'end', inline: 'nearest' });

How can I detect the encoding/codepage of a text file

10Y (!) had passed since this was asked, and still I see no mention of MS's good, non-GPL'ed solution: IMultiLanguage2 API.

Most libraries already mentioned are based on Mozilla's UDE - and it seems reasonable that browsers have already tackled similar problems. I don't know what is chrome's solution, but since IE 5.0 MS have released theirs, and it is:

  1. Free of GPL-and-the-like licensing issues,
  2. Backed and maintained probably forever,
  3. Gives rich output - all valid candidates for encoding/codepages along with confidence scores,
  4. Surprisingly easy to use (it is a single function call).

It is a native COM call, but here's some very nice work by Carsten Zeumer, that handles the interop mess for .net usage. There are some others around, but by and large this library doesn't get the attention it deserves.

Manually Set Value for FormBuilder Control

  let cloneObj = Object.assign({}, this.form.getRawValue(), someClass);
  this.form.complexForm.patchValue(cloneObj);

If you don't want manually set each field.