Programs & Examples On #Verify

Openssl : error "self signed certificate in certificate chain"

Here is one-liner to verify certificate chain:

openssl verify -verbose -x509_strict -CAfile ca.pem cert_chain.pem

This doesn't require to install CA anywhere.

See How does an SSL certificate chain bundle work? for details.

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Best way to check that element is not present using Selenium WebDriver with java

Use findElements instead of findElement.

findElements will return an empty list if no matching elements are found instead of an exception. Also, we can make sure that the element is present or not.

Ex: List elements = driver.findElements(By.yourlocatorstrategy);

if(elements.size()>0){
    do this..
 } else {
    do that..
 }

Spring Data: "delete by" is supported?

If you take a look at the source code of Spring Data JPA, and particularly the PartTreeJpaQuery class, you will see that is tries to instantiate PartTree. Inside that class the following regular expression

private static final Pattern PREFIX_TEMPLATE = Pattern.compile("^(find|read|get|count|query)(\\p{Lu}.*?)??By")

should indicate what is allowed and what's not.

Of course if you try to add such a method you will actually see that is does not work and you get the full stacktrace.

I should note that I was using looking at version 1.5.0.RELEASE of Spring Data JPA

How to export data from Spark SQL to CSV

The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:

df.coalesce(1).
    write.
    format("com.databricks.spark.csv").
    option("header", "true").
    save("myfile.csv")

and rename the output of the lib (name "part-00000") to a desire filename.

This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/

Import a custom class in Java

In the same package you don't need to import the class.

Otherwise, it is very easy. In Eclipse or NetBeans just write the class you want to use and press on Ctrl + Space. The IDE will automatically import the class.

General information:

You can import a class with import keyword after package information:

Example:

package your_package;


import anotherpackage.anotherclass;

public class Your_Class {
    ...
    private Vector variable;
    ...
}

You can instance the class with:

Anotherclass foo = new Anotherclass();

Initialize a Map containing arrays

Per Mozilla's Map documentation, you can initialize as follows:

private _gridOptions:Map<string, Array<string>> = 
    new Map([
        ["1", ["test"]],
        ["2", ["test2"]]
    ]);

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

Swift: Testing optionals for nil

In Xcode Beta 5, they no longer let you do:

var xyz : NSString?

if xyz {
  // Do something using `xyz`.
}

This produces an error:

does not conform to protocol 'BooleanType.Protocol'

You have to use one of these forms:

if xyz != nil {
   // Do something using `xyz`.
}

if let xy = xyz {
   // Do something using `xy`.
}

Handling InterruptedException in Java

What is the difference between the following ways of handling InterruptedException? What is the best way to do it?

You've probably come to ask this question because you've called a method that throws InterruptedException.

First of all, you should see throws InterruptedException for what it is: A part of the method signature and a possible outcome of calling the method you're calling. So start by embracing the fact that an InterruptedException is a perfectly valid result of the method call.

Now, if the method you're calling throws such exception, what should your method do? You can figure out the answer by thinking about the following:

Does it make sense for the method you are implementing to throw an InterruptedException? Put differently, is an InterruptedException a sensible outcome when calling your method?

  • If yes, then throws InterruptedException should be part of your method signature, and you should let the exception propagate (i.e. don't catch it at all).

    Example: Your method waits for a value from the network to finish the computation and return a result. If the blocking network call throws an InterruptedException your method can not finish computation in a normal way. You let the InterruptedException propagate.

    int computeSum(Server server) throws InterruptedException {
        // Any InterruptedException thrown below is propagated
        int a = server.getValueA();
        int b = server.getValueB();
        return a + b;
    }
    
  • If no, then you should not declare your method with throws InterruptedException and you should (must!) catch the exception. Now two things are important to keep in mind in this situation:

    1. Someone interrupted your thread. That someone is probably eager to cancel the operation, terminate the program gracefully, or whatever. You should be polite to that someone and return from your method without further ado.

    2. Even though your method can manage to produce a sensible return value in case of an InterruptedException the fact that the thread has been interrupted may still be of importance. In particular, the code that calls your method may be interested in whether an interruption occurred during execution of your method. You should therefore log the fact an interruption took place by setting the interrupted flag: Thread.currentThread().interrupt()

    Example: The user has asked to print a sum of two values. Printing "Failed to compute sum" is acceptable if the sum can't be computed (and much better than letting the program crash with a stack trace due to an InterruptedException). In other words, it does not make sense to declare this method with throws InterruptedException.

    void printSum(Server server) {
         try {
             int sum = computeSum(server);
             System.out.println("Sum: " + sum);
         } catch (InterruptedException e) {
             Thread.currentThread().interrupt();  // set interrupt flag
             System.out.println("Failed to compute sum");
         }
    }
    

By now it should be clear that just doing throw new RuntimeException(e) is a bad idea. It isn't very polite to the caller. You could invent a new runtime exception but the root cause (someone wants the thread to stop execution) might get lost.

Other examples:

Implementing Runnable: As you may have discovered, the signature of Runnable.run does not allow for rethrowing InterruptedExceptions. Well, you signed up on implementing Runnable, which means that you signed up to deal with possible InterruptedExceptions. Either choose a different interface, such as Callable, or follow the second approach above.

 

Calling Thread.sleep: You're attempting to read a file and the spec says you should try 10 times with 1 second in between. You call Thread.sleep(1000). So, you need to deal with InterruptedException. For a method such as tryToReadFile it makes perfect sense to say, "If I'm interrupted, I can't complete my action of trying to read the file". In other words, it makes perfect sense for the method to throw InterruptedExceptions.

String tryToReadFile(File f) throws InterruptedException {
    for (int i = 0; i < 10; i++) {
        if (f.exists())
            return readFile(f);
        Thread.sleep(1000);
    }
    return null;
}

This post has been rewritten as an article here.

Python function as a function argument?

Can a Python function be an argument of another function?

Yes.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

To be more specific ... with various arguments ...

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>

Putty: Getting Server refused our key Error

When using Cpanel you can check if the key is authorized in

SSH Access >> Public keys >> Manage >> Authorize or Deauthorize.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

Multiple conditions in a C 'for' loop

Completing Mr. Crocker's answer, be careful about ++ or -- operators or I don't know maybe other operators. They can affect the loop. for example I saw a code similar to this one in a course:

for(int i=0; i++*i<-1, i<3; printf(" %d", i));

The result would be $ 1 2$. So the first statement has affected the loop while the outcome of the following is lots of zeros.

for(int i=0; i<3; printf(" %d", i));

Using the AND and NOT Operator in Python

You should write :

if (self.a != 0) and (self.b != 0) :

"&" is the bit wise operator and does not suit for boolean operations. The equivalent of "&&" is "and" in Python.

A shorter way to check what you want is to use the "in" operator :

if 0 not in (self.a, self.b) :

You can check if anything is part of a an iterable with "in", it works for :

  • Tuples. I.E : "foo" in ("foo", 1, c, etc) will return true
  • Lists. I.E : "foo" in ["foo", 1, c, etc] will return true
  • Strings. I.E : "a" in "ago" will return true
  • Dict. I.E : "foo" in {"foo" : "bar"} will return true

As an answer to the comments :

Yes, using "in" is slower since you are creating an Tuple object, but really performances are not an issue here, plus readability matters a lot in Python.

For the triangle check, it's easier to read :

0 not in (self.a, self.b, self.c)

Than

(self.a != 0) and (self.b != 0) and (self.c != 0) 

It's easier to refactor too.

Of course, in this example, it really is not that important, it's very simple snippet. But this style leads to a Pythonic code, which leads to a happier programmer (and losing weight, improving sex life, etc.) on big programs.

Eclipse error "Could not find or load main class"

Check that your project has a builder by either:

  • check project properties (in the "package explorer", right click on the project, select "properties"), there the second section is "Builders", and it should hold the default "Java Builder"
  • or look in the ".project" file (in .../workspace/yourProjectName/.project) the section "buildSpec" should not be empty.

There must be other ways, but what I did was:

  • shut down eclipse
  • edit the ."project" file to add the "buildSpec" section
  • restart eclipse

A proper minimal java ".project" file should look like:

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
        <name>myProjectName</name>
        <comment></comment>
        <projects>
        </projects>
        <buildSpec>
                <buildCommand>
                        <name>org.eclipse.jdt.core.javabuilder</name>
                        <arguments>
                        </arguments>
                </buildCommand>
        </buildSpec>
        <natures>       
                    <nature>org.eclipse.jdt.core.javanature</nature>
        </natures>      
</projectDescription>

jQuery call function after load

$(window).bind("load", function() {

   // code here 
});

How do I convert a C# List<string[]> to a Javascript array?

JSON is valid JavaScript Object anyway, while you are printing JavaScript itself, you don't need to encode/decode JSON further once it is converted to JSON.

<script type="text/javascript">
    var addresses = @Html.Raw(Model.Addresses);
</script>

Following will be printed, and it is valid JavaScript Expression.

<script type="text/javascript">
    var addresses = [["123 Street St.","City","CA","12345"],["456 Street St.","City","UT","12345"],["789 Street St.","City","OR","12345"]];
</script>

AngularJS - convert dates in controller

All solutions here doesn't really bind the model to the input because you will have to change back the dateAsString to be saved as date in your object (in the controller after the form will be submitted).

If you don't need the binding effect, but just to show it in the input,

a simple could be:

<input type="date" value="{{ item.date | date: 'yyyy-MM-dd' }}" id="item_date" />

Then, if you like, in the controller, you can save the edited date in this way:

  $scope.item.date = new Date(document.getElementById('item_date').value).getTime();

be aware: in your controller, you have to declare your item variable as $scope.item in order for this to work.

How do I install and use curl on Windows?

After adding curl.exe's path to the System Variable 'Path'

you can open command prompt and run 'curl -V' to see if it is working.

Maven plugin in Eclipse - Settings.xml file is missing

The settings file is never created automatically, you must create it yourself, whether you use embedded or "real" maven.

Create it at the following location <your home folder>/.m2/settings.xml e.g. C:\Users\YourUserName\.m2\settings.xml on Windows or /home/YourUserName/.m2/settings.xml on Linux

Here's an empty skeleton you can use:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies/>
  <profiles/>
  <activeProfiles/>
</settings>

If you use Eclipse to edit it, it will give you auto-completion when editing it.

And here's the Maven settings.xml Reference page

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

How do I enumerate through a JObject?

For people like me, linq addicts, and based on svick's answer, here a linq approach:

using System.Linq;
//...
//make it linq iterable. 
var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();

Now you can make linq expressions like:

JToken x = obj_linq
          .Where( d => d.Key == "my_key")
          .Select(v => v)
          .FirstOrDefault()
          .Value;
string y = ((JValue)x).Value;

Or just:

var y = obj_linq
       .Where(d => d.Key == "my_key")
       .Select(v => ((JValue)v.Value).Value)
       .FirstOrDefault();

Or this one to iterate over all data:

obj_linq.ToList().ForEach( x => { do stuff } ); 

Directory Chooser in HTML page

Can't be done in pure HTML/JavaScript for security reasons.

Selecting a file for upload is the best you can do, and even then you won't get its full original path in modern browsers.

You may be able to put something together using Java or Flash (e.g. using SWFUpload as a basis), but it's a lot of work and brings additional compatibility issues.

Another thought would be opening an iframe showing the user's C: drive (or whatever) but even if that's possible nowadays (could be blocked for security reasons, haven't tried in a long time) it will be impossible for your web site to communicate with the iframe (again for security reasons).

What do you need this for?

How to use support FileProvider for sharing content to other apps?

grantUriPermission (from Android document)

Normally you should use Intent#FLAG_GRANT_READ_URI_PERMISSION or Intent#FLAG_GRANT_WRITE_URI_PERMISSION with the Intent being used to start an activity instead of this function directly. If you use this function directly, you should be sure to call revokeUriPermission(Uri, int) when the target should no longer be allowed to access it.

So I test and I see that.

  • If we use grantUriPermission before we start a new activity, we DON'T need FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION in Intent to overcome SecurityException

  • If we don't use grantUriPermission. We need to use FLAG_GRANT_READ_URI_PERMISSION or FLAG_GRANT_WRITE_URI_PERMISSION to overcome SecurityException but

    • Your intent MUST contain Uri by setData or setDataAndType else SecurityException still throw. (one interesting I see: setData and setType can not work well together so if you need both Uri and type you need setDataAndType. You can check inside Intent code, currently when you setType, it will also set uri= null and when you setUri it will also set type=null)

Assign multiple values to array in C

You can use:

GLfloat coordinates[8] = {1.0f, ..., 0.0f};

but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).

The other two ways that spring to mind are to blat the contents if they're fixed:

GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));

or provide a function that looks like your initialisation code anyway:

void setCoords (float *p0, float p1, ..., float p8) {
    p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
    p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);

keeping in mind those ellipses (...) are placeholders, not things to literally insert in the code.

How can I introduce multiple conditions in LIKE operator?

I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.

This worked for me in Oracle 11g:

REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*'); 

HAProxy redirecting http to https (ssl)

frontend unsecured *:80
    mode http
    redirect location https://foo.bar.com

What does the variable $this mean in PHP?

It refers to the instance of the current class, as meder said.

See the PHP Docs. It's explained under the first example.

IsNothing versus Is Nothing

VB is full of things like that trying to make it both "like English" and comfortable for people who are used to languages that use () and {} a lot. And on the other side, as you already probably know, most of the time you can use () with function calls if you want to, but don't have to.

I prefer IsNothing()... but I use C and C#, so that's just what is comfortable. And I think it's more readable. But go with whatever feels more comfortable to you.

How to set a single, main title above all the subplots with Pyplot?

If your subplots also have titles, you may need to adjust the main title size:

plt.suptitle("Main Title", size=16)

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

How to make URL/Phone-clickable UILabel?

Swift 4.2, Xcode 9.3 version

class LinkedLabel: UILabel {

    fileprivate let layoutManager = NSLayoutManager()
    fileprivate let textContainer = NSTextContainer(size: CGSize.zero)
    fileprivate var textStorage: NSTextStorage?


    override init(frame aRect:CGRect){
        super.init(frame: aRect)
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.initialize()
    }

    func initialize(){

        let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTapOnLabel))
        self.isUserInteractionEnabled = true
        self.addGestureRecognizer(tap)
    }

    override var attributedText: NSAttributedString?{
        didSet{
            if let _attributedText = attributedText{
                self.textStorage = NSTextStorage(attributedString: _attributedText)

                self.layoutManager.addTextContainer(self.textContainer)
                self.textStorage?.addLayoutManager(self.layoutManager)

                self.textContainer.lineFragmentPadding = 0.0;
                self.textContainer.lineBreakMode = self.lineBreakMode;
                self.textContainer.maximumNumberOfLines = self.numberOfLines;
            }

        }
    }

    @objc func handleTapOnLabel(tapGesture:UITapGestureRecognizer){

        let locationOfTouchInLabel = tapGesture.location(in: tapGesture.view)
        let labelSize = tapGesture.view?.bounds.size
        let textBoundingBox = self.layoutManager.usedRect(for: self.textContainer)
        let textContainerOffset = CGPoint(x: ((labelSize?.width)! - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x, y: ((labelSize?.height)! - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y)

        let locationOfTouchInTextContainer = CGPoint(x: locationOfTouchInLabel.x - textContainerOffset.x, y: locationOfTouchInLabel.y - textContainerOffset.y)
        let indexOfCharacter = self.layoutManager.characterIndex(for: locationOfTouchInTextContainer, in: self.textContainer, fractionOfDistanceBetweenInsertionPoints: nil)


        self.attributedText?.enumerateAttribute(NSAttributedStringKey.link, in: NSMakeRange(0, (self.attributedText?.length)!), options: NSAttributedString.EnumerationOptions(rawValue: UInt(0)), using:{
            (attrs: Any?, range: NSRange, stop: UnsafeMutablePointer<ObjCBool>) in

            if NSLocationInRange(indexOfCharacter, range){
                if let _attrs = attrs{

                    UIApplication.shared.openURL(URL(string: _attrs as! String)!)
                }
            }
        })

    }}

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

The upper error occure due to lot of reason. So I can put why this error occure and how to solve it.

REASON 1 : Duplicate of class file name

SOLUTION :

when your refactoring of some of your class files to a library project. and that time you write name of class file So, double check that you do not have any duplicate names

REASON 2 : When you have lot of cache Memory

SOLUTION :

Sometime if you have lot of cache memory then this error occure so solve it. go to File/Invalidate caches / Restart then select Invalidate and Restart it will clean your cache memory.

REASON 3 : When there is internal bug or used beta Version to Switch back to stable version.

SOLUTION :

Solution is just simple go to Build menu and click Clean Project and after cleaning click Rebuild Project.

REASON 4 : When you memory of the system Configuration is low.

SOLUTION :

open Task Manager and stop the other application which are not most used at that time so it will free the space and solve OutOfMemory.

REASON 5 : The problem is your method count has exceed from 65K.

SOLUTION :

open your Project build.gradle file add

defaultConfig {
        ...
        multiDexEnabled true
    }

and in dependencies add below line.

dependencies 
    {
       compile 'com.android.support:multidex:1.0.0'
    }

Git Pull is Not Possible, Unmerged Files

Say the remote is origin and the branch is master, and say you already have master checked out, might try the following:

git fetch origin
git reset --hard origin/master

This basically just takes the current branch and points it to the HEAD of the remote branch.

WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.

Or you can use the plumbing commands to do essentially the same:

git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard

EDIT: I'd like to briefly explain why this works.

The .git folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.

A branch is just a named pointer to a given hash. Here's an example set:

$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master

Each of these files contains a hash pointing to a commit:

$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b

These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:

git reset --hard origin/master

git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.

To see this at work go ahead and try out the following:

git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD

How to limit file upload type file size in PHP?

Hope this helps :-)

if(isset($_POST['submit'])){
    ini_set("post_max_size", "30M");
    ini_set("upload_max_filesize", "30M");
    ini_set("memory_limit", "20000M"); 
    $fileName='product_demo.png';

    if($_FILES['imgproduct']['size'] > 0 && 
            (($_FILES["imgproduct"]["type"] == "image/gif") || 
                ($_FILES["imgproduct"]["type"] == "image/jpeg")|| 
                ($_FILES["imgproduct"]["type"] == "image/pjpeg") || 
                ($_FILES["imgproduct"]["type"] == "image/png") &&
                ($_FILES["imgproduct"]["size"] < 2097152))){

        if ($_FILES["imgproduct"]["error"] > 0){
            echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
        } else {    
            $rnd=rand(100,999);
            $rnd=$rnd."_";
            $fileName = $rnd.trim($_FILES['imgproduct']['name']);
            $tmpName  = $_FILES['imgproduct']['tmp_name'];
            $fileSize = $_FILES['imgproduct']['size'];
            $fileType = $_FILES['imgproduct']['type'];  
            $target = "upload/";
            echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ; 
            move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
        }
    } else {
        echo "Sorry, there was a problem uploading your file.";
    }
}

How to detect if javascript files are loaded?

Further to @T.J. Crowder 's answer, I've added a recursive outer loop that allows one to iterate through all the scripts in an array and then execute a function once all the scripts are loaded:

loadList([array of scripts], 0, function(){// do your post-scriptload stuff})

function loadList(list, i, callback)
{
    {
        loadScript(list[i], function()
        {
            if(i < list.length-1)
            {
                loadList(list, i+1, callback);  
            }
            else
            {
                callback();
            }
        })
    }
}

Of course you can make a wrapper to get rid of the '0' if you like:

function prettyLoadList(list, callback)
{
    loadList(list, 0, callback);
}

Nice work @T.J. Crowder - I was cringing at the 'just add a couple seconds delay before running the callback' I saw in other threads.

How to call javascript function from code-behind

If the order of the execution is not important and you need both some javascript AND some codebehind to be fired on an asp element, heres what you can do.

What you can take away from my example: I have a div covering the ASP control that I want both javascript and codebehind to be ran from. The div's onClick method AND the calendar's OnSelectionChanged event both get fired this way.

In this example, i am using an ASP Calendar control, and im controlling it from both javascript and codebehind:

Front end code:

        <div onclick="showHideModal();">
            <asp:Calendar 
                OnSelectionChanged="DatepickerDateChange" ID="DatepickerCalendar" runat="server" 
                BorderWidth="1px" DayNameFormat="Shortest" Font-Names="Verdana" 
                Font-Size="8pt" ShowGridLines="true" BackColor="#B8C9E1" BorderColor="#003E51" Width="100%"> 
                <OtherMonthDayStyle ForeColor="#6C5D34"> </OtherMonthDayStyle> 
                <DayHeaderStyle  ForeColor="black" BackColor="#D19000"> </DayHeaderStyle>
                <TitleStyle BackColor="#B8C9E1" ForeColor="Black"> </TitleStyle> 
                <DayStyle BackColor="White"> </DayStyle> 
                <SelectedDayStyle BackColor="#003E51" Font-Bold="True"> </SelectedDayStyle> 
            </asp:Calendar>
        </div>

Codebehind:

        protected void DatepickerDateChange(object sender, EventArgs e)
        {
            if (toFromPicked.Value == "MainContent_fromDate")
            {
                fromDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
            else
            {
                toDate.Text = DatepickerCalendar.SelectedDate.ToShortDateString();
            }
        }

Android "hello world" pushnotification example

Firebase: https://firebase.google.com/docs/cloud-messaging/

GCM(Deprecated): http://developer.android.com/google/gcm/index.html

I don't have much knowledge about C2DM. Use GCM, it's very easy to implement and configure.

Only read selected columns

The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

Column selection (col_select)

The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().

Select columns by name
data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr  [ 4]: carrier, tailnum, origin, dest
#> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
#>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
#>  1 N142…  2013     1     1      517            515         2      830
#>  2 N242…  2013     1     1      533            529         4      850
#>  3 N619…  2013     1     1      542            540         2      923
#>  4 N804…  2013     1     1      544            545        -1     1004
#>  5 N668…  2013     1     1      554            600        -6      812
#>  6 N394…  2013     1     1      554            558        -4      740
#>  7 N516…  2013     1     1      555            600        -5      913
#>  8 N829…  2013     1     1      557            600        -3      709
#>  9 N593…  2013     1     1      557            600        -3      838
#> 10 N3AL…  2013     1     1      558            600        -2      753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> #   time_hour <dttm>

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm super late to this but I didn't like the other answers

Installing Homebrew

For brew run

"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing node & npm

You SHOULD NOT use brew to install node and npm.

I've seen a few places suggested that you should use Homebrew to install Node (like alexpods answer and in this Team Treehouse blog Post) but installing this way you're more prone to run into issues as npm and brew are both package managers and you should have a package manager manage another package manager this leads to problems, like this bug offical npm issues Error: Refusing to delete: /usr/local/bin/npm or this Can't uninstall npm module on OSX

You can read more on the topic in DanHerbert's post Fixing npm On Mac OS X for Homebrew Users, where he goes on to say

Also, using the Homebrew installation of npm will require you to use sudo when installing global packages. Since one of the core ideas behind Homebrew is that apps can be installed without giving them root access, this is a bad idea.

For Everything else

I'd use npm; but you really should just follow the install instruction for each modules following the directions on there website as they will be more aware of any issue or bug they have than anyone else

How to get an input text value in JavaScript

All the above solutions are useful. And they used the line lol = document.getElementById('lolz').value; inside the function function kk().

What I suggest is, you may call that variable from another function fun_inside()

function fun_inside()
{    
lol = document.getElementById('lolz').value;
}
function kk(){
fun_inside();
alert(lol);
}

It can be useful when you built complex projects.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

How do I create a Linked List Data Structure in Java?

The above linked list display in opposite direction. I think the correct implementation of insert method should be

public void insert(int d1, double d2) { 
    Link link = new Link(d1, d2); 

    if(first==null){
        link.nextLink = null;
        first = link; 
        last=link;
    }
    else{
        last.nextLink=link;
        link.nextLink=null;
        last=link;
    }
} 

How to find the socket connection state in C?

TCP keepalive socket option (SO_KEEPALIVE) would help in this scenario and close server socket in case of connection loss.

Detect when an HTML5 video finishes

Here is a full example, I hope it helps =).

<!DOCTYPE html> 
<html> 
<body> 

<video id="myVideo" controls="controls">
  <source src="your_video_file.mp4" type="video/mp4">
  <source src="your_video_file.mp4" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        if(!e) { e = window.event; }
        alert("Video Finished");
    }
</script>
</body> 
</html>

How to allow only a number (digits and decimal point) to be typed in an input?

DEMO - - jsFiddle

Directive

   .directive('onlyNum', function() {
      return function(scope, element, attrs) {

         var keyCode = [8,9,37,39,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105,110];
          element.bind("keydown", function(event) {
            console.log($.inArray(event.which,keyCode));
            if($.inArray(event.which,keyCode) == -1) {
                scope.$apply(function(){
                    scope.$eval(attrs.onlyNum);
                    event.preventDefault();
                });
                event.preventDefault();
            }

        });
     };
  });

HTML

 <input type="number" only-num>

Note : Do not forget include jQuery with angular js

SQL Server: use CASE with LIKE

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select 
    case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable

How to use bootstrap-theme.css with bootstrap 3?

Bootstrap-theme.css is the additional CSS file, which is optional for you to use. It gives 3D effects on the buttons and some other elements.

What does numpy.random.seed(0) do?

A random seed specifies the start point when a computer generates a random number sequence.

For example, let’s say you wanted to generate a random number in Excel (Note: Excel sets a limit of 9999 for the seed). If you enter a number into the Random Seed box during the process, you’ll be able to use the same set of random numbers again. If you typed “77” into the box, and typed “77” the next time you run the random number generator, Excel will display that same set of random numbers. If you type “99”, you’ll get an entirely different set of numbers. But if you revert back to a seed of 77, then you’ll get the same set of random numbers you started with.

For example, “take a number x, add 900 +x, then subtract 52.” In order for the process to start, you have to specify a starting number, x (the seed). Let’s take the starting number 77:

Add 900 + 77 = 977 Subtract 52 = 925 Following the same algorithm, the second “random” number would be:

900 + 925 = 1825 Subtract 52 = 1773 This simple example follows a pattern, but the algorithms behind computer number generation are much more complicated

Show ImageView programmatically

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

Convert Numeric value to Varchar

First convert the numeric value then add the 'S':

 select convert(varchar(10),StandardCost) +'S'
 from DimProduct where ProductKey = 212

Bootstrap 3 hidden-xs makes row narrower

.row {
    margin-right: 15px;
}

throw this in your CSS

SQL Server: combining multiple rows into one row

There's a convenient method for this in MySql called GROUP_CONCAT. An equivalent for SQL Server doesn't exist, but you can write your own using the SQLCLR. Luckily someone already did that for you.

Your query then turns into this (which btw is a much nicer syntax):

SELECT CUSTOMFIELD, ISSUE, dbo.GROUP_CONCAT(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602
GROUP BY CUSTOMFIELD, ISSUE

But please note that this method is good for at the most 100 rows within a group. Beyond that, you'll have major performance problems. SQLCLR aggregates have to serialize any intermediate results and that quickly piles up to quite a lot of work. Keep this in mind!

Interestingly the FOR XML doesn't suffer from the same problem but instead uses that horrendous syntax.

Facebook key hash does not match any stored key hashes

DATE UPDATED EVERY TIME I GOT UPVOTE AS I KNOW IT STILL VALID

DATE: 27/02/2021 (27th of Feb, 2021)

This is how I solved this problem

  1. I have got the SHA1 from signingReport

(found in gradle-->tasks/android/signingReport)

Copy the SHA1 value to your clipboard

like this XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX

  1. Facebook sdk requires it to be in base64 hash key so we open http://tomeko.net/online_tools/hex_to_base64.php

to convert your SHA1 value to base64.

This is what Facebook requires get the generated hash " ********************= "

  1. open https://developers.facebook.com/

  2. select your project in the setting tab, basic/Key Hashes add the generated key.

  3. don't forget to save changes.

How to set standard encoding in Visual Studio

I don't know of a global setting nither but you can try this:

  1. Save all Visual Studio templates in UTF-8
  2. Write a Visual Studio Macro/Addin that will listen to the DocumentSaved event and will save the file in UTF-8 format (if not already).
  3. Put a proxy on your source control that will make sure that new files are always UTF-8.

How to count string occurrence in string?

You can use match to define such function:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

`ui-router` $stateParams vs. $state.params

Another reason to use $state.params is for non-URL based state, which (to my mind) is woefully underdocumented and very powerful.

I just discovered this while googling about how to pass state without having to expose it in the URL and answered a question elsewhere on SO.

Basically, it allows this sort of syntax:

<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>

How do you change the text in the Titlebar in Windows Forms?

this.Text = "Your Text Here"

Place this under Initialize Component and it should change on form load.

How can I check if a URL exists via PHP?

function url_exists($url) {
    $headers = @get_headers($url);
    return (strpos($headers[0],'200')===false)? false:true;
}

How to set header and options in axios?

Here is the Right way:-

_x000D_
_x000D_
axios.post('url', {"body":data}, {_x000D_
    headers: {_x000D_
    'Content-Type': 'application/json'_x000D_
    }_x000D_
  }_x000D_
)
_x000D_
_x000D_
_x000D_

How can I get a resource "Folder" from inside my jar File?

As the other answers point out, once the resources are inside a jar file, things get really ugly. In our case, this solution:

https://stackoverflow.com/a/13227570/516188

works very well in the tests (since when the tests are run the code is not packed in a jar file), but doesn't work when the app actually runs normally. So what I've done is... I hardcode the list of the files in the app, but I have a test which reads the actual list from disk (can do it since that works in tests) and fails if the actual list doesn't match with the list the app returns.

That way I have simple code in my app (no tricks), and I'm sure I didn't forget to add a new entry in the list thanks to the test.

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

Rebasing a Git merge commit

There are two options here.

One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.

Another is to use the --rebase-merges option on git rebase, which is described as follows from the manual:

By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."

Joining two table entities in Spring Data JPA

This has been an old question but solution is very simple to that. If you are ever unsure about how to write criterias, joins etc in hibernate then best way is using native queries. This doesn't slow the performance and very useful. Eq. below

    @Query(nativeQuery = true, value = "your sql query")
returnTypeOfMethod methodName(arg1, arg2);

How to convert float to int with Java

Math.round(value) round the value to the nearest whole number.

Use

1) b=(int)(Math.round(a));

2) a=Math.round(a);  
   b=(int)a;

opening a window form from another form programmatically

You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you : Accessing UI Control from BackgroundWorker Thread

Creating a system overlay window (always on top)

Well try my code, atleast it gives you a string as overlay, you can very well replace it with a button or an image. You wont believe this is my first ever android app LOL. Anyways if you are more experienced with android apps than me, please try

  • changing parameters 2 and 3 in "new WindowManager.LayoutParams"
  • try some different event approach

Put spacing between divs in a horizontal row?

Quite a few ways to apprach this problem.

Use the box-sizing css3 property and simulate the margins with borders.

http://jsfiddle.net/Z7mFr/1/

div.inside {
 width: 25%;
 float:left;
 border-right: 5px solid grey;
 background-color: blue;
 box-sizing:border-box;
 -moz-box-sizing:border-box; /* Firefox */
 -webkit-box-sizing:border-box; /* Safari */
}

<div style="width:100%; height: 200px; background-color: grey;">
 <div class="inside">A</div>
 <div class="inside">B</div>
 <div class="inside">C</div>
 <div class="inside">D</div>
</div>

Reduce the percentage of your elements widths and add some margin-right.

http://jsfiddle.net/mJfz3/

.outer {
 width:100%;
 background:#999;
 overflow:auto;
}

.inside {
 float:left;
 width:24%;
 margin-right:1%;
 background:#333;
}

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

For the love of all that is holy...

In my case, I had to set the openssl.cafile PHP config variable to the PEM file path.

I trust it is very true that there are many systems where setting curl.cainfo in PHP's config is exactly what is needed, but in the environment I'm working with, which is the eboraas/laravel docker container, which uses Debian 8 (jessie) and PHP 5.6, setting that variable did not do the trick.

I noticed that the output of php -i did not mention anything about that particular config setting, but it did have a few lines about openssl. There is both an openssl.capath and openssl.cafile option, but just setting the second one allowed curl via PHP to finally be okay with HTTPS URLs.

What is the purpose of the HTML "no-js" class?

The no-js class is used by the Modernizr feature detection library. When Modernizr loads, it replaces no-js with js. If JavaScript is disabled, the class remains. This allows you to write CSS which easily targets either condition.

From Modernizrs' Anotated Source (no longer maintained):

Remove "no-js" class from element, if it exists: docElement.className=docElement.className.replace(/\bno-js\b/,'') + ' js';

Here is a blog post by Paul Irish describing this approach: http://www.paulirish.com/2009/avoiding-the-fouc-v3/


I like to do this same thing, but without Modernizr. I put the following <script> in the <head> to change the class to js if JavaScript is enabled. I prefer to use .replace("no-js","js") over the regex version because its a bit less cryptic and suits my needs.

<script>
    document.documentElement.className = 
       document.documentElement.className.replace("no-js","js");
</script>

Prior to this technique, I would generally just apply js-dependant styles directly with JavaScript. For example:

$('#someSelector').hide();
$('.otherStuff').css({'color' : 'blue'});

With the no-js trick, this can Now be done with css:

.js #someSelector {display: none;}
.otherStuff { color: blue; }
.no-js .otherStuff { color: green }

This is preferable because:

  • It loads faster with no FOUC (flash of unstyled content)
  • Separation of concerns, etc...

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Why is Visual Studio 2010 not able to find/open PDB files?

Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.

Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at

Move the session_start(); to top of the page always.

<?php
@ob_start();
session_start();
?>

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

In Java you would do something similar to:

Transport transport = session.getTransport("smtps");
transport.connect (smtp_host, smtp_port, smtp_username, smtp_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();    

Note 'smtpS' protocol. Also socketFactory properties is no longer necessary in modern JVMs but you might need to set 'mail.smtps.auth' and 'mail.smtps.starttls.enable' to 'true' for Gmail. 'mail.smtps.debug' could be helpful too.

Check table exist or not before create it in Oracle

Well there are lot of answeres already provided and lot are making sense too.

Some mentioned it is just warning and some giving a temp way to disable warnings. All that will work but add risk when number of transactions in your DB is high.

I came across similar situation today and here is very simple query I came up with...

declare
begin
  execute immediate '
    create table "TBL" ("ID" number not null)';
  exception when others then
    if SQLCODE = -955 then null; else raise; end if;
end;
/

955 is failure code.

This is simple, if exception come while running query it will be suppressed. and you can use same for SQL or Oracle.

How to set Linux environment variables with Ansible

I did not have enough reputation to comment and hence am adding a new answer.
Gasek answer is quite correct. Just one thing: if you are updating the .bash_profile file or the /etc/profile, those changes would be reflected only after you do a new login. In case you want to set the env variable and then use it in subsequent tasks in the same playbook, consider adding those environment variables in the .bashrc file.
I guess the reason behind this is the login and the non-login shells.
Ansible, while executing different tasks, reads the parameters from a .bashrc file instead of the .bash_profile or the /etc/profile.

As an example, if I updated my path variable to include the custom binary in the .bash_profile file of the respective user and then did a source of the file. The next subsequent tasks won't recognize my command. However if you update in the .bashrc file, the command would work.

 - name: Adding the path in the bashrc files
   lineinfile: dest=/root/.bashrc line='export PATH=$PATH:path-to-mysql/bin' insertafter='EOF' regexp='export PATH=\$PATH:path-to-mysql/bin' state=present
 
-  - name: Source the bashrc file
   shell: source /root/.bashrc

 - name: Start the mysql client
   shell: mysql -e "show databases";

This would work, but had I done it using profile files the mysql -e "show databases" would have given an error.

- name: Adding the path in the Profile files
   lineinfile: dest=/root/.bash_profile line='export PATH=$PATH:{{install_path}}/{{mysql_folder_name}}/bin' insertafter='EOF' regexp='export PATH=\$PATH:{{install_path}}/{{mysql_folder_name}}/bin' state=present

 - name: Source the bash_profile file
   shell: source /root/.bash_profile

 - name: Start the mysql client
   shell: mysql -e "show databases";

This one won't work, if we have all these tasks in the same playbook.

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

What is the purpose of a self executing function in javascript?

IIRC it allows you to create private properties and methods.

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

---- Remove Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT all"

---- Delete Data ----
EXEC sp_MSForEachTable "DELETE FROM ?"

---- Add Constraint ----
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

---- Reset Identity value ----
EXEC sp_MSForEachTable "DBCC CHECKIDENT ( '?', RESEED, 0)"

What is the difference between DBMS and RDBMS?

A DBMS is used for storage of data in files. In DBMS relationships can be established between two files. Data is stored in flat files with metadata whereas RDBMS stores the data in tabular form with additional condition of data that enforces relationships among the tables. Unlike RDBMS, DBMS does not support client server architecture. RDBMS imposes integrity constraints and also follows normalization which is not supported in DBMS.

How can I add comments in MySQL?

"A comment for a column can be specified with the COMMENT option. The comment is displayed by the SHOW CREATE TABLE and SHOW FULL COLUMNS statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"

As an example

--
-- Table structure for table 'accesslog'
--

CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry', 
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

When should I use the Visitor Design Pattern?

Based on the excellent answer of @Federico A. Ramponi.

Just imagine you have this hierarchy:

public interface IAnimal
{
    void DoSound();
}

public class Dog : IAnimal
{
    public void DoSound()
    {
        Console.WriteLine("Woof");
    }
}

public class Cat : IAnimal
{
    public void DoSound(IOperation o)
    {
        Console.WriteLine("Meaw");
    }
}

What happen if you need to add a "Walk" method here? That will be painful to the whole design.

At the same time, adding the "Walk" method generate new questions. What about "Eat" or "Sleep"? Must we really add a new method to the Animal hierarchy for every new action or operation that we want to add? That's ugly and most important, we will never be able to close the Animal interface. So, with the visitor pattern, we can add new method to the hierarchy without modifying the hierarchy!

So, just check and run this C# example:

using System;
using System.Collections.Generic;

namespace VisitorPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            var animals = new List<IAnimal>
            {
                new Cat(), new Cat(), new Dog(), new Cat(), 
                new Dog(), new Dog(), new Cat(), new Dog()
            };

            foreach (var animal in animals)
            {
                animal.DoOperation(new Walk());
                animal.DoOperation(new Sound());
            }

            Console.ReadLine();
        }
    }

    public interface IOperation
    {
        void PerformOperation(Dog dog);
        void PerformOperation(Cat cat);
    }

    public class Walk : IOperation
    {
        public void PerformOperation(Dog dog)
        {
            Console.WriteLine("Dog walking");
        }

        public void PerformOperation(Cat cat)
        {
            Console.WriteLine("Cat Walking");
        }
    }

    public class Sound : IOperation
    {
        public void PerformOperation(Dog dog)
        {
            Console.WriteLine("Woof");
        }

        public void PerformOperation(Cat cat)
        {
            Console.WriteLine("Meaw");
        }
    }

    public interface IAnimal
    {
        void DoOperation(IOperation o);
    }

    public class Dog : IAnimal
    {
        public void DoOperation(IOperation o)
        {
            o.PerformOperation(this);
        }
    }

    public class Cat : IAnimal
    {
        public void DoOperation(IOperation o)
        {
            o.PerformOperation(this);
        }
    }
}

What does the "On Error Resume Next" statement do?

When an error occurs, the execution will continue on the next line without interrupting the script.

MySQL create stored procedure syntax with delimiter

Getting started with stored procedure syntax in MySQL (using the terminal):

1. Open a terminal and login to mysql like this:

el@apollo:~$ mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
mysql> 

2. Take a look to see if you have any procedures:

mysql> show procedure status;
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name          | Type      | Definer | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
|   yourdb  | sp_user_login | PROCEDURE | root@%  | 2013-12-06 14:10:25 | 2013-12-06 14:10:25 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+---------------+-----------+---------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.01 sec)

I have one defined, you probably have none to start out.

3. Change to the database, delete it.

mysql> use yourdb;
Database changed

mysql> drop procedure if exists sp_user_login;
Query OK, 0 rows affected (0.01 sec)
    
mysql> show procedure status;
Empty set (0.00 sec)
    

4. Ok so now I have no stored procedures defined. Make the simplest one:

mysql> delimiter //
mysql> create procedure foobar()
    -> begin select 'hello'; end//
Query OK, 0 rows affected (0.00 sec)

The // will communicate to the terminal when you are done entering commands for the stored procedure. the stored procedure name is foobar. it takes no parameters and should return "hello".

5. See if it's there, remember to set back your delimiter!:

 mysql> show procedure status;
 -> 
 -> 

Gotcha! Why didn't this work? You set the delimiter to // remember? Set it back to ;

6. Set the delimiter back and look at the procedure:

mysql> delimiter ;
mysql> show procedure status;
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| Db        | Name   | Type      | Definer        | Modified            | Created             | Security_type | Comment | character_set_client | collation_connection | Database Collation |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
| yourdb    | foobar | PROCEDURE | root@localhost | 2013-12-06 14:27:23 | 2013-12-06 14:27:23 | DEFINER       |         | utf8                 | utf8_general_ci      | latin1_swedish_ci  |
+-----------+--------+-----------+----------------+---------------------+---------------------+---------------+---------+----------------------+----------------------+--------------------+
1 row in set (0.00 sec)

   

7. Run it:

mysql> call foobar();
+-------+
| hello |
+-------+
| hello |
+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Hello world complete, lets overwrite it with something better.

8. Drop foobar, redefine it to accept a parameter, and re run it:

mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> show procedure status;
Empty set (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar (in var1 int)
    -> begin select var1 + 2 as result;
    -> end//
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter ;
mysql> call foobar(5);
+--------+
| result |
+--------+
|      7 |
+--------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)

Nice! We made a procedure that takes input, modifies it, and does output. Now lets do an out variable.

9. Remove foobar, Make an out variable, run it:

mysql> delimiter ;
mysql> drop procedure foobar;
Query OK, 0 rows affected (0.00 sec)

mysql> delimiter //
mysql> create procedure foobar(out var1 varchar(100))
    -> begin set var1="kowalski, what's the status of the nuclear reactor?";
    -> end//
Query OK, 0 rows affected (0.00 sec)


mysql> delimiter ;
mysql> call foobar(@kowalski_status);
Query OK, 0 rows affected (0.00 sec)

mysql> select @kowalski_status;
+-----------------------------------------------------+
| @kowalski_status                                    |
+-----------------------------------------------------+
| kowalski, what's the status of the nuclear reactor? |
+-----------------------------------------------------+
1 row in set (0.00 sec)

10. Example of INOUT usage in MySQL:

mysql> select 'ricksays' into @msg;
Query OK, 1 row affected (0.00 sec)


mysql> delimiter //
mysql> create procedure foobar (inout msg varchar(100))
-> begin
-> set msg = concat(@msg, " never gonna let you down");
-> end//


mysql> delimiter ;


mysql> call foobar(@msg);
Query OK, 0 rows affected (0.00 sec)


mysql> select @msg;
+-----------------------------------+
| @msg                              |
+-----------------------------------+
| ricksays never gonna let you down |
+-----------------------------------+
1 row in set (0.00 sec)

Ok it worked, it joined the strings together. So you defined a variable msg, passed in that variable into stored procedure called foobar, and @msg was written to by foobar.

Now you know how to make stored procedures with delimiters. Continue this tutorial here, start in on variables within stored procedures: http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/

How to execute VBA Access module?

Well it depends on how you want to call this code.

Are you calling it from a button click on a form, if so then on the properties for the button on form, go to the Event tab, then On Click item, select [Event Procedure]. This will open the VBA code window for that button. You would then call your Module.Routine and then this would trigger when you click the button.

Similar to this:

Private Sub Command1426_Click()
    mdl_ExportMorning.ExportMorning
End Sub

This button click event calls the Module mdl_ExportMorning and the Public Sub ExportMorning.

Display all views on oracle database

for all views (you need dba privileges for this query)

select view_name from dba_views

for all accessible views (accessible by logged user)

select view_name from all_views

for views owned by logged user

select view_name from user_views

C++ String array sorting

The multiset container uses a red-black tree to keep elements sorted.

// using the multiset container to sort a list of strings.
#include <iostream>
#include <set>
#include <string>
#include <vector>


std::vector<std::string> people = {
  "Joe",
  "Adam",
  "Mark",
  "Jesse",
  "Jess",
  "Fred",
  "Susie",
  "Jill",
  "Fred", // two freds.
  "Adam",
  "Jack",
  "Adam", // three adams.
  "Zeke",
  "Phil"};

int main(int argc, char **argv) {
  std::multiset<std::string> g(people.begin(), people.end()); // """sort"""
  std::vector<std::string> all_sorted (g.begin(), g.end());
  for (int i = 0; i < all_sorted.size(); i++) {
    std::cout << all_sorted[i] << std::endl;
  }
}

Sample Output:

Adam
Adam
Adam
Fred
Fred
Jack
Jess
Jesse
Jill
Joe
Mark
Phil
Susie
Zeke

Note the advantage is that the multiset stays sorted after insertions and deletions, great for displaying say active connections or what not.

Convert Swift string to array

Suppose you have four text fields "otpOneTxt","otpTwoTxt","otpThreeTxt","otpFourTxt" and a string "getOtp"

            let getup = "5642"
            let array = self.getOtp.map({ String($0) })
            
            otpOneTxt.text = array[0] //5
           
            otpTwoTxt.text = array[1] //6
           
            otpThreeTxt.text = array[2] //4
            
            otpFourTxt.text = array[3] //2

How to declare Return Types for Functions in TypeScript

You can read more about function types in the language specification in sections 3.5.3.5 and 3.5.5.

The TypeScript compiler will infer types when it can, and this is done you do not need to specify explicit types. so for the greeter example, greet() returns a string literal, which tells the compiler that the type of the function is a string, and no need to specify a type. so for instance in this sample, I have the greeter class with a greet method that returns a string, and a variable that is assigned to number literal. the compiler will infer both types and you will get an error if you try to assign a string to a number.

class Greeter {
    greet() {
        return "Hello, ";  // type infered to be string
    }
} 

var x = 0; // type infered to be number

// now if you try to do this, you will get an error for incompatable types
x = new Greeter().greet(); 

Similarly, this sample will cause an error as the compiler, given the information, has no way to decide the type, and this will be a place where you have to have an explicit return type.

function foo(){
    if (true)
        return "string"; 
    else 
        return 0;
}

This, however, will work:

function foo() : any{
    if (true)
        return "string"; 
    else 
        return 0;
}

How to compile C program on command line using MinGW?

I encountered the same error message after unpacking MinGW archives to C:\MinGW and setting the path to environment variable as C:\MinGW\bin;.

When I try to compile I get this error!

gcc: error: CreateProcess: No such file or directory

I finally figured out that some of the downloaded archives were reported broken while unpaking them to C:\MinGW (yet I ignored this initially). Once I deleted the broken files and re-downloaded the whole archives again from SourceForge, unpacked them to C:\MinGW successfully the error was gone, and the compiler worked fine and output my desired hello.exe.

I ran this:

gcc hello.c -o hello

The result result was this (a blinking underscore):

_

copy db file with adb pull results in 'permission denied' error

If you get could not copy and permissions are right disable selinux.

Check if selinux is enabled.

$ adb shell
$su
# getenforce
Enforcing

Selinux is enabled and blocking/enforcing. Disable selinux

# setenforce 0

do your stuff and set selinux to enforcing.

# setenforce 1

Timeout a command in bash without unnecessary delay

Building on @loup's answer...

If you want to timeout a process and silence the kill job/pid output, run:

( (sleep 1 && killall program 2>/dev/null) &) && program --version 

This puts the backgrounded process into a subshell so you don't see the job output.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

In my case I had 2 different apps sharing the same app pool. The first one was using the .net4.5 framwork and the new one was using 2.0. When I changed the second app to it's own app pool it starting working fine with no changes to the web.config.

How to upgrade rubygems

You can update all gems by just performing:

sudo gem update

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

how to make negative numbers into positive

You have to use:

abs() for int
fabs() for double
fabsf() for float

Above function will also work but you can also try something like this.

    if(a<0)
    {
         a=-a;
    }

Add a list item through javascript

The above answer was helpful for me, but it might be useful (or best practice) to add the name on submit, as I wound up doing. Hopefully this will be helpful to someone. CodePen Sample

    <form id="formAddName">
      <fieldset>
        <legend>Add Name </legend>
            <label for="firstName">First Name</label>
            <input type="text" id="firstName" name="firstName" />

        <button>Add</button>
      </fieldset>
    </form>

      <ol id="demo"></ol>

<script>
    var list = document.getElementById('demo');
    var entry = document.getElementById('formAddName');
    entry.onsubmit = function(evt) {
    evt.preventDefault();
    var firstName = document.getElementById('firstName').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(firstName));
    list.appendChild(entry);
  }
</script>

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

Open Sublime Text from Terminal in macOS

Please note not to write into /usr/bin but instead into /usr/local/bin. The first one is for app that write themselves the binary into the system and the latest is for that specific usage of making our own system-wide binaries (which is our case here when symlinking).

Also /usr/local/bin is read after /usr/bin and therefore also a good place to override any default app.

Considering this, the right symlinking would be:

ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/local/bin/subl

Access files stored on Amazon S3 through web browser

You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").

http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html

Your policy will look something like the following. You can use the S3 console at http://aws.amazon.com/console to upload it.

 {
  "Version":"2008-10-17",
  "Statement":[{
    "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": {
            "AWS": "*"
         },
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::bucket/*"
      ]
    }
  ]
}

If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.

Vim 80 column layout concerns

Simon Howard's answer is great. But /\%81v.\+/ fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on VIM wiki and HS's choice of colors above:

highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9
match OverLength /\%>80v.\+/

And now VIM will highlight anything that exceeds column 80.

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

Returning Arrays in Java

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

Swift do-try-catch syntax

Swift is worry that your case statement is not covering all cases, to fix it you need to create a default case:

do {
    let sandwich = try makeMeSandwich(kitchen)
    print("i eat it \(sandwich)")
} catch SandwichError.NotMe {
    print("Not me error")
} catch SandwichError.DoItYourself {
    print("do it error")
} catch Default {
    print("Another Error")
}

Where do alpha testers download Google Play Android apps?

Here is a check list for you:

1) Is your app published? (Production APK is not required for publishing)

2) Did your alpha/beta testers "Accept invitation" to Google+ community or Google group?

3) Are your alpha/beta testers logged in their Google+ account?

4) Are your alpha/beta testers using your link from Google Play developer console? It has format like this: https://play.google.com/apps/testing/com.yourdomain.package

Android emulator-5554 offline

In my case, I have unchecked "GPU Host" and its worked :)

Centering in CSS Grid

The CSS place-items shorthand property sets the align-items and justify-items properties, respectively. If the second value is not set, the first value is also used for it.

.parent {
  display: grid;
  place-items: center;
}

Convert YYYYMMDD to DATE

Use SELECT CONVERT(date, '20140327')

In your case,

SELECT [FIRST_NAME],
       [MIDDLE_NAME],
       [LAST_NAME],
       CONVERT(date, [GRADUATION_DATE])     
FROM mydb

How can I load storyboard programmatically from class?

In attribute inspector give the identifier for that view controller and the below code works for me

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
DetailViewController *detailViewController = [storyboard instantiateViewControllerWithIdentifier:@"DetailViewController"];
[self.navigationController pushViewController:detailViewController animated:YES];

Add characters to a string in Javascript

Simple use text = text + string2

How to refresh or show immediately in datagridview after inserting?

You can set the datagridview DataSource to null and rebind it again.

private void button1_Click(object sender, EventArgs e)
{
    myAccesscon.ConnectionString = connectionString;

    dataGridView.DataSource = null;
    dataGridView.Update();
    dataGridView.Refresh();
    OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
    myAccesscon.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable bookings = new DataTable();
    da.Fill(bookings);
    dataGridView.DataSource = bookings;
    myAccesscon.Close();
}

CSS text-decoration underline color

As far as I know it's not possible... but you can try something like this:

_x000D_
_x000D_
.underline _x000D_
{_x000D_
    color: blue;_x000D_
    border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
    <span class="underline">hello world</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between $(document.body) and $('body')

$(document.body) is using the global reference document to get a reference to the body, whereas $('body') is a selector in which jQuery will get the reference to the <body> element on the document.

No major difference that I can see, not any noticeable performance gain from one to the other.

How to use vim in the terminal?

You can definetely build your code from Vim, that's what the :make command does.

However, you need to go through the basics first : type vimtutor in your terminal and follow the instructions to the end.

After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.

For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.

In a few months you'll find yourself hitting o, v and i all the time in every textfield everywhere.

Have fun!

C++ - Hold the console window open?

The right way

cin.get();

cin.get() is C++ compliant, and portable. It will retrieve the next character from the standard input (stdin). The user can press enter and your program will then continue to execute, or terminate in our case.

Microsoft's take

Microsoft has a Knowledge Base Article titled Preventing the Console Window from Disappearing. It describes how to pause execution only when necessary, i.e. only when the user has spawned a new console window by executing the program from explorer. The code is in C which I've reproduced here:

#include <windows.h>
#include <stdio.h>
#include <conio.h>

CONSOLE_SCREEN_BUFFER_INFO csbi;
HANDLE hStdOutput;
BOOL bUsePause;

void main(void)
{
        hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
        if (!GetConsoleScreenBufferInfo(hStdOutput, &csbi))
        {
                printf("GetConsoleScreenBufferInfo failed: %d\n", GetLastError());
                return;
        }

        // if cursor position is (0,0) then use pause
        bUsePause = ((!csbi.dwCursorPosition.X) &&
                     (!csbi.dwCursorPosition.Y));

        printf("Interesting information to read.\n");
        printf("More interesting information to read.\n");

        // only pause if running in separate console window.
        if (bUsePause)
        {
                int ch;
                printf("\n\tPress any key to exit...\n");
                ch = getch();
        }
}

I've used this myself and it's a nice way to do it, under windows only of course. Note also you can achieve this non-programatically under windows by launching your program with this command:

cmd /K consoleapp.exe

The wrong way

Do not use any of the following to achieve this:

system("PAUSE");

This will execute the windows command 'pause' by spawning a new cmd.exe/command.com process within your program. This is both completely unnecessary and also non-portable since the pause command is windows-specific. Unfortunately I've seen this a lot.

getch();

This is not a part of the C/C++ standard library. It is just a compiler extension and some compilers won't support it.

How to fix Error: listen EADDRINUSE while using nodejs?

Under a controller env, you could use:

pkill node before running your script should do the job.

Bear in mind this command will kill all the node processes, which might be right if you have i.e a container running only one instance, our you have such env where you can guarantee that.

In any other scenario, I recommend using a command to kill a certain process id or name you found by looking for it programmatically. like if your process is called, node-server-1 you could do pkill node-server-1.

This resource might be useful to understand: https://www.thegeekstuff.com/2009/12/4-ways-to-kill-a-process-kill-killall-pkill-xkill/

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

For a decimal, use the ToString method, and specify the Invariant culture to get a period as decimal separator:

value.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture)

The long type is an integer, so there is no fraction part. You can just format it into a string and add some zeros afterwards:

value.ToString() + ".00"

Force uninstall of Visual Studio

This is an odd solution, but it worked for me.

I wanted to uninstall Visual Studio 2015 and do a clean install afterwards, but when I tried to remove it through the Control Panel, it was giving me a generic error.

I fixed it by deleting the Visual Studio 2015 folder in Program Files (x86). After that, the Control Panel uninstall worked fine.

No connection could be made because the target machine actively refused it?

For me, I wanted to start the mongo in shell (irrelevant of the exact context of the question, but having the same error message before even starting the mongo in shell)

The process 'MongoDB Service' wasn't running in Services

Start cmd as Administrator and type,

net start MongoDB

Just to see MongoDB is up and running just type mongo, in cmd it will give Mongo version details and Mongo Connection URL

How can I force gradle to redownload dependencies?

Only a manual deletion of the specific dependency in the cache folder works... an artifactory built by a colleague in enterprise repo.

Splitting applicationContext to multiple files

There are two types of contexts we are dealing with:

1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)

2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).

Here is an example of web.xml which includes multiple application context file

_x000D_
_x000D_
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
                            http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
    <display-name>Spring Web Application example</display-name>_x000D_
_x000D_
    <!-- Configurations for the root application context (parent context) -->_x000D_
    <listener>_x000D_
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
    </listener>_x000D_
    <context-param>_x000D_
        <param-name>contextConfigLocation</param-name>_x000D_
        <param-value>_x000D_
            /WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
            /WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
        </param-value>_x000D_
    </context-param>_x000D_
_x000D_
    <!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
    <servlet>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
        <init-param>_x000D_
            <param-name>contextConfigLocation</param-name>_x000D_
            <param-value>_x000D_
                /WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
            </param-value>_x000D_
        </init-param>_x000D_
    </servlet>_x000D_
    <servlet-mapping>_x000D_
        <servlet-name>spring-mvc</servlet-name>_x000D_
        <url-pattern>/admin/*</url-pattern>_x000D_
    </servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
_x000D_
_x000D_

How to change the font size on a matplotlib plot

From the matplotlib documentation,

font = {'family' : 'normal',
        'weight' : 'bold',
        'size'   : 22}

matplotlib.rc('font', **font)

This sets the font of all items to the font specified by the kwargs object, font.

Alternatively, you could also use the rcParams update method as suggested in this answer:

matplotlib.rcParams.update({'font.size': 22})

or

import matplotlib.pyplot as plt
plt.rcParams.update({'font.size': 22})

You can find a full list of available properties on the Customizing matplotlib page.

Pure JavaScript Send POST Data Without a Form

The [new-ish at the time of writing in 2017] Fetch API is intended to make GET requests easy, but it is able to POST as well.

let data = {element: "barium"};

fetch("/post/data/here", {
  method: "POST", 
  body: JSON.stringify(data)
}).then(res => {
  console.log("Request complete! response:", res);
});

If you are as lazy as me (or just prefer a shortcut/helper):

window.post = function(url, data) {
  return fetch(url, {method: "POST", body: JSON.stringify(data)});
}

// ...

post("post/data/here", {element: "osmium"});

.NET Console Application Exit Event

You can use the ProcessExit event of the AppDomain:

class Program
{
    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);           
        // do some work

    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Update

Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:

  • Avoid cross-threading problems; if external COM objects were created on the MessagePump thread, it's easier to deal with them there.
  • There is a time limit on ProcessExit (3 seconds by default), so if cleaning up is time consuming, it may fail if pefromed within that event handler.

Here is the code:

class Program
{
    private static bool _quitRequested = false;
    private static object _syncLock = new object();
    private static AutoResetEvent _waitHandle = new AutoResetEvent(false);

    static void Main(string[] args)
    {
        AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit);
        // start the message pumping thread
        Thread msgThread = new Thread(MessagePump);
        msgThread.Start();
        // read input to detect "quit" command
        string command = string.Empty;
        do
        {
            command = Console.ReadLine();
        } while (!command.Equals("quit", StringComparison.InvariantCultureIgnoreCase));
        // signal that we want to quit
        SetQuitRequested();
        // wait until the message pump says it's done
        _waitHandle.WaitOne();
        // perform any additional cleanup, logging or whatever
    }

    private static void SetQuitRequested()
    {
        lock (_syncLock)
        {
            _quitRequested = true;
        }
    }

    private static void MessagePump()
    {
        do
        {
            // act on messages
        } while (!_quitRequested);
        _waitHandle.Set();
    }

    static void CurrentDomain_ProcessExit(object sender, EventArgs e)
    {
        Console.WriteLine("exit");
    }
}

Numpy: Get random set of rows from 2D array

If you want to generate multiple random subsets of rows, for example if your doing RANSAC.

num_pop = 10
num_samples = 2
pop_in_sample = 3
rows_to_sample = np.random.random([num_pop, 5])
random_numbers = np.random.random([num_samples, num_pop])
samples = np.argsort(random_numbers, axis=1)[:, :pop_in_sample]
# will be shape [num_samples, pop_in_sample, 5]
row_subsets = rows_to_sample[samples, :]

How to handle the new window in Selenium WebDriver using Java?

I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}

How do I get rid of an element's offset using CSS?

Quick fix:

position: relative;
top: -12px;
left: -2px;

this should balance out those offsets, but maybe you should take a look at your whole layout and see how that box interacts with other boxes.

As for terminology, left, right, top and bottom are CSS offset properties. They are used for positioning elements at a specific location (when used with absolute or fixed positioning), or to move them relative to their default location (when used with relative positioning). Margins on the other hand specify gaps between boxes and they sometimes collapse, so they can't be reliably used as offsets.

But note that in your case that offset may not be computed (solely) from CSS offsets.

OpenCV Python rotate image by X degrees around specific point

Here's an example for rotating about an arbitrary point (x,y) using only openCV

def rotate_about_point(x, y, degree, image):
    rot_mtx = cv.getRotationMatrix2D((x, y), angle, 1)
    abs_cos = abs(rot_mtx[0, 0])
    abs_sin = abs(rot_mtx[0, 1])
    rot_wdt = int(frm_hgt * abs_sin + frm_wdt * abs_cos)
    rot_hgt = int(frm_hgt * abs_cos + frm_wdt * abs_sin)
    rot_mtx += np.asarray([[0, 0, -lftmost_x],
                           [0, 0, -topmost_y]])
    rot_img = cv.warpAffine(image, rot_mtx, (rot_wdt, rot_hgt),
                            borderMode=cv.BORDER_CONSTANT)
    return rot_img

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

If username/password contains any special characters then inside the camel configuration use RAW for Configuring the values like

  • RAW(se+re?t&23) where se+re?t&23 is actual password

  • RAW({abc.ftp.password}) where {abc.ftp.password} values comes from a spring property file.

By using RAW, solved my issue.

http://camel.apache.org/how-do-i-configure-endpoints.html

Jersey stopped working with InjectionManagerFactory not found

As far as I can see dependencies have changed between 2.26-b03 and 2.26-b04 (HK2 was moved to from compile to testCompile)... there might be some change in the jersey dependencies that has not been completed yet (or which lead to a bug).

However, right now the simple solution is to stick to an older version :-)

How can I remove time from date with Moment.js?

Use format('LL')

Depending on what you're trying to do with it, format('LL') could do the trick. It produces something like this:

Moment().format('LL'); // => April 29, 2016

How do I push a local Git branch to master branch in the remote?

Follow the below steps for push the local repo into Master branchenter code here

$git status

Render HTML to PDF in Django site

I just whipped this up for CBV. Not used in production but generates a PDF for me. Probably needs work for the error reporting side of things but does the trick so far.

import StringIO
from cgi import escape
from xhtml2pdf import pisa
from django.http import HttpResponse
from django.template.response import TemplateResponse
from django.views.generic import TemplateView

class PDFTemplateResponse(TemplateResponse):

    def generate_pdf(self, retval):

        html = self.content

        result = StringIO.StringIO()
        rendering = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)

        if rendering.err:
            return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
        else:
            self.content = result.getvalue()

    def __init__(self, *args, **kwargs):
        super(PDFTemplateResponse, self).__init__(*args, mimetype='application/pdf', **kwargs)
        self.add_post_render_callback(self.generate_pdf)


class PDFTemplateView(TemplateView):
    response_class = PDFTemplateResponse

Used like:

class MyPdfView(PDFTemplateView):
    template_name = 'things/pdf.html'

What exactly does numpy.exp() do?

exp(x) = e^x where e= 2.718281(approx)

import numpy as np

ar=np.array([1,2,3])
ar=np.exp(ar)
print ar

outputs:

[ 2.71828183  7.3890561  20.08553692]

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

Parse Json string in C#

you can try with System.Web.Script.Serialization.JavaScriptSerializer:

var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);

MySQL FULL JOIN?

Full join in mysql :(left union right) or (right unoin left)

 SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    left JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

    Union

    SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
    FROM Persons
    Right JOIN Orders
    ON Persons.P_Id=Orders.P_Id
    ORDER BY Persons.LastName

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

All three template options - <%@include>, <jsp:include> and <%@tag> are valid, and all three cover different use cases.

With <@include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.

<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".

Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.

Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

How can I download HTML source in C#

You can download files with the WebClient class:

using System.Net;

using (WebClient client = new WebClient ()) // WebClient class inherits IDisposable
{
    client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");

    // Or you can get the file content without saving it
    string htmlCode = client.DownloadString("http://yoursite.com/page.html");
}

Getting value of HTML text input

If your page is refreshed on submitting - yes, but only through the querystring: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx (You must use method "GET" then). Else, you can return its value from the php script.

Archive the artifacts in Jenkins

An artifact can be any result of your build process. The important thing is that it doesn't matter on which client it was built it will be tranfered from the workspace back to the master (server) and stored there with a link to the build. The advantage is that it is versionized this way, you only have to setup backup on your master and that all artifacts are accesible via the web interface even if all build clients are offline.

It is possible to define a regular expression as the artifact name. In my case I zipped all the files I wanted to store in one file with a constant name during the build.

Changing nav-bar color after scrolling?

  1. So I'm using querySelector to get the navbar
  2. I added a scroll event to the window to track the scrollY property
  3. I check if it's higher than 50 then I add the active class to the navbar, else if it contains it already, I simply remove it and I'm pretty sure the conditions can be more currated and simplified.

I made this codepen to help you out!

const navbar = document.querySelector('#nav')

window.addEventListener('scroll', function(e) {
  const lastPosition = window.scrollY
  if (lastPosition > 50 ) {
    navbar.classList.add('active')
  } else if (navbar.classList.contains('active')) {
    navbar.classList.remove('active')
  } else {
    navbar.classList.remove('active')
  }
})

How do I use arrays in cURL POST requests

    $ch = curl_init();

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

    $data = http_build_query($data);

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

    $output = curl_exec($ch);

MySQL and PHP - insert NULL rather than empty string

If you don't pass values, you'll get nulls for defaults.

But you can just pass the word NULL without quotes.

How do I reformat HTML code using Sublime Text 2?

For me, the HTML Prettify solution was extremely simple. I went to the HTML Prettify page.

  1. Needed the Sublime Package Manager
  2. Followed the Instructions for installing the package manager here
  3. typed cmd + shift + p to bring up the menu
  4. Typed prettify
  5. Chose the HTML prettify selection in the menu

Boom. Done. Looks great

vba pass a group of cells as range to function

There is another way to pass multiple ranges to a function, which I think feels much cleaner for the user. When you call your function in the spreadsheet you wrap each set of ranges in brackets, for example: calculateIt( (A1,A3), (B6,B9) )

The above call assumes your two Sessions are in A1 and A3, and your two Customers are in B6 and B9.

To make this work, your function needs to loop through each of the Areas in the input ranges. For example:

Function calculateIt(Sessions As Range, Customers As Range) As Single

    ' check we passed the same number of areas
    If (Sessions.Areas.Count <> Customers.Areas.Count) Then
        calculateIt = CVErr(xlErrNA)
        Exit Function
    End If

    Dim mySession, myCustomers As Range

    ' run through each area and calculate
    For a = 1 To Sessions.Areas.Count

        Set mySession = Sessions.Areas(a)
        Set myCustomers = Customers.Areas(a)

        ' calculate them...
    Next a

End Function

The nice thing is, if you have both your inputs as a contiguous range, you can call this function just as you would a normal one, e.g. calculateIt(A1:A3, B6:B9).

Hope that helps :)

Python Infinity - Any caveats?

So does C99.

The IEEE 754 floating point representation used by all modern processors has several special bit patterns reserved for positive infinity (sign=0, exp=~0, frac=0), negative infinity (sign=1, exp=~0, frac=0), and many NaN (Not a Number: exp=~0, frac?0).

All you need to worry about: some arithmetic may cause floating point exceptions/traps, but those aren't limited to only these "interesting" constants.

Automatically create requirements.txt

If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.

You can use :

import os
import sys
from fuzzywuzzy import fuzz
import subprocess

path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"


files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
      for file in files:
        if file.endswith('.py'):
              pyfiles.append(os.path.join(root, file))

stopWords = ['from', 'import',',','.']

importables = []

for file in pyfiles:
    with open(file) as f:
        content = f.readlines()

        for line in content:
            if "import" in line:
                for sw in stopWords:
                    line = ' '.join(line.split(sw))

                importables.append(line.strip().split(' ')[0])

importables = set(importables)

subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)

with open(path+'/requirements.txt') as req:
    modules = req.readlines()
    modules = {m.split('=')[0].lower() : m for m in modules}


notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']

new_requirements = []
for req_module in importables:
    try :
        new_requirements.append(modules[req_module])

    except KeyError:
        for k,v in modules.items():
            if len(req_module)>1 and req_module not in notList:
                if fuzz.partial_ratio(req_module,k) > 90:
                    new_requirements.append(modules[k])

new_requirements = [i for i in set(new_requirements)]

new_requirements

with open(path+'/requirements.txt','w') as req:
    req.write(''.join(new_requirements))

P.S: It may have a few additional libraries as it checks on fuzzylogic.

How can I issue a single command from the command line through sql plus?

I'm able to run an SQL query by piping it to SQL*Plus:

@echo select count(*) from table; | sqlplus username/password@database

Give

@echo execute some_procedure | sqlplus username/password@databasename

a try.

Redirect all output to file in Bash

To get the output on the console AND in a file file.txt for example.

make 2>&1 | tee file.txt

Note: & (in 2>&1) specifies that 1 is not a file name but a file descriptor.

Formatting code snippets for blogging on Blogger

This can be done fairly easily with SyntaxHighlighter. I have step-by-step instructions for setting up SyntaxHighlighter in Blogger on my blog. SyntaxHighlighter is very easy to use. It lets you post snippets in raw form and then wrap them in pre blocks like:

<pre name="code" class="brush: erlang"><![CDATA[
-module(trim).

-export([string_strip_right/1, reverse_tl_reverse/1, bench/0]).

bench() -> [nbench(N) || N <- [1,1000,1000000]].

nbench(N) -> {N, bench(["a" || _ <- lists:seq(1,N)])}.

bench(String) ->
    {{string_strip_right,
    lists:sum([
        element(1, timer:tc(trim, string_strip_right, [String]))
        || _ <- lists:seq(1,1000)])},
    {reverse_tl_reverse,
    lists:sum([
        element(1, timer:tc(trim, reverse_tl_reverse, [String]))
        || _ <- lists:seq(1,1000)])}}.

string_strip_right(String) -> string:strip(String, right, $\n).

reverse_tl_reverse(String) ->
    lists:reverse(tl(lists:reverse(String))).
]]></pre>

Just change the brush name to "python" or "java" or "javascript" and paste in the code of your choice. The CDATA tagging let's you put pretty much any code in there without worrying about entity escaping or other typical annoyances of code blogging.

How to Get a Sublist in C#

Use the Where clause from LINQ:

List<object> x = new List<object>();
x.Add("A");
x.Add("B");
x.Add("C");
x.Add("D");
x.Add("B");

var z = x.Where(p => p == "A");
z = x.Where(p => p == "B");

In the statements above "p" is the object that is in the list. So if you used a data object, i.e.:

public class Client
{
    public string Name { get; set; }
}

then your linq would look like this:

List<Client> x = new List<Client>();
x.Add(new Client() { Name = "A" });
x.Add(new Client() { Name = "B" });
x.Add(new Client() { Name = "C" });
x.Add(new Client() { Name = "D" });
x.Add(new Client() { Name = "B" });

var z = x.Where(p => p.Name == "A");
z = x.Where(p => p.Name == "B");

How can I generate random alphanumeric strings?

public static class StringHelper
{
    private static readonly Random random = new Random();

    private const int randomSymbolsDefaultCount = 8;
    private const string availableChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    private static int randomSymbolsIndex = 0;

    public static string GetRandomSymbols()
    {
        return GetRandomSymbols(randomSymbolsDefaultCount);
    }

    public static string GetRandomSymbols(int count)
    {
        var index = randomSymbolsIndex;
        var result = new string(
            Enumerable.Repeat(availableChars, count)
                      .Select(s => {
                          index += random.Next(s.Length);
                          if (index >= s.Length)
                              index -= s.Length;
                          return s[index];
                      })
                      .ToArray());
        randomSymbolsIndex = index;
        return result;
    }
}

How to change line-ending settings

For a repository setting solution, that can be redistributed to all developers, check out the text attribute in the .gitattributes file. This way, developers dont have to manually set their own line endings on the repository, and because different repositories can have different line ending styles, global core.autocrlf is not the best, at least in my opinion.

For example unsetting this attribute on a given path [. - text] will force git not to touch line endings when checking in and checking out. In my opinion, this is the best behavior, as most modern text editors can handle both type of line endings. Also, if you as a developer still want to do line ending conversion when checking in, you can still set the path to match certain files or set the eol attribute (in .gitattributes) on your repository.

Also check out this related post, which describes .gitattributes file and text attribute in more detail: What's the best CRLF (carriage return, line feed) handling strategy with Git?

AddRange to a Collection

Here is a bit more advanced/production-ready version:

    public static class CollectionExtensions
    {
        public static TCol AddRange<TCol, TItem>(this TCol destination, IEnumerable<TItem> source)
            where TCol : ICollection<TItem>
        {
            if(destination == null) throw new ArgumentNullException(nameof(destination));
            if(source == null) throw new ArgumentNullException(nameof(source));

            // don't cast to IList to prevent recursion
            if (destination is List<TItem> list)
            {
                list.AddRange(source);
                return destination;
            }

            foreach (var item in source)
            {
                destination.Add(item);
            }

            return destination;
        }
    }

How do I create a link using javascript?

There are a couple of ways:

If you want to use raw Javascript (without a helper like JQuery), then you could do something like:

var link = "http://google.com";
var element = document.createElement("a");
element.setAttribute("href", link);
element.innerHTML = "your text";

// and append it to where you'd like it to go:
document.body.appendChild(element);

The other method is to write the link directly into the document:

document.write("<a href='" + link + "'>" + text + "</a>");

What is the simplest C# function to parse a JSON string into an object?

I think this is what you want:

JavaScriptSerializer JSS = new JavaScriptSerializer();
T obj = JSS.Deserialize<T>(String);

Find Facebook user (url to profile page) by known email address

Facebook has a strict policy on sharing only the content which a profile makes public to the end user.. Still what you want is possible if the user has actually left the email id open to public domain.. A wild try u can do is send batch requests for the maximum possible batch size to ids..."http://graph.facebook.com/ .. and parse the result to check if email exists and if it does then it matches to the one you want.. you don't need any access_token for the public information ..

in case you want email id of a FB user only possible way is that they authorize ur app and then you can use the access_token thus generated for the required task.

Parsing JSON objects for HTML table

another nice recursive way to generate HTML from a nested JSON object (currently not supporting arrays):

// generate HTML code for an object
var make_table = function(json, css_class='tbl_calss', tabs=1){
    // helper to tabulate the HTML tags. will return '\t\t\t' for num_of_tabs=3
    var tab = function(num_of_tabs){
        var s = '';
        for (var i=0; i<num_of_tabs; i++){
            s += '\t';
        }
        //console.log('tabbing done. tabs=' + tabs)
        return s;
    }
    // recursive function that returns a fixed block of <td>......</td>.
    var generate_td = function(json){ 
        if (!(typeof(json) == 'object')){
            // for primitive data - direct wrap in <td>...</td>
            return tab(tabs) + '<td>'+json+'</td>\n';
        }else{
            // recursive call for objects to open a new sub-table inside the <td>...</td>
            // (object[key] may be also an object)
            var s = tab(++tabs)+'<td>\n';
            s +=        tab(++tabs)+'<table class="'+css_class+'">\n';
            for (var k in json){
                s +=        tab(++tabs)+'<tr>\n';
                s +=          tab(++tabs)+'<td>' + k + '</td>\n';
                s +=                      generate_td(json[k]);
                s +=        tab(--tabs)+'</tr>' + tab(--tabs) + '\n';


            }
            // close the <td>...</td> external block
            s +=        tab(tabs--)+'</table>\n';
            s +=    tab(tabs--)+'</td>\n';
            return s;
        }
    }
    // construct the complete HTML code
    var html_code = '' ;
    html_code += tab(++tabs)+'<table class="'+css_class+'">\n';
    html_code +=   tab(++tabs)+'<tr>\n';
    html_code +=     generate_td(json);
    html_code +=   tab(tabs--)+'</tr>\n';
    html_code += tab(tabs--)+'</table>\n';
    return html_code;
}

Illegal Escape Character "\"

Use "\\" to escape the \ character.

Ajax call Into MVC Controller- Url Issue

starting from mihai-labo's answer, why not skip declaring the requrl variable altogether and put the url generating code directly in front of "url:", like:

 $.ajax({
    type: "POST",
    url: '@Url.Action("Action", "Controller", null, Request.Url.Scheme, null)',
    data: "{queryString:'" + searchVal + "'}",
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    success: function (data) {
        alert("here" + data.d.toString());
    }
});

How to horizontally align ul to center of div?

Make the left and right margins of your UL auto and assign it a width:

#headermenu ul {
    margin: 0 auto;
    width: 620px;
}

Edit: As kleinfreund has suggested, you can also center align the container and give the ul an inline-block display, but you then also have to give the LIs either a left float or an inline display.

#headermenu { 
    text-align: center;
}
#headermenu ul { 
    display: inline-block;
}
#headermenu ul li {
    float: left; /* or display: inline; */
}

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

Laravel supports aliases on tables and columns with AS. Try

$users = DB::table('really_long_table_name AS t')
           ->select('t.id AS uid')
           ->get();

Let's see it in action with an awesome tinker tool

$ php artisan tinker
[1] > Schema::create('really_long_table_name', function($table) {$table->increments('id');});
// NULL
[2] > DB::table('really_long_table_name')->insert(['id' => null]);
// true
[3] > DB::table('really_long_table_name AS t')->select('t.id AS uid')->get();
// array(
//   0 => object(stdClass)(
//     'uid' => '1'
//   )
// )

python - find index position in list based of partial string

Your idea to use enumerate() was correct.

indices = []
for i, elem in enumerate(mylist):
    if 'aa' in elem:
        indices.append(i)

Alternatively, as a list comprehension:

indices = [i for i, elem in enumerate(mylist) if 'aa' in elem]

How to convert String to DOM Document object in java?

     public static void main(String[] args) {
    final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
                            "<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
                            "<role>Developer</role><gen>Male</gen></Emp>";
   DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
        DocumentBuilder builder;  
        try 
        {  
            builder = factory.newDocumentBuilder();  
            Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) ); 

        } catch (Exception e) {  
            e.printStackTrace();  
        } 
  }

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I'd like explain the different alter table syntaxes - See the MySQL documentation

For adding/removing defaults on a column:

ALTER TABLE table_name
ALTER COLUMN col_name {SET DEFAULT literal | DROP DEFAULT}

For renaming a column, changing it's data type and optionally changing the column order:

ALTER TABLE table_name
CHANGE [COLUMN] old_col_name new_col_name column_definition
[FIRST|AFTER col_name]

For changing a column's data type and optionally changing the column order:

ALTER TABLE table_name
MODIFY [COLUMN] col_name column_definition
[FIRST | AFTER col_name]

How do I parse command line arguments in Bash?

From digitalpeer.com with minor modifications:

Usage myscript.sh -p=my_prefix -s=dirname -l=libname

#!/bin/bash
for i in "$@"
do
case $i in
    -p=*|--prefix=*)
    PREFIX="${i#*=}"

    ;;
    -s=*|--searchpath=*)
    SEARCHPATH="${i#*=}"
    ;;
    -l=*|--lib=*)
    DIR="${i#*=}"
    ;;
    --default)
    DEFAULT=YES
    ;;
    *)
            # unknown option
    ;;
esac
done
echo PREFIX = ${PREFIX}
echo SEARCH PATH = ${SEARCHPATH}
echo DIRS = ${DIR}
echo DEFAULT = ${DEFAULT}

To better understand ${i#*=} search for "Substring Removal" in this guide. It is functionally equivalent to `sed 's/[^=]*=//' <<< "$i"` which calls a needless subprocess or `echo "$i" | sed 's/[^=]*=//'` which calls two needless subprocesses.

const vs constexpr on variables

I believe there is a difference. Let's rename them so that we can talk about them more easily:

const     double PI1 = 3.141592653589793;
constexpr double PI2 = 3.141592653589793;

Both PI1 and PI2 are constant, meaning you can not modify them. However only PI2 is a compile-time constant. It shall be initialized at compile time. PI1 may be initialized at compile time or run time. Furthermore, only PI2 can be used in a context that requires a compile-time constant. For example:

constexpr double PI3 = PI1;  // error

but:

constexpr double PI3 = PI2;  // ok

and:

static_assert(PI1 == 3.141592653589793, "");  // error

but:

static_assert(PI2 == 3.141592653589793, "");  // ok

As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.

Get table name by constraint name

SELECT owner, table_name
  FROM dba_constraints
 WHERE constraint_name = <<your constraint name>>

will give you the name of the table. If you don't have access to the DBA_CONSTRAINTS view, ALL_CONSTRAINTS or USER_CONSTRAINTS should work as well.

How to remove only 0 (Zero) values from column in excel 2010

You shouldn't use a space " " instead of "0" because the excel deal with the space as a value.

So, the answer is with the option by (Ctrl + F). Then, click the options and put in the Find with "0". Next, click (Match entire cell contents. Finally, replaced or replaced all up to you.

This solution can give more also. You can use (*) before or after the values to delete any parts you want.

Thanks.

passing 2 $index values within nested ng-repeat

What about using this syntax (take a look in this plunker). I just discovered this and it's pretty awesome.

ng-repeat="(key,value) in data"

Example:

<div ng-repeat="(indexX,object) in data">
    <div ng-repeat="(indexY,value) in object">
       {{indexX}} - {{indexY}} - {{value}}
    </div>
</div>

With this syntax you can give your own name to $index and differentiate the two indexes.

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

How can I create a memory leak in Java?

The answer depends entirely on what the interviewer thought they were asking.

Is it possible in practice to make Java leak? Of course it is, and there are plenty of examples in the other answers.

But there are multiple meta-questions that may have been being asked?

  • Is a theoretically "perfect" Java implementation vulnerable to leaks?
  • Does the candidate understand the difference between theory and reality?
  • Does the candidate understand how garbage collection works?
  • Or how garbage collection is supposed to work in an ideal case?
  • Do they know they can call other languages through native interfaces?
  • Do they know to leak memory in those other languages?
  • Does the candidate even know what memory management is, and what is going on behind the scene in Java?

I'm reading your meta-question as "What's an answer I could have used in this interview situation". And hence, I'm going to focus on interview skills instead of Java. I believe you're more likely to repeat the situation of not knowing the answer to a question in an interview than you are to be in a place of needing to know how to make Java leak. So, hopefully, this will help.

One of the most important skills you can develop for interviewing is learning to actively listen to the questions and working with the interviewer to extract their intent. Not only does this let you answer their question the way they want, but also shows that you have some vital communication skills. And when it comes down to a choice between many equally talented developers, I'll hire the one who listens, thinks, and understands before they respond every time.

How to find when a web page was last updated

No, you cannot know when a page was last updated or last changed or uploaded to a server (which might, depending on interpretation, be three different things) just by accessing the page.

A server may, and should (according to the HTTP 1.1 protocol), send a Last-Modified header, which you can find out in several ways, e.g. using Rex Swain’s HTTP Viewer. However, according to the protocol, this is just

“the date and time at which the origin server believes the variant was last modified”.

And the protocol realistically adds:

“The exact meaning of this header field depends on the implementation of the origin server and the nature of the original resource. For files, it may be just the file system last-modified time. For entities with dynamically included parts, it may be the most recent of the set of last-modify times for its component parts. For database gateways, it may be the last-update time stamp of the record. For virtual objects, it may be the last time the internal state changed.”

In practice, web pages are very often dynamically created from a Content Management System or otherwise, and in such cases, the Last-Modified header typically shows a data stamp of creating the response, which is normally very close to the time of the request. This means that the header is practically useless in such cases.

Even in the case of a “static” page (the server simply picks up a file matching the request and sends it), the Last-Modified date stamp normally indicates just the last write access to the file on the server. This might relate to a time when the file was restored from a backup copy, or a time when the file was edited on the server without making any change to the content, or a time when it was uploaded onto the server, possibly replacing an older identical copy. In these cases, assuming that the time stamp is technically correct, it indicates a time after which the page has not been changed (but not necessarily the time of last change).

How do I launch a program from command line without opening a new cmd window?

You can use the call command...

Type: call /?

Usage: call [drive:][path]filename [batch-parameters]

For example call "Example File/Input File/My Program.bat" [This is also capable with calling files that have a .exe, .cmd, .txt, etc.

NOTE: THIS COMMAND DOES NOT ALWAYS WORK!!!

Not all computers are capable to run this command, but if it does work than it is very useful, and you won't have to open a brand new window...

How to test whether a service is running from the command line

Try

sc query state= all 

for a list of services and whether they are running or not.

Groovy / grails how to determine a data type?

To determine the class of an object simply call:

someObject.getClass()

You can abbreviate this to someObject.class in most cases. However, if you use this on a Map it will try to retrieve the value with key 'class'. Because of this, I always use getClass() even though it's a little longer.

If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:

(somObject instanceof Date)

or to check if the class of an object is exactly a particular class (not a subclass of it), use:

(somObject.getClass() == Date)

JavaScript: Parsing a string Boolean value?

You can use JSON.parse or jQuery.parseJSON and see if it returns true using something like this:

function test (input) {
    try {
        return !!$.parseJSON(input.toLowerCase());
    } catch (e) { }
}

Find html label associated with a given input

It is actually far easier to add an id to the label in the form itself, for example:

<label for="firstName" id="firstNameLabel">FirstName:</label>

<input type="text" id="firstName" name="firstName" class="input_Field" 
       pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
       title="Alphabetic, Space, Dash Only, 2-25 Characters Long" 
       autocomplete="on" required
/>

Then, you can simply use something like this:

if (myvariableforpagelang == 'es') {
   // set field label to spanish
   document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
   // set field tooltip (title to spanish
   document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}

The javascript does have to be in a body onload function to work.

Just a thought, works beautifully for me.

Android - running a method periodically using postDelayed() call

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        //Do something after 100ms
        Toast.makeText(c, "check", Toast.LENGTH_SHORT).show();  
        handler.postDelayed(this, 2000);
      }
    }, 1500);

An array of List in c#

Since no context was given to this question and you are a relatively new user, I want to make sure that you are aware that you can have a list of lists. It's not the same as array of list and you asked specifically for that, but nevertheless:

List<List<int>> myList = new List<List<int>>();

you can initialize them through collection initializers like so:

List<List<int>> myList = new List<List<int>>(){{1,2,3},{4,5,6},{7,8,9}};

Get Bitmap attached to ImageView

For those who are looking for Kotlin solution to get Bitmap from ImageView.

var bitmap = (image.drawable as BitmapDrawable).bitmap

@synthesize vs @dynamic, what are the differences?

As per the Apple documentation.

You use the @synthesize statement in a class’s implementation block to tell the compiler to create implementations that match the specification you gave in the @property declaration.

You use the @dynamic statement to tell the compiler to suppress a warning if it can’t find an implementation of accessor methods specified by an @property declaration.

More info:-

https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/DeclaredProperty.html

How do I remove accents from characters in a PHP string?

I can't reproduce your problem. I get the expected result.

How exactly are you using mb_detect_encoding() to verify your string is in fact UTF-8?

If I simply call mb_detect_encoding($input) on both a UTF-8 and ISO-8859-1 encoded version of your string, both of them return "UTF-8", so that function isn't particularly reliable.

iconv() gives me a PHP "notice" when it gets the wrongly encoded string and only echoes "F", but that might just be because of different PHP/iconv settings/versions (?).

I suggest to you try calling mb_check_encoding($input, "utf-8") first to verify that your string really is UTF-8. I think it probably isn't.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

Problem with file_get_contents for the requests https in Windows, uncomment the following lines in the php.ini file:

extension=php_openssl.dll
extension_dir = "ext"

How to query data out of the box using Spring data JPA by both Sort and Pageable?

Spring Pageable has a Sort included. So if your request has the values it will return a sorted pageable.

request: domain.com/endpoint?sort=[FIELDTOSORTBY]&[FIELDTOSORTBY].dir=[ASC|DESC]&page=0&size=20

That should return a sorted pageable by field provided in the provided order.

str_replace with array

Because str_replace() replaces left to right, it might replace a previously inserted value when doing multiple replacements.

    // Outputs F because A is replaced with B, then B is replaced with C, and so on...
    // Finally E is replaced with F, because of left to right replacements.
    $search  = array('A', 'B', 'C', 'D', 'E');
    $replace = array('B', 'C', 'D', 'E', 'F');
    $subject = 'A';
    echo str_replace($search, $replace, $subject);

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

Since there are so many possibilities for what might be wrong. Here's another possibility to look at. I ran into something where I had set up my own roles on a database. (For instance, "Administrator", "Manager", "DataEntry", "Customer", each with their own kinds of limitations) The only ones who could use it were "Manager" role or above--because they were also set up as sysadmin because they were adding users to the database (and they were highly trusted). Also, the users that were being added were Windows Domain users--using their domain credentials. (Everyone with access to the database had to be on our domain, but not everyone on the domain had access to the database--and only a few of them had access to change it.)

Anyway, this working system suddenly stopped working and I was getting error messages similar to the above. What I ended up doing that solved it was to go through all the permissions for the "public" role in that database and add those permissions to all of the roles that I had created. I know that everyone is supposed to be in the "public" role even though you can't add them (or rather, you can "add" them, but they won't "stay added").

So, in "SQL Server Management Studio", I went into my application's database, in other words (my localized names are obscured within <> brackets): " (SQL Server - sa)"\Databases\\Security\Roles\Database Roles\public". Right-click on "public" and select "Properties". In the "Database Role Properties - public" dialog, select the "Securables" page. Go through the list and for each element in the list, come up with an SQL "Grant" statement to grant exactly that permission to another role. So, for instance, there is a scalar function "[dbo].[fn_diagramobjects]" on which the "public" role has "Execute" privilege. So, I added the following line:

EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @RoleName + '];' ) 

Once I had done this for all the elements in the "Securables" list, I wrapped that up in a while loop on a cursor selecting through all the roles in my roles table. This explicitly granted all the permissions of the "public" role to my database roles. At that point, all my users were working again (even after I removed their "sysadmin" access--done as a temporary measure while I figured out what happened.)

I'm sure there's a better (more elegant) way to do this by doing some kind of a query on the database objects and selecting on the public role, but after about half and hour of investigating, I wasn't figuring it out, so I just did it the brute-force method. In case it helps someone else, here's my code.

CREATE PROCEDURE [dbo].[GrantAccess]
AS
DECLARE @AppRoleName AS sysname

DECLARE AppRoleCursor CURSOR LOCAL SCROLL_LOCKS FOR
    SELECT AppRoleName FROM [dbo].[RoleList];

OPEN AppRoleCursor

FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
WHILE @@FETCH_STATUS = 0
BEGIN

    EXEC ( 'GRANT EXECUTE ON [dbo].[fn_diagramobjects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_alterdiagram] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_creatediagram] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_dropdiagram] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagramdefinition] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_helpdiagrams] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT EXECUTE ON [dbo].[sp_renamediagram] TO [' + @AppRoleName + '];' ) 

    EXEC ( 'GRANT SELECT ON [sys].[all_columns] TO [' + @AppRoleName + '];' )
    EXEC ( 'GRANT SELECT ON [sys].[all_objects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[all_parameters] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[all_sql_modules] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[all_views] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[allocation_units] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[assemblies] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[assembly_files] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[assembly_modules] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[assembly_references] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[assembly_types] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[asymmetric_keys] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[certificates] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[change_tracking_tables] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[check_constraints] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[column_type_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[column_xml_schema_collection_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[computed_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[conversation_endpoints] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[conversation_groups] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[conversation_priorities] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[crypt_properties] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[data_spaces] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specification_details] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_audit_specifications] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_files] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_permissions] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_principal_aliases] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_principals] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[database_role_members] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[default_constraints] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[destination_data_spaces] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[event_notifications] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[events] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[extended_procedures] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[extended_properties] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[filegroups] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[foreign_key_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[foreign_keys] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_catalogs] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_catalog_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_index_fragments] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_indexes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stoplists] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[fulltext_stopwords] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[function_order_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[identity_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[index_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[indexes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[internal_tables] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[key_constraints] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[key_encryptions] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[message_type_xml_schema_collection_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[module_assembly_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedure_parameters] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[numbered_procedures] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[objects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[parameter_type_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[parameter_xml_schema_collection_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[parameters] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[partition_functions] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[partition_parameters] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[partition_range_values] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[partition_schemes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[partitions] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[plan_guides] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[procedures] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[remote_service_bindings] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[routes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[schemas] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_message_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_contract_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_contracts] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_message_types] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_queue_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[service_queues] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[services] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[spatial_index_tessellations] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[spatial_indexes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sql_dependencies] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sql_modules] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[stats] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[stats_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[symmetric_keys] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[synonyms] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[syscolumns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[syscomments] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysconstraints] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysdepends] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysfilegroups] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysfiles] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysforeignkeys] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysfulltextcatalogs] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysindexes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysindexkeys] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysmembers] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysobjects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[syspermissions] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysprotects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysreferences] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[system_columns] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[system_objects] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[system_parameters] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[system_sql_modules] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[system_views] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[systypes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[sysusers] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[table_types] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[tables] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[transmission_queue] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[trigger_events] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[triggers] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[type_assembly_usages] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[types] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[views] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_indexes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_attributes] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_collections] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_component_placements] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_components] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_elements] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_facets] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_model_groups] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_namespaces] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_types] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcard_namespaces] TO [' + @AppRoleName + '];' ) 
    EXEC ( 'GRANT SELECT ON [sys].[xml_schema_wildcards] TO [' + @AppRoleName + '];' ) 

    FETCH NEXT FROM AppRoleCursor INTO @AppRoleName
END

CLOSE AppRoleCursor
RETURN 0

GO

Once that is in the system, I just needed to "Exec GrantAccess" to make it work. (Of course, I have a table [RoleList] which contains a "AppRoleName" field that contains the names of the database roles.

So, the mystery remains: why did all my users lose their "public" role and why could I not give it back to them? Was this part of an update to SQL Server 2008 R2? Was it because I ran another script to delete each user and add them back so to refresh their connection with the domain? Well, this solves the issue for now.

One last warning: you probably should check the "public" role on your system before running this to make sure there isn't something missing or wrong, here. It's always possible something is different about your system.

Hope this helps someone else.

VBA - If a cell in column A is not blank the column B equals

If you really want a vba solution you can loop through a range like this:

Sub Check()
    Dim dat As Variant
    Dim rng As Range
    Dim i As Long

    Set rng = Range("A1:A100")
    dat = rng
    For i = LBound(dat, 1) To UBound(dat, 1)
        If dat(i, 1) <> "" Then
            rng(i, 2).Value = "My Text"
        End If
    Next
End Sub

*EDIT*

Instead of using varients you can just loop through the range like this:

Sub Check()
    Dim rng As Range
    Dim i As Long

    'Set the range in column A you want to loop through
    Set rng = Range("A1:A100")
    For Each cell In rng
        'test if cell is empty
        If cell.Value <> "" Then
            'write to adjacent cell
            cell.Offset(0, 1).Value = "My Text"
        End If
    Next
End Sub

How can I color a UIImage in Swift?

Swift 4 and 5

extension UIImageView {
  func setImageColor(color: UIColor) {
    let templateImage = self.image?.withRenderingMode(.alwaysTemplate)
    self.image = templateImage
    self.tintColor = color
  }
}

Call like this:

let imageView = UIImageView(image: UIImage(named: "your_image_name"))
imageView.setImageColor(color: UIColor.purple)

Alternativ For Swift 3, 4 or 5

extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }

}

For Swift 2.3

extension UIImage {
func maskWithColor(color: UIColor) -> UIImage? {

    let maskImage = self.CGImage
    let width = self.size.width
    let height = self.size.height
    let bounds = CGRectMake(0, 0, width, height)

    let colorSpace = CGColorSpaceCreateDeviceRGB()
    let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
    let bitmapContext = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, colorSpace, bitmapInfo.rawValue) //needs rawValue of bitmapInfo

    CGContextClipToMask(bitmapContext, bounds, maskImage)
    CGContextSetFillColorWithColor(bitmapContext, color.CGColor)
    CGContextFillRect(bitmapContext, bounds)

    //is it nil?
    if let cImage = CGBitmapContextCreateImage(bitmapContext) {
        let coloredImage = UIImage(CGImage: cImage)

        return coloredImage

    } else {
        return nil
    } 
 }
}

Call like this:

let image = UIImage(named: "your_image_name")
testImage.image =  image?.maskWithColor(color: UIColor.blue)

How to get main window handle from process id?

This is my solution using pure Win32/C++ based on the top answer. The idea is to wrap everything required into one function without the need for external callback functions or structures:

#include <utility>

HWND FindTopWindow(DWORD pid)
{
    std::pair<HWND, DWORD> params = { 0, pid };

    // Enumerate the windows using a lambda to process each window
    BOOL bResult = EnumWindows([](HWND hwnd, LPARAM lParam) -> BOOL 
    {
        auto pParams = (std::pair<HWND, DWORD>*)(lParam);

        DWORD processId;
        if (GetWindowThreadProcessId(hwnd, &processId) && processId == pParams->second)
        {
            // Stop enumerating
            SetLastError(-1);
            pParams->first = hwnd;
            return FALSE;
        }

        // Continue enumerating
        return TRUE;
    }, (LPARAM)&params);

    if (!bResult && GetLastError() == -1 && params.first)
    {
        return params.first;
    }

    return 0;
}

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.