Programs & Examples On #Function templates

A function template behaves like a regular function except that works with types specified on the template arguments. The template arguments could be part of the function arguments and/or the function body. Each unique combination of template arguments will become an unique function when instantiated.

Can a class member function template be virtual?

My current solution is the following (with RTTI disabled - you could use std::type_index, too):

#include <type_traits>
#include <iostream>
#include <tuple>

class Type
{
};

template<typename T>
class TypeImpl : public Type
{

};

template<typename T>
inline Type* typeOf() {
    static Type* typePtr = new TypeImpl<T>();
    return typePtr;
}

/* ------------- */

template<
    typename Calling
    , typename Result = void
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action);

template<typename Cls>
class ChildClasses
{
public:
    using type = std::tuple<>;
};

template<typename... Childs>
class ChildClassesHelper
{
public:
    using type = std::tuple<Childs...>;
};

//--------------------------

class A;
class B;
class C;
class D;

template<>
class ChildClasses<A> : public ChildClassesHelper<B, C, D> {};

template<>
class ChildClasses<B> : public ChildClassesHelper<C, D> {};

template<>
class ChildClasses<C> : public ChildClassesHelper<D> {};

//-------------------------------------------

class A
{
public:
    virtual Type* GetType()
    {
        return typeOf<A>();
    }

    template<
        typename T,
        bool checkType = true
    >
        /*virtual*/void DoVirtualGeneric()
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<A>(this, [&](auto* other) -> decltype(auto)
                {
                    return other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "A";
    }
};

class B : public A
{
public:
    virtual Type* GetType()
    {
        return typeOf<B>();
    }
    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<B>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "B";
    }
};

class C : public B
{
public:
    virtual Type* GetType() {
        return typeOf<C>();
    }

    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<C>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "C";
    }
};

class D : public C
{
public:
    virtual Type* GetType() {
        return typeOf<D>();
    }
};

int main()
{
    A* a = new A();
    a->DoVirtualGeneric<int>();
}

// --------------------------

template<typename Tuple>
class RestTuple {};

template<
    template<typename...> typename Tuple,
    typename First,
    typename... Rest
>
class RestTuple<Tuple<First, Rest...>> {
public:
    using type = Tuple<Rest...>;
};

// -------------
template<
    typename CandidatesTuple
    , typename Result
    , typename From
    , typename Action
>
inline constexpr Result DoComplexDispatchInternal(From* from, Action&& action, Type* fromType)
{
    using FirstCandidate = std::tuple_element_t<0, CandidatesTuple>;

    if constexpr (std::tuple_size_v<CandidatesTuple> == 1)
    {
        return action(static_cast<FirstCandidate*>(from));
    }
    else {
        if (fromType == typeOf<FirstCandidate>())
        {
            return action(static_cast<FirstCandidate*>(from));
        }
        else {
            return DoComplexDispatchInternal<typename RestTuple<CandidatesTuple>::type, Result>(
                from, action, fromType
            );
        }
    }
}

template<
    typename Calling
    , typename Result
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action)
{
    using ChildsOfCalling = typename ChildClasses<Calling>::type;
    if constexpr (std::tuple_size_v<ChildsOfCalling> == 0)
    {
        return action(static_cast<Calling*>(from));
    }
    else {
        auto fromType = from->GetType();
        using Candidates = decltype(std::tuple_cat(std::declval<std::tuple<Calling>>(), std::declval<ChildsOfCalling>()));
        return DoComplexDispatchInternal<Candidates, Result>(
            from, std::forward<Action>(action), fromType
        );
    }
}

The only thing I don't like is that you have to define/register all child classes.

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

Adjusting HttpWebRequest Connection Timeout in C#

No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.

To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

How can I get the baseurl of site?

I believe that the answers above doesn't consider when the site is not in the root of the website.

This is a for WebApi controller:

string baseUrl = (Url.Request.RequestUri.GetComponents(
                    UriComponents.SchemeAndServer, UriFormat.Unescaped).TrimEnd('/') 
                 + HttpContext.Current.Request.ApplicationPath).TrimEnd('/') ;

Chain-calling parent initialisers in python

You can simply write :

class A(object):

    def __init__(self):
        print "Initialiser A was called"

class B(A):

    def __init__(self):
        A.__init__(self)
        # A.__init__(self,<parameters>) if you want to call with parameters
        print "Initialiser B was called"

class C(B):

    def __init__(self):
        # A.__init__(self) # if you want to call most super class...
        B.__init__(self)
        print "Initialiser C was called"

Global variables in Java

In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program. We can have static variables to have the scope of global variables.

MySQL error: key specification without a key length

The solution to the problem is that in your CREATE TABLE statement, you may add the constraint UNIQUE ( problemtextfield(300) ) after the column create definitions to specify a key length of 300 characters for a TEXT field, for example. Then the first 300 characters of the problemtextfield TEXT field would need to be unique, and any differences after that would be disregarded.

Sorting rows in a data table

This will help you...

DataTable dt = new DataTable();         
dt.DefaultView.Sort = "Column_name desc";
dt = dt.DefaultView.ToTable();

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

How to convert Json array to list of objects in c#

As others have already pointed out, the reason you are not getting the results you expect is because your JSON does not match the class structure that you are trying to deserialize into. You either need to change your JSON or change your classes. Since others have already shown how to change the JSON, I will take the opposite approach here.

To match the JSON you posted in your question, your classes should be defined like those below. Notice I've made the following changes:

  1. I added a Wrapper class corresponding to the outer object in your JSON.
  2. I changed the Values property of the ValueSet class from a List<Value> to a Dictionary<string, Value> since the values property in your JSON contains an object, not an array.
  3. I added some additional [JsonProperty] attributes to match the property names in your JSON objects.

Class definitions:

class Wrapper
{
    [JsonProperty("JsonValues")]
    public ValueSet ValueSet { get; set; }
}

class ValueSet
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("values")]
    public Dictionary<string, Value> Values { get; set; }
}

class Value
{
    [JsonProperty("id")]
    public string Id { get; set; }
    [JsonProperty("diaplayName")]
    public string DisplayName { get; set; }
}

You need to deserialize into the Wrapper class, not the ValueSet class. You can then get the ValueSet from the Wrapper.

var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

Here is a working program to demonstrate:

class Program
{
    static void Main(string[] args)
    {
        string jsonString = @"
        {
            ""JsonValues"": {
                ""id"": ""MyID"",
                ""values"": {
                    ""value1"": {
                        ""id"": ""100"",
                        ""diaplayName"": ""MyValue1""
                    },
                    ""value2"": {
                        ""id"": ""200"",
                        ""diaplayName"": ""MyValue2""
                    }
                }
            }
        }";

        var valueSet = JsonConvert.DeserializeObject<Wrapper>(jsonString).ValueSet;

        Console.WriteLine("id: " + valueSet.Id);
        foreach (KeyValuePair<string, Value> kvp in valueSet.Values)
        {
            Console.WriteLine(kvp.Key + " id: " + kvp.Value.Id);
            Console.WriteLine(kvp.Key + " name: " + kvp.Value.DisplayName);
        }
    }
}

And here is the output:

id: MyID
value1 id: 100
value1 name: MyValue1
value2 id: 200
value2 name: MyValue2

Apache Spark: The number of cores vs. the number of executors

Spark Dynamic allocation gives flexibility and allocates resources dynamically. In this number of min and max executors can be given. Also the number of executors that has to be launched at the starting of the application can also be given.

Read below on the same:

http://spark.apache.org/docs/latest/configuration.html#dynamic-allocation

How to compare variables to undefined, if I don’t know whether they exist?

if (!obj) {
    // object (not class!) doesn't exist yet
}
else ...

How to create virtual column using MySQL SELECT?

SELECT only retrieves data from the database, it does not change the table itself.

If you write

SELECT a AS b FROM x

"b" is just an alias name in the query. It does not create an extra column. Your result in the example would only contain one column named "b". But the column in the table would stay "a". "b" is just another name.

I don't really understand what you mean with "so I can use it with each item later on". Do you mean later in the select statement or later in your application. Perhaps you could provide some example code.

How to ensure a <select> form field is submitted when it is disabled?

The easiest way i found was to create a tiny javascript function tied to your form :

function enablePath() {
    document.getElementById('select_name').disabled= "";
}

and you call it in your form here :

<form action="act.php" method="POST" name="form_name" onSubmit="enablePath();">

Or you can call it in the function you use to check your form :)

Android SDK location should not contain whitespace, as this cause problems with NDK tools

As long as you aren't using the NDK you can just ignore that warning.

By the way: This warning has nothing to do with parallel installations.

How to group by month from Date field using sql

I would use this:

SELECT  Closing_Date = DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), 
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Closing_Date), 0), Category;

This will group by the first of every month, so

`DATEADD(MONTH, DATEDIFF(MONTH, 0, '20130128'), 0)` 

will give '20130101'. I generally prefer this method as it keeps dates as dates.

Alternatively you could use something like this:

SELECT  Closing_Year = DATEPART(YEAR, Closing_Date),
        Closing_Month = DATEPART(MONTH, Closing_Date),
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY DATEPART(YEAR, Closing_Date), DATEPART(MONTH, Closing_Date), Category;

It really depends what your desired output is. (Closing Year is not necessary in your example, but if the date range crosses a year boundary it may be).

Failed to instantiate module error in Angular js

For me the error occurred due to my browser using a cached version of the js file containing the module. Clearing the cache and reloading the page solved the problem.

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Another solution if you are running php script in CLI(cmd)

The php.ini file that needs edit is different in this case. In my WAMP installation the php.ini file that is loaded in command line is:

\wamp\bin\php\php5.5.12\php.ini

instead of \wamp\bin\apache\apache2.4.9\bin\php.ini which loads when php is run from browser

How to strip comma in Python string

Use replace method of strings not strip:

s = s.replace(',','')

An example:

>>> s = 'Foo, bar'
>>> s.replace(',',' ')
'Foo  bar'
>>> s.replace(',','')
'Foo bar'
>>> s.strip(',') # clears the ','s at the start and end of the string which there are none
'Foo, bar'
>>> s.strip(',') == s
True

No module named pkg_resources

July 2018 Update

Most people should now use pip install setuptools (possibly with sudo).

Some may need to (re)install the python-setuptools package via their package manager (apt-get install, yum install, etc.).

This issue can be highly dependent on your OS and dev environment. See the legacy/other answers below if the above isn't working for you.

Explanation

This error message is caused by a missing/broken Python setuptools package. Per Matt M.'s comment and setuptools issue #581, the bootstrap script referred to below is no longer the recommended installation method.

The bootstrap script instructions will remain below, in case it's still helpful to anyone.

Legacy Answer

I encountered the same ImportError today while trying to use pip. Somehow the setuptools package had been deleted in my Python environment.

To fix the issue, run the setup script for setuptools:

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

(or if you don't have wget installed (e.g. OS X), try

curl https://bootstrap.pypa.io/ez_setup.py | python

possibly with sudo prepended.)

If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.*

See Installation Instructions for further details.


* If you already have a working distribute, upgrading it to the "compatibility wrapper" that switches you over to setuptools is easier. But if things are already broken, don't try that.

Binding an enum to a WinForms combo box, and then setting it

This is probably never going to be seen among all the other responses, but this is the code I came up with, this has the benefit of using the DescriptionAttribute if it exists, but otherwise using the name of the enum value itself.

I used a dictionary because it has a ready made key/value item pattern. A List<KeyValuePair<string,object>> would also work and without the unnecessary hashing, but a dictionary makes for cleaner code.

I get members that have a MemberType of Field and that are literal. This creates a sequence of only members that are enum values. This is robust since an enum cannot have other fields.

public static class ControlExtensions
{
    public static void BindToEnum<TEnum>(this ComboBox comboBox)
    {
        var enumType = typeof(TEnum);

        var fields = enumType.GetMembers()
                              .OfType<FieldInfo>()
                              .Where(p => p.MemberType == MemberTypes.Field)
                              .Where(p => p.IsLiteral)
                              .ToList();

        var valuesByName = new Dictionary<string, object>();

        foreach (var field in fields)
        {
            var descriptionAttribute = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute;

            var value = (int)field.GetValue(null);
            var description = string.Empty;

            if (!string.IsNullOrEmpty(descriptionAttribute?.Description))
            {
                description = descriptionAttribute.Description;
            }
            else
            {
                description = field.Name;
            }

            valuesByName[description] = value;
        }

        comboBox.DataSource = valuesByName.ToList();
        comboBox.DisplayMember = "Key";
        comboBox.ValueMember = "Value";
    }


}

Android: Test Push Notification online (Google Cloud Messaging)

POSTMAN : A google chrome extension

Use postman to send message instead of server. Postman settings are as follows :

Request Type: POST

URL: https://android.googleapis.com/gcm/send

Header
  Authorization  : key=your key //Google API KEY
  Content-Type : application/json

JSON (raw) :
{       
  "registration_ids":["yours"],
  "data": {
    "Hello" : "World"
  } 
}

on success you will get

Response :
{
  "multicast_id": 6506103988515583000,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    {
      "message_id": "0:1432811719975865%54f79db3f9fd7ecd"
    }
  ]
}

Simple 3x3 matrix inverse code (C++)

This piece of code computes the transposed inverse of the matrix A:

double determinant =    +A(0,0)*(A(1,1)*A(2,2)-A(2,1)*A(1,2))
                        -A(0,1)*(A(1,0)*A(2,2)-A(1,2)*A(2,0))
                        +A(0,2)*(A(1,0)*A(2,1)-A(1,1)*A(2,0));
double invdet = 1/determinant;
result(0,0) =  (A(1,1)*A(2,2)-A(2,1)*A(1,2))*invdet;
result(1,0) = -(A(0,1)*A(2,2)-A(0,2)*A(2,1))*invdet;
result(2,0) =  (A(0,1)*A(1,2)-A(0,2)*A(1,1))*invdet;
result(0,1) = -(A(1,0)*A(2,2)-A(1,2)*A(2,0))*invdet;
result(1,1) =  (A(0,0)*A(2,2)-A(0,2)*A(2,0))*invdet;
result(2,1) = -(A(0,0)*A(1,2)-A(1,0)*A(0,2))*invdet;
result(0,2) =  (A(1,0)*A(2,1)-A(2,0)*A(1,1))*invdet;
result(1,2) = -(A(0,0)*A(2,1)-A(2,0)*A(0,1))*invdet;
result(2,2) =  (A(0,0)*A(1,1)-A(1,0)*A(0,1))*invdet;

Though the question stipulated non-singular matrices, you might still want to check if determinant equals zero (or very near zero) and flag it in some way to be safe.

Laravel Eloquent groupBy() AND also return count of each group

Works that way as well, a bit more tidy. getQuery() just returns the underlying builder, which already contains the table reference.

$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
                     ->select('browser', $browser_total_raw)
                     ->groupBy('browser')
                     ->pluck('total','browser');

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

I can also confirm this error.

Workaround: is to use external maven inside m2eclipse, instead of it's embedded maven.

That is done in three steps:

1 Install maven on local machine (the test-machine was Ubuntu 10.10)

mvn --version

Apache Maven 2.2.1 (rdebian-4) Java version: 1.6.0_20 Java home: /usr/lib/jvm/java-6-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux" version: "2.6.35-32-generic" arch: "amd64" Family: "unix"

2 Run maven externally link how to run maven from console

> cd path-to-pom.xml
> mvn test
    [INFO] Scanning for projects...
    [INFO] ------------------------------------------------------------------------
    [INFO] Building Simple
    [INFO]    task-segment: [test]
    [INFO] ------------------------------------------------------------------------
    [...]
    [INFO] Surefire report directory: [...]/workspace/Simple/target/surefire-reports
    
    -------------------------------------------------------
     T E S T S
    -------------------------------------------------------
    Running net.tverrbjelke.experiment.MainAppTest
    Hello World
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 sec
    
    Results :
    
    Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
    
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESSFUL
    [INFO] ------------------------------------------------------------------------
    [...]

3 inside m2eclipse: switch from embedded maven to local maven

  • find out where local maven home installation dir is (mvn --version, or google for your MAVEN_HOME, for me this helped me that is /usr/share/maven2 )
  • in eclipse Menu->Window->Preferences->Maven->Installation-> enter that string. Then you should have switched to your new external maven.
  • then run your Project as e.g. "maven test".

The error-message should be gone.

Config Error: This configuration section cannot be used at this path

For Windows Server 2012 and IIS 8, the procedure is similar.

The Web Server (IIS) and Application Server should be installed, and you should also have the optional Web Server (IIS) Support under Application Server.

Windows Server 2012 and IIS 8 Requirements for MVC

How do I fix MSB3073 error in my post-build event?

In my case, the dll I was creating by building the project was still in use in the background. I killed the application and then xcopy worked fine as expected.

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

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

delay does not work on none queue functions, so we should use setTimeout().

And you don't need to separate things. All you need to do is including everything in a setTimeOut method:

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

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

just cast the field as char

Eg: cast(updatedate) as char as updatedate

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

SURE: Simply,

This is what you need :

io.to(socket.id).emit("event", data);

whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.

first we need to store all the socket.ids in array,

var people={};

people[name] =  socket.id;

here name is the receiver name. Example:

people["ccccc"]=2387423cjhgfwerwer23;

So, now we can get that socket.id with the receiver name whenever we are sending message:

for this we need to know the receivername. You need to emit receiver name to the server.

final thing is:

 socket.on('chat message', function(data){
io.to(people[data.receiver]).emit('chat message', data.msg);
});

Hope this works well for you.

Good Luck!!

Printing object properties in Powershell

The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects

add the following text to a file named print_object.ps1:

$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *

open powershell command prompt, go to the directory where that file exists and type the following:

powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated

Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.

Name node is in safe mode. Not able to leave

use below command to turn off the safe mode

$> hdfs dfsadmin -safemode leave

How to convert string to long

IF your input is String then I recommend you to store the String into a double and then convert the double to the long.

String str = "123.45";
Double  a = Double.parseDouble(str);

long b = Math.round(a);

maxReceivedMessageSize and maxBufferSize in app.config

binding name="BindingName" 
maxReceivedMessageSize="2097152" 
maxBufferSize="2097152" 
maxBufferPoolSize="2097152" 

on client side and server side

How to force composer to reinstall a library?

I didn't want to delete all the packages in vendor/ directory, so here is how I did it:

  1. rm -rf vendor/package-i-messed-up
  2. composer install again

Remove Duplicates from range of cells in excel vba

You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.

Sub dedupe_abcd()
    Dim icol As Long

    With Sheets("Sheet1")   '<-set this worksheet reference properly!
        icol = Application.Match("abcd", .Rows(1), 0)
        With .Cells(1, 1).CurrentRegion
            .RemoveDuplicates Columns:=icol, Header:=xlYes
        End With
    End With
End Sub

Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

In order to populate all of the column names into a comma-delimited list for a Select statement for the solutions mentioned for this question, I use the following options as they are a little less verbose than most responses here. Although, most responses here are still perfectly acceptable, however.

1)

SELECT column_name + ',' 
FROM   information_schema.columns 
WHERE  table_name = 'YourTable'

2) This is probably the simplest approach to creating columns, if you have SQL Server SSMS.

1) Go to the table in Object Explorer and click on the + to the left of the table name or double-click the table name to open the sub list.

2) Drag the column subfolder over to the main query area and it will autopaste the entire column list for you.

Setting background color for a JFrame

Retrieve the content pane for the frame and use the setBackground() method inherited from Component to change the color.

Example:

myJFrame.getContentPane().setBackground( desiredColor );

JQuery .each() backwards

You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.

Try the following:

//get an array of the matching DOM elements   
var liItems = $("ul#myUL li").get();

//iterate through this array in reverse order    
for(var i = liItems.length - 1; i >= 0; --i)
{
  //do Something
}

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

Problems with Android Fragment back stack

First of all thanks @Arvis for an eye opening explanation.

I prefer different solution to the accepted answer here for this problem. I don't like messing with overriding back behavior any more than absolutely necessary and when I've tried adding and removing fragments on my own without default back stack poping when back button is pressed I found my self in fragment hell :) If you .add f2 over f1 when you remove it f1 won't call any of callback methods like onResume, onStart etc. and that can be very unfortunate.

Anyhow this is how I do it:

Currently on display is only fragment f1.

f1 -> f2

Fragment2 f2 = new Fragment2();
this.getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,f2).addToBackStack(null).commit();

nothing out of the ordinary here. Than in fragment f2 this code takes you to fragment f3.

f2 -> f3

Fragment3 f3 = new Fragment3();
getActivity().getSupportFragmentManager().popBackStack();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

I'm not sure by reading docs if this should work, this poping transaction method is said to be asynchronous, and maybe a better way would be to call popBackStackImmediate(). But as far I can tell on my devices it's working flawlessly.

The said alternative would be:

final FragmentActivity activity = getActivity();
activity.getSupportFragmentManager().popBackStackImmediate();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.main_content, f3).addToBackStack(null).commit();

Here there will actually be brief going back to f1 beofre moving on to f3, so a slight glitch there.

This is actually all you have to do, no need to override back stack behavior...

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Invert colors of an image in CSS or JavaScript

You can apply the style via javascript. This is the Js code below that applies the filter to the image with the ID theImage.

function invert(){
document.getElementById("theImage").style.filter="invert(100%)";
}

And this is the

<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png"></img>

Now all you need to do is call invert() We do this when the image is clicked.

_x000D_
_x000D_
function invert(){_x000D_
document.getElementById("theImage").style.filter="invert(100%)";_x000D_
}
_x000D_
<h4> Click image to invert </h4>_x000D_
_x000D_
<img id="theImage" class="img-responsive" src="http://i.imgur.com/1H91A5Y.png" onClick="invert()" ></img>
_x000D_
_x000D_
_x000D_

We use this on our website

Create sequence of repeated values, in sequence?

Another base R option could be gl():

gl(5, 3)

Where the output is a factor:

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
Levels: 1 2 3 4 5

If integers are needed, you can convert it:

as.numeric(gl(5, 3))

 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5

How to deep merge instead of shallow merge?

I use lodash:

import _ = require('lodash');
value = _.merge(value1, value2);

Force page scroll position to top at page refresh in HTML

The supercalifragilisticexpialidocious answer is:

add this at the top of your js file or script tag

document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera

document.body.scrollTop = 0; // For Safari

Forcing label to flow inline with input that they label

If you want they to be paragraph, then use it.

<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>

Both <label> and <input> are paragraph and flow content so you can insert as paragraph elements and as block elements.

Defining private module functions in python

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

Split string into tokens and save them in an array

Why strtok() is a bad idea

Do not use strtok() in normal code, strtok() uses static variables which have some problems. There are some use cases on embedded microcontrollers where static variables make sense but avoid them in most other cases. strtok() behaves unexpected when more than 1 thread uses it, when it is used in a interrupt or when there are some other circumstances where more than one input is processed between successive calls to strtok(). Consider this example:

#include <stdio.h>
#include <string.h>

//Splits the input by the / character and prints the content in between
//the / character. The input string will be changed
void printContent(char *input)
{
    char *p = strtok(input, "/");
    while(p)
    {
        printf("%s, ",p);
        p = strtok(NULL, "/");
    }
}

int main(void)
{
    char buffer[] = "abc/def/ghi:ABC/DEF/GHI";
    char *p = strtok(buffer, ":");
    while(p)
    {
        printContent(p);
        puts(""); //print newline
        p = strtok(NULL, ":");
    }
    return 0;
}

You may expect the output:

abc, def, ghi,
ABC, DEF, GHI,

But you will get

abc, def, ghi,

This is because you call strtok() in printContent() resting the internal state of strtok() generated in main(). After returning, the content of strtok() is empty and the next call to strtok() returns NULL.

What you should do instead

You could use strtok_r() when you use a POSIX system, this versions does not need static variables. If your library does not provide strtok_r() you can write your own version of it. This should not be hard and Stackoverflow is not a coding service, you can write it on your own.

Read CSV file column by column

Finds all files in folder and write that data to ArrayList row.

Initialize

ArrayList<ArrayList<String>> row=new ArrayList<ArrayList<String>>();
BufferedReader br=null;

For Accessing row

for(ArrayList<String> data:row){
data.get(col no); 
}
or row.get(0).get(0) // getting first row first col

Functions that reads all files from folders and concatenate them row.

static void readData(){
String path="C:\\Users\\Galaxy Computers\\Desktop\\Java project\\Nasdaq\\";
File files=new File(path);
String[] list=files.list();

try {
        String sCurrentLine;
       char check;
       for(String filename:list){ 
        br = new BufferedReader(new FileReader(path+filename));
        br.readLine();//If file contains uneccessary first line.
        while ((sCurrentLine = br.readLine()) != null) {

           row.add(splitLine(sCurrentLine));
        }
        }
        }

    } catch (IOException e) {
        e.printStackTrace();
    } 
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }


   static ArrayList<String> splitLine(String line){
   String[] ar=line.split(",");
   ArrayList<String> d=new ArrayList<String>();
   for(String data:ar){
    d.add(data);
   }

   return d; 
   } 

PostgreSQL: Show tables in PostgreSQL


Using psql : \dt

Or:

SELECT c.relname AS Tables_in FROM pg_catalog.pg_class c
        LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE pg_catalog.pg_table_is_visible(c.oid)
        AND c.relkind = 'r'
        AND relname NOT LIKE 'pg_%'
ORDER BY 1

Press any key to continue

I've created a little Powershell function to emulate MSDOS pause. This handles whether running Powershell ISE or non ISE. (ReadKey does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox. This can sometimes be confusing, because the MessageBox does not always come to the forefront. Anyway, here it goes:

Usage: pause "Press any key to continue"

Function definition:

Function pause ($message)
{
    # Check if running Powershell ISE
    if ($psISE)
    {
        Add-Type -AssemblyName System.Windows.Forms
        [System.Windows.Forms.MessageBox]::Show("$message")
    }
    else
    {
        Write-Host "$message" -ForegroundColor Yellow
        $x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    }
}

Deep copy, shallow copy, clone

Unfortunately, "shallow copy", "deep copy" and "clone" are all rather ill-defined terms.


In the Java context, we first need to make a distinction between "copying a value" and "copying an object".

int a = 1;
int b = a;     // copying a value
int[] s = new int[]{42};
int[] t = s;   // copying a value (the object reference for the array above)

StringBuffer sb = new StringBuffer("Hi mom");
               // copying an object.
StringBuffer sb2 = new StringBuffer(sb);

In short, an assignment of a reference to a variable whose type is a reference type is "copying a value" where the value is the object reference. To copy an object, something needs to use new, either explicitly or under the hood.


Now for "shallow" versus "deep" copying of objects. Shallow copying generally means copying only one level of an object, while deep copying generally means copying more than one level. The problem is in deciding what we mean by a level. Consider this:

public class Example {
    public int foo;
    public int[] bar;
    public Example() { };
    public Example(int foo, int[] bar) { this.foo = foo; this.bar = bar; };
}

Example eg1 = new Example(1, new int[]{1, 2});
Example eg2 = ... 

The normal interpretation is that a "shallow" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to the same array as in the original; e.g.

Example eg2 = new Example(eg1.foo, eg1.bar);

The normal interpretation of a "deep" copy of eg1 would be a new Example object whose foo equals 1 and whose bar field refers to a copy of the original array; e.g.

Example eg2 = new Example(eg1.foo, Arrays.copy(eg1.bar));

(People coming from a C / C++ background might say that a reference assignment produces a shallow copy. However, that's not what we normally mean by shallow copying in the Java context ...)

Two more questions / areas of uncertainty exist:

  • How deep is deep? Does it stop at two levels? Three levels? Does it mean the whole graph of connected objects?

  • What about encapsulated data types; e.g. a String? A String is actually not just one object. In fact, it is an "object" with some scalar fields, and a reference to an array of characters. However, the array of characters is completely hidden by the API. So, when we talk about copying a String, does it make sense to call it a "shallow" copy or a "deep" copy? Or should we just call it a copy?


Finally, clone. Clone is a method that exists on all classes (and arrays) that is generally thought to produce a copy of the target object. However:

  • The specification of this method deliberately does not say whether this is a shallow or deep copy (assuming that is a meaningful distinction).

  • In fact, the specification does not even specifically state that clone produces a new object.

Here's what the javadoc says:

"Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object. The general intent is that, for any object x, the expression x.clone() != x will be true, and that the expression x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements. While it is typically the case that x.clone().equals(x) will be true, this is not an absolute requirement."

Note, that this is saying that at one extreme the clone might be the target object, and at the other extreme the clone might not equal the original. And this assumes that clone is even supported.

In short, clone potentially means something different for every Java class.


Some people argue (as @supercat does in comments) that the Java clone() method is broken. But I think the correct conclusion is that the concept of clone is broken in the context of OO. AFAIK, it is impossible to develop a unified model of cloning that is consistent and usable across all object types.

How to remove entry from $PATH on mac

On MAC OS X Leopard and higher

cd /etc/paths.d

There may be a text file in the above directory that contains the path you are trying to remove.

vim textfile //check and see what is in it when you are done looking type :q 
//:q just quits, no saves

If its the one you want to remove do this

rm textfile //remove it, delete it

Here is a link to a site that has more info on it, even though it illustrates 'adding' the path. However, you may gain some insight.

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

Not able to launch IE browser using Selenium2 (Webdriver) with Java

It needs to set same Security level in all zones. To do that follow the steps below:

  1. Open IE
  2. Go to Tools -> Internet Options -> Security
  3. Set all zones (Internet, Local intranet, Trusted sites, Restricted sites) to the same protected mode, enabled or disabled should not matter.

Finally, set Zoom level to 100% by right clicking on the gear located at the top right corner and enabling the status-bar. Default zoom level is now displayed at the lower right.

Node/Express file upload

Here is an easier way that worked for me:

const express = require('express');
var app = express();
var fs = require('fs');

app.post('/upload', async function(req, res) {

  var file = JSON.parse(JSON.stringify(req.files))

  var file_name = file.file.name

  //if you want just the buffer format you can use it
  var buffer = new Buffer.from(file.file.data.data)

  //uncomment await if you want to do stuff after the file is created

  /*await*/
  fs.writeFile(file_name, buffer, async(err) => {

    console.log("Successfully Written to File.");


    // do what you want with the file it is in (__dirname + "/" + file_name)

    console.log("end  :  " + new Date())

    console.log(result_stt + "")

    fs.unlink(__dirname + "/" + file_name, () => {})
    res.send(result_stt)
  });


});

How to unlock android phone through ADB

Another way just for your information.

Use an USB OTG cable and connect with an USB mouse, you can touch the screen by clicking your mouse !

How do emulators work and how are they written?

Yes, you have to interpret the whole binary machine code mess "by hand". Not only that, most of the time you also have to simulate some exotic hardware that doesn't have an equivalent on the target machine.

The simple approach is to interpret the instructions one-by-one. That works well, but it's slow. A faster approach is recompilation - translating the source machine code to target machine code. This is more complicated, as most instructions will not map one-to-one. Instead you will have to make elaborate work-arounds that involve additional code. But in the end it's much faster. Most modern emulators do this.

How to create web service (server & Client) in Visual Studio 2012?

  1. Create a new empty Asp.NET Web Application.
  2. Solution Explorer right click on the project root.
  3. Choose the menu item Add-> Web Service

how to pass value from one php page to another using session

Solution using just POST - no $_SESSION

page1.php

<form action="page2.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>

page2.php

<?php
    // this page outputs the contents of the textarea if posted
    $textarea1 = ""; // set var to avoid errors
    if(isset($_POST['textarea1'])){
        $textarea1 = $_POST['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

Solution using $_SESSION and POST

page1.php

<?php

    session_start(); // needs to be before anything else on page to use $_SESSION
    $textarea1 = "";
    if(isset($_POST['textarea1'])){
        $_SESSION['textarea1'] = $_POST['textarea1'];
    }

?>


<form action="page1.php" method="post">
    <textarea name="textarea1" id="textarea1"></textarea><br />
    <input type="submit" value="submit" />
</form>
<br /><br />
<a href="page2.php">Go to page2</a>

page2.php

<?php
    session_start(); // needs to be before anything else on page to use $_SESSION
    // this page outputs the textarea1 from the session IF it exists
    $textarea1 = ""; // set var to avoid errors
    if(isset($_SESSION['textarea1'])){
        $textarea1 = $_SESSION['textarea1']
    }
?>
<textarea><?php echo $textarea1;?></textarea>

WARNING!!! - This contains no validation!!!

Should I Dispose() DataSet and DataTable?

Datasets implement IDisposable thorough MarshalByValueComponent, which implements IDisposable. Since datasets are managed there is no real benefit to calling dispose.

How do the major C# DI/IoC frameworks compare?

I came across another performance comparison(latest update 10 April 2014). It compares the following:

Here is a quick summary from the post:

Conclusion

Ninject is definitely the slowest container.

MEF, LinFu and Spring.NET are faster than Ninject, but still pretty slow. AutoFac, Catel and Windsor come next, followed by StructureMap, Unity and LightCore. A disadvantage of Spring.NET is, that can only be configured with XML.

SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try!

Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.

You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.

Some informtion about Common Service Selector Library from the site:

The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.

Update

13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.

04.11.2011: "added Simple Injector, the performance is the best of all contestants".

Easiest way to ignore blank lines when reading a file in Python

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

How to hide only the Close (x) button?

If you really want to hide it, as in "not visible", then you will probably have to create a borderless form and draw the caption components yourself. VisualStyles library has the Windows Elements available. You would also have to add back in the functionality of re-sizing the form or moving the form by grabbing the caption bar. Not to mention the system menu in the corner.

In most cases, it's hard to justify having the "close" button not available, especially when you want a modal form with minimizing capabilities. Minimizing a modal form really makes no sense.

How to import a CSS file in a React Component

The following imports an external CSS file in a React component and outputs the CSS rules in the <head /> of the website.

  1. Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. In webpack.config.js:
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. In a component file:
import './path/to/file.css';

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

png has a wider color pallete than gif and gif is properitary while png is not. gif can do animations, what normal-png cannot. png-transparency is only supported by browser roughly more recent than IE6, but there is a Javascript fix for that problem. Both support alpha transparency. In general I would say that you should use png for most webgraphics while using jpeg for photos, screenshots, or similiar because png compression does not work too good on thoose.

How to fix "Only one expression can be specified in the select list when the subquery is not introduced with EXISTS" error?

Try this one -

"SELECT 
       ID, Salt, password, BannedEndDate
     , (
          SELECT COUNT(1)
          FROM dbo.LoginFails l
          WHERE l.UserName = u.UserName
               AND IP = '" + Request.ServerVariables["REMOTE_ADDR"] + "'
      ) AS cnt
FROM dbo.Users u
WHERE u.UserName = '" + LoginModel.Username + "'"

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

The answer may sound silly, but after wasting hours of time, this is how I got it to work

mysql -u root -p

I got the error message

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Even though I was typing the correct password(the temporary password you get when you first install mysql)

I got it right when I typed in the password when the password prompt was blinking

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

How do you cache an image in Javascript

There are a few things you can look at:

Pre-loading your images
Setting a cache time in an .htaccess file
File size of images and base64 encoding them.

Preloading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.

How to convert An NSInteger to an int?

Commonly used in UIsegmentedControl, "error" appear when compiling in 64bits instead of 32bits, easy way for not pass it to a new variable is to use this tips, add (int):

[_monChiffre setUnite:(int)[_valUnites selectedSegmentIndex]];

instead of :

[_monChiffre setUnite:[_valUnites selectedSegmentIndex]];

git replacing LF with CRLF

A GitHub's article on line endings is commonly mentioned when talking about this topic.

My personal experience with using the often recommended core.autocrlf config setting was very mixed.

I'm using Windows with Cygwin, dealing with both Windows and UNIX projects at different times. Even my Windows projects sometimes use bash shell scripts, which require UNIX (LF) line endings.

Using GitHub's recommended core.autocrlf setting for Windows, if I check out a UNIX project (which does work perfectly on Cygwin - or maybe I'm contributing to a project that I use on my Linux server), the text files are checked out with Windows (CRLF) line endings, creating problems.

Basically, for a mixed environment like I have, setting the global core.autocrlf to any of the options will not work well in some cases. This option might be set on a local (repository) git config, but even that wouldn't be good enough for a project that contains both Windows- and UNIX-related stuff (e.g. I have a Windows project with some bash utility scripts).

The best choice I've found is to create per-repository .gitattributes files. The GitHub article mentions it.
Example from that article:

# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto

# Explicitly declare text files you want to always be normalized and converted
# to native line endings on checkout.
*.c text
*.h text

# Declare files that will always have CRLF line endings on checkout.
*.sln text eol=crlf

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

In one of my project's repository:

* text=auto

*.txt         text eol=lf
*.xml         text eol=lf
*.json        text eol=lf
*.properties  text eol=lf
*.conf        text eol=lf

*.awk  text eol=lf
*.sed  text eol=lf
*.sh   text eol=lf

*.png  binary
*.jpg  binary

*.p12  binary

It's a bit more things to set up, but do it once per project, and any contributor on any OS should have no troubles with line endings when working with this project.

collapse cell in jupyter notebook

UPDATE:

The newer jupyter-lab is a more modern and feature-rich interface which supports cell folding by default. See @intsco's answer below

Original answer:

The jupyter contrib nbextensions Python package contains a code-folding extension that can be enabled within the notebook. Follow the link (Github) for documentation.

To install using command line:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user

To make life easier in managing them, I'd also recommend the jupyter nbextensions configurator package. This provides an extra tab in your Notebook interface from where you can easily (de)activate all installed extensions.

Installation:

pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

Marker content (infoWindow) Google Maps

We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:

Create a new function with your information for the infoWindow in it:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open(map, marker);
            });
        }

Then call the function with the array ID and the marker you want to create:

addInfoWindow(marker, hotels[i][3]);

Calling async method on button click

use below code

 Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));

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

I corrected my path variable but command prompt need to Restart otherwise, it won't be able to verify the change to the path variable. May be helpful for someone like me. so "restart command prompt"

Replace a string in shell script using a variable

Not specific to the question, but for folks who need the same kind of functionality expanded for clarity from previous answers:

# create some variables
str="someFileName.foo"
find=".foo"
replace=".bar"
# notice the the str isn't prefixed with $
#    this is just how this feature works :/
result=${str//$find/$replace}
echo $result    
# result is: someFileName.bar

str="someFileName.sally"
find=".foo"
replace=".bar"
result=${str//$find/$replace}
echo $result    
# result is: someFileName.sally because ".foo" was not found

How can I display the current branch and folder path in terminal?

To expand on the existing great answers, a very simple way to get a great looking terminal is to use the open source Dotfiles project.

https://github.com/mathiasbynens/dotfiles


enter image description here


Installation is dead simple on OSX and Linux. Run the following command in Terminal.

git clone https://github.com/mathiasbynens/dotfiles.git && cd dotfiles && source bootstrap.sh

This is going to:

  1. Git clone the repo.
  2. cd into the folder.
  3. Run the installation bash script.

How to copy and edit files in Android shell?

Android supports the dd command.

dd if=/path/file of=/path/file

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

Generating (pseudo)random alpha-numeric strings

If you want a very easy way to do this, you can lean on existing PHP functions. This is the code I use:

substr( sha1( time() ), 0, 15 )

time() gives you the current time in seconds since epoch, sha1() encrypts it to a string of 0-9a-f, and substr() lets you choose a length. You don't have to start at character 0, and whatever the difference is between the two numbers will be the length of the string.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

php execute a background process

Assuming this is running on a Linux machine, I've always handled it like this:

exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

This launches the command $cmd, redirects the command output to $outputfile, and writes the process id to $pidfile.

That lets you easily monitor what the process is doing and if it's still running.

function isRunning($pid){
    try{
        $result = shell_exec(sprintf("ps %d", $pid));
        if( count(preg_split("/\n/", $result)) > 2){
            return true;
        }
    }catch(Exception $e){}

    return false;
}

How to copy Java Collections list

Every other Object not --> you need to iterate and do a copy by yourself.

To avoid this implement Cloneable.

public class User implements Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    private String user;
    private String password;
    ...

    @Override
    public Object clone() {
        Object o = null;
        try {
          o = super.clone();
        } catch(CloneNotSupportedException e) {
        }
        return o;
     }
 }

....

  public static void main(String[] args) {

      List<User> userList1 = new ArrayList<User>();

      User user1 = new User();
      user1.setUser("User1");
      user1.setPassword("pass1");
      ...

      User user2 = new User();
      user2.setUser("User2");
      user2.setPassword("pass2");
      ...

      userList1 .add(user1);
      userList1 .add(user2);

      List<User> userList2 = new ArrayList<User>();


      for(User u: userList1){
          u.add((User)u.clone());
      }

      //With this you can avoid 
      /*
        for(User u: userList1){
            User tmp = new User();
            tmp.setUser(u.getUser);
            tmp.setPassword(u.getPassword);
            ...
            u.add(tmp);               
        }
       */

  }

What does the function then() mean in JavaScript?

The traditional way to deal with asynchronous calls in JavaScript has been with callbacks. Say we had to make three calls to the server, one after the other, to set up our application. With callbacks, the code might look something like the following (assuming a xhrGET function to make the server call):

// Fetch some server configuration
    xhrGET('/api/server-config', function(config) {
        // Fetch the user information, if he's logged in
        xhrGET('/api/' + config.USER_END_POINT, function(user) {
            // Fetch the items for the user
            xhrGET('/api/' + user.id + '/items', function(items) {
                // Actually display the items here
            });
        });
    });

In this example, we first fetch the server configuration. Then based on that, we fetch information about the current user, and then finally get the list of items for the current user. Each xhrGET call takes a callback function that is executed when the server responds.

Now of course the more levels of nesting we have, the harder the code is to read, debug, maintain, upgrade, and basically work with. This is generally known as callback hell. Also, if we needed to handle errors, we need to possibly pass in another function to each xhrGET call to tell it what it needs to do in case of an error. If we wanted to have just one common error handler, that is not possible.

The Promise API was designed to solve this nesting problem and the problem of error handling.

The Promise API proposes the following:

  1. Each asynchronous task will return a promise object.
  2. Each promise object will have a then function that can take two arguments, a success handler and an error handler.
  3. The success or the error handler in the then function will be called only once, after the asynchronous task finishes.
  4. The then function will also return a promise, to allow chaining multiple calls.
  5. Each handler (success or error) can return a value, which will be passed to the next function as an argument, in the chain of promises.
  6. If a handler returns a promise (makes another asynchronous request), then the next handler (success or error) will be called only after that request is finished.

So the previous example code might translate to something like the following, using promises and the $http service(in AngularJs):

$http.get('/api/server-config').then(
    function(configResponse) {
        return $http.get('/api/' + configResponse.data.USER_END_POINT);
    }
).then(
    function(userResponse) {
        return $http.get('/api/' + userResponse.data.id + '/items');
    }
).then(
    function(itemResponse) {
        // Display items here
    }, 
    function(error) {
        // Common error handling
    }
);

Propagating Success and Error

Chaining promises is a very powerful technique that allows us to accomplish a lot of functionality, like having a service make a server call, do some postprocessing of the data, and then return the processed data to the controller. But when we work with promise chains, there are a few things we need to keep in mind.

Consider the following hypothetical promise chain with three promises, P1, P2, and P3. Each promise has a success handler and an error handler, so S1 and E1 for P1, S2 and E2 for P2, and S3 and E3 for P3:

xhrCall()
  .then(S1, E1) //P1
  .then(S2, E2) //P2
  .then(S3, E3) //P3

In the normal flow of things, where there are no errors, the application would flow through S1, S2, and finally, S3. But in real life, things are never that smooth. P1 might encounter an error, or P2 might encounter an error, triggering E1 or E2.

Consider the following cases:

• We receive a successful response from the server in P1, but the data returned is not correct, or there is no data available on the server (think empty array). In such a case, for the next promise P2, it should trigger the error handler E2.

• We receive an error for promise P2, triggering E2. But inside the handler, we have data from the cache, ensuring that the application can load as normal. In that case, we might want to ensure that after E2, S3 is called.

So each time we write a success or an error handler, we need to make a call—given our current function, is this promise a success or a failure for the next handler in the promise chain?

If we want to trigger the success handler for the next promise in the chain, we can just return a value from the success or the error handler

If, on the other hand, we want to trigger the error handler for the next promise in the chain, we can do that using a deferred object and calling its reject() method

Now What is deferred object?

Deferred objects in jQuery represents a unit of work that will be completed later, typically asynchronously. Once the unit of work completes, the deferred object can be set to resolved or failed.

A deferred object contains a promise object. Via the promise object you can specify what is to happen when the unit of work completes. You do so by setting callback functions on the promise object.

Deferred objects in Jquery : https://api.jquery.com/jquery.deferred/

Deferred objects in AngularJs : https://docs.angularjs.org/api/ng/service/$q

Permissions error when connecting to EC2 via SSH on Mac OSx

I had the same problem using the AWS Toolkit for Eclipse. I created the Getting Started instance OK and opened a shell. However, the user was set to ec2-user. I used the Open Shell As... command and set the user to root. Then it worked.

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

I had the same problem with Versions displaying the same message. I simply right clicked the offending files and selected 'Revert...' from the right-click menu and all was good.

Basically Versions (actually Subversion) thinks you still want to add the file, but it cannot find it because you deleted it in the file system. The Revert option tells Subversion to forget about adding it.

Resource leak: 'in' is never closed

The Scanner should be closed. It is a good practice to close Readers, Streams...and this kind of objects to free up resources and aovid memory leaks; and doing so in a finally block to make sure that they are closed up even if an exception occurs while handling those objects.

Typescript: Type 'string | undefined' is not assignable to type 'string'

You can now use the non-null assertion operator that is here exactly for your use case.

It tells TypeScript that even though something looks like it could be null, it can trust you that it's not:

let name1:string = person.name!; 
//                            ^ note the exclamation mark here  

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

Set new id with jQuery

I just wrote a quick plugin to run a test using your same snippet and it works fine

$.fn.test = function() {
      return this.each(function(){
        var new_id = 5;
        $(this).attr('id',   this.id + '_' + new_id);
        $(this).attr('name', this.name + '_' + new_id);
        $(this).attr('value', 'test');
      });
    };

$(document).ready(function() {
    $('#field_id').test()
});

<body>
  <div id="container">

  <input type="text" name="field_name" id="field_id" value="meh" />
  </div>
</body>

So I can only presume something else is going on in your code. Can you provide some more details?

Nested iframes, AKA Iframe Inception

You probably have a timing issue. Your document.ready commend is probably firing before the the second iFrame is loaded. You dont have enough info to help much further- but let us know if that seems like the possible issue.

'AND' vs '&&' as operator

Let me explain the difference between “and” - “&&” - "&".

"&&" and "and" both are logical AND operations and they do the same thing, but the operator precedence is different.

The precedence (priority) of an operator specifies how "tightly" it binds two expressions together. For example, in the expression 1 + 5 * 3, the answer is 16 and not 18 because the multiplication ("*") operator has a higher precedence than the addition ("+") operator.

Mixing them together in single operation, could give you unexpected results in some cases I recommend always using &&, but that's your choice.


On the other hand "&" is a bitwise AND operation. It's used for the evaluation and manipulation of specific bits within the integer value.

Example if you do (14 & 7) the result would be 6.

7   = 0111
14  = 1110
------------
    = 0110 == 6

Make Adobe fonts work with CSS3 @font-face in IE9

Try this, add this lines in the web.config.

<system.webServer>
  <staticContent>
     <mimeMap fileExtension=".woff" mimeType="application/octet-stream" />
  </staticContent>
</system.webServer>

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I resolved all of my issues by adding this into project.properties

cordova.system.library.7=com.android.support:appcompat-v7:27.1.0

How to measure height, width and distance of object using camera?

First of all i will say Nice Thaught to develop such app.

Now i am not sure about it, but if you can able to get the face-detection like thing for any object in android camera so with help of that you can achieve that things.

Well i am not sure about it but still have give some view so you can get idea of it.

All the Best. :))

How to find SQL Server running port?

This is the one that works for me:

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL 

What is the difference between supervised learning and unsupervised learning?

I'll try to keep it simple.

Supervised Learning: In this technique of learning, we are given a data set and the system already knows the correct output of the data set. So here, our system learns by predicting a value of its own. Then, it does an accuracy check by using a cost function to check how close its prediction was to the actual output.

Unsupervised Learning: In this approach, we have little or no knowledge of what our result would be. So instead, we derive structure from the data where we don't know effect of variable. We make structure by clustering the data based on relationship among the variable in data. Here, we don't have a feedback based on our prediction.

How do I upgrade to Python 3.6 with conda?

In the past, I have found it quite difficult to try to upgrade in-place.

Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda to create environments, this may be destructive because conda creates environments with hard-links inside your Anaconda/envs directory.

So if you use environments, you may first want to export your environments. After activating your environment, do something like:

conda env export > environment.yml

After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):

$ rm -rf ~/anaconda3/

and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:

$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh 

(see here for a more recent one),

and then executing it:

$ bash Anaconda3-4.3.0-Linux-x86_64.sh 

Authorize attribute in ASP.NET MVC

One advantage is that you are compiling access into the application, so it cannot accidentally be changed by someone modifying the Web.config.

This may not be an advantage to you, and might be a disadvantage. But for some kinds of access, it may be preferrable.

Plus, I find that authorization information in the Web.config pollutes it, and makes it harder to find things. So in some ways its preference, in others there is no other way to do it.

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

What is the difference between an IntentService and a Service?

Service is a base class of service implementation. Service runs on the application's main thread which may reduce the application performance. Thus, IntentService, which is a direct subclass of Service is available to make things easier.

The IntentService is used to perform a certain task in the background. Once done, the instance of IntentService terminates itself automatically. Examples for its usage would be to download a certain resource from the Internet.

Differences

  1. Service class uses the application's main thread, while IntentService creates a worker thread and uses that thread to run the service.
  2. IntentService creates a queue that passes one intent at a time to onHandleIntent(). Thus, implementing a multi-thread should be made by extending Service class directly. Service class needs a manual stop using stopSelf(). Meanwhile, IntentService automatically stops itself when it finishes execution.
  3. IntentService implements onBind() that returns null. This means that the IntentService can not be bound by default.
  4. IntentService implements onStartCommand() that sends Intent to queue and to onHandleIntent().

In brief, there are only two things to do to use IntentService. Firstly, to implement the constructor. And secondly, to implement onHandleIntent(). For other callback methods, the super is needed to be called so that it can be tracked properly.

What is System, out, println in System.out.println() in Java

The first answer you posted (System is a built-in class...) is pretty spot on.

You can add that the System class contains large portions which are native and that is set up by the JVM during startup, like connecting the System.out printstream to the native output stream associated with the "standard out" (console).

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

Using NULL in C++?

In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:

Should I use NULL or 0?

In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.

If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

LINQ's Distinct() on a particular property

What if I want to obtain a distinct list based on one or more properties?

Simple! You want to group them and pick a winner out of the group.

List<Person> distinctPeople = allPeople
  .GroupBy(p => p.PersonId)
  .Select(g => g.First())
  .ToList();

If you want to define groups on multiple properties, here's how:

List<Person> distinctPeople = allPeople
  .GroupBy(p => new {p.PersonId, p.FavoriteColor} )
  .Select(g => g.First())
  .ToList();

How do I fit an image (img) inside a div and keep the aspect ratio?

You will need some JavaScript to prevent cropping if you don't know the dimension of the image at the time you're writing the css.

HTML & JavaScript

<div id="container">
    <img src="something.jpg" alt="" />
</div>

<script type="text/javascript">
(function() {

var img = document.getElementById('container').firstChild;
img.onload = function() {
    if(img.height > img.width) {
        img.height = '100%';
        img.width = 'auto';
    }
};

}());
</script>

CSS

#container {
   width: 48px;
   height: 48px;
}

#container img {
   width: 100%;
}

If you use a JavaScript Library you might want to take advantage of it.

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Is there a way to compile node.js source files?

Node.js runs on top of the V8 Javascript engine, which itself optimizes performance by compiling javascript code into native code... so no reason really for compiling then, is there?

https://developers.google.com/v8/design#mach_code

Converting time stamps in excel to dates

The answer of @NeplatnyUdaj is right but consider that Excel want the function name in the set language, in my case German. Then you need to use "DATUM" instead of "DATE":

=(((COLUMN_ID_HERE/60)/60)/24)+DATUM(1970,1,1)

How can I run a PHP script inside a HTML file?

You can't run PHP in an html page ending with .html. Unless the page is actually PHP and the extension was changed with .htaccess from .php to .html

What you mean is:

index.html
<html>
...
<?php echo "Hello world";?> //This is impossible


index.php //The file extension can be changed using htaccess, ex: its type stays php but will be visible to visitors as index.html

<?php echo "Hello world";?>

If '<selector>' is an Angular component, then verify that it is part of this module

I am using Angular v11 and was facing this error while trying to lazy load a component (await import('./my-component.component')) and even if import and export were correctly set.

I finally figured out that the solution was deleting the separate dedicated module's file and move the module content inside the component file itself.

rm -r my-component.module.ts

and add module inside my-component.ts (same file)

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.page.html',
  styleUrls: ['./my-component.page.scss'],
})
export class MyComponent {
}

@NgModule({
  imports: [CommonModule],
  declarations: [MyComponent],
})
export class MyComponentModule {}

Equivalent of Oracle's RowID in SQL Server

From the Oracle docs

ROWID Pseudocolumn

For each row in the database, the ROWID pseudocolumn returns the address of the row. Oracle Database rowid values contain information necessary to locate a row:

  • The data object number of the object
  • The data block in the datafile in which the row resides
  • The position of the row in the data block (first row is 0)
  • The datafile in which the row resides (first file is 1). The file number is relative to the tablespace.

The closest equivalent to this in SQL Server is the rid which has three components File:Page:Slot.

In SQL Server 2008 it is possible to use the undocumented and unsupported %%physloc%% virtual column to see this. This returns a binary(8) value with the Page ID in the first four bytes, then 2 bytes for File ID, followed by 2 bytes for the slot location on the page.

The scalar function sys.fn_PhysLocFormatter or the sys.fn_PhysLocCracker TVF can be used to convert this into a more readable form

CREATE TABLE T(X INT);

INSERT INTO T VALUES(1),(2)

SELECT %%physloc%% AS [%%physloc%%],
       sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot]
FROM T

Example Output

+--------------------+----------------+
|    %%physloc%%     | File:Page:Slot |
+--------------------+----------------+
| 0x2926020001000000 | (1:140841:0)   |
| 0x2926020001000100 | (1:140841:1)   |
+--------------------+----------------+

Note that this is not leveraged by the query processor. Whilst it is possible to use this in a WHERE clause

SELECT *
FROM T
WHERE %%physloc%% = 0x2926020001000100 

SQL Server will not directly seek to the specified row. Instead it will do a full table scan, evaluate %%physloc%% for each row and return the one that matches (if any do).

To reverse the process carried out by the 2 previously mentioned functions and get the binary(8) value corresponding to known File,Page,Slot values the below can be used.

DECLARE @FileId int = 1,
        @PageId int = 338,
        @Slot   int = 3

SELECT CAST(REVERSE(CAST(@PageId AS BINARY(4))) AS BINARY(4)) +
       CAST(REVERSE(CAST(@FileId AS BINARY(2))) AS BINARY(2)) +
       CAST(REVERSE(CAST(@Slot   AS BINARY(2))) AS BINARY(2))

git - Your branch is ahead of 'origin/master' by 1 commit

git reset HEAD^ --soft (Save your changes, back to last commit)

git reset HEAD^ --hard (Discard changes, back to last commit)

How to display image from URL on Android

I tried this code working for me,get image directly from url

      private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;
      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
              e.printStackTrace();
          }
          return mIcon11;
      }

      protected void onPostExecute(Bitmap result) {
          bmImage.setImageBitmap(result);
      }
    }

use inside onCreate() method

new DownloadImageTask((ImageView) findViewById(R.id.image)) .execute("http://scoopak.com/wp-content/uploads/2013/06/free-hd-natural-wallpapers-download-for-pc.jpg");

How do I search for files in Visual Studio Code?

Other answers don't mention this command is named workbench.action.quickOpen.

You can use this to search the Keyboard Shortcuts menu located in Preferences.

On MacOS the default keybinding is cmd ? + P.

(Coming from Sublime Text, I always change this to cmd ? + T)

403 Forbidden You don't have permission to access /folder-name/ on this server

if permission issue and you have ssh access in root folder

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

will resolve your error

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime

What is the difference between Cloud, Grid and Cluster?

Cloud: is simply an aggregate of computing power. You can think of the entire "cloud" as single server, for your purposes. It's conceptually much like an old school mainframe where you could submit your jobs to and have it return the result, except that nowadays the concept is applied more widely. (I.e. not just raw computing, also entire services, or storage ...)

Grid: a grid is simply many computers which together might solve a given problem/crunch data. The fundamental difference between a grid and a cluster is that in a grid each node is relatively independent of others; problems are solved in a divide and conquer fashion.

Cluster: conceptually it is essentially smashing up many machines to make a really big & powerful one. This is a much more difficult architecture than cloud or grid to get right because you have to orchestrate all nodes to work together, and provide consistency of things such as cache, memory, and not to mention clocks. Of course clouds have much the same problem, but unlike clusters clouds are not conceptually one big machine, so the entire architecture doesn't have to treat it as such. You can for instance not allocate the full capacity of your data center to a single request, whereas that is kind of the point of a cluster: to be able to throw 100% of the oomph at a single problem.

Is it possible to install both 32bit and 64bit Java on Windows 7?

As stated by pnt you can have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

Taking it further from there: Here's how it might be possible to set any runtime parameters for each of those installations:

You can run javacpl.exe or javacpl.cpl of the respective Java-version itself (bin-folder). The specific control panel opens fine. Adding parameters there is possible.

Check if an element contains a class in JavaScript?

I know there a lot of answers but most of these are for additional functions and additional classes. This is the one I personally use; much cleaner and much less lines of code!

if( document.body.className.match('category-page') ) { 
  console.log('yes');
}

python tuple to dict

Here are couple ways of doing it:

>>> t = ((1, 'a'), (2, 'b'))

>>> # using reversed function
>>> dict(reversed(i) for i in t)
{'a': 1, 'b': 2}

>>> # using slice operator
>>> dict(i[::-1] for i in t)
{'a': 1, 'b': 2}

Sort rows in data.table in decreasing order on string key `order(-x,v)` gives error on data.table 1.9.4 or earlier

DT[order(-x)] works as expected. I have data.table version 1.9.4. Maybe this was fixed in a recent version.
Also, I suggest the setorder(DT, -x) syntax in keeping with the set* commands like setnames, setkey

How to calculate the sentence similarity using word2vec model of gensim with python

This is actually a pretty challenging problem that you are asking. Computing sentence similarity requires building a grammatical model of the sentence, understanding equivalent structures (e.g. "he walked to the store yesterday" and "yesterday, he walked to the store"), finding similarity not just in the pronouns and verbs but also in the proper nouns, finding statistical co-occurences / relationships in lots of real textual examples, etc.

The simplest thing you could try -- though I don't know how well this would perform and it would certainly not give you the optimal results -- would be to first remove all "stop" words (words like "the", "an", etc. that don't add much meaning to the sentence) and then run word2vec on the words in both sentences, sum up the vectors in the one sentence, sum up the vectors in the other sentence, and then find the difference between the sums. By summing them up instead of doing a word-wise difference, you'll at least not be subject to word order. That being said, this will fail in lots of ways and isn't a good solution by any means (though good solutions to this problem almost always involve some amount of NLP, machine learning, and other cleverness).

So, short answer is, no, there's no easy way to do this (at least not to do it well).

How to insert image in mysql database(table)?

You should use LOAD_FILE like so:

LOAD_FILE('/some/path/image.png')

Printing long int value in C

Use printf("%ld",a);

Have a look at format specifiers for printf

Find the PID of a process that uses a port on Windows

Command:

netstat -aon | findstr 4723

Output:

TCP    0.0.0.0:4723           0.0.0.0:0                LISTENING       10396

Now cut the process ID, "10396", using the for command in Windows.

Command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

10396

If you want to cut the 4th number of the value means "LISTENING" then command in Windows.

Command:

for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

LISTENING

how to detect search engine bots with php?

100% Working Bot detector. It is working on my website successfully.

function isBotDetected() {

    if ( preg_match('/abacho|accona|AddThis|AdsBot|ahoy|AhrefsBot|AISearchBot|alexa|altavista|anthill|appie|applebot|arale|araneo|AraybOt|ariadne|arks|aspseek|ATN_Worldwide|Atomz|baiduspider|baidu|bbot|bingbot|bing|Bjaaland|BlackWidow|BotLink|bot|boxseabot|bspider|calif|CCBot|ChinaClaw|christcrawler|CMC\/0\.01|combine|confuzzledbot|contaxe|CoolBot|cosmos|crawler|crawlpaper|crawl|curl|cusco|cyberspyder|cydralspider|dataprovider|digger|DIIbot|DotBot|downloadexpress|DragonBot|DuckDuckBot|dwcp|EasouSpider|ebiness|ecollector|elfinbot|esculapio|ESI|esther|eStyle|Ezooms|facebookexternalhit|facebook|facebot|fastcrawler|FatBot|FDSE|FELIX IDE|fetch|fido|find|Firefly|fouineur|Freecrawl|froogle|gammaSpider|gazz|gcreep|geona|Getterrobo-Plus|get|girafabot|golem|googlebot|\-google|grabber|GrabNet|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|HTTrack|ia_archiver|iajabot|IDBot|Informant|InfoSeek|InfoSpiders|INGRID\/0\.1|inktomi|inspectorwww|Internet Cruiser Robot|irobot|Iron33|JBot|jcrawler|Jeeves|jobo|KDD\-Explorer|KIT\-Fireball|ko_yappo_robot|label\-grabber|larbin|legs|libwww-perl|linkedin|Linkidator|linkwalker|Lockon|logo_gif_crawler|Lycos|m2e|majesticsEO|marvin|mattie|mediafox|mediapartners|MerzScope|MindCrawler|MJ12bot|mod_pagespeed|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|NationalDirectory|naverbot|NEC\-MeshExplorer|NetcraftSurveyAgent|NetScoop|NetSeer|newscan\-online|nil|none|Nutch|ObjectsSearch|Occam|openstat.ru\/Bot|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pingdom|pinterest|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|rambler|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Scrubby|Search\-AU|searchprocess|search|SemrushBot|Senrigan|seznambot|Shagseeker|sharp\-info\-agent|sift|SimBot|Site Valet|SiteSucker|skymob|SLCrawler\/2\.0|slurp|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|spider|suke|tach_bw|TechBOT|TechnoratiSnoop|templeton|teoma|titin|topiclink|twitterbot|twitter|UdmSearch|Ukonline|UnwindFetchor|URL_Spider_SQL|urlck|urlresolver|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|wapspider|WebBandit\/1\.0|webcatcher|WebCopier|WebFindBot|WebLeacher|WebMechanic|WebMoose|webquest|webreaper|webspider|webs|WebWalker|WebZip|wget|whowhere|winona|wlm|WOLP|woriobot|WWWC|XGET|xing|yahoo|YandexBot|YandexMobileBot|yandex|yeti|Zeus/i', $_SERVER['HTTP_USER_AGENT'])
    ) {
        return true; // 'Above given bots detected'
    }

    return false;

} // End :: isBotDetected()

The entity cannot be constructed in a LINQ to Entities query

There is another way that I found works, you have to build a class that derives from your Product class and use that. For instance:

public class PseudoProduct : Product { }

public IQueryable<Product> GetProducts(int categoryID)
{
    return from p in db.Products
           where p.CategoryID== categoryID
           select new PseudoProduct() { Name = p.Name};
}

Not sure if this is "allowed", but it works.

Create an ISO date object in javascript

This worked for me:

_x000D_
_x000D_
var start = new Date("2020-10-15T00:00:00.000+0000");
 //or
start = new date("2020-10-15T00:00:00.000Z");

collection.find({
    start_date:{
        $gte: start
    }
})...etc
_x000D_
_x000D_
_x000D_ new Date(2020,9,15,0,0,0,0) may lead to wrong date: i mean non ISO format (remember javascript count months from 0 to 11 so it's 9 for october)

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

complex if statement in python

I think the most pythonic way to do this for me, will be

elif var in [80,443] + range(1024,65535):

although it could take a little time and memory (it's generating numbers from 1024 to 65535). If there's a problem with that, I'll do:

elif 1024 <= var <= 65535 or var in [80,443]:

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Save it.

Error: Can't set headers after they are sent to the client

In my case, In a loop, I put res.render() so might have been tried to call multiple times.

PHP: Inserting Values from the Form into MySQL

<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");

?>



<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
 //$("form").submit(function(e){

     $("#btn1").click(function(e){
     e.preventDefault();
    // alert('here');
        $(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');

    });
    //}
});
</script>

</head>

<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file"  name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>

<tr><td>Address:</td><td><textarea  cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input  type="number"  maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio"  name="r1" value="Male" checked="checked"/>Male<input type="radio"  name="r1" value="feale"/>Female</td></tr>
<tr><td><input  id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){


move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);

                     $fname = $_FILES['e5']['name'][$key];
                     $imgarryimp[]=$fname;
                     //echo $fname;

                     if(strlen($fname)>0)
                      {
                         $img = $fname;
                      }
                      $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
}
exit;





                      // echo $values;exit;
                      //foreach($_POST['e1'] as $row) 
    //{ 

    $d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";

       if($con->query($d)==TRUE)
         {
         echo "Yoy Data Save Successfully!!!";
         }
    //}
    //exit;


}
?>

</form>

<table>
<?php 
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>

</body>
</html>

Get all mysql selected rows into an array

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

how to make jni.h be found?

For me it was a simple matter of being sure to include the JDK installation (I'd only had the JRE). My R CMD javareconf output was looking like:

Java interpreter : /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
Java version     : 1.8.0_191
Java home path   : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java compiler    : not present
Java headers gen.:
Java archive tool:

trying to compile and link a JNI program
detected JNI cpp flags    :
detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG      -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
conftest.c:1:17: fatal error: jni.h: No such file or directory
compilation terminated.
/usr/lib/R/etc/Makeconf:159: recipe for target 'conftest.o' failed
make: *** [conftest.o] Error 1
Unable to compile a JNI program


JAVA_HOME        : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java library path:
JNI cpp flags    :
JNI linker flags :
Updating Java configuration in /usr/lib/R
Done.

And indeed there was no include file in my $JAVA_HOME. Very simple remedy:

sudo apt-get install openjdk-8-jre openjdk-8-jdk

(note that this is specifically intended to install the openJDK and not the one from Oracle)

Afterwards all is well:

Java interpreter : /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
Java version     : 1.8.0_191
Java home path   : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java compiler    : /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/javac
Java headers gen.: /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/javah
Java archive tool: /usr/lib/jvm/java-8-openjdk-amd64/jre/../bin/jar

trying to compile and link a JNI program
detected JNI cpp flags    : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux
detected JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
gcc -std=gnu99 -I/usr/share/R/include -DNDEBUG -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include -I/usr/lib/jvm/java-8-openjdk-amd64/jre/../include/linux     -fpic  -g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g  -c conftest.c -o conftest.o
g++ -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o conftest.so conftest.o -L/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/amd64/server -ljvm -L/usr/lib/R/lib -lR


JAVA_HOME        : /usr/lib/jvm/java-8-openjdk-amd64/jre
Java library path: $(JAVA_HOME)/lib/amd64/server
JNI cpp flags    : -I$(JAVA_HOME)/../include -I$(JAVA_HOME)/../include/linux
JNI linker flags : -L$(JAVA_HOME)/lib/amd64/server -ljvm
Updating Java configuration in /usr/lib/R
Done.

Is Xamarin free in Visual Studio 2015?

Visual studio community edition is bundled with xamarin and which is free as well.

Horizontal scroll css?

Just set your width to auto:

#myWorkContent{
    width: auto;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}

This way your div can be as wide as possible, so you can add as many kitty images as possible ;3

Your div's width will expand based on the child elements it contains.

jsFiddle

Get git branch name in Jenkins Pipeline/Jenkinsfile

Use multibranch pipeline job type, not the plain pipeline job type. The multibranch pipeline jobs do posess the environment variable env.BRANCH_NAME which describes the branch.

In my script..

stage('Build') {
    node {
        echo 'Pulling...' + env.BRANCH_NAME
        checkout scm
        
    }
}

Yields...

Pulling...master

What should I do when 'svn cleanup' fails?

The latest verion (I'm using 1.9.5) solve this problem by adding an option of "Break locks" on the clean up menu. Just make sure this check box is selected when doing clean up.

eclean up window

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

Edit: isMounted is deprecated and will probably be removed in later versions of React. See this and this, isMounted is an Antipattern.


As the warning states, you are calling this.setState on an a component that was mounted but since then has been unmounted.

To make sure your code is safe, you can wrap it in

if (this.isMounted()) {
    this.setState({'time': remainTimeInfo});
}

to ensure that the component is still mounted.

Detecting endianness programmatically in a C++ program

How about this?

#include <cstdio>

int main()
{
    unsigned int n = 1;
    char *p = 0;

    p = (char*)&n;
    if (*p == 1)
        std::printf("Little Endian\n");
    else 
        if (*(p + sizeof(int) - 1) == 1)
            std::printf("Big Endian\n");
        else
            std::printf("What the crap?\n");
    return 0;
}

How to kill a process in MacOS?

If you know the process name you can use:

killall Dock

If you don't you can open Activity Monitor and find it.

iterating through Enumeration of hastable keys throws NoSuchElementException error

Each time you do e.nextElement() you skip one. So you skip two elements in each iteration of your loop.

"Cloning" row or column vectors

To answer the actual question, now that nearly a dozen approaches to working around a solution have been posted: x.transpose reverses the shape of x. One of the interesting side-effects is that if x.ndim == 1, the transpose does nothing.

This is especially confusing for people coming from MATLAB, where all arrays implicitly have at least two dimensions. The correct way to transpose a 1D numpy array is not x.transpose() or x.T, but rather

x[:, None]

or

x.reshape(-1, 1)

From here, you can multiply by a matrix of ones, or use any of the other suggested approaches, as long as you respect the (subtle) differences between MATLAB and numpy.

Creating a Zoom Effect on an image on hover using CSS?

_x000D_
_x000D_
    .img-wrap:hover img {_x000D_
        transform: scale(0.8);_x000D_
    }_x000D_
    .img-wrap img {_x000D_
        display: block;_x000D_
        transition: all 0.3s ease 0s;_x000D_
        width: 100%;_x000D_
    }
_x000D_
    <div class="img-wrap">_x000D_
    <img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
    </div>
_x000D_
_x000D_
_x000D_

This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

HTML-Tooltip position relative to mouse pointer

You can use jQuery UI plugin, following are reference URLs

Set track to TRUE for Tooltip position relative to mouse pointer eg.

_x000D_
_x000D_
$('.tooltip').tooltip({ track: true });
_x000D_
_x000D_
_x000D_

Pass variables from servlet to jsp

If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.

Can I dynamically add HTML within a div tag from C# on load event?

Use asp:Panel for that. It translates into a div.

insert data into database using servlet and jsp in eclipse

Same problem fetch main problem in PreparedStatement use simple statement then you successfully insert record same use below.

String  st2="insert into 
user(gender,name,address,telephone,fax,email,
     destination,sdate,edate,Participant,hcategory,
     Culture,Nature,People,Cities,Beaches,Festivals,username,password) 
values('"+gender+"','"+name+"','"+address+"','"+phone+"','"+fax+"',
       '"+email+"','"+desti+"','"+sdate+"','"+edate+"','"+parti+"',
       '"+hotel+"','"+chk1+"','"+chk2+"','"+chk3+"','"+chk4+"',
       '"+chk5+"','"+chk6+"','"+user+"','"+password+"')";


int i=stm.executeUpdate(st2);

MSBUILD : error MSB1008: Only one project can be specified

You need to put qoutes around the path and file name.
So use MSBuild "C:\Path Name\File Name.Exe" /[Options]

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

How to convert JSONObjects to JSONArray?

Even shorter and with json-functions:

JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());

What is "String args[]"? parameter in main method Java

in public static void main(String args[]) args is an array of console line argument whose data type is String. in this array, you can store various string arguments by invoking them at the command line as shown below: java myProgram Shaan Royal then Shaan and Royal will be stored in the array as arg[0]="Shaan"; arg[1]="Royal"; you can do this manually also inside the program, when you don't call them at the command line.

Learning to write a compiler

Python comes bundled with a python compiler written in Python. You can see the source code, and it includes all phases, from parsing, abstract syntax tree, emitting code, etc. Hack it.

How to calculate the time interval between two time strings

Try this

import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time

OUTPUT :

0:00:05

How do I get into a non-password protected Java keystore or change the password?

The password of keystore by default is: "changeit". I functioned to my commands you entered here, for the import of the certificate. I hope you have already solved your problem.

How to display the value of the bar on each bar with pyplot.barh()?

I have noticed api example code contains an example of barchart with the value of the bar displayed on each bar:

"""
========
Barchart
========

A bar plot with errorbars and height labels on individual bars
"""
import numpy as np
import matplotlib.pyplot as plt

N = 5
men_means = (20, 35, 30, 35, 27)
men_std = (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std)

women_means = (25, 32, 34, 20, 25)
women_std = (3, 5, 2, 3, 3)
rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std)

# add some text for labels, title and axes ticks
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind + width / 2)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))

ax.legend((rects1[0], rects2[0]), ('Men', 'Women'))


def autolabel(rects):
    """
    Attach a text label above each bar displaying its height
    """
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)

plt.show()

output:

enter image description here

FYI What is the unit of height variable in "barh" of matplotlib? (as of now, there is no easy way to set a fixed height for each bar)

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

How to remove the querystring and get only the url?

Assuming you still want to get the URL without the query args (if they are not set), just use a shorthand if statement to check with strpos:

$request_uri = strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ? strtok( $_SERVER["REQUEST_URI"], '?' ) : $_SERVER['REQUEST_URI'];

UTF-8 encoding problem in Spring MVC

In Spring 5, or maybe in earlier versions, there is MediaType class. It has already correct line, if you want to follow DRY:

public static final String APPLICATION_JSON_UTF8_VALUE = "application/json;charset=UTF-8";

So I use this set of controller-related annotations:

@RestController
@RequestMapping(value = "my/api/url", produces = APPLICATION_JSON_UTF8_VALUE)
public class MyController {
    // ... Methods here
}

It is marked deprecated in the docs, but I've run into this issue and it is better than copy-pastying the aforementioned line on every method/controller throughout your application, I think.

How to download Xcode DMG or XIP file?

You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).

You must login to have a valid session before downloading anything below.

*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)

*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.

Xcode 12

  • 12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)

  • 12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)

  • 12.2

  • 12.1

  • 12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)

Xcode 11

Xcode 10 (unsupported for iTunes Connect)

  • 10.3 (Requires macOS 10.14.3 or later)
  • 10.2.1 (Requires macOS 10.14.3 or later)
  • 10.1 (Last version supporting macOS 10.13.6 High Sierra)
  • 10 (Subsequent versions were unsupported for iTunes Connect from March 2019)

Xcode 9

Xcode 8

Xcode 7

Xcode 6

Even Older Versions (unsupported for iTunes Connect)

"Debug certificate expired" error in Eclipse Android plugins

To fix this problem, simply delete the debug.keystore file.

The default storage location for AVDs is

In ~/.android/ on OS X and Linux.

In C:\Documents and Settings\.android\ on Windows XP

In C:\Users\.android\ on Windows Vista and Windows 7.

Also see this link, which can be helpful.

http://developer.android.com/tools/publishing/app-signing.html

VS 2017 Metadata file '.dll could not be found

In my case I run the tests and got error CS0006. It turned out that I run tests in Release mode. Switch to Debug mode fixed this error.

Android 1.6: "android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application"

Ditto on the getApplicationContext thing.

The documents on the android site says to use it, but it doesn't work...grrrrr :-P

Just do:

dialog = new Dialog(this); 

"this" is usually your Activity from which you start the dialog.

How to append to the end of an empty list?

You don't need the assignment operator. append returns None.

How to generate .NET 4.0 classes from xsd?

Along with WSDL, I had xsd files. The above did not work in my case gave error. It worked as follows

wsdl /l:C# /out:D:\FileName.cs D:\NameApi\wsdl_1_1\RESAdapterService.wsdl 
D:\CXTypes.xsd D:\CTypes.xsd 
D:\Preferences.xsd 

Can we have multiple <tbody> in same <table>?

I have created a JSFiddle where I have two nested ng-repeats with tables, and the parent ng-repeat on tbody. If you inspect any row in the table, you will see there are six tbody elements, i.e. the parent level.

HTML

<div>
        <table class="table table-hover table-condensed table-striped">
            <thead>
                <tr>
                    <th>Store ID</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>Cost</th>
                    <th>Sales</th>
                    <th>Revenue</th>
                    <th>Employees</th>
                    <th>Employees H-sum</th>
                </tr>
            </thead>
            <tbody data-ng-repeat="storedata in storeDataModel.storedata">
                <tr id="storedata.store.storeId" class="clickableRow" title="Click to toggle collapse/expand day summaries for this store." data-ng-click="selectTableRow($index, storedata.store.storeId)">
                    <td>{{storedata.store.storeId}}</td>
                    <td>{{storedata.store.storeName}}</td>
                    <td>{{storedata.store.storeAddress}}</td>
                    <td>{{storedata.store.storeCity}}</td>
                    <td>{{storedata.data.costTotal}}</td>
                    <td>{{storedata.data.salesTotal}}</td>
                    <td>{{storedata.data.revenueTotal}}</td>
                    <td>{{storedata.data.averageEmployees}}</td>
                    <td>{{storedata.data.averageEmployeesHours}}</td>
                </tr>
                <tr data-ng-show="dayDataCollapse[$index]">
                    <td colspan="2">&nbsp;</td>
                    <td colspan="7">
                        <div>
                            <div class="pull-right">
                                <table class="table table-hover table-condensed table-striped">
                                    <thead>
                                        <tr>
                                            <th></th>
                                            <th>Date [YYYY-MM-dd]</th>
                                            <th>Cost</th>
                                            <th>Sales</th>
                                            <th>Revenue</th>
                                            <th>Employees</th>
                                            <th>Employees H-sum</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr data-ng-repeat="dayData in storeDataModel.storedata[$index].data.dayData">
                                            <td class="pullright">
                                                <button type="btn btn-small" title="Click to show transactions for this specific day..." data-ng-click=""><i class="icon-list"></i>
                                                </button>
                                            </td>
                                            <td>{{dayData.date}}</td>
                                            <td>{{dayData.cost}}</td>
                                            <td>{{dayData.sales}}</td>
                                            <td>{{dayData.revenue}}</td>
                                            <td>{{dayData.employees}}</td>
                                            <td>{{dayData.employeesHoursSum}}</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

( Side note: This fills up the DOM if you have a lot of data on both levels, so I am therefore working on a directive to fetch data and replace, i.e. adding into DOM when clicking parent and removing when another is clicked or same parent again. To get the kind of behavior you find on Prisjakt.nu, if you scroll down to the computers listed and click on the row (not the links). If you do that and inspect elements you will see that a tr is added and then removed if parent is clicked again or another. )

Swift: How to get substring from start to last index of character

I've modified andrewz' post to make it compatible with Swift 2.0 (and maybe Swift 3.0). In my humble opinion, this extension is easier to understand and similar to what is available in other languages (like PHP).

extension String {

    func length() -> Int {
        return self.lengthOfBytesUsingEncoding(NSUTF16StringEncoding)
    }
    func substring(from:Int = 0, to:Int = -1) -> String {
       var nto=to
        if nto < 0 {
            nto = self.length() + nto
        }
        return self.substringWithRange(Range<String.Index>(
           start:self.startIndex.advancedBy(from),
           end:self.startIndex.advancedBy(nto+1)))
    }
    func substring(from:Int = 0, length:Int) -> String {
        return self.substringWithRange(Range<String.Index>(
            start:self.startIndex.advancedBy(from),
            end:self.startIndex.advancedBy(from+length)))
    }
}

How to overcome TypeError: unhashable type: 'list'

    python 3.2

    with open("d://test.txt") as f:
              k=(((i.split("\n"))[0].rstrip()).split() for i in f.readlines())
              d={}
              for i,_,v in k:
                      d.setdefault(i,[]).append(v)

Error inflating class android.support.v7.widget.Toolbar?

I know this is an old question, but I recently ran into this same issue. It ended up being a Proguard problem (when I set minifyEnabled to false it stopped happening.)

To stop it, with proguard enabled, I added the following to my proguard rules file, thanks to a solution I found elsewhere (after discovering that the problem was proguard)

-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.** { *; }

Not sure if they're necessary, but I also added these lines:

-keep class com.google.** { *; }
-keep interface com.google.** { *; }

How to get the input from the Tkinter Text Widget?

In order to obtain the string in a Text widget one can simply use get method defined for Text which accepts 1 to 2 arguments as start and end positions of characters, text_widget_object.get(start, end=None). If only start is passed and end isn't passed it returns only the single character positioned at start, if end is passed as well, it returns all characters in between positions start and end as string.

There are also special strings, that are variables to the underlying Tk. One of them would be "end" or tk.END which represents the variable position of the very last char in the Text widget. An example would be to returning all text in the widget, with text_widget_object.get('1.0', 'end') or text_widget_object.get('1.0', 'end-1c') if you don't want the last newline character.

Demo

See below demonstration that selects the characters in between the given positions with sliders:

try:
    import tkinter as tk
except:
    import Tkinter as tk


class Demo(tk.LabelFrame):
    """
    A LabeFrame that in order to demonstrate the string returned by the
    get method of Text widget, selects the characters in between the
    given arguments that are set with Scales.
    """

    def __init__(self, master, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)
        self.start_arg = ''
        self.end_arg = None
        self.position_frames = dict()
        self._create_widgets()
        self._layout()
        self.update()


    def _create_widgets(self):
        self._is_two_args = tk.Checkbutton(self,
                                    text="Use 2 positional arguments...")
        self.position_frames['start'] = PositionFrame(self,
                                    text="start='{}.{}'.format(line, column)")
        self.position_frames['end'] = PositionFrame(   self,
                                    text="end='{}.{}'.format(line, column)")
        self.text = TextWithStats(self, wrap='none')
        self._widget_configs()


    def _widget_configs(self):
        self.text.update_callback = self.update
        self._is_two_args.var = tk.BooleanVar(self, value=False)
        self._is_two_args.config(variable=self._is_two_args.var,
                                    onvalue=True, offvalue=False)
        self._is_two_args['command'] = self._is_two_args_handle
        for _key in self.position_frames:
            self.position_frames[_key].line.slider['command'] = self.update
            self.position_frames[_key].column.slider['command'] = self.update


    def _layout(self):
        self._is_two_args.grid(sticky='nsw', row=0, column=1)
        self.position_frames['start'].grid(sticky='nsew', row=1, column=0)
        #self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
        self.text.grid(sticky='nsew', row=2, column=0,
                                                    rowspan=2, columnspan=2)
        _grid_size = self.grid_size()
        for _col in range(_grid_size[0]):
            self.grid_columnconfigure(_col, weight=1)
        for _row in range(_grid_size[1] - 1):
            self.grid_rowconfigure(_row + 1, weight=1)


    def _is_two_args_handle(self):
        self.update_arguments()
        if self._is_two_args.var.get():
            self.position_frames['end'].grid(sticky='nsew', row=1, column=1)
        else:
            self.position_frames['end'].grid_remove()


    def update(self, event=None):
        """
        Updates slider limits, argument values, labels representing the
        get method call.
        """

        self.update_sliders()
        self.update_arguments()


    def update_sliders(self):
        """
        Updates slider limits based on what's written in the text and
        which line is selected.
        """

        self._update_line_sliders()
        self._update_column_sliders()


    def _update_line_sliders(self):
        if self.text.lines_length:
            for _key in self.position_frames:
                self.position_frames[_key].line.slider['state'] = 'normal'
                self.position_frames[_key].line.slider['from_'] = 1
                _no_of_lines = self.text.line_count
                self.position_frames[_key].line.slider['to'] = _no_of_lines
        else:
            for _key in self.position_frames:
                self.position_frames[_key].line.slider['state'] = 'disabled'


    def _update_column_sliders(self):
        if self.text.lines_length:
            for _key in self.position_frames:
                self.position_frames[_key].column.slider['state'] = 'normal'
                self.position_frames[_key].column.slider['from_'] = 0
                _line_no = int(self.position_frames[_key].line.slider.get())-1
                _max_line_len = self.text.lines_length[_line_no]
                self.position_frames[_key].column.slider['to'] = _max_line_len
        else:
            for _key in self.position_frames:
                self.position_frames[_key].column.slider['state'] = 'disabled'


    def update_arguments(self):
        """
        Updates the values representing the arguments passed to the get
        method, based on whether or not the 2nd positional argument is
        active and the slider positions.
        """

        _start_line_no = self.position_frames['start'].line.slider.get()
        _start_col_no = self.position_frames['start'].column.slider.get()
        self.start_arg = "{}.{}".format(_start_line_no, _start_col_no)
        if self._is_two_args.var.get():
            _end_line_no = self.position_frames['end'].line.slider.get()
            _end_col_no = self.position_frames['end'].column.slider.get()
            self.end_arg = "{}.{}".format(_end_line_no, _end_col_no)
        else:
            self.end_arg = None
        self._update_method_labels()
        self._select()


    def _update_method_labels(self):
        if self.end_arg:
            for _key in self.position_frames:
                _string = "text.get('{}', '{}')".format(
                                                self.start_arg, self.end_arg)
                self.position_frames[_key].label['text'] = _string
        else:
            _string = "text.get('{}')".format(self.start_arg)
            self.position_frames['start'].label['text'] = _string


    def _select(self):
        self.text.focus_set()
        self.text.tag_remove('sel', '1.0', 'end')
        self.text.tag_add('sel', self.start_arg, self.end_arg)
        if self.end_arg:
            self.text.mark_set('insert', self.end_arg)
        else:
            self.text.mark_set('insert', self.start_arg)


class TextWithStats(tk.Text):
    """
    Text widget that stores stats of its content:
    self.line_count:        the total number of lines
    self.lines_length:      the total number of characters per line
    self.update_callback:   can be set as the reference to the callback
                            to be called with each update
    """

    def __init__(self, master, update_callback=None, *args, **kwargs):
        tk.Text.__init__(self, master, *args, **kwargs)
        self._events = ('<KeyPress>',
                        '<KeyRelease>',
                        '<ButtonRelease-1>',
                        '<ButtonRelease-2>',
                        '<ButtonRelease-3>',
                        '<Delete>',
                        '<<Cut>>',
                        '<<Paste>>',
                        '<<Undo>>',
                        '<<Redo>>')
        self.line_count = None
        self.lines_length = list()
        self.update_callback = update_callback
        self.update_stats()
        self.bind_events_on_widget_to_callback( self._events,
                                                self,
                                                self.update_stats)


    @staticmethod
    def bind_events_on_widget_to_callback(events, widget, callback):
        """
        Bind events on widget to callback.
        """

        for _event in events:
            widget.bind(_event, callback)


    def update_stats(self, event=None):
        """
        Update self.line_count, self.lines_length stats and call
        self.update_callback.
        """

        _string = self.get('1.0', 'end-1c')
        _string_lines = _string.splitlines()
        self.line_count = len(_string_lines)
        del self.lines_length[:]
        for _line in _string_lines:
            self.lines_length.append(len(_line))
        if self.update_callback:
            self.update_callback()


class PositionFrame(tk.LabelFrame):
    """
    A LabelFrame that has two LabelFrames which has Scales.
    """

    def __init__(self, master, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)
        self._create_widgets()
        self._layout()


    def _create_widgets(self):
        self.line = SliderFrame(self, orient='vertical', text="line=")
        self.column = SliderFrame(self, orient='horizontal', text="column=")
        self.label = tk.Label(self, text="Label")


    def _layout(self):
        self.line.grid(sticky='ns', row=0, column=0, rowspan=2)
        self.column.grid(sticky='ew', row=0, column=1, columnspan=2)
        self.label.grid(sticky='nsew', row=1, column=1)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)


class SliderFrame(tk.LabelFrame):
    """
    A LabelFrame that encapsulates a Scale.
    """

    def __init__(self, master, orient, *args, **kwargs):
        tk.LabelFrame.__init__(self, master, *args, **kwargs)

        self.slider = tk.Scale(self, orient=orient)
        self.slider.pack(fill='both', expand=True)


if __name__ == '__main__':
    root = tk.Tk()
    demo = Demo(root, text="text.get(start, end=None)")

    with open(__file__) as f:
        demo.text.insert('1.0', f.read())
    demo.text.update_stats()
    demo.pack(fill='both', expand=True)
    root.mainloop()

How do you convert CString and std::string std::wstring to each other?

This works fine:

//Convert CString to std::string
inline std::string to_string(const CString& cst)
{
    return CT2A(cst.GetString());
}

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')

AngularJS dynamic routing

Ok solved it.

Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting

In my app.js routing config:

$routeProvider.when('/pages/:name', {
    templateUrl: '/pages/home.html', 
    controller: CMSController 
});

Then in my CMS controller:

function CMSController($scope, $route, $routeParams) {

    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";

    $.get($route.current.templateUrl, function (data) {
        $scope.$apply(function () {
            $('#views').html($compile(data)($scope));
        });
    });
    ...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];

With #views being my <div id="views" ng-view></div>

So now it works with standard routing and dynamic routing.

To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio into my browser and hey presto portfolio.html was displayed....

Updated Added $apply and $compile to the html so that dynamic content can be injected.

A cron job for rails: best practices?

I used clockwork gem and it works pretty well for me. There is also clockworkd gem that allows a script to run as a daemon.

Rails raw SQL example

You can do this:

sql = "Select * from ... your sql query here"
records_array = ActiveRecord::Base.connection.execute(sql)

records_array would then be the result of your sql query in an array which you can iterate through.

How to document Python code using Doxygen

This is documented on the doxygen website, but to summarize here:

You can use doxygen to document your Python code. You can either use the Python documentation string syntax:

"""@package docstring
Documentation for this module.

More details.
"""

def func():
    """Documentation for a function.

    More details.
    """
    pass

In which case the comments will be extracted by doxygen, but you won't be able to use any of the special doxygen commands.

Or you can (similar to C-style languages under doxygen) double up the comment marker (#) on the first line before the member:

## @package pyexample
#  Documentation for this module.
#
#  More details.

## Documentation for a function.
#
#  More details.
def func():
    pass

In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting OPTMIZE_OUTPUT_JAVA to YES.

Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?

adding x and y axis labels in ggplot2

[Note: edited to modernize ggplot syntax]

Your example is not reproducible since there is no ex1221new (there is an ex1221 in Sleuth2, so I guess that is what you meant). Also, you don't need (and shouldn't) pull columns out to send to ggplot. One advantage is that ggplot works with data.frames directly.

You can set the labels with xlab() and ylab(), or make it part of the scale_*.* call.

library("Sleuth2")
library("ggplot2")
ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  xlab("My x label") +
  ylab("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area("Nitrogen") + 
  scale_x_continuous("My x label") +
  scale_y_continuous("My y label") +
  ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

enter image description here

An alternate way to specify just labels (handy if you are not changing any other aspects of the scales) is using the labs function

ggplot(ex1221, aes(Discharge, Area)) +
  geom_point(aes(size=NO3)) + 
  scale_size_area() + 
  labs(size= "Nitrogen",
       x = "My x label",
       y = "My y label",
       title = "Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")

which gives an identical figure to the one above.

Declaring array of objects

After seeing how you responded in the comments. It seems like it would be best to use push as others have suggested. This way you don't need to know the indices, but you can still add to the array.

var arr = [];
function funcInJsFile() {
    // Do Stuff
    var obj = {x: 54, y: 10};
    arr.push(obj);
}

In this case, every time you use that function, it will push a new object into the array.

php multidimensional array get values

For people who searched for php multidimensional array get values and actually want to solve problem comes from getting one column value from a 2 dimensinal array (like me!), here's a much elegant way than using foreach, which is array_column

For example, if I only want to get hotel_name from the below array, and form to another array:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
    ]
];

I can do this using array_column:

$hotel_name = array_column($hotels, 'hotel_name');

print_r($hotel_name); // Which will give me ['Hotel A', 'Hotel B']

For the actual answer for this question, it can also be beautified by array_column and call_user_func_array('array_merge', $twoDimensionalArray);

Let's make the data in PHP:

$hotels = [
    [
        'hotel_name' => 'Hotel A',
        'info' => 'Hotel A Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 1,
                    'price' => 200
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 2,
                    'price' => 150
                ]
            ],
        ]
    ],
    [
        'hotel_name' => 'Hotel B',
        'info' => 'Hotel B Info',
        'rooms' => [
            [
                'room_name' => 'Luxury Room',
                'bed' => 2,
                'boards' => [
                    'board_id' => 3,
                    'price' => 900
                ]
            ],
            [
                'room_name' => 'Non Luxy Room',
                'bed' => 4,
                'boards' => [
                    'board_id' => 4,
                    'price' => 300
                ]
            ],
        ]
    ]
];

And here's the calculation:

$rooms = array_column($hotels, 'rooms');
$rooms = call_user_func_array('array_merge', $rooms);
$boards = array_column($rooms, 'boards');

foreach($boards as $board){
    $board_id = $board['board_id'];
    $price = $board['price'];
    echo "Board ID is: ".$board_id." and price is: ".$price . "<br/>";
}

Which will give you the following result:

Board ID is: 1 and price is: 200
Board ID is: 2 and price is: 150
Board ID is: 3 and price is: 900
Board ID is: 4 and price is: 300

Android : Capturing HTTP Requests with non-rooted android device

There is many ways to do that but one of them is fiddler

Fiddler Configuration

  1. Go to options
  2. In HTTPS tab, enable Capture HTTPS Connects and Decrypt HTTPS traffic
  3. In Connections tab, enable Allow remote computers to connect
  4. Restart fiddler

Android Configuration

  1. Connect to same network
  2. Modify network settings
  3. Add proxy for connection with your PC's IP address ( or hostname ) and default fiddler's port ( 8888 / you can change that in settings )

Now you can see full log from your device in fiddler

Also you can find a full instruction here

How to perform update operations on columns of type JSONB in Postgres 9.4

Matheus de Oliveira created handy functions for JSON CRUD operations in postgresql. They can be imported using the \i directive. Notice the jsonb fork of the functions if jsonb if your data type.

9.3 json https://gist.github.com/matheusoliveira/9488951

9.4 jsonb https://gist.github.com/inindev/2219dff96851928c2282

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

In my case app crash only on real device and it occurred for standard library's. I tryied a lot of steps meintioned before, after 1h i just delete app from real device and install it again.

Install dependencies globally and locally using package.json

All modules from package.json are installed to ./node_modules/

I couldn't find this explicitly stated but this is the package.json reference for NPM.