Programs & Examples On #Chaining

Chaining is an object-oriented programming technique where methods return the object on which they were called so that another method may be called on the same object, thus forming a method chain.

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I solved this issue after changing the "Gradle Version" and "Android Plugin version".

You just goto "File>>Project Structure>>Project>>" and make changes here. I have worked a combination of versions from another working project of mine and added to the Project where I was getting this problem.

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I have resolved this issue after selecting the "Target Compatibility" to 1.8 Java version. File -> Project Structure -> Modules.

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I Had the same issue and finally discovered the reason. In my case it was a badly written Java method:

@FormUrlEncoded
@POST("register-user/")
Call<RegisterUserApiResponse> registerUser(
        @Field("email") String email,
        @Field("password") String password,            
        @Field("date") String birthDate,
);

Note the illegal comma after the "date" field. For some reason the compiler could not reveal this exact error, and came with the ':app:compileDebugKotlin'. > Compilation error thing.

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

Migrate to androidX library

With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.

Source: https://developer.android.com/jetpack/androidx/migrate

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

You can fix this issue by adding a project ext property googlePlayServicesVersion to app/App_Resources/Android/app.gradle file like this:

project.ext {
    googlePlayServicesVersion = "+"
}

Call async/await functions in parallel

Update:

The original answer makes it difficult (and in some cases impossible) to correctly handle promise rejections. The correct solution is to use Promise.all:

const [someResult, anotherResult] = await Promise.all([someCall(), anotherCall()]);

Original answer:

Just make sure you call both functions before you await either one:

// Call both functions
const somePromise = someCall();
const anotherPromise = anotherCall();

// Await both promises    
const someResult = await somePromise;
const anotherResult = await anotherPromise;

configuring project ':app' failed to find Build Tools revision

also try to increase gradle version in your project's build.gradle. It helped me

Can an AWS Lambda function call another

I'm having the same problem but the Lambda function that I implement will insert an entry in DynamoDB, so my solution uses DynamoDB Triggers.

I make the DB invoke a Lambda function for every insert/update in the table, so this separates the implementation of two Lambda functions.

Documentation is here: http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.Lambda.html

Here is a guided walkthrough: https://aws.amazon.com/blogs/aws/dynamodb-update-triggers-streams-lambda-cross-region-replication-app/

Confusing "duplicate identifier" Typescript error message

remove this @types/express-validator from package.json file, then run npm install

Read More

Author message: This package has been deprecated This is a stub types definition for express-validator (https://github.com/ctavan/express-validator). express-validator provides its own type definitions, so you don't need @types/express-validator installed!

How to access the value of a promise?

Parsing the comment a little differently than your current understanding might help:

// promiseB will be resolved immediately after promiseA is resolved

This states that promiseB is a promise but will be resolved immediately after promiseA is resolved. Another way of looking at this means that promiseA.then() returns a promise that is assigned to promiseB.

// and its value will be the result of promiseA incremented by 1

This means that the value that promiseA resolved to is the value that promiseB will receive as its successCallback value:

promiseB.then(function (val) {
  // val is now promiseA's result + 1
});

What's the difference between returning value or Promise.resolve from then()

You already got a good formal answer. I figured I should add a short one.

The following things are identical with Promises/A+ promises:

  • Calling Promise.resolve (In your Angular case that's $q.when)
  • Calling the promise constructor and resolving in its resolver. In your case that's new $q.
  • Returning a value from a then callback.
  • Calling Promise.all on an array with a value and then extract that value.

So the following are all identical for a promise or plain value X:

Promise.resolve(x);
new Promise(function(resolve, reject){ resolve(x); });
Promise.resolve().then(function(){ return x; });
Promise.all([x]).then(function(arr){ return arr[0]; });

And it's no surprise, the promises specification is based on the Promise Resolution Procedure which enables easy interoperation between libraries (like $q and native promises) and makes your life overall easier. Whenever a promise resolution might occur a resolution occurs creating overall consistency.

Get top most UIViewController

 extension UIApplication {
    
    public var mainKeyWindow: UIWindow? {
        return windows.first(where: { $0.isKeyWindow }) ?? keyWindow
    }

    public var rootViewController: UIViewController? {
        guard let keyWindow = UIApplication.shared.mainKeyWindow, let rootViewController = keyWindow.rootViewController else {
            return nil
        }
        return rootViewController
    }

    public func topViewController(controller: UIViewController? = UIApplication.shared.rootViewController) -> UIViewController? {

        if controller == nil {
            return topViewController(controller: rootViewController)
        }
        
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }

        if let tabController = controller as? UITabBarController {
            if let selectedViewController = tabController.selectedViewController {
                return topViewController(controller: selectedViewController)
            }
        }

        if let presentedViewController = controller?.presentedViewController {
            return topViewController(controller: presentedViewController)
        }

        return controller
    }
}

Swift 5.2 and above

Laravel Mail::send() sending to multiple to or bcc addresses

Try this:

$toemail = explode(',', str_replace(' ', '', $request->toemail));

Collision resolution in Java HashMap

It isn't defined to do so. In order to achieve this functionality, you need to create a map that maps keys to lists of values:

Map<Foo, List<Bar>> myMap;

Or, you could use the Multimap from google collections / guava libraries

Replace multiple characters in one replace call

_x000D_
_x000D_
String.prototype.replaceAll=function(obj,keydata='key'){
 const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}

const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
_x000D_
_x000D_
_x000D_

String.prototype.replaceAll=function(keydata,obj){ const keys=keydata.split('key'); return Object.entries(obj).reduce((a,[key,val])=> a.replace(${keys[0]}${key}${keys[1]},val),this) }

const data='hids dv sdc sd ${yathin} ${ok}' console.log(data.replaceAll('${key}',{yathin:12,ok:'hi'}))

pandas: filter rows of DataFrame with operator chaining

I'm not entirely sure what you want, and your last line of code does not help either, but anyway:

"Chained" filtering is done by "chaining" the criteria in the boolean index.

In [96]: df
Out[96]:
   A  B  C  D
a  1  4  9  1
b  4  5  0  2
c  5  5  1  0
d  1  3  9  6

In [99]: df[(df.A == 1) & (df.D == 6)]
Out[99]:
   A  B  C  D
d  1  3  9  6

If you want to chain methods, you can add your own mask method and use that one.

In [90]: def mask(df, key, value):
   ....:     return df[df[key] == value]
   ....:

In [92]: pandas.DataFrame.mask = mask

In [93]: df = pandas.DataFrame(np.random.randint(0, 10, (4,4)), index=list('abcd'), columns=list('ABCD'))

In [95]: df.ix['d','A'] = df.ix['a', 'A']

In [96]: df
Out[96]:
   A  B  C  D
a  1  4  9  1
b  4  5  0  2
c  5  5  1  0
d  1  3  9  6

In [97]: df.mask('A', 1)
Out[97]:
   A  B  C  D
a  1  4  9  1
d  1  3  9  6

In [98]: df.mask('A', 1).mask('D', 6)
Out[98]:
   A  B  C  D
d  1  3  9  6

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

Chaining multiple filter() in Django, is this a bug?

These two style of filtering are equivalent in most cases, but when query on objects base on ForeignKey or ManyToManyField, they are slightly different.

Examples from the documentation.

model
Blog to Entry is a one-to-many relation.

from django.db import models

class Blog(models.Model):
    ...

class Entry(models.Model):
    blog = models.ForeignKey(Blog)
    headline = models.CharField(max_length=255)
    pub_date = models.DateField()
    ...

objects
Assuming there are some blog and entry objects here.
enter image description here

queries

Blog.objects.filter(entry__headline_contains='Lennon', 
    entry__pub_date__year=2008)
Blog.objects.filter(entry__headline_contains='Lennon').filter(
    entry__pub_date__year=2008)  
    

For the 1st query (single filter one), it match only blog1.

For the 2nd query (chained filters one), it filters out blog1 and blog2.
The first filter restricts the queryset to blog1, blog2 and blog5; the second filter restricts the set of blogs further to blog1 and blog2.

And you should realize that

We are filtering the Blog items with each filter statement, not the Entry items.

So, it's not the same, because Blog and Entry are multi-valued relationships.

Reference: https://docs.djangoproject.com/en/1.8/topics/db/queries/#spanning-multi-valued-relationships
If there is something wrong, please correct me.

Edit: Changed v1.6 to v1.8 since the 1.6 links are no longer available.

Multiple selector chaining in jQuery?

$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

Configure hibernate to connect to database via JNDI Datasource

Apparently, you did it right. But here is a list of things you'll need with examples from a working application:

1) A context.xml file in META-INF, specifying your data source:

<Context>
    <Resource 
        name="jdbc/DsWebAppDB" 
        auth="Container" 
        type="javax.sql.DataSource" 
        username="sa" 
        password="" 
        driverClassName="org.h2.Driver" 
        url="jdbc:h2:mem:target/test/db/h2/hibernate" 
        maxActive="8" 
        maxIdle="4"/>
</Context>

2) web.xml which tells the container that you are using this resource:

<resource-env-ref>
    <resource-env-ref-name>jdbc/DsWebAppDB</resource-env-ref-name>
    <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type>
</resource-env-ref>

3) Hibernate configuration which consumes the data source. In this case, it's a persistence.xml, but it's similar in hibernate.cfg.xml

<persistence-unit name="dswebapp">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
        <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/DsWebAppDB"/>
    </properties>
</persistence-unit>

Better way to find control in ASP.NET

The following example defines a Button1_Click event handler. When invoked, this handler uses the FindControl method to locate a control with an ID property of TextBox2 on the containing page. If the control is found, its parent is determined using the Parent property and the parent control's ID is written to the page. If TextBox2 is not found, "Control Not Found" is written to the page.

private void Button1_Click(object sender, EventArgs MyEventArgs)
{
      // Find control on page.
      Control myControl1 = FindControl("TextBox2");
      if(myControl1!=null)
      {
         // Get control's parent.
         Control myControl2 = myControl1.Parent;
         Response.Write("Parent of the text box is : " + myControl2.ID);
      }
      else
      {
         Response.Write("Control not found");
      }
}

How to tell a Mockito mock object to return something different the next time it is called?

For Anyone using spy() and the doReturn() instead of the when() method:

what you need to return different object on different calls is this:

doReturn(obj1).doReturn(obj2).when(this.spyFoo).someMethod();

.

For classic mocks:

when(this.mockFoo.someMethod()).thenReturn(obj1, obj2);

or with an exception being thrown:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenThrow(new IllegalArgumentException())
        .thenReturn(obj2, obj3);

Remove all multiple spaces in Javascript and replace with single space

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

jQuery: Handle fallback for failed AJAX Request

I prefer to this approach because you can return the promise and use .then(successFunction, failFunction); anywhere you need to.

var promise = $.ajax({
    type: 'GET',
    dataType: 'json',
    url: url,
    timeout: 5000
  }).then(function( data, textStatus, jqXHR ) {
    alert('request successful');
  }, function( jqXHR, textStatus, errorThrown ) {
    alert('request failed');
});

//also access the success and fail using variable
promise.then(successFunction, failFunction);

How to do constructor chaining in C#

I just want to bring up a valid point to anyone searching for this. If you are going to work with .NET versions before 4.0 (VS2010), please be advised that you have to create constructor chains as shown above.

However, if you're staying in 4.0, I have good news. You can now have a single constructor with optional arguments! I'll simplify the Foo class example:

class Foo {
  private int id;
  private string name;

  public Foo(int id = 0, string name = "") {
    this.id = id;
    this.name = name;
  }
}

class Main() {
  // Foo Int:
  Foo myFooOne = new Foo(12);
  // Foo String:
  Foo myFooTwo = new Foo(name:"Timothy");
  // Foo Both:
  Foo myFooThree = new Foo(13, name:"Monkey");
}

When you implement the constructor, you can use the optional arguments since defaults have been set.

I hope you enjoyed this lesson! I just can't believe that developers have been complaining about construct chaining and not being able to use default optional arguments since 2004/2005! Now it has taken SO long in the development world, that developers are afraid of using it because it won't be backwards compatible.

How to find list of possible words from a letter matrix [Boggle Solver]

I'd have to give more thought to a complete solution, but as a handy optimisation, I wonder whether it might be worth pre-computing a table of frequencies of digrams and trigrams (2- and 3-letter combinations) based on all the words from your dictionary, and use this to prioritise your search. I'd go with the starting letters of words. So if your dictionary contained the words "India", "Water", "Extreme", and "Extraordinary", then your pre-computed table might be:

'IN': 1
'WA': 1
'EX': 2

Then search for these digrams in the order of commonality (first EX, then WA/IN)

How to make function decorators and chain them together?

And of course you can return lambdas as well from a decorator function:

def makebold(f): 
    return lambda: "<b>" + f() + "</b>"
def makeitalic(f): 
    return lambda: "<i>" + f() + "</i>"

@makebold
@makeitalic
def say():
    return "Hello"

print say()

In jQuery, what's the best way of formatting a number to 2 decimal places?

Maybe something like this, where you could select more than one element if you'd like?

$("#number").each(function(){
    $(this).val(parseFloat($(this).val()).toFixed(2));
});

Can I call a constructor from another constructor (do constructor chaining) in C++?

In C++11, a constructor can call another constructor overload:

class Foo  {
     int d;         
public:
    Foo  (int i) : d(i) {}
    Foo  () : Foo(42) {} //New to C++11
};

Additionally, members can be initialized like this as well.

class Foo  {
     int d = 5;         
public:
    Foo  (int i) : d(i) {}
};

This should eliminate the need to create the initialization helper method. And it is still recommended not calling any virtual functions in the constructors or destructors to avoid using any members that might not be initialized.

Using "super" in C++

I won't say much except present code with comments that demonstrates that super doesn't mean calling base!

super != base.

In short, what is "super" supposed to mean anyway? and then what is "base" supposed to mean?

  1. super means, calling the last implementor of a method (not base method)
  2. base means, choosing which class is default base in multiple inheritance.

This 2 rules apply to in class typedefs.

Consider library implementor and library user, who is super and who is base?

for more info here is working code for copy paste into your IDE:

#include <iostream>

// Library defiens 4 classes in typical library class hierarchy
class Abstract
{
public:
    virtual void f() = 0;
};

class LibraryBase1 :
    virtual public Abstract
{
public:
    void f() override
    {
        std::cout << "Base1" << std::endl;
    }
};

class LibraryBase2 :
    virtual public Abstract
{
public:
    void f() override
    {
        std::cout << "Base2" << std::endl;
    }
};

class LibraryDerivate :
    public LibraryBase1,
    public LibraryBase2
{
    // base is meaningfull only for this class,
    // this class decides who is my base in multiple inheritance
private:
    using base = LibraryBase1;

protected:
    // this is super! base is not super but base!
    using super = LibraryDerivate;

public:
    void f() override
    {
        std::cout << "I'm super not my Base" << std::endl;
        std::cout << "Calling my *default* base: " << std::endl;
        base::f();
    }
};

// Library user
struct UserBase :
    public LibraryDerivate
{
protected:
    // NOTE: If user overrides f() he must update who is super, in one class before base!
    using super = UserBase; // this typedef is needed only so that most derived version
    // is called, which calls next super in hierarchy.
    // it's not needed here, just saying how to chain "super" calls if needed

    // NOTE: User can't call base, base is a concept private to each class, super is not.
private:
    using base = LibraryDerivate; // example of typedefing base.

};

struct UserDerived :
    public UserBase
{
    // NOTE: to typedef who is super here we would need to specify full name
    // when calling super method, but in this sample is it's not needed.

    // Good super is called, example of good super is last implementor of f()
    // example of bad super is calling base (but which base??)
    void f() override
    {
        super::f();
    }
};

int main()
{
    UserDerived derived;
    // derived calls super implementation because that's what
    // "super" is supposed to mean! super != base
    derived.f();

    // Yes it work with polymorphism!
    Abstract* pUser = new LibraryDerivate;
    pUser->f();

    Abstract* pUserBase = new UserBase;
    pUserBase->f();
}

Another important point here is this:

  1. polymorphic call: calls downward
  2. super call: calls upwards

inside main() we use polymorphic call downards that super calls upwards, not really useful in real life, but it demonstrates the difference.

Hidden features of Python

Using keyword arguments as assignments

Sometimes one wants to build a range of functions depending on one or more parameters. However this might easily lead to closures all referring to the same object and value:

funcs = [] 
for k in range(10):
     funcs.append( lambda: k)

>>> funcs[0]()
9
>>> funcs[7]()
9

This behaviour can be avoided by turning the lambda expression into a function depending only on its arguments. A keyword parameter stores the current value that is bound to it. The function call doesn't have to be altered:

funcs = [] 
for k in range(10):
     funcs.append( lambda k = k: k)

>>> funcs[0]()
0
>>> funcs[7]()
7

How do you remove all the options of a select box and then add one option and select it with jQuery?

Uses the jquery prop() to clear the selected option

$('#mySelect option:selected').prop('selected', false);

How to change font in ipython notebook

In your notebook (simple approach). Add new cell with following code

%%html
<style type='text/css'>
.CodeMirror{
    font-size: 12px;
}

div.output_area pre {
    font-size: 12px;
}
</style>

How to get the Full file path from URI

one of the answers that exist on the current page (this), is correct but it has some mistakes. for example, it won't work on devices with API 29+. I'll update the above code and post its new version. I think this post should be marked as the final answer.

Updated code: (Added WhatsApp support)

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    private static Uri contentUri = null;

    Context context;

    public FileUtils( Context context) {
        this.context=context;
    }

    @SuppressLint("NewApi")
    public static String getPath( final Uri uri) {
        // check here to KITKAT or new version
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        String selection = null;
        String[] selectionArgs = null;
        // DocumentProvider
        if (isKitKat ) {
            // ExternalStorageProvider

           if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                String fullPath = getPathFromExtSD(split);
                if (fullPath != "") {
                    return fullPath;
                } else {
                    return null;
                }
            }


            // DownloadsProvider

            if (isDownloadsDocument(uri)) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    final String id;
                    Cursor cursor = null;
                    try {
                        cursor = context.getContentResolver().query(uri, new String[]{MediaStore.MediaColumns.DISPLAY_NAME}, null, null, null);
                        if (cursor != null && cursor.moveToFirst()) {
                            String fileName = cursor.getString(0);
                            String path = Environment.getExternalStorageDirectory().toString() + "/Download/" + fileName;
                            if (!TextUtils.isEmpty(path)) {
                                return path;
                            }
                        }
                    }
                    finally {
                        if (cursor != null)
                            cursor.close();
                    }
                    id = DocumentsContract.getDocumentId(uri);
                    if (!TextUtils.isEmpty(id)) {
                        if (id.startsWith("raw:")) {
                            return id.replaceFirst("raw:", "");
                        }
                        String[] contentUriPrefixesToTry = new String[]{
                                "content://downloads/public_downloads",
                                "content://downloads/my_downloads"
                        };
                        for (String contentUriPrefix : contentUriPrefixesToTry) {
                            try {
                                final Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));


                                return getDataColumn(context, contentUri, null, null);
                            } catch (NumberFormatException e) {
                                //In Android 8 and Android P the id is not a number
                                return uri.getPath().replaceFirst("^/document/raw:", "").replaceFirst("^raw:", "");
                            }
                        }


                    }
                }
                else {
                    final String id = DocumentsContract.getDocumentId(uri);

                    if (id.startsWith("raw:")) {
                        return id.replaceFirst("raw:", "");
                    }
                    try {
                        contentUri = ContentUris.withAppendedId(
                                Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                    }
                    catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    if (contentUri != null) {

                        return getDataColumn(context, contentUri, null, null);
                    }
                }
            }


            // MediaProvider
           if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;

                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                selection = "_id=?";
                selectionArgs = new String[]{split[1]};


                return getDataColumn(context, contentUri, selection,
                        selectionArgs);
            }

           if (isGoogleDriveUri(uri)) {
                return getDriveFilePath(uri);
            }

           if(isWhatsAppFile(uri)){
                return getFilePathForWhatsApp(uri);
            }


           if ("content".equalsIgnoreCase(uri.getScheme())) {

                if (isGooglePhotosUri(uri)) {
                    return uri.getLastPathSegment();
                }
                if (isGoogleDriveUri(uri)) {
                    return getDriveFilePath(uri);
                }
                if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
                {

                    // return getFilePathFromURI(context,uri);
                    return copyFileToInternalStorage(uri,"userfiles");
                    // return getRealPathFromURI(context,uri);
                }
                else
                {
                    return getDataColumn(context, uri, null, null);
                }

           }
           if ("file".equalsIgnoreCase(uri.getScheme())) {
                return uri.getPath();
            }
        }
        else {

            if(isWhatsAppFile(uri)){
                return getFilePathForWhatsApp(uri);
            }

            if ("content".equalsIgnoreCase(uri.getScheme())) {
                String[] projection = {
                        MediaStore.Images.Media.DATA
                };
                Cursor cursor = null;
                try {
                    cursor = context.getContentResolver()
                            .query(uri, projection, selection, selectionArgs, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    if (cursor.moveToFirst()) {
                        return cursor.getString(column_index);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }




        return null;
    }

    private  boolean fileExists(String filePath) {
        File file = new File(filePath);

        return file.exists();
    }

    private String getPathFromExtSD(String[] pathData) {
        final String type = pathData[0];
        final String relativePath = "/" + pathData[1];
        String fullPath = "";

        // on my Sony devices (4.4.4 & 5.1.1), `type` is a dynamic string
        // something like "71F8-2C0A", some kind of unique id per storage
        // don't know any API that can get the root path of that storage based on its id.
        //
        // so no "primary" type, but let the check here for other devices
        if ("primary".equalsIgnoreCase(type)) {
            fullPath = Environment.getExternalStorageDirectory() + relativePath;
            if (fileExists(fullPath)) {
                return fullPath;
            }
        }

        // Environment.isExternalStorageRemovable() is `true` for external and internal storage
        // so we cannot relay on it.
        //
        // instead, for each possible path, check if file exists
        // we'll start with secondary storage as this could be our (physically) removable sd card
        fullPath = System.getenv("SECONDARY_STORAGE") + relativePath;
        if (fileExists(fullPath)) {
            return fullPath;
        }

        fullPath = System.getenv("EXTERNAL_STORAGE") + relativePath;
        if (fileExists(fullPath)) {
            return fullPath;
        }

        return fullPath;
    }

    private String getDriveFilePath(Uri uri) {
        Uri returnUri = uri;
        Cursor returnCursor = context.getContentResolver().query(returnUri, null, null, null, null);
        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));
        File file = new File(context.getCacheDir(), name);
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            //int bufferSize = 1024;
            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            Log.e("File Size", "Size " + file.length());
            inputStream.close();
            outputStream.close();
            Log.e("File Path", "Path " + file.getPath());
            Log.e("File Size", "Size " + file.length());
        } catch (Exception e) {
            Log.e("Exception", e.getMessage());
        }
        return file.getPath();
    }

    /***
     * Used for Android Q+
     * @param uri
     * @param newDirName if you want to create a directory, you can set this variable
     * @return
     */
    private String copyFileToInternalStorage(Uri uri,String newDirName) {
        Uri returnUri = uri;

        Cursor returnCursor = context.getContentResolver().query(returnUri, new String[]{
                OpenableColumns.DISPLAY_NAME,OpenableColumns.SIZE
        }, null, null, null);


        /*
         * Get the column indexes of the data in the Cursor,
         *     * move to the first row in the Cursor, get the data,
         *     * and display it.
         * */
        int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
        returnCursor.moveToFirst();
        String name = (returnCursor.getString(nameIndex));
        String size = (Long.toString(returnCursor.getLong(sizeIndex)));

        File output;
        if(!newDirName.equals("")) {
            File dir = new File(context.getFilesDir() + "/" + newDirName);
            if (!dir.exists()) {
                dir.mkdir();
            }
            output = new File(context.getFilesDir() + "/" + newDirName + "/" + name);
        }
        else{
            output = new File(context.getFilesDir() + "/" + name);
        }
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(output);
            int read = 0;
            int bufferSize = 1024;
            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }

            inputStream.close();
            outputStream.close();

        }
        catch (Exception e) {

            Log.e("Exception", e.getMessage());
        }

        return output.getPath();
    }

    private String getFilePathForWhatsApp(Uri uri){
            return  copyFileToInternalStorage(uri,"whatsapp");
    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection,
                    selection, selectionArgs, null);

            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        }
        finally {
            if (cursor != null)
                cursor.close();
        }

        return null;
    }

    private  boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    private  boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    private  boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    private  boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public boolean isWhatsAppFile(Uri uri){
        return "com.whatsapp.provider.media".equals(uri.getAuthority());
    }

    private  boolean isGoogleDriveUri(Uri uri) {
        return "com.google.android.apps.docs.storage".equals(uri.getAuthority()) || "com.google.android.apps.docs.storage.legacy".equals(uri.getAuthority());
    }


}

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Need to find element in selenium by css

Only using class names is not sufficient in your case.

  • By.cssSelector(".ban") has 15 matching nodes
  • By.cssSelector(".hot") has 11 matching nodes
  • By.cssSelector(".ban.hot") has 5 matching nodes

Therefore you need more restrictions to narrow it down. Option 1 and 2 below are available for css selector, 1 might be the one that suits your needs best.

Option 1: Using list items' index (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes

Example:

driver.FindElement(By.CssSelector("#rightbar > .menu > li:nth-of-type(3) > h5"));
driver.FindElement(By.XPath("//*[@id='rightbar']/ul/li[3]/h5"));

Option 2: Using Selenium's FindElements, then index them. (CssSelector or XPath)

Limitations

  • Not stable enough if site's structure changes
  • Not the native selector's way

Example:

// note that By.CssSelector(".ban.hot") and //*[contains(@class, 'ban hot')] are different, but doesn't matter in your case
IList<IWebElement> hotBanners = driver.FindElements(By.CssSelector(".ban.hot"));
IWebElement banUsStates = hotBanners[3];

Option 3: Using text (XPath only)

Limitations

  • Not for multilanguage sites
  • Only for XPath, not for Selenium's CssSelector

Example:

driver.FindElement(By.XPath("//h5[contains(@class, 'ban hot') and text() = 'us states']"));

Option 4: Index the grouped selector (XPath only)

Limitations

  • Not stable enough if site's structure changes
  • Only for XPath, not CssSelector

Example:

driver.FindElement(By.XPath("(//h5[contains(@class, 'ban hot')])[3]"));

Option 5: Find the hidden list items link by href, then traverse back to h5 (XPath only)

Limitations

  • Only for XPath, not CssSelector
  • Low performance
  • Tricky XPath

Example:

driver.FindElement(By.XPath(".//li[.//ul/li/a[contains(@href, 'geo.craigslist.org/iso/us/al')]]/h5"));

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

PHP to search within txt file and echo the whole line

looks like you're better off systeming out to system("grep \"$QUERY\"") since that script won't be particularly high performance either way. Otherwise http://php.net/manual/en/function.file.php shows you how to loop over lines and you can use http://php.net/manual/en/function.strstr.php for finding matches.

In C#, how to check whether a string contains an integer?

You could use char.IsDigit:

     bool isIntString = "your string".All(char.IsDigit)

Will return true if the string is a number

    bool containsInt = "your string".Any(char.IsDigit)

Will return true if the string contains a digit

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

push object into array

can be done like this too.

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

What is the simplest and most robust way to get the user's current location on Android?

EDIT: Updated with the latest Location Service API from Google Play Services library (July 2014)

I would recommend you to use the new Location Service API, available from the Google Play Services library, which provides a more powerful, high-level framework that automates tasks such as location provider choice and power management. According to the official documentation: "... Location API make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. They also let you minimize power consumption by using all of the capabilities of the device hardware."

For further information visit: Making Your App Location-Aware

To see a full example using the latest Location Service API visit: Android LocationClient class is deprecated but used in documentation

regex pattern to match the end of a string

Should be

~/([^/]*)$~

Means: Match a / and then everything, that is not a / ([^/]*) until the end ($, "end"-anchor).

I use the ~ as delimiter, because now I don't need to escape the forward-slash /.

Python pip install module is not found. How to link python to pip location?

For me the problem was that I had weird configuration settings in file pydistutils.cfg

Try running rm ~/.pydistutils.cfg

Ignore .pyc files in git repository

i try to use the sentence of a prior post and don't work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore

Enjoy.

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

How to refer to relative paths of resources when working with a code repository

Try to use a filename relative to the current files path. Example for './my_file':

fn = os.path.join(os.path.dirname(__file__), 'my_file')

In Python 3.4+ you can also use pathlib:

fn = pathlib.Path(__file__).parent / 'my_file'

What does the "at" (@) symbol do in Python?

@ symbol is also used to access variables inside a plydata / pandas dataframe query, pandas.DataFrame.query. Example:

df = pandas.DataFrame({'foo': [1,2,15,17]})
y = 10
df >> query('foo > @y') # plydata
df.query('foo > @y') # pandas

The smallest difference between 2 Angles

A simple method, which I use in C++ is:

double deltaOrientation = angle1 - angle2;
double delta =  remainder(deltaOrientation, 2*M_PI);

Border Height on CSS

.main-box{  
    border: solid 10px;
}
.sub-box{
    border-right: 1px solid;
}

//draws a line on right side of the box. later add a margin-top and margin-bottom. i.e.,

.sub-box{
    border-right: 1px solid;
    margin-top: 10px;;
    margin-bottom: 10px;
}

This might help in drawing a line on the right-side of the box with a gap on top and bottom.

No output to console from a WPF application?

Although John Leidegren keeps shooting down the idea, Brian is correct. I've just got it working in Visual Studio.

To be clear a WPF application does not create a Console window by default.

You have to create a WPF Application and then change the OutputType to "Console Application". When you run the project you will see a console window with your WPF window in front of it.

It doesn't look very pretty, but I found it helpful as I wanted my app to be run from the command line with feedback in there, and then for certain command options I would display the WPF window.

How to convert HH:mm:ss.SSS to milliseconds?

Using JODA:

PeriodFormatter periodFormat = new PeriodFormatterBuilder()
  .minimumParsedDigits(2)
  .appendHour() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendMinute() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendSecond()
  .appendSeparator(".")
  .appendMillis3Digit()
  .toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();

React-Native: Module AppRegistry is not a registered callable module

Hopefully this can save someone a headache. I got this error after upgrading my react-native version. Confusingly it only appeared on the android side of things.

My file structure includes an index.ios.js and an index.android.js. Both contain the code:

AppRegistry.registerComponent('App', () => App);

What I had to do was, in android/app/src/main/java/com/{projectName}/MainApplication.java, change index to index.android:

@Override
protected String getJSMainModuleName() {
    return "index.android"; // was "index"
}

Then in app/build/build.gradle, change the entryFile from index.js to index.android.js

project.ext.react = [
    entryFile: "index.android.js" // was index.js"
]

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

had the same issue. I had imported a newer version of json library (deleted the old one - but not removed it from the build path). Resolved it by removing the reference to the old one from the build path

What is the equivalent of Java's System.out.println() in Javascript?

I'm using Chrome and print() literally prints the text on paper. This is what works for me:

document.write("My message");

Centering a background image, using CSS

background-repeat:no-repeat;
background-position:center center;

Does not vertically center the background image when using a html 4.01 'STRICT' doctype.

Adding:

background-attachment: fixed;

Should fix the problem

(So Alexander is right)

python object() takes no parameters error

You must press twice on tap and (_) key each time, it must look like:

__init__

header('HTTP/1.0 404 Not Found'); not doing anything

No, it probably is actually working. It's just not readily visible. Instead of just using the header call, try doing that, then including 404.php, and then calling die.

You can test the fact that the HTTP/1.0 404 Not Found works by creating a PHP file named, say, test.php with this content:

<?php

header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";

Then viewing the result with curl -D /dev/stdout reveals:

HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html

PHP continues.

Android Location Providers - GPS or Network Provider?

There are some great answers mentioned here. Another approach you could take would be to use some free SDKs available online like Atooma, tranql and Neura, that can be integrated with your Android application (it takes less than 20 min to integrate). Along with giving you the accurate location of your user, it can also give you good insights about your user’s activities. Also, some of them consume less than 1% of your battery

Any way to replace characters on Swift String?

This is easy in swift 4.2. just use replacingOccurrences(of: " ", with: "_") for replace

var myStr = "This is my string"
let replaced = myStr.replacingOccurrences(of: " ", with: "_")
print(replaced)

How to test web service using command line curl

Answering my own question.

curl -X GET --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X DELETE --basic --user username:password \
     https://www.example.com/mobile/resource

curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
     -d 'param2_name=param2_value' https://www.example.com/mobile/resource

POSTing a file and additional parameter

curl -X POST -F 'param_name=@/filepath/filename' \
     -F 'extra_param_name=extra_param_value' --basic --user username:password \
     https://www.example.com/mobile/resource

Best way to compare two complex objects

If you don't want to implement IEquatable, you can always use Reflection to compare all the properties: - if they're value type, just compare them -if they are reference type, call the function recursively to compare its "inner" properties.

I'm not thinking about performace, but about simplicity. It depends, however on the exact design of your objects. It could get complicated depending on your objects shape (for example if there are cyclic dependencies between properties). There are, however, several solutions out there that you can use, like this one:

Another option is to serialize the object as text, for example using JSON.NET, and comparing the serialization result. (JSON.NET can handle Cyclic dependencies between properties).

I don't know if by fastest you mean the fastest way to implement it or a code that runs fast. You should not optimize before knowing if you need to. Premature optimization is the root of all evil

How to load a model from an HDF5 file in Keras?

If you stored the complete model, not only the weights, in the HDF5 file, then it is as simple as

from keras.models import load_model
model = load_model('model.h5')

Convert XML String to Object

You can use xsd.exe to create schema bound classes in .Net then XmlSerializer to Deserialize the string : http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.deserialize.aspx

No mapping found for HTTP request with URI Spring MVC

First check whether the java classes are compiled or not in your [PROJECT_NAME]\target\classes directory.

If not you have some compilation errors in your java classes.

How to scroll HTML page to given anchor?

_x000D_
_x000D_
jQuery("a[href^='#']").click(function(){_x000D_
    jQuery('html, body').animate({_x000D_
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top_x000D_
    }, 1000);_x000D_
    return false;_x000D_
});
_x000D_
_x000D_
_x000D_

How can I view a git log of just one user's commits?

On github there is also a secret way...

You can filter commits by author in the commit view by appending param ?author=github_handle. For example, the link https://github.com/dynjs/dynjs/commits/master?author=jingweno shows a list of commits to the Dynjs project

How to print multiple lines of text with Python

You can use triple quotes (single ' or double "):

a = """
text
text
text
"""

print(a)

How to create a QR code reader in a HTML5 website?

The jsqrcode library by Lazarsoft is now working perfectly using just HTML5, i.e. getUserMedia (WebRTC). You can find it on GitHub.

I also found a great fork which is much simplified. Just one file (plus jQuery) and one call of a method: see html5-qrcode on GitHub.

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

PowerShell to remove text from a string

This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.

To keep the text which falls between the equal sign and the comma:

-replace "^.*?=(.*?),.*?$",'$1'

This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.

Debug vs Release in CMake

With CMake, it's generally recommended to do an "out of source" build. Create your CMakeLists.txt in the root of your project. Then from the root of your project:

mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release ..
make

And for Debug (again from the root of your project):

mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
make

Release / Debug will add the appropriate flags for your compiler. There are also RelWithDebInfo and MinSizeRel build configurations.


You can modify/add to the flags by specifying a toolchain file in which you can add CMAKE_<LANG>_FLAGS_<CONFIG>_INIT variables, e.g.:

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-Wall")
set(CMAKE_CXX_FLAGS_RELEASE_INIT "-Wall")

See CMAKE_BUILD_TYPE for more details.


As for your third question, I'm not sure what you are asking exactly. CMake should automatically detect and use the compiler appropriate for your different source files.

MySQL SELECT DISTINCT multiple columns

can this help?

select 
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d

How to calculate number of days between two dates

This works for me:

_x000D_
_x000D_
const from = '2019-01-01';_x000D_
const to   = '2019-01-08';_x000D_
_x000D_
Math.abs(_x000D_
    moment(from, 'YYYY-MM-DD')_x000D_
      .startOf('day')_x000D_
      .diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')_x000D_
  ) + 1_x000D_
);
_x000D_
_x000D_
_x000D_

Algorithm to randomly generate an aesthetically-pleasing color palette

I'd strongly recommend using a CG HSVtoRGB shader function, they are awesome... it gives you natural color control like a painter instead of control like a crt monitor, which you arent presumably!

This is a way to make 1 float value. i.e. Grey, into 1000 ds of combinations of color and brightness and saturation etc:

int rand = a global color randomizer that you can control by script/ by a crossfader etc.
float h = perlin(grey,23.3*rand)
float s = perlin(grey,54,4*rand)
float v = perlin(grey,12.6*rand)

Return float4 HSVtoRGB(h,s,v);

result is AWESOME COLOR RANDOMIZATION! it's not natural but it uses natural color gradients and it looks organic and controlleably irridescent / pastel parameters.

For perlin, you can use this function, it is a fast zig zag version of perlin.

function  zig ( xx : float ): float{    //lfo nz -1,1
    xx= xx+32;
    var x0 = Mathf.Floor(xx);
    var x1 = x0+1;
    var v0 = (Mathf.Sin (x0*.014686)*31718.927)%1;
    var v1 = (Mathf.Sin  (x1*.014686)*31718.927)%1;
    return Mathf.Lerp( v0 , v1 , (xx)%1 )*2-1;
}

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

localStorage.clear()

That'll clear the stored data. Then refresh and things should start to work.

How to sort an array in descending order in Ruby

It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:

#!/usr/bin/ruby

require 'benchmark'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

n = 500
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse!")   { n.times { ary.sort_by{ |a| a[:bar] }.reverse } }
end

                          user     system      total        real
sort                  3.960000   0.010000   3.970000 (  3.990886)
sort reverse          4.040000   0.000000   4.040000 (  4.038849)
sort_by -a[:bar]      0.690000   0.000000   0.690000 (  0.692080)
sort_by a[:bar]*-1    0.700000   0.000000   0.700000 (  0.699735)
sort_by.reverse!      0.650000   0.000000   0.650000 (  0.654447)

I think it's interesting that @Pablo's sort_by{...}.reverse! is fastest. Before running the test I thought it would be slower than "-a[:bar]" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.


Please note that these results are different in Ruby 1.9

Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:

                           user     system      total        real
sort                   1.340000   0.010000   1.350000 (  1.346331)
sort reverse           1.300000   0.000000   1.300000 (  1.310446)
sort_by -a[:bar]       0.430000   0.000000   0.430000 (  0.429606)
sort_by a[:bar]*-1     0.420000   0.000000   0.420000 (  0.414383)
sort_by.reverse!       0.400000   0.000000   0.400000 (  0.401275)

These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.


Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:

#!/usr/bin/ruby

require 'benchmark'

puts "Running Ruby #{RUBY_VERSION}"

ary = []
1000.times {
  ary << {:bar => rand(1000)}
}

n = 500

puts "n=#{n}"
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse")    { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
  x.report("sort_by.reverse!")   { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end

# >> Running Ruby 2.1.1
# >> n=500
# >>                            user     system      total        real
# >> sort                   0.670000   0.000000   0.670000 (  0.667754)
# >> sort reverse           0.650000   0.000000   0.650000 (  0.655582)
# >> sort_by -a[:bar]       0.260000   0.010000   0.270000 (  0.255919)
# >> sort_by a[:bar]*-1     0.250000   0.000000   0.250000 (  0.258924)
# >> sort_by.reverse        0.250000   0.000000   0.250000 (  0.245179)
# >> sort_by.reverse!       0.240000   0.000000   0.240000 (  0.242340)

New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:

Running Ruby 2.2.1
n=500
                           user     system      total        real
sort                   0.650000   0.000000   0.650000 (  0.653191)
sort reverse           0.650000   0.000000   0.650000 (  0.648761)
sort_by -a[:bar]       0.240000   0.010000   0.250000 (  0.245193)
sort_by a[:bar]*-1     0.240000   0.000000   0.240000 (  0.240541)
sort_by.reverse        0.230000   0.000000   0.230000 (  0.228571)
sort_by.reverse!       0.230000   0.000000   0.230000 (  0.230040)

Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:

Running Ruby 2.7.1
n=500     
                           user     system      total        real
sort                   0.494707   0.003662   0.498369 (  0.501064)
sort reverse           0.480181   0.005186   0.485367 (  0.487972)
sort_by -a[:bar]       0.121521   0.003781   0.125302 (  0.126557)
sort_by a[:bar]*-1     0.115097   0.003931   0.119028 (  0.122991)
sort_by.reverse        0.110459   0.003414   0.113873 (  0.114443)
sort_by.reverse!       0.108997   0.001631   0.110628 (  0.111532)

...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.

The source for Array#reverse is:

               static VALUE
rb_ary_reverse_m(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    VALUE dup = rb_ary_new2(len);

    if (len > 0) {
        const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
        VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
        do *p2-- = *p1++; while (--len > 0);
    }
    ARY_SET_LEN(dup, RARRAY_LEN(ary));
    return dup;
}

do *p2-- = *p1++; while (--len > 0); is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.

Is there a standardized method to swap two variables in Python?

I would not say it is a standard way to swap because it will cause some unexpected errors.

nums[i], nums[nums[i] - 1] = nums[nums[i] - 1], nums[i]

nums[i] will be modified first and then affect the second variable nums[nums[i] - 1].

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

When should one use a spinlock instead of mutex?

Continuing with Mecki's suggestion, this article pthread mutex vs pthread spinlock on Alexander Sandler's blog, Alex on Linux shows how the spinlock & mutexes can be implemented to test the behavior using #ifdef.

However, be sure to take the final call based on your observation, understanding as the example given is an isolated case, your project requirement, environment may be entirely different.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

If you trying to get worked hours with some accuracy, try this (tested in SQL Server 2016)

SELECT DATEDIFF(MINUTE,job_start, job_end)/60.00;

Various DATEDIFF functionalities are:

SELECT DATEDIFF(year,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(quarter,     '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(month,       '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(dayofyear,   '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(day,         '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(week,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(hour,        '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(minute,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(second,      '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');
SELECT DATEDIFF(millisecond, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

Ref: https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql?view=sql-server-2017

Watermark / hint text / placeholder TextBox

I can't believe that no one posted the obvious Extended WPF Toolkit - WatermarkTextBox from Xceed. It works quite well and is open source in case you want to customise.

PostgreSQL JOIN data from 3 tables

Something like:

select t1.name, t2.image_id, t3.path
from table1 t1 inner join table2 t2 on t1.person_id = t2.person_id
inner join table3 t3 on t2.image_id=t3.image_id

Executing a stored procedure within a stored procedure

T-SQL is not asynchronous, so you really have no choice but to wait until SP2 ends. Luckily, that's what you want.

CREATE PROCEDURE SP1 AS
   EXEC SP2
   PRINT 'Done'

How to import a csv file into MySQL workbench?

It seems a little tricky since it really had bothered me for a long time.

You just need to open the table (right click the "Select Rows- Limit 10000") and you will open a new window. In this new window, you will find "import icon".

DataGridView checkbox column - value and functionality

To test if the column is checked or not:

for (int i = 0; i < dgvName.Rows.Count; i++)
{
    if ((bool)dgvName.Rows[i].Cells[8].Value)
    {
    // Column is checked
    }
}

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

Convert an array into an ArrayList

As an ArrayList that line would be

import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();

To use the ArrayList you have do

hand.get(i); //gets the element at position i 
hand.add(obj); //adds the obj to the end of the list
hand.remove(i); //removes the element at position i
hand.add(i, obj); //adds the obj at the specified index
hand.set(i, obj); //overwrites the object at i with the new obj

Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

How to truncate float values?

use numpy.round

import numpy as np
precision = 3
floats = [1.123123123, 2.321321321321]
new_float = np.round(floats, precision)

cast or convert a float to nvarchar?

DECLARE @MyFloat [float]

SET @MyFloat = 1000109360.050

SELECT REPLACE (RTRIM (REPLACE (REPLACE (RTRIM ((REPLACE (CAST (CAST (@MyFloat AS DECIMAL (38 ,18 )) AS VARCHAR( max)), '0' , ' '))), ' ' , '0'), '.', ' ')), ' ','.')

Java Delegates?

Short story: ­­­­­­­­­­­­­­­­­­­no.

Introduction

The newest version of the Microsoft Visual J++ development environment supports a language construct called delegates or bound method references. This construct, and the new keywords delegate and multicast introduced to support it, are not a part of the JavaTM programming language, which is specified by the Java Language Specification and amended by the Inner Classes Specification included in the documentation for the JDKTM 1.1 software.

It is unlikely that the Java programming language will ever include this construct. Sun already carefully considered adopting it in 1996, to the extent of building and discarding working prototypes. Our conclusion was that bound method references are unnecessary and detrimental to the language. This decision was made in consultation with Borland International, who had previous experience with bound method references in Delphi Object Pascal.

We believe bound method references are unnecessary because another design alternative, inner classes, provides equal or superior functionality. In particular, inner classes fully support the requirements of user-interface event handling, and have been used to implement a user-interface API at least as comprehensive as the Windows Foundation Classes.

We believe bound method references are harmful because they detract from the simplicity of the Java programming language and the pervasively object-oriented character of the APIs. Bound method references also introduce irregularity into the language syntax and scoping rules. Finally, they dilute the investment in VM technologies because VMs are required to handle additional and disparate types of references and method linkage efficiently.

How to use matplotlib tight layout with Figure?

Just call fig.tight_layout() as you normally would. (pyplot is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)

There shouldn't be a difference between the QtAgg backend and the default backend (or if there is, it's a bug).

E.g.

import matplotlib.pyplot as plt

#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so 
#--    we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

plt.show()

Before Tight Layout

enter image description here

After Tight Layout

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, ncols=4)

for i, ax in enumerate(axes.flat, start=1):
    ax.set_title('Test Axes {}'.format(i))
    ax.set_xlabel('X axis')
    ax.set_ylabel('Y axis')

fig.tight_layout()

plt.show()

enter image description here

Share variables between files in Node.js?

Save any variable that want to be shared as one object. Then pass it to loaded module so it could access the variable through object reference..

// main.js
var myModule = require('./module.js');
var shares = {value:123};

// Initialize module and pass the shareable object
myModule.init(shares);

// The value was changed from init2 on the other file
console.log(shares.value); // 789

On the other file..

// module.js
var shared = null;

function init2(){
    console.log(shared.value); // 123
    shared.value = 789;
}

module.exports = {
    init:function(obj){
        // Save the shared object on current module
        shared = obj;

        // Call something outside
        init2();
    }
}

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Parsing jQuery AJAX response

 $.ajax({     
     type: "POST",
     url: '/admin/systemgoalssystemgoalupdate?format=html',
     data: formdata,
     success: function (data) {
         console.log(data);
     },
     dataType: "json"
 });

Check that a variable is a number in UNIX shell

In either ksh93 or bash with the extglob option enabled:

if [[ $var == +([0-9]) ]]; then ...

How to add Google Maps Autocomplete search box?

for me work this:

_x000D_
_x000D_
<input type="text"required id="autocomplete">_x000D_
_x000D_
<script>_x000D_
function initAutocomplete() {_x000D_
   new google.maps.places.Autocomplete(_x000D_
          (document.getElementById('autocomplete')),_x000D_
          {types: ['geocode']}_x000D_
   );_x000D_
}_x000D_
</script>_x000D_
<script src="https://maps.googleapis.com/maps/api/js?key=&libraries=places&callback=initAutocomplete"_x000D_
                async defer></script>
_x000D_
_x000D_
_x000D_

How to change onClick handler dynamically?

If you want to pass variables from the current function, another way to do this is, for example:

document.getElementById("space1").onclick = new Function("lrgWithInfo('"+myVar+"')");

If you don't need to pass information from this function, it's just:

document.getElementById("space1").onclick = new Function("lrgWithInfo('13')");

How to split page into 4 equal parts?

I did not want to add style to <body> tag and <html> tag.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 100%;
    height: 50vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 50%;
    height: 100%;
}

.quodrant1{
    top: 0;
    left: 50vh;
    background-color: red;
}

.quodrant2{
    top: 0;
    left: 0;
    background-color: yellow;
}

.quodrant3{
    top: 50vw;
    left: 0;
    background-color: blue;
}

.quodrant4{ 
    top: 50vw;
    left: 50vh;
    background-color: green;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Or making it looks nicer.

_x000D_
_x000D_
.quodrant{
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
}

.qtop,
.qbottom{
    width: 96%;
    height: 46vh;
}

.quodrant1,
.quodrant2,
.quodrant3,
.quodrant4{
    display: inline;
    float: left;
    width: 46%;
    height: 96%;
    border-radius: 30px;
    margin: 2%;
}

.quodrant1{
    background-color: #948be5;
}

.quodrant2{
    background-color: #22e235;
}

.quodrant3{
    background-color: #086e75;
}

.quodrant4{ 
    background-color: #7cf5f9;
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link type="text/css" rel="stylesheet" href="main.css" />
</head>
<body>

<div class='quodrant'>
    <div class='qtop'>
        <div class='quodrant1'></div>
        <div class='quodrant2'></div>
    </div>
    <div class='qbottom'>
        <div class='quodrant3'></div>
        <div class='quodrant4'></div>
    </div>
</div>

<script type="text/javascript" src="main.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_

Equivalent of shell 'cd' command to change the working directory?

You can change the working directory with:

import os

os.chdir(path)

There are two best practices to follow when using this method:

  1. Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
  2. Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.

Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

In my case, at some point I set my global config to use a cert that was meant for a project.

npm config list

/path/to/global/.npmrc
NODE_EXTRA_CA_CERTS = "./certs/chain.pem"

I opened the file, removed the line and npm install worked again.

How do I return a proper success/error message for JQuery .ajax() using PHP?

In order to build an AJAX webservice, you need TWO files :

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

$.ajax({
     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     },
     error: function(data) {
          //console.log(data);
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);
     }
});

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

<?php
    //...
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object
    //...

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result=array();
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']
        die(json_encode($result));
    }
?>

Close iOS Keyboard by touching anywhere using Swift

Able to achieve this by adding a global tap gesture recognizer to the window property in the AppDelegate.

This was a very catch all approach and might not be the desired solution for some but it worked for me. Please let me know if there any pitfalls to this solution.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        // Globally dismiss the keyboard when the "background" is tapped.
        window?.addGestureRecognizer(
            UITapGestureRecognizer(
              target: window, 
              action: #selector(UIWindow.endEditing(_:))
            )
        )

        return true
    }
}

Java inner class and static nested class

I have illustrated various possible correct and error scenario which can occur in java code.

    class Outter1 {

        String OutStr;

        Outter1(String str) {
            OutStr = str;
        }

        public void NonStaticMethod(String st)  {

            String temp1 = "ashish";
            final String  tempFinal1 = "ashish"; 

            //  below static attribute not permitted
            // static String tempStatic1 = "static";    

            //  below static with final attribute not permitted         
            // static final String  tempStatic1 = "ashish";  

            // synchronized keyword is not permitted below          
            class localInnerNonStatic1 {            

                synchronized    public void innerMethod(String str11) {
                    str11 = temp1 +" sharma";
                    System.out.println("innerMethod ===> "+str11);
                }

                /* 
        //  static method with final not permitted
          public static void innerStaticMethod(String str11) { 

                    str11 = temp1 +" india";
                    System.out.println("innerMethod ===> "+str11);
                }*/
            }

            // static class not permitted below
            //  static class localInnerStatic1 {   }                            

        }

        public static  void StaticMethod(String st)     {

            String temp1 = "ashish";
            final String  tempFinal1 = "ashish"; 

            // static attribute not permitted below
            //static String tempStatic1 = "static";     

            //  static with final attribute not permitted below
            // static final String  tempStatic1 = "ashish";                         

            class localInnerNonStatic1 {
                public void innerMethod(String str11) {
                    str11 = temp1 +" sharma";
                    System.out.println("innerMethod ===> "+str11);
                }

                /*
    // static method with final not permitted
    public static void innerStaticMethod(String str11) {  
                    str11 = temp1 +" india";
                    System.out.println("innerMethod ===> "+str11);
                }*/
            }

            // static class not permitted below
            //  static class localInnerStatic1 {   }    

        }

        // synchronized keyword is not permitted
        static  class inner1 {          

            static String  temp1 = "ashish";
            String  tempNonStatic = "ashish";
            // class localInner1 {

            public void innerMethod(String str11) {
                str11 = temp1 +" sharma";
                str11 = str11+ tempNonStatic +" sharma";
                System.out.println("innerMethod ===> "+str11);
            }

            public static void innerStaticMethod(String str11) {
                //  error in below step
                str11 = temp1 +" india";    
                //str11 = str11+ tempNonStatic +" sharma";
                System.out.println("innerMethod ===> "+str11);
            }
            //}
        }

        //synchronized keyword is not permitted below
        class innerNonStatic1 {             

//This is important we have to keep final with static modifier in non
// static innerclass below
            static final String  temp1 = "ashish";  
            String  tempNonStatic = "ashish";
            // class localInner1 {

            synchronized    public void innerMethod(String str11) {
                tempNonStatic = tempNonStatic +" ...";
                str11 = temp1 +" sharma";
                str11 = str11+ tempNonStatic +" sharma";
                System.out.println("innerMethod ===> "+str11);
            }

            /*
            //  error in below step
            public static void innerStaticMethod(String str11) {   
                            //  error in below step
                            // str11 = tempNonStatic +" india";                     
                            str11 = temp1 +" india";
                            System.out.println("innerMethod ===> "+str11);
                        }*/
                    //}
                }
    }

Import SQL dump into PostgreSQL database

You can do it in pgadmin3. Drop the schema(s) that your dump contains. Then right-click on the database and choose Restore. Then you can browse for the dump file.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

C#: Converting byte array to string and printing out to console

This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing , character.

public static string PrintBytes(this byte[] byteArray)
{
    var sb = new StringBuilder("new byte[] { ");
    for(var i = 0; i < byteArray.Length;i++)
    {
        var b = byteArray[i];
        sb.Append(b);
        if (i < byteArray.Length -1)
        {
            sb.Append(", ");
        }
    }
    sb.Append(" }");
    return sb.ToString();
}

The output from this method would be:

new byte[] { 48, ... 135, 31, 178, 7, 157 }

Including non-Python files with setup.py

None of the answers worked for me because my files were at the top level, outside the package. I used a custom build command instead.

import os
import setuptools
from setuptools.command.build_py import build_py
from shutil import copyfile

HERE = os.path.abspath(os.path.dirname(__file__))
NAME = "thepackage"

class BuildCommand(build_py):
    def run(self):
        build_py.run(self)

        if not self.dry_run:
            target_dir = os.path.join(self.build_lib, NAME)
            for fn in ["VERSION", "LICENSE.txt"]:
                copyfile(os.path.join(HERE, fn), os.path.join(target_dir,fn))

 
 
setuptools.setup(
    name=NAME,
    cmdclass={"build_py": BuildCommand},
    description=DESCRIPTION,
    ...
)

ImportError: No module named Crypto.Cipher

To date, I'm having same issue when importing from Crypto.Cipher import AES even when I've installed/reinstalled pycrypto a few times. End up it's because pip defaulted to python3.

~ pip --version
pip 18.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

installing pycrypto with pip2 should solve this issue.

Laravel check if collection is empty

I prefer

(!$mentor)

Is more effective and accurate

How to get the error message from the error code returned by GetLastError()?

i'll leave this here since i will need to use it later. It's a source for a small binary compatible tool that will work equally well in assembly, C and C++.

GetErrorMessageLib.c (compiled to GetErrorMessageLib.dll)

#include <Windows.h>

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
__declspec(dllexport)
int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{    
    LPSTR tmp;
    DWORD result_len;

    result_len = FormatMessageA (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPSTR)&tmp,
        0,
        NULL
    );        

    if (result_len == 0) {
        return -1;
    }

    // FormatMessage's return is 1 character too short.
    ++result_len;

    strncpy(lpResult, tmp, dwBytes);

    lpResult[dwBytes - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_len <= dwBytes) {
        return 0;
    } else {
        return result_len;
    }
}

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
__declspec(dllexport)
int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{   
    LPWSTR tmp;
    DWORD nchars;
    DWORD result_bytes;

    nchars = dwBytes >> 1;

    result_bytes = 2 * FormatMessageW (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&tmp,
        0,
        NULL
    );    

    if (result_bytes == 0) {
        return -1;
    } 

    // FormatMessage's return is 1 character too short.
    result_bytes += 2;

    wcsncpy(lpResult, tmp, nchars);
    lpResult[nchars - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_bytes <= dwBytes) {
        return 0;
    } else {
        return result_bytes * 2;
    }
}

inline version(GetErrorMessage.h):

#ifndef GetErrorMessage_H 
#define GetErrorMessage_H 
#include <Windows.h>    

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
static inline int GetErrorMessageA(DWORD dwErrorCode, LPSTR lpResult, DWORD dwBytes)
{    
    LPSTR tmp;
    DWORD result_len;

    result_len = FormatMessageA (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPSTR)&tmp,
        0,
        NULL
    );        

    if (result_len == 0) {
        return -1;
    }

    // FormatMessage's return is 1 character too short.
    ++result_len;

    strncpy(lpResult, tmp, dwBytes);

    lpResult[dwBytes - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_len <= dwBytes) {
        return 0;
    } else {
        return result_len;
    }
}

/***
 * returns 0 if there was enough space, size of buffer in bytes needed
 * to fit the result, if there wasn't enough space. -1 on error.
 */
static inline int GetErrorMessageW(DWORD dwErrorCode, LPWSTR lpResult, DWORD dwBytes)
{   
    LPWSTR tmp;
    DWORD nchars;
    DWORD result_bytes;

    nchars = dwBytes >> 1;

    result_bytes = 2 * FormatMessageW (
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        dwErrorCode,
        LANG_SYSTEM_DEFAULT,
        (LPWSTR)&tmp,
        0,
        NULL
    );    

    if (result_bytes == 0) {
        return -1;
    } 

    // FormatMessage's return is 1 character too short.
    result_bytes += 2;

    wcsncpy(lpResult, tmp, nchars);
    lpResult[nchars - 1] = 0;
    LocalFree((HLOCAL)tmp);

    if (result_bytes <= dwBytes) {
        return 0;
    } else {
        return result_bytes * 2;
    }
}

#endif /* GetErrorMessage_H */

dynamic usecase(assumed that error code is valid, otherwise a -1 check is needed):

#include <Windows.h>
#include <Winbase.h>
#include <assert.h>
#include <stdio.h>

int main(int argc, char **argv)
{   
    int (*GetErrorMessageA)(DWORD, LPSTR, DWORD);
    int (*GetErrorMessageW)(DWORD, LPWSTR, DWORD);
    char result1[260];
    wchar_t result2[260];

    assert(LoadLibraryA("GetErrorMessageLib.dll"));

    GetErrorMessageA = (int (*)(DWORD, LPSTR, DWORD))GetProcAddress (
        GetModuleHandle("GetErrorMessageLib.dll"),
        "GetErrorMessageA"
    );        
    GetErrorMessageW = (int (*)(DWORD, LPWSTR, DWORD))GetProcAddress (
        GetModuleHandle("GetErrorMessageLib.dll"),
        "GetErrorMessageW"
    );        

    GetErrorMessageA(33, result1, sizeof(result1));
    GetErrorMessageW(33, result2, sizeof(result2));

    puts(result1);
    _putws(result2);

    return 0;
}

regular use case(assumes error code is valid, otherwise -1 return check is needed):

#include <stdio.h>
#include "GetErrorMessage.h"
#include <stdio.h>

int main(int argc, char **argv)
{
    char result1[260];
    wchar_t result2[260];

    GetErrorMessageA(33, result1, sizeof(result1));
    puts(result1);

    GetErrorMessageW(33, result2, sizeof(result2));
    _putws(result2);

    return 0;
}

example using with assembly gnu as in MinGW32(again, assumed that error code is valid, otherwise -1 check is needed).

    .global _WinMain@16

    .section .text
_WinMain@16:
    // eax = LoadLibraryA("GetErrorMessageLib.dll")
    push $sz0
    call _LoadLibraryA@4 // stdcall, no cleanup needed

    // eax = GetProcAddress(eax, "GetErrorMessageW")
    push $sz1
    push %eax
    call _GetProcAddress@8 // stdcall, no cleanup needed

    // (*eax)(errorCode, szErrorMessage)
    push $200
    push $szErrorMessage
    push errorCode       
    call *%eax // cdecl, cleanup needed
    add $12, %esp

    push $szErrorMessage
    call __putws // cdecl, cleanup needed
    add $4, %esp

    ret $16

    .section .rodata
sz0: .asciz "GetErrorMessageLib.dll"    
sz1: .asciz "GetErrorMessageW"
errorCode: .long 33

    .section .data
szErrorMessage: .space 200

result: The process cannot access the file because another process has locked a portion of the file.

Setting max-height for table cell contents

Just put the labels in a div inside the TD and put the height and overflow.. like below.

<table>
<tr>
  <td><div style="height:40px; overflow:hidden">Sample</div></td>
  <td><div style="height:40px; overflow:hidden">Text</div></td>
  <td><div style="height:40px; overflow:hidden">Here</div></td>
</tr>
</table>

How to retrieve raw post data from HttpServletRequest in java

We had a situation where IE forced us to post as text/plain, so we had to manually parse the parameters using getReader. The servlet was being used for long polling, so when AsyncContext::dispatch was executed after a delay, it was literally reposting the request empty handed.

So I just stored the post in the request when it first appeared by using HttpServletRequest::setAttribute. The getReader method empties the buffer, where getParameter empties the buffer too but stores the parameters automagically.

    String input = null;

    // we have to store the string, which can only be read one time, because when the
    // servlet awakens an AsyncContext, it reposts the request and returns here empty handed
    if ((input = (String) request.getAttribute("com.xp.input")) == null) {
        StringBuilder buffer = new StringBuilder();
        BufferedReader reader = request.getReader();

        String line;
        while((line = reader.readLine()) != null){
            buffer.append(line);
        }
        // reqBytes = buffer.toString().getBytes();

        input = buffer.toString();
        request.setAttribute("com.xp.input", input);
    }

    if (input == null) {
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.print("{\"act\":\"fail\",\"msg\":\"invalid\"}");
    }       

Binding to static property

Leanest answer (.net 4.5 and later):

    static public event EventHandler FilterStringChanged;
    static string _filterString;
    static public string FilterString
    {
        get { return _filterString; }
        set
        {
            _filterString= value;
            FilterStringChanged?.Invoke(null, EventArgs.Empty);
        }
    }

and XAML:

    <TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>

Don't neglect the brackets

PHP "pretty print" json_encode

And for PHP 5.3, you can use this function, which can be embedded in a class or used in procedural style:

http://svn.kd2.org/svn/misc/libs/tools/json_readable_encode.php

Transform only one axis to log10 scale with ggplot2

Another solution using scale_y_log10 with trans_breaks, trans_format and annotation_logticks()

library(ggplot2)

m <- ggplot(diamonds, aes(y = price, x = color))

m + geom_boxplot() +
  scale_y_log10(
    breaks = scales::trans_breaks("log10", function(x) 10^x),
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  ) +
  theme_bw() +
  annotation_logticks(sides = 'lr') +
  theme(panel.grid.minor = element_blank())

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

I've investigated this issue, referring to the LayoutInflater docs and setting up a small sample demonstration project. The following tutorials shows how to dynamically populate a layout using LayoutInflater.

Before we get started see what LayoutInflater.inflate() parameters look like:

  • resource: ID for an XML layout resource to load (e.g., R.layout.main_page)
  • root: Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
  • attachToRoot: Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.

  • Returns: The root View of the inflated hierarchy. If root was supplied and attachToRoot is true, this is root; otherwise it is the root of the inflated XML file.

Now for the sample layout and code.

Main layout (main.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

Added into this container is a separate TextView, visible as small red square if layout parameters are successfully applied from XML (red.xml):

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="25dp"
    android:layout_height="25dp"
    android:background="#ff0000"
    android:text="red" />

Now LayoutInflater is used with several variations of call parameters

public class InflaterTest extends Activity {

    private View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      setContentView(R.layout.main);
      ViewGroup parent = (ViewGroup) findViewById(R.id.container);

      // result: layout_height=wrap_content layout_width=match_parent
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view);

      // result: layout_height=100 layout_width=100
      view = LayoutInflater.from(this).inflate(R.layout.red, null);
      parent.addView(view, 100, 100);

      // result: layout_height=25dp layout_width=25dp
      // view=textView due to attachRoot=false
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, false);
      parent.addView(view);

      // result: layout_height=25dp layout_width=25dp 
      // parent.addView not necessary as this is already done by attachRoot=true
      // view=root due to parent supplied as hierarchy root and attachRoot=true
      view = LayoutInflater.from(this).inflate(R.layout.red, parent, true);
    }
}

The actual results of the parameter variations are documented in the code.

SYNOPSIS: Calling LayoutInflater without specifying root leads to inflate call ignoring the layout parameters from the XML. Calling inflate with root not equal null and attachRoot=true does load the layout parameters, but returns the root object again, which prevents further layout changes to the loaded object (unless you can find it using findViewById()). The calling convention you most likely would like to use is therefore this one:

loadedView = LayoutInflater.from(context)
                .inflate(R.layout.layout_to_load, parent, false);

To help with layout issues, the Layout Inspector is highly recommended.

Gets last digit of a number

public static void main(String[] args) {

    System.out.println(lastDigit(2347));
}

public static int lastDigit(int number)
{
    //your code goes here. 
    int last = number % 10;

    return last;
}

0/p:

7

Invalid application path

The error message might be a bug. I ignored it and everything worked for me.

IIS Invalid Application Path Screen Shot

See Here: http://forums.iis.net/t/1177952.aspx

and here http://forums.iis.net/p/1182820/2000936.aspx

mysql update multiple columns with same now()

There are 2 ways to this;

First, I would advice you declare now() as a variable before injecting it into the sql statement. Lets say;

var x = now();
mysql> UPDATE table SET last_update=$x, last_monitor=$x WHERE id=1;

Logically if you want a different input for last_monitor then you will add another variable like;

var y = time();
mysql> UPDATE table SET last_update=$x, last_monitor=$y WHERE id=1;

This way you can use the variables as many times as you can, not only in mysql statements but also in the server-side scripting-language(like PHP) you are using in your project. Remember these same variables can be inserted as inputs in a form on the front-end of the application. That makes the project dynamic and not static.

Secondly if now() indicates time of update then using mysql you can decalre the property of the row as a timestamp. Every time a row is inserted or updated time is updated too.

Angular File Upload

In Angular 7/8/9

Source Link

enter image description here

Using Bootstrap Form

<form>
    <div class="form-group">
        <fieldset class="form-group">

            <label>Upload Logo</label>
            {{imageError}}
            <div class="custom-file fileInputProfileWrap">
                <input type="file" (change)="fileChangeEvent($event)" class="fileInputProfile">
                <div class="img-space">

                    <ng-container *ngIf="isImageSaved; else elseTemplate">
                        <img [src]="cardImageBase64" />
                    </ng-container>
                    <ng-template #elseTemplate>

                        <img src="./../../assets/placeholder.png" class="img-responsive">
                    </ng-template>

                </div>

            </div>
        </fieldset>
    </div>
    <a class="btn btn-danger" (click)="removeImage()" *ngIf="isImageSaved">Remove</a>
</form>

In Component Class

fileChangeEvent(fileInput: any) {
    this.imageError = null;
    if (fileInput.target.files && fileInput.target.files[0]) {
        // Size Filter Bytes
        const max_size = 20971520;
        const allowed_types = ['image/png', 'image/jpeg'];
        const max_height = 15200;
        const max_width = 25600;

        if (fileInput.target.files[0].size > max_size) {
            this.imageError =
                'Maximum size allowed is ' + max_size / 1000 + 'Mb';

            return false;
        }

        if (!_.includes(allowed_types, fileInput.target.files[0].type)) {
            this.imageError = 'Only Images are allowed ( JPG | PNG )';
            return false;
        }
        const reader = new FileReader();
        reader.onload = (e: any) => {
            const image = new Image();
            image.src = e.target.result;
            image.onload = rs => {
                const img_height = rs.currentTarget['height'];
                const img_width = rs.currentTarget['width'];

                console.log(img_height, img_width);


                if (img_height > max_height && img_width > max_width) {
                    this.imageError =
                        'Maximum dimentions allowed ' +
                        max_height +
                        '*' +
                        max_width +
                        'px';
                    return false;
                } else {
                    const imgBase64Path = e.target.result;
                    this.cardImageBase64 = imgBase64Path;
                    this.isImageSaved = true;
                    // this.previewImagePath = imgBase64Path;
                }
            };
        };

        reader.readAsDataURL(fileInput.target.files[0]);
    }
}

removeImage() {
    this.cardImageBase64 = null;
    this.isImageSaved = false;
}

Twitter bootstrap float div right

You have two span6 divs within your row so that will take up the whole 12 spans that a row is made up of.

Adding pull-right to the second span6 div isn't going to do anything to it as it's already sitting to the right.

If you mean you want to have the text in the second span6 div aligned to the right then simple add a new class to that div and give it the text-align: right value e.g.

.myclass {
    text-align: right;
}

UPDATE:

EricFreese pointed out that in the 2.3 release of Bootstrap (last week) they've added text-align utility classes that you can use:

  • .text-left
  • .text-center
  • .text-right

http://twitter.github.com/bootstrap/base-css.html#typography

no default constructor exists for class

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values.

How do I check out an SVN project into Eclipse as a Java project?

If the were checked as plugin-projects, than you just need to check them out. But do not select the "trunk"(for example) to speed it up. You must select all the projects you want to check out and proceed. Eclipse will than recognize them as such.

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

WAMP Cannot access on local network 403 Forbidden

For those who may be running WAMP 3.1.4 with Apache 2.4.35 on Windows 10 (64-bit)

If you're having issues with external devices connecting to your localhost, and receiving a 403 Forbidden error, it may be an issue with your httpd.conf and the httpd-vhosts.conf files and the "Require local" line they both have within them.

[Before] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
   Require local     <--- This is the offending line.
 </Directory>
</VirtualHost>

[After] httpd-vhosts.conf

<VirtualHost *:80>
 ServerName localhost
 ServerAlias localhost
 DocumentRoot "${INSTALL_DIR}/www"
 <Directory "${INSTALL_DIR}/www/">
   Options +Indexes +Includes +FollowSymLinks +MultiViews
   AllowOverride All
 </Directory>
</VirtualHost>

Additionally, you'll need to update your httpd.conf file as follows:

[Before] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

    Require local  #<--- This is the offending line.
</Directory>

[After] httpd.conf

DocumentRoot "${INSTALL_DIR}/www"
<Directory "${INSTALL_DIR}/www/">
#   onlineoffline tag - don't remove

#   Require local
</Directory>

Make sure to restart your WAMP server via (System tray at bottom-right of screen --> left-click WAMP icon --> "Restart all Services").

Then refresh your machine's browser on localhost to ensure you've still got proper connectivity there, and then refresh your other external devices that you were previously attempting to connect.

Disclaimer: If you're in a corporate setting, this is untested from a security perspective; please ensure you're keenly aware of your local development environment's access protocols before implementing any sweeping changes.

Test a weekly cron job

The solution I am using is as follows:

  1. Edit crontab(use command :crontab -e) to run the job as frequently as needed (every 1 minute or 5 minutes)
  2. Modify the shell script which should be executed using cron to prints the output into some file (e.g: echo "Working fine" >>
    output.txt)
  3. Check the output.txt file using the command : tail -f output.txt, which will print the latest additions into this file, and thus you can track the execution of the script

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

This is the job for style property:

document.getElementById("remember").style.visibility = "visible";

How to open a PDF file in an <iframe>?

This is the code to link an HTTP(S) accessible PDF from an <iframe>:

<iframe src="https://research.google.com/pubs/archive/44678.pdf"
   width="800" height="600">

Fiddle: http://jsfiddle.net/cEuZ3/1545/

EDIT: and you can use Javascript, from the <a> tag (onclick event) to set iFrame' SRC attribute at run-time...

EDIT 2: Apparently, it is a bug (but there are workarounds):

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

Open file with associated application

In .Net Core (as of v2.2) it should be:

new Process
{
    StartInfo = new ProcessStartInfo(@"file path")
    {
        UseShellExecute = true
    }
}.Start();

Related github issue can be found here

How do I ignore ampersands in a SQL script running from SQL Plus?

According to this nice FAQ there are a couple solutions.

You might also be able to escape the ampersand with the backslash character \ if you can modify the comment.

How to add soap header in java

i was facing the same issue and solved it by removing the xmlns:wsu attribute.Try not adding it in the usernameToken.Hope this solves your issue too.

How to check if a float value is a whole number

All the answers are good but a sure fire method would be

def whole (n):
     return (n*10)%10==0

The function returns True if it's a whole number else False....I know I'm a bit late but here's one of the interesting methods which I made...

Edit: as stated by the comment below, a cheaper equivalent test would be:

def whole(n):
    return n%1==0

Convert decimal to hexadecimal in UNIX shell script

echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc

Read String line by line

You can also use the split method of String:

String[] lines = myString.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

Singleton in Android

Tip: To create singleton class In Android Studio, right click in your project and open menu:

New -> Java Class -> Choose Singleton from dropdown menu

enter image description here

Scala best way of turning a Collection into a Map-by-key?

You can use

c map (t => t.getP -> t) toMap

but be aware that this needs 2 traversals.

Filter Linq EXCEPT on properties

MoreLinq has something useful for this MoreLinq.Source.MoreEnumerable.ExceptBy

https://github.com/gsscoder/morelinq/blob/master/MoreLinq/ExceptBy.cs

namespace MoreLinq
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    static partial class MoreEnumerable
    {
        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector)
        {
            return ExceptBy(first, second, keySelector, null);
        }

        /// <summary>
        /// Returns the set of elements in the first sequence which aren't
        /// in the second sequence, according to a given key selector.
        /// </summary>
        /// <remarks>
        /// This is a set operation; if multiple elements in <paramref name="first"/> have
        /// equal keys, only the first such element is returned.
        /// This operator uses deferred execution and streams the results, although
        /// a set of keys from <paramref name="second"/> is immediately selected and retained.
        /// </remarks>
        /// <typeparam name="TSource">The type of the elements in the input sequences.</typeparam>
        /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
        /// <param name="first">The sequence of potentially included elements.</param>
        /// <param name="second">The sequence of elements whose keys may prevent elements in
        /// <paramref name="first"/> from being returned.</param>
        /// <param name="keySelector">The mapping from source element to key.</param>
        /// <param name="keyComparer">The equality comparer to use to determine whether or not keys are equal.
        /// If null, the default equality comparer for <c>TSource</c> is used.</param>
        /// <returns>A sequence of elements from <paramref name="first"/> whose key was not also a key for
        /// any element in <paramref name="second"/>.</returns>

        public static IEnumerable<TSource> ExceptBy<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            if (first == null) throw new ArgumentNullException("first");
            if (second == null) throw new ArgumentNullException("second");
            if (keySelector == null) throw new ArgumentNullException("keySelector");
            return ExceptByImpl(first, second, keySelector, keyComparer);
        }

        private static IEnumerable<TSource> ExceptByImpl<TSource, TKey>(this IEnumerable<TSource> first,
            IEnumerable<TSource> second,
            Func<TSource, TKey> keySelector,
            IEqualityComparer<TKey> keyComparer)
        {
            var keys = new HashSet<TKey>(second.Select(keySelector), keyComparer);
            foreach (var element in first)
            {
                var key = keySelector(element);
                if (keys.Contains(key))
                {
                    continue;
                }
                yield return element;
                keys.Add(key);
            }
        }
    }
}

Is there a Google Voice API?

Be nice if there was a Javascript API version. That way can integrate w/ other AJAX apps or browser extensions/gadgets/widgets.

Right now, current APIs restrict to web app technologies that support Java, .NET, or Python, more for server side, unless may use Google Web Toolkit to translate Java code to Javascript.

$lookup on ObjectId's in an array

Starting with MongoDB v3.4 (released in 2016), the $lookup aggregation pipeline stage can also work directly with an array. There is no need for $unwind any more.

This was tracked in SERVER-22881.

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

How can I see the request headers made by curl when sending a request to the server?

I think curl --verbose/-v is the easiest. It will spit out the request headers (lines prefixed with '>') without having to write to a file:

$ curl -v -I -H "Testing: Test header so you see this works" http://stackoverflow.com/
* About to connect() to stackoverflow.com port 80 (#0)
*   Trying 69.59.196.211... connected
* Connected to stackoverflow.com (69.59.196.211) port 80 (#0)
> HEAD / HTTP/1.1
> User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/0.9.8h zlib/1.2.3 libssh2/0.15-CVS
> Host: stackoverflow.com
> Accept: */*
> Testing: Test header so you see this works
>
< HTTP/1.0 200 OK
...

Define an <img>'s src attribute in CSS

#divID {
    background-image: url("http://imageurlhere.com");
    background-repeat: no-repeat;
    width: auto; /*or your image's width*/
    height: auto; /*or your image's height*/
    margin: 0;
    padding: 0;
}

Autocompletion of @author in Intellij

One more option, not exactly what you asked, but can be useful:

Go to Settings -> Editor -> File and code templates -> Includes tab (on the right). There is a template header for the new files, you can use the username here:

/**
 * @author myname
 */

For system username use:

/**
 * @author ${USER}
 */

Screen shot from Intellij 2016.02

Spring Boot: Cannot access REST Controller on localhost (404)

For me, the problem was that I had set up the Application in a way that it always immediately shut down after starting. So by the time I tried out if I could access the controller, the Application wasn't running anymore. The problem with immediately shutting down is adressed in this thread.

How does Go update third-party packages?

Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.

A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:

go get -u github.com/... // ('...' being the wildcard). 

This would go ahead and only update your github packages in the current $GOPATH

Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:

go get -u github.com/orgA/...

Capitalize words in string

Ivo's answer is good, but I prefer to not match on \w because there's no need to capitalize 0-9 and A-Z. We can ignore those and only match on a-z.

'your string'.replace(/\b[a-z]/g, match => match.toUpperCase())
// => 'Your String'

It's the same output, but I think clearer in terms of self-documenting code.

Convert XML to JSON (and back) using Javascript

A while back I wrote this tool https://bitbucket.org/surenrao/xml2json for my TV Watchlist app, hope this helps too.

Synopsys: A library to not only convert xml to json, but is also easy to debug (without circular errors) and recreate json back to xml. Features :- Parse xml to json object. Print json object back to xml. Can be used to save xml in IndexedDB as X2J objects. Print json object.

What's the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):

  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not pending anymore):

  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) When x is a Promise that is pending:

  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Read more on this topic on the Promise.prototype.then() docs.

Attach the Source in Eclipse of a jar

This worked for me for Eclipse-Luna:

  1. Right Click on the *.jar in the Referenced Libraries folder under your project, then click on Properties
  2. Use the Java Source Attachment page to point to the Workspace location or the External location to the source code of that jar.

UIImageView - How to get the file name of the image assigned?

Nope. No way to do that natively. You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).

How do I make a self extract and running installer

Okay I have got it working, hope this information is useful.

  1. First of all I now realize that not only do self-extracting zip start extracting with doubleclick, but they require no extraction application to be installed on the users computer because the extractor code is in the archive itself. This means that you will get a different user experience depending on what you application you use to create the sfx

  2. I went with WinRar as follows, this does not require you to create an sfx file, everything can be created via the gui:

    • Select files, right click and select Add to Archive
    • Use Browse.. to create the archive in the folder above
    • Change Archive Format to Zip
    • Enable Create SFX archive
    • Select Advanced tab
    • Select SFX Options
    • Select Setup tab
    • Enter setup.exe into the Run after Extraction field
    • Select Modes tab
    • Enable Unpack to temporary folder
    • Select text and Icon tab
    • Enter a more appropriate title for your task
    • Select OK
    • Select OK

The resultant exe unzips to a temporary folder and then starts the installer

center image in div with overflow hidden

you the have to corp your image from sides to hide it try this

3 Easy and Fast CSS Techniques for Faux Image Cropping | Css ...

one of the demo for the first way on the site above

try demo

i will do some reading on it too

Case statement in MySQL

Another thing to keep in mind is there are two different CASEs with MySQL: one like what @cdhowie and others describe here (and documented here: http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case) and something which is called a CASE, but has completely different syntax and completely different function, documented here: https://dev.mysql.com/doc/refman/5.0/en/case.html

Invariably, I first use one when I want the other.

How to backup a local Git repository?

I started hacking away a bit on Yar's script and the result is on github, including man pages and install script:

https://github.com/najamelan/git-backup

Installation:

git clone "https://github.com/najamelan/git-backup.git"
cd git-backup
sudo ./install.sh

Welcoming all suggestions and pull request on github.

#!/usr/bin/env ruby
#
# For documentation please sea man git-backup(1)
#
# TODO:
# - make it a class rather than a function
# - check the standard format of git warnings to be conform
# - do better checking for git repo than calling git status
# - if multiple entries found in config file, specify which file
# - make it work with submodules
# - propose to make backup directory if it does not exists
# - depth feature in git config (eg. only keep 3 backups for a repo - like rotate...)
# - TESTING



# allow calling from other scripts
def git_backup


# constants:
git_dir_name    = '.git'          # just to avoid magic "strings"
filename_suffix = ".git.bundle"   # will be added to the filename of the created backup


# Test if we are inside a git repo
`git status 2>&1`

if $?.exitstatus != 0

   puts 'fatal: Not a git repository: .git or at least cannot get zero exit status from "git status"'
   exit 2


else # git status success

   until        File::directory?( Dir.pwd + '/' + git_dir_name )             \
            or  File::directory?( Dir.pwd                      ) == '/'


         Dir.chdir( '..' )
   end


   unless File::directory?( Dir.pwd + '/.git' )

      raise( 'fatal: Directory still not a git repo: ' + Dir.pwd )

   end

end


# git-config --get of version 1.7.10 does:
#
# if the key does not exist git config exits with 1
# if the key exists twice in the same file   with 2
# if the key exists exactly once             with 0
#
# if the key does not exist       , an empty string is send to stdin
# if the key exists multiple times, the last value  is send to stdin
# if exaclty one key is found once, it's value      is send to stdin
#


# get the setting for the backup directory
# ----------------------------------------

directory = `git config --get backup.directory`


# git config adds a newline, so remove it
directory.chomp!


# check exit status of git config
case $?.exitstatus

   when 1 : directory = Dir.pwd[ /(.+)\/[^\/]+/, 1]

            puts 'Warning: Could not find backup.directory in your git config file. Please set it. See "man git config" for more details on git configuration files. Defaulting to the same directroy your git repo is in: ' + directory

   when 2 : puts 'Warning: Multiple entries of backup.directory found in your git config file. Will use the last one: ' + directory

   else     unless $?.exitstatus == 0 then raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus ) end

end


# verify directory exists
unless File::directory?( directory )

   raise( 'fatal: backup directory does not exists: ' + directory )

end


# The date and time prefix
# ------------------------

prefix           = ''
prefix_date      = Time.now.strftime( '%F'       ) + ' - ' # %F = YYYY-MM-DD
prefix_time      = Time.now.strftime( '%H:%M:%S' ) + ' - '
add_date_default = true
add_time_default = false

prefix += prefix_date if git_config_bool( 'backup.prefix-date', add_date_default )
prefix += prefix_time if git_config_bool( 'backup.prefix-time', add_time_default )



# default bundle name is the name of the repo
bundle_name = Dir.pwd.split('/').last

# set the name of the file to the first command line argument if given
bundle_name = ARGV[0] if( ARGV[0] )


bundle_name = File::join( directory, prefix + bundle_name + filename_suffix )


puts "Backing up to bundle #{bundle_name.inspect}"


# git bundle will print it's own error messages if it fails
`git bundle create #{bundle_name.inspect} --all --remotes`


end # def git_backup



# helper function to call git config to retrieve a boolean setting
def git_config_bool( option, default_value )

   # get the setting for the prefix-time from git config
   config_value = `git config --get #{option.inspect}`

   # check exit status of git config
   case $?.exitstatus

      # when not set take default
      when 1 : return default_value

      when 0 : return true unless config_value =~ /(false|no|0)/i

      when 2 : puts 'Warning: Multiple entries of #{option.inspect} found in your git config file. Will use the last one: ' + config_value
               return true unless config_value =~ /(false|no|0)/i

      else     raise( 'fatal: unknown exit status from git-config: ' + $?.exitstatus )

   end
end

# function needs to be called if we are not included in another script
git_backup if __FILE__ == $0

How to extract one column of a csv file

Many answers for this questions are great and some have even looked into the corner cases. I would like to add a simple answer that can be of daily use... where you mostly get into those corner cases (like having escaped commas or commas in quotes etc.,).

FS (Field Separator) is the variable whose value is dafaulted to space. So awk by default splits at space for any line.

So using BEGIN (Execute before taking input) we can set this field to anything we want...

awk 'BEGIN {FS = ","}; {print $3}'

The above code will print the 3rd column in a csv file.

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

You should simply apply the following transformation to your input data array.

input_data = input_data.reshape((-1, image_side1, image_side2, channels))

UIView's frame, bounds, center, origin, when to use what?

They are related values, and kept consistent by the property setter/getter methods (and using the fact that frame is a purely synthesized value, not backed by an actual instance variable).

The main equations are:

frame.origin = center - bounds.size / 2

(which is the same as)

center = frame.origin + bounds.size / 2

(and there’s also)

frame.size = bounds.size

That's not code, just equations to express the invariant between the three properties. These equations also assume your view's transform is the identity, which it is by default. If it's not, then bounds and center keep the same meaning, but frame can change. Unless you're doing non-right-angle rotations, the frame will always be the transformed view in terms of the superview's coordinates.

This stuff is all explained in more detail with a useful mini-library here:

http://bynomial.com/blog/?p=24

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

dll missing in JDBC

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

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

$(this).serialize() -- How to add a value?

Don't forget you can always do:

<input type="hidden" name="NonFormName" value="NonFormValue" />

in your actual form, which may be better for your code depending on the case.

ssh : Permission denied (publickey,gssapi-with-mic)

I had the same issue while using vagrant. So from my Mac I was trying to ssh to a vagrant box (CentOS 7)

Solved it by amending the /etc/ssh/sshd_config PasswordAuthentication yes then re-started the service using sudo systemctl restart sshd

Hope this helps.

PHP decoding and encoding json with unicode characters

$json = array('tag' => 'Odómetro'); // Original array
$json = json_encode($json); // {"Tag":"Od\u00f3metro"}
$json = json_decode($json); // Od\u00f3metro becomes  Odómetro
echo $json->{'tag'}; // Odómetro
echo utf8_decode($json->{'tag'}); // Odómetro

You were close, just use utf8_decode.

How to dynamically remove items from ListView on a button click?

<ImageView
    android:id="@+id/btnDelete"
    android:layout_width="35dp"
    android:layout_height="match_parent"
    android:layout_alignBottom="@+id/editTipo"
    android:layout_alignParentRight="true"
    android:background="@drawable/abc_ic_clear"
    android:onClick="item_delete_handler"/>

And create Event item_delete_handler,

How to export data to CSV in PowerShell?

You can always use the

echo "Column1`tColumn2`tColumn3..." >> results.csv

You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:

echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
    $count = 0
    $count2 = 13490

    if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
        echo "$name`tUp" >> results.csv
    }
    else {
        echo "$name`tDown" >> results.csv
    }

    $count++
    Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)

}

This is the easiest way to me. The output I get is :

Host|State
----------
H1  |Up
H2  |UP
H3  |Down

You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look

How to find the index of an element in an array in Java?

Very Heavily Edited. I think either you want this:

class CharStorage {
    /** set offset to 1 if you want b=1, o=2, y=3 instead of b=0... */
    private final int offset=0;
    private int array[]=new int[26];

    /** Call this with up to 26 characters to initialize the array.  For 
      * instance, if you pass "boy" it will init to b=0,o=1,y=2.
      */
    void init(String s) {
        for(int i=0;i<s.length;i++)
            store(s.charAt(i)-'a' + offset,i); 
    }

    void store(char ch, int value) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        array[ch-'a']=value;
    }

    int get(char ch) {
        if(ch < 'a' || ch > 'z') throw new IllegalArgumentException();
        return array[ch-'a'];
    }
}

(Note that you may have to adjust the init method if you want to use 1-26 instead of 0-25)

or you want this:

int getLetterPossitionInAlphabet(char c) {
    return c - 'a' + 1
}

The second is if you always want a=1, z=26. The first will let you put in a string like "qwerty" and assign q=0, w=1, e=2, r=3...

How do I get client IP address in ASP.NET CORE?

Running .NET core (3.1.4) on IIS behind a Load balancer did not work with other suggested solutions.

Manually reading the X-Forwarded-For header does.

IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
    // when running behind a load balancer you can expect this header
    var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
    ip = IPAddress.Parse(header);
}
else
{
    // this will always have a value (running locally in development won't have the header)
    ip = Request.HttpContext.Connection.RemoteIpAddress;
}

PostgreSQL, checking date relative to "today"

select * from mytable where mydate > now() - interval '1 year';

If you only care about the date and not the time, substitute current_date for now()

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

how to write value into cell with vba code without auto type conversion?

Cells(1,1).Value2 = "'123,456"

note the single apostrophe before the number - this will signal to excel that whatever follows has to be interpreted as text.

How to push objects in AngularJS between ngRepeat arrays

You'd be much better off using the same array with both lists, and creating angular filters to achieve your goal.

http://docs.angularjs.org/guide/dev_guide.templates.filters.creating_filters

Rough, untested code follows:

appModule.filter('checked', function() {
    return function(input, checked) {
        if(!input)return input;
        var output = []
        for (i in input){
            var item = input[i];
            if(item.checked == checked)output.push(item);
        }
        return output
    }
});

and the view (i added an "uncheck" button too)

<div id="AddItem">
     <h3>Add Item</h3>

    <input value="1" type="number" placeholder="1" ng-model="itemAmount">
    <input value="" type="text" placeholder="Name of Item" ng-model="itemName">
    <br/>
    <button ng-click="addItem()">Add to list</button>
</div>
<!-- begin: LIST OF CHECKED ITEMS -->
<div id="CheckedList">
     <h3>Checked Items: {{getTotalCheckedItems()}}</h3>

     <h4>Checked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:true" class="item-checked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td> 
               <i>this item is checked!</i>
               <button ng-click="item.checked = false">uncheck item</button>

            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF CHECKED ITEMS -->
<!-- begin: LIST OF UNCHECKED ITEMS -->
<div id="UncheckedList">
     <h3>Unchecked Items: {{getTotalItems()}}</h3>

     <h4>Unchecked:</h4>

    <table>
        <tr ng-repeat="item in items | checked:false" class="item-unchecked">
            <td><b>amount:</b> {{item.amount}} -</td>
            <td><b>name:</b> {{item.name}} -</td>
            <td>
                <button ng-click="item.checked = true">check item</button>
            </td>
        </tr>
    </table>
</div>
<!-- end: LIST OF ITEMS -->

Then you dont need the toggle methods etc in your controller

What's the difference between align-content and align-items?

The main difference is when the height of the elements are not the same! Then you can see how in the row, they are all center\end\start

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

Moment JS - check if a date is today or in the future

invert isBefore method of moment to check if a date is same as today or in future like this:

!moment(yourDate).isBefore(moment(), "day");

Graph visualization library in JavaScript

I've just put together what you may be looking for: http://www.graphdracula.net

It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:

var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");

I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!


You may want to have a look at other projects, too! Below are two meta-comparisons:

  • SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.

  • DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":Selection DataVisualization.ch

Here's a list of similar projects (some have been already mentioned here):

Pure JavaScript Libraries

  • vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.

  • Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.

  • The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.

  • D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.

  • Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.

  • sigma.js Lightweight but powerful library for drawing graphs

  • jsPlumb jQuery plug-in for creating interactive connected graphs

  • Springy - a force-directed graph layout algorithm

  • Processing.js Javascript port of the Processing library by John Resig

  • JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.

  • RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.

  • JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package

  • mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.

Commercial libraries

Abandoned libraries

  • Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)

  • Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.

  • arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.

  • jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.

  • jsdot Client side graph drawing application. Abandoned in 2011.

  • Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.

  • Moo Wheel Interactive JS representation for connections and relations (2008)

  • JSViz 2007-era graph visualization script

  • dagre Graph layout for JavaScript

Non-Javascript Libraries

How to show row number in Access query like ROW_NUMBER in SQL

by VB function:

Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue

If Not m_RowNr(1) = strQName Then
  m_RowNr(0) = 1
  m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
  m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
  m_RowNr(0) = m_RowNr(0) + 1
End If

m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)

End Function

Usage(without sorting option):

SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id

if sorting required or multiple tables join then create intermediate table:

 SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
 INTO table_with_Nr
 From table A
 Order By A.id

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

C++ catching all exceptions

try{
    // ...
} catch (...) {
    // ...
}

will catch all C++ exceptions, but it should be considered bad design. You can use c++11's new current_exception mechanism, but if you don't have the ability to use c++11 (legacy code systems requiring a rewrite), then you have no named exception pointer to use to get a message or name. You may want to add separate catch clauses for the various exceptions you can catch, and only catch everything at the bottom to record an unexpected exception. E.g.:

try{
    // ...
} catch (const std::exception& ex) {
    // ...
} catch (const std::string& ex) {
    // ...
} catch (...) {
    // ...
}

Difference between git pull and git pull --rebase

In the very most simple case of no collisions

  • with rebase: rebases your local commits ontop of remote HEAD and does not create a merge/merge commit
  • without/normal: merges and creates a merge commit

See also:

man git-pull

More precisely, git pull runs git fetch with the given parameters and calls git merge to merge the retrieved branch heads into the current branch. With --rebase, it runs git rebase instead of git merge.

See also:
When should I use git pull --rebase?
http://git-scm.com/book/en/Git-Branching-Rebasing

An existing connection was forcibly closed by the remote host

This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.

    SocketError errorCode;
    int nBytesRec = socket.EndReceive(ar, out errorCode);
    if (errorCode != SocketError.Success)
    {
        nBytesRec = 0;
    }

How to override a JavaScript function

You could override it or preferably extend it's implementation like this

parseFloat = (function(_super) {
    return function() {
        // Extend it to log the value for example that is passed
        console.log(arguments[0]);
        // Or override it by always subtracting 1 for example
        arguments[0] = arguments[0] - 1;
        return _super.apply(this, arguments);
    };         

})(parseFloat);

And call it as you would normally call it:

var result = parseFloat(1.345); // It should log the value 1.345 but get the value 0.345

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

This is with reference to the original question
$('select').val(['a','c']);
$('select').trigger('change');

Java Byte Array to String to Byte Array

Can you not just send the bytes as bytes, or convert each byte to a character and send as a string? Doing it like you are will take up a minimum of 85 characters in the string, when you only have 11 bytes to send. You could create a string representation of the bytes, so it'd be "[B@405217f8", which can easily be converted to a bytes or bytearray object in Python. Failing that, you could represent them as a series of hexadecimal digits ("5b42403430353231376638") taking up 22 characters, which could be easily decoded on the Python side using binascii.unhexlify().

How to get xdebug var_dump to show full object/array

I know this is late but it might be of some use:

echo "<pre>";
print_r($array);
echo "</pre>";

Write a mode method in Java to find the most frequently occurring element in an array

THIS CODE CALCULATES MODE, MEDIAN, AND MEAN. IT IS TESTED AND IT DOES WORK. It is a complete program from start to finish and will compile.

import java.util.Arrays;
import java.util.Random;
import java.math.*;
/**
 *
 * @author Mason
 */
public class MODE{

    public static void main(String args[])
    {
        System.out.print("Enter the quantity of random numbers  ===>>  ");
        int listSize = Expo.enterInt();
        System.out.println();
        ArrayStats intStats = new ArrayStats(listSize);
        intStats.randomize();
        intStats.computeMean();
        intStats.computeMedian();
        intStats.computeMode();
        intStats.displayStats();
        System.out.println();
    }
}


class ArrayStats
{

    private int list[];
    private int size;
    private double mean;        
    private double median;      
    private int mode;           

    public ArrayStats(int s)//initializes class object
    {
        size = s;
        list = new int[size];
    }

    public void randomize()
    {
        //This will provide same numbers every time... If you want to randomize this, you can
        Random rand = new Random(555);
        for (int k = 0; k < size; k++)
            list[k] = rand.nextInt(11) + 10;  
    }

    public void computeMean()
    {
               double accumulator=0;
               for (int index=0;index<size;index++)
               accumulator+= list[index];

               mean = accumulator/size;
    }

        public void computeMedian()
{
        Arrays.sort(list);
                if((size%2!=0))
                    median = list[((size-1)/2)];
                else if(size!=1&&size%2==0)
                {
                    double a =(size)/2-0.5;
                    int a2 =  (int)Math.ceil(a);
                    double b =(size)/2-0.5;
                    int b2 = (int)Math.floor(b);
                    median = (double)(list[a2]+list[b2])/2;
                }
                else if (size ==1)
                    median = list[0];
        }

    public void computeMode()
    {
 int popularity1 = 0;
  int popularity2 = 0;
  int array_item; //Array contains integer value. Make it String if array contains string value.
  for(int i =0;i<list.length;i++){
      array_item = list[i];
      for(int j =0;j<list.length;j++){
          if(array_item == list[j])
             popularity1 ++;
      }
      if(popularity1 >= popularity2){
          mode = array_item;
          popularity2 = popularity1;
      }


      popularity1 = 0;
  }}

    public void displayStats()
    {
        System.out.println(Arrays.toString(list));
        System.out.println();
        System.out.println("Mean: " + mean);
        System.out.println("Median: " + median);
        System.out.println("Mode: " + mode);
        System.out.println();
    }

}

CSS list item width/height does not work

Declare the a element as display: inline-block and drop the width and height from the li element.

Alternatively, apply a float: left to the li element and use display: block on the a element. This is a bit more cross browser compatible, as display: inline-block is not supported in Firefox <= 2 for example.

The first method allows you to have a dynamically centered list if you give the ul element a width of 100% (so that it spans from left to right edge) and then apply text-align: center.

Use line-height to control the text's Y-position inside the element.

python's re: return True if string contains regex pattern

You can do something like this:

Using search will return a SRE_match object, if it matches your search string.

>>> import re
>>> m = re.search(u'ba[r|z|d]', 'bar')
>>> m
<_sre.SRE_Match object at 0x02027288>
>>> m.group()
'bar'
>>> n = re.search(u'ba[r|z|d]', 'bas')
>>> n.group()

If not, it will return None

Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    n.group()
AttributeError: 'NoneType' object has no attribute 'group'

And just to print it to demonstrate again:

>>> print n
None

How can I convert string date to NSDate?

Swift 3,4:

2 useful conversions:

string(from: Date) // to convert from Date to a String
date(from: String) // to convert from String to Date

Usage: 1.

let date = Date() //gives today's date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd.MM.yyyy"
let todaysDateInUKFormat = dateFormatter.string(from: date)

2.

 let someDateInString = "23.06.2017"
 var getDateFromString = dateFormatter.date(from: someDateInString)

C#: How to add subitems in ListView

Great !! It has helped me a lot. I used to do the same using VB6 but now it is completely different. we should add this

listView1.View = System.Windows.Forms.View.Details;
listView1.GridLines = true; 
listView1.FullRowSelect = true;

Pass correct "this" context to setTimeout callback?

EDIT: In summary, back in 2010 when this question was asked the most common way to solve this problem was to save a reference to the context where the setTimeout function call is made, because setTimeout executes the function with this pointing to the global object:

var that = this;
if (this.options.destroyOnHide) {
     setTimeout(function(){ that.tip.destroy() }, 1000);
} 

In the ES5 spec, just released a year before that time, it introduced the bind method, this wasn't suggested in the original answer because it wasn't yet widely supported and you needed polyfills to use it but now it's everywhere:

if (this.options.destroyOnHide) {
     setTimeout(function(){ this.tip.destroy() }.bind(this), 1000);
}

The bind function creates a new function with the this value pre-filled.

Now in modern JS, this is exactly the problem arrow functions solve in ES6:

if (this.options.destroyOnHide) {
     setTimeout(() => { this.tip.destroy() }, 1000);
}

Arrow functions do not have a this value of its own, when you access it, you are accessing the this value of the enclosing lexical scope.

HTML5 also standardized timers back in 2011, and you can pass now arguments to the callback function:

if (this.options.destroyOnHide) {
     setTimeout(function(that){ that.tip.destroy() }, 1000, this);
}

See also:

user authentication libraries for node.js?

Session + If

I guess the reason that you haven't found many good libraries is that using a library for authentication is mostly over engineered.

What you are looking for is just a session-binder :) A session with:

if login and user == xxx and pwd == xxx 
   then store an authenticated=true into the session 
if logout destroy session

thats it.


I disagree with your conclusion that the connect-auth plugin is the way to go.

I'm using also connect but I do not use connect-auth for two reasons:

  1. IMHO breaks connect-auth the very powerful and easy to read onion-ring architecture of connect. A no-go - my opinion :). You can find a very good and short article about how connect works and the onion ring idea here.

  2. If you - as written - just want to use a basic or http login with database or file. Connect-auth is way too big. It's more for stuff like OAuth 1.0, OAuth 2.0 & Co


A very simple authentication with connect

(It's complete. Just execute it for testing but if you want to use it in production, make sure to use https) (And to be REST-Principle-Compliant you should use a POST-Request instead of a GET-Request b/c you change a state :)

var connect = require('connect');
var urlparser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlparser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this example with your Database, Auth-File or other things
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // This user is not authorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are not authorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);

NOTE

I wrote this statement over a year ago and have currently no active node projects. So there are may be API-Changes in Express. Please add a comment if I should change anything.

How to have css3 animation to loop forever

add this styles

animation-iteration-count:infinite;

How to check if all inputs are not empty with jQuery

var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
}); 
console.log(isValid);

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Are iframes considered 'bad practice'?

There are definitely uses for iframes folks. How else would you put the weather networks widget on your page? The only other way is to grab their XML and parse it, but then of course you need conditions to throw up the pertenant weather graphics... not really worth it, but way cleaner if you have the time.

Extract code country from phone number [libphonenumber]

Okay, so I've joined the google group of libphonenumber ( https://groups.google.com/forum/?hl=en&fromgroups#!forum/libphonenumber-discuss ) and I've asked a question.

I don't need to set the country in parameter if my phone number begins with "+". Here is an example :

PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
    // phone must begin with '+'
    PhoneNumber numberProto = phoneUtil.parse(phone, "");
    int countryCode = numberProto.getCountryCode();
} catch (NumberParseException e) {
    System.err.println("NumberParseException was thrown: " + e.toString());
}

Why did Servlet.service() for servlet jsp throw this exception?

The problem is in your JSP, most likely you are calling a method on an object that is null at runtime.

It is happening in the _jspInit() call, which is a little more unusual... the problem code is probably a method declaration like <%! %>


Update: I've only reproduced this by overriding the _jspInit() method. Is that what you're doing? If so, it's not recommended - that's why it starts with an _.

What exactly is the meaning of an API?

Lets say you are developing a game and you want the game user to login their facebook profile(to get your profile information) before playing it,so how your game is going to access facebook? Now here comes the API.Facebook has already written the program(API) for you to do it, you have to just use those programs in your game application.using Facebook-API you can use their services in your application.Here is a good and detailed look on API... http://money.howstuffworks.com/business-communications/how-to-leverage-an-api-for-conferencing1.htm

Git Symlinks in Windows

I was asking this exact same question a while back (not here, just in general) and ended up coming up with a very similar solution to OP's proposition. First I'll provide direct answers to questions 1 2 & 3, and then I'll post the solution I ended up using.

  1. There are indeed a few downsides to the proposed solution, mainly regarding an increased potential for repository pollution, or accidentally adding duplicate files while they're in their "Windows symlink" states. (More on this under "limitations" below.)
  2. Yes, a post-checkout script is implementable! Maybe not as a literal post-git checkout step, but the solution below has met my needs well enough that a literal post-checkout script wasn't necessary.
  3. Yes!

The Solution:

Our developers are in much the same situation as OP's: a mixture of Windows and Unix-like hosts, repositories and submodules with many git symlinks, and no native support (yet) in the release version of MsysGit for intelligently handling these symlinks on Windows hosts.

Thanks to Josh Lee for pointing out the fact that git commits symlinks with special filemode 120000. With this information it's possible to add a few git aliases that allow for the creation and manipulation of git symlinks on Windows hosts.

  1. Creating git symlinks on Windows

    git config --global alias.add-symlink '!'"$(cat <<'ETX'
    __git_add_symlink() {
      if [ $# -ne 2 ] || [ "$1" = "-h" ]; then
        printf '%b\n' \
            'usage: git add-symlink <source_file_or_dir> <target_symlink>\n' \
            'Create a symlink in a git repository on a Windows host.\n' \
            'Note: source MUST be a path relative to the location of target'
        [ "$1" = "-h" ] && return 0 || return 2
      fi
    
      source_file_or_dir=${1#./}
      source_file_or_dir=${source_file_or_dir%/}
    
      target_symlink=${2#./}
      target_symlink=${target_symlink%/}
      target_symlink="${GIT_PREFIX}${target_symlink}"
      target_symlink=${target_symlink%/.}
      : "${target_symlink:=.}"
    
      if [ -d "$target_symlink" ]; then
        target_symlink="${target_symlink%/}/${source_file_or_dir##*/}"
      fi
    
      case "$target_symlink" in
        (*/*) target_dir=${target_symlink%/*} ;;
        (*) target_dir=$GIT_PREFIX ;;
      esac
    
      target_dir=$(cd "$target_dir" && pwd)
    
      if [ ! -e "${target_dir}/${source_file_or_dir}" ]; then
        printf 'error: git-add-symlink: %s: No such file or directory\n' \
            "${target_dir}/${source_file_or_dir}" >&2
        printf '(Source MUST be a path relative to the location of target!)\n' >&2
        return 2
      fi
    
      git update-index --add --cacheinfo 120000 \
          "$(printf '%s' "$source_file_or_dir" | git hash-object -w --stdin)" \
          "${target_symlink}" \
        && git checkout -- "$target_symlink" \
        && printf '%s -> %s\n' "${target_symlink#$GIT_PREFIX}" "$source_file_or_dir" \
        || return $?
    }
    __git_add_symlink
    ETX
    )"
    

    Usage: git add-symlink <source_file_or_dir> <target_symlink>, where the argument corresponding to the source file or directory must take the form of a path relative to the target symlink. You can use this alias the same way you would normally use ln.

    E.g., the repository tree:

    dir/
    dir/foo/
    dir/foo/bar/
    dir/foo/bar/baz      (file containing "I am baz")
    dir/foo/bar/lnk_file (symlink to ../../../file)
    file                 (file containing "I am file")
    lnk_bar              (symlink to dir/foo/bar/)
    

    Can be created on Windows as follows:

    git init
    mkdir -p dir/foo/bar/
    echo "I am baz" > dir/foo/bar/baz
    echo "I am file" > file
    git add -A
    git commit -m "Add files"
    git add-symlink ../../../file dir/foo/bar/lnk_file
    git add-symlink dir/foo/bar/ lnk_bar
    git commit -m "Add symlinks"
    
  2. Replacing git symlinks with NTFS hardlinks+junctions

    git config --global alias.rm-symlinks '!'"$(cat <<'ETX'
    __git_rm_symlinks() {
      case "$1" in (-h)
        printf 'usage: git rm-symlinks [symlink] [symlink] [...]\n'
        return 0
      esac
      ppid=$$
      case $# in
        (0) git ls-files -s | grep -E '^120000' | cut -f2 ;;
        (*) printf '%s\n' "$@" ;;
      esac | while IFS= read -r symlink; do
        case "$symlink" in
          (*/*) symdir=${symlink%/*} ;;
          (*) symdir=. ;;
        esac
    
        git checkout -- "$symlink"
        src="${symdir}/$(cat "$symlink")"
    
        posix_to_dos_sed='s_^/\([A-Za-z]\)_\1:_;s_/_\\\\_g'
        doslnk=$(printf '%s\n' "$symlink" | sed "$posix_to_dos_sed")
        dossrc=$(printf '%s\n' "$src" | sed "$posix_to_dos_sed")
    
        if [ -f "$src" ]; then
          rm -f "$symlink"
          cmd //C mklink //H "$doslnk" "$dossrc"
        elif [ -d "$src" ]; then
          rm -f "$symlink"
          cmd //C mklink //J "$doslnk" "$dossrc"
        else
          printf 'error: git-rm-symlink: Not a valid source\n' >&2
          printf '%s =/=> %s  (%s =/=> %s)...\n' \
              "$symlink" "$src" "$doslnk" "$dossrc" >&2
          false
        fi || printf 'ESC[%d]: %d\n' "$ppid" "$?"
    
        git update-index --assume-unchanged "$symlink"
      done | awk '
        BEGIN { status_code = 0 }
        /^ESC\['"$ppid"'\]: / { status_code = $2 ; next }
        { print }
        END { exit status_code }
      '
    }
    __git_rm_symlinks
    ETX
    )"
    
    git config --global alias.rm-symlink '!git rm-symlinks'  # for back-compat.
    

    Usage:

    git rm-symlinks [symlink] [symlink] [...]
    

    This alias can remove git symlinks one-by-one or all-at-once in one fell swoop. Symlinks will be replaced with NTFS hardlinks (in the case of files) or NTFS junctions (in the case of directories). The benefit of using hardlinks+junctions over "true" NTFS symlinks is that elevated UAC permissions are not required in order for them to be created.

    To remove symlinks from submodules, just use git's built-in support for iterating over them:

    git submodule foreach --recursive git rm-symlinks
    

    But, for every drastic action like this, a reversal is nice to have...

  3. Restoring git symlinks on Windows

    git config --global alias.checkout-symlinks '!'"$(cat <<'ETX'
    __git_checkout_symlinks() {
      case "$1" in (-h)
        printf 'usage: git checkout-symlinks [symlink] [symlink] [...]\n'
        return 0
      esac
      case $# in
        (0) git ls-files -s | grep -E '^120000' | cut -f2 ;;
        (*) printf '%s\n' "$@" ;;
      esac | while IFS= read -r symlink; do
        git update-index --no-assume-unchanged "$symlink"
        rmdir "$symlink" >/dev/null 2>&1
        git checkout -- "$symlink"
        printf 'Restored git symlink: %s -> %s\n' "$symlink" "$(cat "$symlink")"
      done
    }
    __git_checkout_symlinks
    ETX
    )"
    
    git config --global alias.co-symlinks '!git checkout-symlinks'
    

    Usage: git checkout-symlinks [symlink] [symlink] [...], which undoes git rm-symlinks, effectively restoring the repository to its natural state (except for your changes, which should stay intact).

    And for submodules:

    git submodule foreach --recursive git checkout-symlinks
    
  4. Limitations:

    • Directories/files/symlinks with spaces in their paths should work. But tabs or newlines? YMMV… (By this I mean: don’t do that, because it will not work.)

    • If yourself or others forget to git checkout-symlinks before doing something with potentially wide-sweeping consequences like git add -A, the local repository could end up in a polluted state.

      Using our "example repo" from before:

      echo "I am nuthafile" > dir/foo/bar/nuthafile
      echo "Updating file" >> file
      git add -A
      git status
      # On branch master
      # Changes to be committed:
      #   (use "git reset HEAD <file>..." to unstage)
      #
      #       new file:   dir/foo/bar/nuthafile
      #       modified:   file
      #       deleted:    lnk_bar           # POLLUTION
      #       new file:   lnk_bar/baz       # POLLUTION
      #       new file:   lnk_bar/lnk_file  # POLLUTION
      #       new file:   lnk_bar/nuthafile # POLLUTION
      #
      

      Whoops...

      For this reason, it's nice to include these aliases as steps to perform for Windows users before-and-after building a project, rather than after checkout or before pushing. But each situation is different. These aliases have been useful enough for me that a true post-checkout solution hasn't been necessary.

Hope that helps!

References:

http://git-scm.com/book/en/Git-Internals-Git-Objects

http://technet.microsoft.com/en-us/library/cc753194

Last Update: 2019-03-13

  • POSIX compliance (well, except for those mklink calls, of course) — no more Bashisms!
  • Directories and files with spaces in them are supported.
  • Zero and non-zero exit status codes (for communicating success/failure of the requested command, respectively) are now properly preserved/returned.
  • The add-symlink alias now works more like ln(1) and can be used from any directory in the repository, not just the repository’s root directory.
  • The rm-symlink alias (singular) has been superseded by the rm-symlinks alias (plural), which now accepts multiple arguments (or no arguments at all, which finds all of the symlinks throughout the repository, as before) for selectively transforming git symlinks into NTFS hardlinks+junctions.
  • The checkout-symlinks alias has also been updated to accept multiple arguments (or none at all, == everything) for selective reversal of the aforementioned transformations.

Final Note: While I did test loading and running these aliases using Bash 3.2 (and even 3.1) for those who may still be stuck on such ancient versions for any number of reasons, be aware that versions as old as these are notorious for their parser bugs. If you experience issues while trying to install any of these aliases, the first thing you should look into is upgrading your shell (for Bash, check the version with CTRL+X, CTRL+V). Alternatively, if you’re trying to install them by pasting them into your terminal emulator, you may have more luck pasting them into a file and sourcing it instead, e.g. as

. ./git-win-symlinks.sh

Good luck!

Count with IF condition in MySQL query

Better still (or shorter anyway):

SUM(ccc_news_comments.id = 'approved')

This works since the Boolean type in MySQL is represented as INT 0 and 1, just like in C. (May not be portable across DB systems though.)

As for COALESCE() as mentioned in other answers, many language APIs automatically convert NULL to '' when fetching the value. For example with PHP's mysqli interface it would be safe to run your query without COALESCE().

C++ string to double conversion

The C++ way of solving conversions (not the classical C) is illustrated with the program below. Note that the intent is to be able to use the same formatting facilities offered by iostream like precision, fill character, padding, hex, and the manipulators, etcetera.

Compile and run this program, then study it. It is simple

#include "iostream"
#include "iomanip"
#include "sstream"
using namespace std;

int main()
{
    // Converting the content of a char array or a string to a double variable
    double d;
    string S;
    S = "4.5";
    istringstream(S) >> d;    
    cout << "\nThe value of the double variable d is " << d << endl;
    istringstream("9.87654") >> d;  
    cout << "\nNow the value of the double variable d is " << d << endl;



    // Converting a double to string with formatting restrictions
    double D=3.771234567;

    ostringstream Q;
    Q.fill('#');
    Q << "<<<" << setprecision(6) << setw(20) << D << ">>>";
    S = Q.str(); // formatted converted double is now in string 

    cout << "\nThe value of the string variable S is " << S << endl;
    return 0;
}

Prof. Martinez

What's the difference between '$(this)' and 'this'?

When using jQuery, it is advised to use $(this) usually. But if you know (you should learn and know) the difference, sometimes it is more convenient and quicker to use just this. For instance:

$(".myCheckboxes").change(function(){ 
    if(this.checked) 
       alert("checked"); 
});

is easier and purer than

$(".myCheckboxes").change(function(){ 
      if($(this).is(":checked")) 
         alert("checked"); 
});

Creating a data frame from two vectors using cbind

Using data.frame instead of cbind should be helpful

x <- data.frame(col1=c(10, 20), col2=c("[]", "[]"), col3=c("[[1,2]]","[[1,3]]"))
x
  col1 col2    col3
1   10   [] [[1,2]]
2   20   [] [[1,3]]

sapply(x, class) # looking into x to see the class of each element
     col1      col2      col3 
"numeric"  "factor"  "factor" 

As you can see elements from col1 are numeric as you wish.

data.frame can have variables of different class: numeric, factor and character but matrix doesn't, once you put a character element into a matrix all the other will become into this class no matter what clase they were before.

Vue 'export default' vs 'new Vue'

export default is used to create local registration for Vue component.

Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e

JavaScript: Class.method vs. Class.prototype.method

Yes, the first one is a static method also called class method, while the second one is an instance method.

Consider the following examples, to understand it in more detail.

In ES5

function Person(firstName, lastName) {
   this.firstName = firstName;
   this.lastName = lastName;
}

Person.isPerson = function(obj) {
   return obj.constructor === Person;
}

Person.prototype.sayHi = function() {
   return "Hi " + this.firstName;
}

In the above code, isPerson is a static method, while sayHi is an instance method of Person.

Below, is how to create an object from Person constructor.

var aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

In ES6

class Person {
   constructor(firstName, lastName) {
      this.firstName = firstName;
      this.lastName = lastName;
   }

   static isPerson(obj) {
      return obj.constructor === Person;
   }

   sayHi() {
      return `Hi ${this.firstName}`;
   }
}

Look at how static keyword was used to declare the static method isPerson.

To create an object of Person class.

const aminu = new Person("Aminu", "Abubakar");

Using the static method isPerson.

Person.isPerson(aminu); // will return true

Using the instance method sayHi.

aminu.sayHi(); // will return "Hi Aminu"

NOTE: Both examples are essentially the same, JavaScript remains a classless language. The class introduced in ES6 is primarily a syntactical sugar over the existing prototype-based inheritance model.

comparing 2 strings alphabetically for sorting purposes

Lets look at some test cases - try running the following expressions in your JS console:

"a" < "b"

"aa" < "ab"

"aaa" < "aab"

All return true.

JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.

In your case it works like so -

1 . "a?aaa" < "?a?b"

compares the first two "a" characters - all equal, lets move to the next character.

2 . "a?a??aa" < "a?b??"

compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.

How to set the allowed url length for a nginx request (error code: 414, uri too large)

For anyone having issues with this on https://forge.laravel.com, I managed to get this to work using a compilation of SO answers;

You will need the sudo password.

sudo nano /etc/nginx/conf.d/uploads.conf

Replace contents with the following;

fastcgi_buffers 8 16k;
fastcgi_buffer_size 32k;

client_max_body_size 24M;
client_body_buffer_size 128k;

client_header_buffer_size 5120k;
large_client_header_buffers 16 5120k;

Get path from open file in Python

And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os Python module.

>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'

This way you can get hold of the directory structure.

How do I iterate over the words of a string?

Get Boost ! : -)

#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>
#include <vector>

using namespace std;
using namespace boost;

int main(int argc, char**argv) {
    typedef vector < string > list_type;

    list_type list;
    string line;

    line = "Somewhere down the road";
    split(list, line, is_any_of(" "));

    for(int i = 0; i < list.size(); i++)
    {
        cout << list[i] << endl;
    }

    return 0;
}

This example gives the output -

Somewhere
down
the
road

Can't change z-index with JQuery

because your jQuery code is wrong. Correctly would be:

var theParent = $(this).parent().get(0); 
$(theParent).css('z-index', 3000);

Sharing a URL with a query string on Twitter

If you add it manual on html site, just replace:

&

With

&amp;

Standard html code for &

C# loop - break vs. continue

A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.

break loop - looping is broken and stops.

continue loop - loop continues to execute with the next iteration.

Connection string with relative path to the database file

   <?xml version="1.0"?>  
<configuration>  
  <appSettings>  
    <!--FailIfMissing=false -->  
    <add key="DbSQLite" value="data source=|DataDirectory|DB.db3;Pooling=true;FailIfMissing=false"/>  
  </appSettings>  
</configuration>  

Check to see if cURL is installed locally?

Assuming you want curl installed: just execute the install command and see what happens.

$ sudo yum install curl

Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: mirrors.cat.pdx.edu
 * epel: mirrors.kernel.org
 * extras: mirrors.cat.pdx.edu
 * remi-php72: repo1.sea.innoscale.net
 * remi-safe: repo1.sea.innoscale.net
 * updates: mirrors.cat.pdx.edu
Package curl-7.29.0-54.el7_7.1.x86_64 already installed and latest version
Nothing to do

How to play or open *.mp3 or *.wav sound file in c++ program?

Use a library to (a) read the sound file(s) and (b) play them back. (I'd recommend trying both yourself at some point in your spare time, but...)

Perhaps (*nix):

Windows: DirectX.

C# 4.0 optional out/ref arguments

What about like this?

public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
    return true;
}

You still have to pass a value to the parameter from C# but it is an optional ref param.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

final

final can be used to mark a variable "unchangeable"

private final String name = "foo";  //the reference name can never change

final can also make a method not "overrideable"

public final String toString() {  return "NULL"; }

final can also make a class not "inheritable". i.e. the class can not be subclassed.

public final class finalClass {...}
public class classNotAllowed extends finalClass {...} // Not allowed

finally

finally is used in a try/catch statement to execute code "always"

lock.lock();
try {
  //do stuff
} catch (SomeException se) {
  //handle se
} finally {
  lock.unlock(); //always executed, even if Exception or Error or se
}

Java 7 has a new try with resources statement that you can use to automatically close resources that explicitly or implicitly implement java.io.Closeable or java.lang.AutoCloseable

finalize

finalize is called when an object is garbage collected. You rarely need to override it. An example:

protected void finalize() {
  //free resources (e.g. unallocate memory)
  super.finalize();
}

const to Non-const Conversion in C++

You can assign a const object to a non-const object just fine. Because you're copying and thus creating a new object, constness is not violated.

Like so:

int main() {
   const int a = 3;
   int b = a;
}

It's different if you want to obtain a pointer or reference to the original, const object:

int main() {
   const int a = 3;
   int& b = a;       // or int* b = &a;
}

//  error: invalid initialization of reference of type 'int&' from
//         expression of type 'const int'

You can use const_cast to hack around the type safety if you really must, but recall that you're doing exactly that: getting rid of the type safety. It's still undefined to modify a through b in the below example:

int main() {
   const int a = 3;
   int& b = const_cast<int&>(a);

   b = 3;
}

Although it compiles without errors, anything can happen including opening a black hole or transferring all your hard-earned savings into my bank account.

If you have arrived at what you think is a requirement to do this, I'd urgently revisit your design because something is very wrong with it.

How to handle command-line arguments in PowerShell

You are reinventing the wheel. Normal PowerShell scripts have parameters starting with -, like script.ps1 -server http://devserver

Then you handle them in param section in the beginning of the file.

You can also assign default values to your params, read them from console if not available or stop script execution:

 param (
    [string]$server = "http://defaultserver",
    [Parameter(Mandatory=$true)][string]$username,
    [string]$password = $( Read-Host "Input password, please" )
 )

Inside the script you can simply

write-output $server

since all parameters become variables available in script scope.

In this example, the $server gets a default value if the script is called without it, script stops if you omit the -username parameter and asks for terminal input if -password is omitted.

Update: You might also want to pass a "flag" (a boolean true/false parameter) to a PowerShell script. For instance, your script may accept a "force" where the script runs in a more careful mode when force is not used.

The keyword for that is [switch] parameter type:

 param (
    [string]$server = "http://defaultserver",
    [string]$password = $( Read-Host "Input password, please" ),
    [switch]$force = $false
 )

Inside the script then you would work with it like this:

if ($force) {
  //deletes a file or does something "bad"
}

Now, when calling the script you'd set the switch/flag parameter like this:

.\yourscript.ps1 -server "http://otherserver" -force

If you explicitly want to state that the flag is not set, there is a special syntax for that

.\yourscript.ps1 -server "http://otherserver" -force:$false

Links to relevant Microsoft documentation (for PowerShell 5.0; tho versions 3.0 and 4.0 are also available at the links):

How to create websockets server in PHP

As far as I'm aware Ratchet is the best PHP WebSocket solution available at the moment. And since it's open source you can see how the author has built this WebSocket solution using PHP.

IntelliJ - Convert a Java project/module into a Maven project/module

I want to add the important hint that converting a project like this can have side effects which are noticeable when you have a larger project. This is due the fact that Intellij Idea (2017) takes some important settings only from the pom.xml then which can lead to some confusion, following sections are affected at least:

  1. Annotation settings are changed for the modules
  2. Compiler output path is changed for the modules
  3. Resources settings are ignored totally and only taken from pom.xml
  4. Module dependencies are messed up and have to checked
  5. Language/Encoding settings are changed for the modules

All these points need review and adjusting but after this it works like charm.

Further more unfortunately there is no sufficient pom.xml template created, I have added an example which might help to solve most problems.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Name</groupId>
<artifactId>Artifact</artifactId>
<version>4.0</version>
<properties>
    <!-- Generic properties -->
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
    <!--All dependencies to put here, including module dependencies-->
</dependencies>
<build>
    <directory>${project.basedir}/target</directory>
    <outputDirectory>${project.build.directory}/classes</outputDirectory>
    <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <testSourceDirectory> ${project.basedir}/src/test/java</testSourceDirectory>

    <resources>
        <resource>
            <directory>${project.basedir}/src/main/java</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
        <resource>
            <directory>${project.basedir}/src/main/resources</directory>
            <includes>
                <include>**/*</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <annotationProcessors/>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Edit 2019:

  • Added recursive resource scan
  • Added directory specification which might be important to avoid confusion of IDEA recarding the content root structure

C# cannot convert method to non delegate type

As mentioned you need to use obj.getTile()

But, in this case I think you are looking to use a Property.

public class Pin
{
    private string title;

    public Pin() { }

    public setTitle(string title) {
        this.title = title;
    }

    public String Title
    {
        get { return title; }
    }
}

This will allow you to use

foreach (Pin obj in ClassListPin.pins)
{
     string t = obj.Title;
}

How to fix Cannot find module 'typescript' in Angular 4?

Run 'npm install' it will install all necessary pkg .

Insert/Update/Delete with function in SQL Server

No, you can not do Insert/Update/Delete.

Functions only work with select statements. And it has only READ-ONLY Database Access.

In addition:

  • Functions compile every time.
  • Functions must return a value or result.
  • Functions only work with input parameters.
  • Try and catch statements are not used in functions.

How to create a stopwatch using JavaScript?

Please see stopwatch.js for a very clean and simple Vanilla Javascript ES6 solution.

How to use ng-if to test if a variable is defined

Try this:

item.shipping!==undefined