Programs & Examples On #Xml column

Swift Beta performance: sorting arrays

tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].


Here is an in-place quicksort in Swift Beta:

func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
    if (end - start < 2){
        return
    }
    var p = a[start + (end - start)/2]
    var l = start
    var r = end - 1
    while (l <= r){
        if (a[l] < p){
            l += 1
            continue
        }
        if (a[r] > p){
            r -= 1
            continue
        }
        var t = a[l]
        a[l] = a[r]
        a[r] = t
        l += 1
        r -= 1
    }
    quicksort_swift(&a, start, r + 1)
    quicksort_swift(&a, r + 1, end)
}

And the same in C:

void quicksort_c(int *a, int n) {
    if (n < 2)
        return;
    int p = a[n / 2];
    int *l = a;
    int *r = a + n - 1;
    while (l <= r) {
        if (*l < p) {
            l++;
            continue;
        }
        if (*r > p) {
            r--;
            continue;
        }
        int t = *l;
        *l++ = *r;
        *r-- = t;
    }
    quicksort_c(a, r - a + 1);
    quicksort_c(l, a + n - l);
}

Both work:

var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]

quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))

// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]

Both are called in the same program as written.

var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
    x_swift[i] = CInt(random())
    x_c[i] = CInt(random())
}

let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();

let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();

This converts the absolute times to seconds:

static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;

mach_timebase_info_data_t timebase_info;

uint64_t abs_to_nanos(uint64_t abs) {
    if ( timebase_info.denom == 0 ) {
        (void)mach_timebase_info(&timebase_info);
    }
    return abs * timebase_info.numer  / timebase_info.denom;
}

double abs_to_seconds(uint64_t abs) {
    return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}

Here is a summary of the compiler's optimazation levels:

[-Onone] no optimizations, the default for debug.
[-O]     perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.

Time in seconds with [-Onone] for n=10_000:

Swift:            0.895296452
C:                0.001223848

Here is Swift's builtin sort() for n=10_000:

Swift_builtin:    0.77865783

Here is [-O] for n=10_000:

Swift:            0.045478346
C:                0.000784666
Swift_builtin:    0.032513488

As you can see, Swift's performance improved by a factor of 20.

As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:

Swift:            0.000706745
C:                0.000742374
Swift_builtin:    0.000603576

And for n=1_000_000:

Swift:            0.107111846
C:                0.114957179
Swift_sort:       0.092688548

For comparison, this is with [-Onone] for n=1_000_000:

Swift:            142.659763258
C:                0.162065333
Swift_sort:       114.095478272

So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.

It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:

A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.

They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.

BETA 3 UPDATE:

n=10_000 with [-O]:

Swift:            0.019697268
C:                0.000718064
Swift_sort:       0.002094721

Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.

FINAL UPDATE:

[-Onone]:

Swift:   0.678056695
C:       0.000973914

[-O]:

Swift:   0.001158492
C:       0.001192406

[-Ounchecked]:

Swift:   0.000827764
C:       0.001078914

Pointers in JavaScript?

In JavaScript, you cannot pass variables by reference to a function. However you can pass an object by reference.

How to get the difference between two arrays of objects in JavaScript

you can do diff a on b and diff b on a, then merge both results

_x000D_
_x000D_
let a = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" },_x000D_
    { value: "4", display: "Ryan" }_x000D_
]_x000D_
_x000D_
let b = [_x000D_
    { value: "0", display: "Jamsheer" },_x000D_
    { value: "1", display: "Muhammed" },_x000D_
    { value: "2", display: "Ravi" },_x000D_
    { value: "3", display: "Ajmal" }_x000D_
]_x000D_
_x000D_
// b diff a_x000D_
let resultA = b.filter(elm => !a.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));_x000D_
_x000D_
// a diff b_x000D_
let resultB = a.filter(elm => !b.map(elm => JSON.stringify(elm)).includes(JSON.stringify(elm)));  _x000D_
_x000D_
// show merge _x000D_
console.log([...resultA, ...resultB]);
_x000D_
_x000D_
_x000D_

Convert from lowercase to uppercase all values in all character variables in dataframe

A side comment here for those using any of these answers. Juba's answer is great, as it's very selective if your variables are either numberic or character strings. If however, you have a combination (e.g. a1, b1, a2, b2) etc. It will not convert the characters properly.

As @Trenton Hoffman notes,

library(dplyr)
df <- mutate_each(df, funs(toupper))

affects both character and factor classes and works for "mixed variables"; e.g. if your variable contains both a character and a numberic value (e.g. a1) both will be converted to a factor. Overall this isn't too much of a concern, but if you end up wanting match data.frames for example

df3 <- df1[df1$v1 %in% df2$v1,]

where df1 has been has been converted and df2 contains a non-converted data.frame or similar, this may cause some problems. The work around is that you briefly have to run

df2 <- df2 %>% mutate_each(funs(toupper), v1)
#or
df2 <- df2 %>% mutate_each(df2, funs(toupper))
#and then
df3 <- df1[df1$v1 %in% df2$v1,]

If you work with genomic data, this is when knowing this can come in handy.

get the latest fragment in backstack

Kotlin

activity.supportFragmentManager.fragments.last()

How to get an enum value from a string value in Java?

I like to use this sort of process to parse commands as strings into enumerations. I normally have one of the enumerations as "unknown" so it helps to have that returned when the others are not found (even on a case insensitive basis) rather than null (that meaning there is no value). Hence I use this approach.

static <E extends Enum<E>> Enum getEnumValue(String what, Class<E> enumClass) {
    Enum<E> unknown=null;
    for (Enum<E> enumVal: enumClass.getEnumConstants()) {  
        if (what.compareToIgnoreCase(enumVal.name()) == 0) {
            return enumVal;
        }
        if (enumVal.name().compareToIgnoreCase("unknown") == 0) {
            unknown=enumVal;
        }
    }  
    return unknown;
}

Working copy locked error in tortoise svn while committing

The accepted answer didn't work for me. To fix that issue, I had to right-click on the file that was locked, select repo-browser. This opened a popup with the files as they are on the SVN server. I then right-clicked on the locked file and selected break lock.

When I closed the repository browser, back on explorer I could finally commit!

How to return value from Action()?

You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.

MyType result;

SimpleUsing.DoUsing(db => 
{
  result = db.SomeQuery(); //whatever returns the MyType result
}); 

//do something with result

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Get Root Directory Path of a PHP project

At this moment, PHP itself does not provide a way to get the project's root directory for sure.

But you can implement a very simple method yourself that will do exactly what you're looking for.

Solution

Create a new file in your project, let say D:/workspace/MySystem/Code/FilesManager.php (use whatever name and path suit you the best). Then, use the following code:

<?php

class FilesManager
{
  public static function rootDirectory()
  {
    // Change the second parameter to suit your needs
    return dirname(__FILE__, 2);
  }
}

Now you can do this in, let's say D:/workspace/MySystem/Code/a/b/c/Feature.php:

echo FilesManager::rootDirectory();

And the expected result should be:

"D:/workspace/MySystem"

The output will be the same no matter where your "feature" file is located in the project.

Explanation

dirname is used to return the parent directory of the first parameter. We use the magic constant __FILE__ to give it FilesManager.php's path. The second parameter tells how many times to go up in the hierarchy. In this case, we need to do it twice, but it really depends where you put your file in the hierarchy. You can omit the second parameter if you only need to got up once, meaning the file is located in the root. But then, you can return __DIR__ directly instead.

This solution is guaranteed to work, no matter where the root is located on your server. Unless you end up moving the utility class somewhere else in the hierarchy.

Additional note

I'd avoid using DOCUMENT_ROOT for the following reasons (according to this answer):

  • It makes your application dependent on the server.
  • The Apache setup may give an incorrect path to the root directory.

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

Using Alert in Response.Write Function in ASP.NET

Try using RegisterScriptBlock. Example from the link:

public void Page_Load(Object sender, EventArgs e)
{
    // Define the name and type of the client scripts on the page.
    String csname1 = "PopupScript";
    String csname2 = "ButtonClickScript";
    Type cstype = this.GetType();

    // Get a ClientScriptManager reference from the Page class.
    ClientScriptManager cs = Page.ClientScript;

    // Check to see if the startup script is already registered.
    if (!cs.IsStartupScriptRegistered(cstype, csname1))
    {
      String cstext1 = "alert('Hello World');";
      cs.RegisterStartupScript(cstype, csname1, cstext1, true);
    }

    // Check to see if the client script is already registered.
    if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
    {
      StringBuilder cstext2 = new StringBuilder();
      cstext2.Append("<script type=\"text/javascript\"> function DoClick() {");
      cstext2.Append("Form1.Message.value='Text from client script.'} </");
      cstext2.Append("script>");
      cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
    }
}

Missing styles. Is the correct theme chosen for this layout?

If you still have the problem after trying all the solutions above, please try modify the API Level as shown below. Incorrect API Level may also cause the problem.

enter image description here

remove empty lines from text file with PowerShell

(Get-Content c:\FileWithEmptyLines.txt) | 
    Foreach { $_ -Replace  "Old content", " New content" } | 
    Set-Content c:\FileWithEmptyLines.txt;

continuing execution after an exception is thrown in java

If you have a method that you want to throw an error but you want to do some cleanup in your method beforehand you can put the code that will throw the exception inside a try block, then put the cleanup in the catch block, then throw the error.

try {

    //Dangerous code: could throw an error

} catch (Exception e) {

    //Cleanup: make sure that this methods variables and such are in the desired state

    throw e;
}

This way the try/catch block is not actually handling the error but it gives you time to do stuff before the method terminates and still ensures that the error is passed on to the caller.

An example of this would be if a variable changed in the method then that variable was the cause of an error. It may be desirable to revert the variable.

How to Select Every Row Where Column Value is NOT Distinct

select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1

Can't use Swift classes inside Objective-C

Just include #import "myProject-Swift.h" in .m or .h file

P.S You will not find "myProject-Swift.h" in file inspector it's hidden. But it is generated by app automatically.

How to resize the jQuery DatePicker control

We can alter in the default 'jquery-ui.css' file as below given code:

div.ui-datepicker {
font-size: 80%; 
}

However, changing the default 'jquery-ui.css' file is not recommended as it might have been used somewhere else in the project. Changing values in the default file can alter datepicker font in other webpages where it has been used.

I used the below code to alter "font-size". I placed it just after datepicker() is called as shown below.

<script>
        $(function () {
            $( "#datepicker" ).datepicker();
            $("div.ui-datepicker").css("font-size", "80%")
        });
</script>

Hope this helps...

encapsulation vs abstraction real world example

Encapsulation is hiding information.

Abstraction is hiding the functionality details.

Encapsulation is performed by constructing the class. Abstraction is achieved by creating either Abstract Classes or Interfaces on top of your class.

In the example given in the question, we are using the class for its functionality and we don't care about how the device achieves that. So we can say the details of the phone are "abstracted" from us.

Encapsulation is hiding WHAT THE PHONE USES to achieve whatever it does; Abstraction is hiding HOW IT DOES it.-

jquery: get elements by class name and add css to each of them

You can try this

 $('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});

The $('div.easy_editor') refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

How do I run a shell script without using "sh" or "bash" commands?

Add . (current directory) to your PATH variable.
You can do this by editing your .profile file.
put following line in your .profile file
PATH=$PATH:.

Just make sure to add Shebang (#!/bin/bash) line at the starting of your script and make the script executable(using chmod +x <File Name>).

Local file access with JavaScript

I am only mentioning this as no one mentioned this. There's no programming language I am aware of which allows manipulation of the underlying filesystem. All programming languages rely on OS interrupts to actually get these things done. JavaScript that runs in the browser only has browser "interrupts" to work with which generally does not grant filesystem access unless the browser has been implemented to support such interrupts.

This being said the obvious way to have file system access using JavaScript is to use Node.js which does have the capability of interacting with the underlying OS directly.

Check for internet connection with Swift

I have made my own solution using NSTimer and Alamofire:

import Alamofire

public class ConnectionHelper: NSObject {
    var request: Alamofire.Request?

    func isInternetConnected(completionHandler: Bool -> Void) {
        NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: "requestTimeout", userInfo: nil, repeats: false)

        request = Alamofire
            .request(
                Method.HEAD,
                "http://www.testurl.com"
            )
            .response { response in
                if response.3?.code == -999 {
                    completionHandler(
                        false
                    )
                } else {
                    completionHandler(
                        true
                    )
                }
        }
    }

    func requestTimeout() {
        request!.cancel()
    }
}

The NSTimer is used as a timeout, and was used due to unreliable results using the Alamofire timeout. The request should be made to a URL you trust to be reliable, such as your own server or the server that is hosting the services you depend on.

When the timer expires, the request is cancelled and the results are returned using a completion handler.

Usage:

ConnectionHelper().isInternetConnected() { internetConnected in
    if internetConnected {
        // Connected
    } else {
        // Not connected
    }
}

How to generate UML diagrams (especially sequence diagrams) from Java code?

There is a Free tool named binarydoc which can generate UML Sequence Diagram, or Control Flow Graph (CFG) from the bytecode (instead of source code) of a Java method.

Here is an sample diagram binarydoc generated for the java method java.net.AbstractPlainSocketImpl.getInputStream:

  • Control Flow Graph of method java.net.AbstractPlainSocketImpl.getInputStream:

Control Flow Graph

  • UML Sequence Diagram of method java.net.AbstractPlainSocketImpl.getInputStream:

UML Sequence Diagram

How can I pass a member function where a free function is expected?

I asked a similar question (C++ openframeworks passing void from other classes) but the answer I found was clearer so here the explanation for future records:

it’s easier to use std::function as in:

 void draw(int grid, std::function<void()> element)

and then call as:

 grid.draw(12, std::bind(&BarrettaClass::draw, a, std::placeholders::_1));

or even easier:

  grid.draw(12, [&]{a.draw()});

where you create a lambda that calls the object capturing it by reference

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

UICollectionView current visible cell index

It will probably be best to use UICollectionViewDelegate methods: (Swift 3)

// Called before the cell is displayed    
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}

// Called when the cell is displayed
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    print(indexPath.row)
}

Setting the default page for ASP.NET (Visual Studio) server configuration

This One Method For Published Solution To Show SpeciFic Page on startup.

Here Is the Route Example to Redirect to Specific Page...

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "YourSolutionName.Controllers" }
        );
    }
}

By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.

Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..

Javascript - object key->value

Use [] notation for string representations of properties:

console.log(obj[name]);

Otherwise it's looking for the "name" property, rather than the "a" property.

Relative instead of Absolute paths in Excel VBA

Here's my quick and simple function for getting the absolute path from a relative path.

The difference from the accepted answer is that this function can handle relative paths that moves up to parent folders.

Example:

Workbooks.Open FileName:=GetAbsolutePath("..\..\TRICATEndurance Summary.html")

Code:

' Gets an absolute path from a relative path in the active workbook
Public Function GetAbsolutePath(relativePath As String) As String
    
    Dim absPath As String
    Dim pos As Integer
    
    absPath = ActiveWorkbook.Path
    
    ' Make sure paths are in correct format
    relativePath = Replace(relativePath, "/", "\")
    absPath = Replace(absPath, "/", "\")
    
    Do While Left$(relativePath, 3) = "..\"
    
        ' Remove level from relative path
        relativePath = Mid$(relativePath, 4)
        
        ' Remove level from absolute path
        pos = InStrRev(absPath, "\")
        absPath = Left$(absPath, pos - 1)
    
    Loop
    
    GetAbsolutePath = PathCombine(absPath, relativePath)
    
End Function

How to debug stored procedures with print statements?

Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.

Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.

  • For even more opinions/observations focus your attention on this SO post here.
  • Specifically look at this answer of the same post by Phil_factor (Ha ha! Love the SQL humor)
  • Regarding the suggestion of using RAISERROR WITH NOWAIT look at this answer of the same post by JimCarden

Don't do these things

  1. Some people are under the impression that they can just use a GO statement after their PRINT statement, but you CANNOT use the GO statement INSIDE of a sproc. So that solution is out.
  2. I don't recommend SELECT-ing your print statements because it is just going to muddy your result set with nonsense and if your sproc is supposed to be consumed by a program later, then you will have to know which result sets to skip when looping through the results from your data reader. This is just a bad idea, so don't do it.
  3. Another problem with SELECT-ING your print statements is that they don't always show up immediately. I have had different experiences with this for different executions, so don't expect any kind of consistency with this methodology.

Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...

It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
    SET NOCOUNT ON;

    -- This will print immediately
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    -- Five second delay to simulate lengthy execution
    WAITFOR DELAY '00:00:05'

    -- This will print after the five second delay
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample]

Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.

Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
    SET NOCOUNT ON;

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P Start';
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    WAITFOR DELAY '00:00:05'

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P End'
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample2]

Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.

How to encode text to base64 in python

It turns out that this is important enough to get it's own module...

import base64
base64.b64encode(b'your name')  # b'eW91ciBuYW1l'
base64.b64encode('your name'.encode('ascii'))  # b'eW91ciBuYW1l'

The character encoding of the plain text document was not declared - mootool script

I fixed this issue by adding a slash at the beginning to my relative path

How to create nested directories using Mkdir in Golang?

If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

The path_test.go is a good illustration on how to use it:

func TestMkdirAll(t *testing.T) {
    tmpDir := TempDir()
    path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
    err := MkdirAll(path, 0777)
    if err != nil {
    t.Fatalf("MkdirAll %q: %s", path, err)
    }
    defer RemoveAll(tmpDir + "/_TestMkdirAll_")
...
}

(Make sure to specify a sensible permission value, as mentioned in this answer)

Provisioning Profiles menu item missing from Xcode 5

Try this:

Xcode >> Preferences >> Accounts

How do I use installed packages in PyCharm?

For PyCharm Community Edition 2016.3.2 it is:

"Project Interpreter" -> Top right settings icon -> "More".

Then on the right side there should be a packages icon. When hovering over it it should say "Show paths for selected interpreter". Click it.

Then click the "Add" button or press "alt+insert" to add a new path.

private final static attribute vs private final attribute

Lets say if the class will not have more than one instance ever, then which one takes more memory:

private static final int ID = 250; or private final int ID = 250;

I've understood that static will refer to the class type with only one copy in the memory and non static will be in a new memory location for each instance variable. However internally if we just compare 1 instance of the same class ever (i.e. more than 1 instance would not be created), then is there any overhead in terms of space used by 1 static final variable?

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

    System.out.println("using keySet");
    for (String key : map.keySet()) {
        System.out.println(key + "=" + map.get(key));
    }
    System.out.println();

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

request exceeds the configured maxQueryStringLength when using [Authorize]

In the root web.config for your project, under the system.web node:

<system.web>
    <httpRuntime maxUrlLength="10999" maxQueryStringLength="2097151" />
...

In addition, I had to add this under the system.webServer node or I got a security error for my long query strings:

<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxUrl="10999" maxQueryString="2097151" />
      </requestFiltering>
    </security>
...

How to use custom packages

another solution:
add src/myproject to $GOPATH.

Then import "mylib" will compile.

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

React Native version mismatch

For me, who is running with a monorepo, there was a hidden react-native version inside yarn.lock. It was not present in any package.json, but was never deleted.

I removed that particular react-native version from yarn.lock, and did a

yarn install

This cleaned out alot of old stuff and made sure that things was working fine.

Wait until all jQuery Ajax requests are done?

I found simple way, it using shift()

function waitReq(id)
{
  jQuery.ajax(
  {
    type: 'POST',
    url: ajaxurl,
    data:
    {
      "page": id
    },
    success: function(resp)
    {
      ...........
      // check array length if not "0" continue to use next array value
      if(ids.length)
      {
        waitReq(ids.shift()); // 2
      )
    },
    error: function(resp)
    {
      ....................
      if(ids.length)
      {
        waitReq(ids.shift());
      )
    }
  });
}

var ids = [1, 2, 3, 4, 5];    
// shift() = delete first array value (then print)
waitReq(ids.shift()); // print 1

count (non-blank) lines-of-code in bash

The neatest command is

grep -vc ^$ fileName

with -c option, you don't even need wc -l

How to do error logging in CodeIgniter (PHP)

Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.

i.e $config['log_threshold'] = [log_level ranges 0-4];

How to validate phone numbers using regex

Here's my best try so far. It handles the formats above but I'm sure I'm missing some other possible formats.

^\d?(?:(?:[\+]?(?:[\d]{1,3}(?:[ ]+|[\-.])))?[(]?(?:[\d]{3})[\-/)]?(?:[ ]+)?)?(?:[a-zA-Z2-9][a-zA-Z0-9 \-.]{6,})(?:(?:[ ]+|[xX]|(i:ext[\.]?)){1,2}(?:[\d]{1,5}))?$

Add new attribute (element) to JSON object using JavaScript

You can also use Object.assign from ECMAScript 2015. It also allows you to add nested attributes at once. E.g.:

const myObject = {};

Object.assign(myObject, {
    firstNewAttribute: {
        nestedAttribute: 'woohoo!'
    }
});

Ps: This will not override the existing object with the assigned attributes. Instead they'll be added. However if you assign a value to an existing attribute then it would be overridden.

SQL Query Where Field DOES NOT Contain $x

SELECT * FROM table WHERE field1 NOT LIKE '%$x%'; (Make sure you escape $x properly beforehand to avoid SQL injection)

Edit: NOT IN does something a bit different - your question isn't totally clear so pick which one to use. LIKE 'xxx%' can use an index. LIKE '%xxx' or LIKE '%xxx%' can't.

Switch statement for string matching in JavaScript

Another option is to use input field of a regexp match result:

str = 'XYZ test';
switch (str) {
  case (str.match(/^xyz/) || {}).input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case (str.match(/test/) || {}).input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

How can I close a window with Javascript on Mozilla Firefox 3?

From a user experience stand-point, you don't want a major action to be done passively.

Something major like a window close should be the result of an action by the user.

How to implement "select all" check box in HTML?

Using jQuery:

// Listen for click on toggle checkbox
$('#select-all').click(function(event) {   
    if(this.checked) {
        // Iterate each checkbox
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;                       
        });
    }
});

HTML:

<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<input type="checkbox" name="checkbox-2" id="checkbox-2" />
<input type="checkbox" name="checkbox-3" id="checkbox-3" />

<!-- select all boxes -->
<input type="checkbox" name="select-all" id="select-all" />

What is a practical use for a closure in JavaScript?

Reference: Practical usage of closures

In practice, closures may create elegant designs, allowing customization of various calculations, deferred calls, callbacks, creating encapsulated scope, etc.

An example is the sort method of arrays which accepts the sort condition function as an argument:

[1, 2, 3].sort(function (a, b) {
    ... // Sort conditions
});

Mapping functionals as the map method of arrays which maps a new array by the condition of the functional argument:

[1, 2, 3].map(function (element) {
    return element * 2;
}); // [2, 4, 6]

Often it is convenient to implement search functions with using functional arguments defining almost unlimited conditions for search:

someCollection.find(function (element) {
    return element.someProperty == 'searchCondition';
});

Also, we may note applying functionals as, for example, a forEach method which applies a function to an array of elements:

[1, 2, 3].forEach(function (element) {
    if (element % 2 != 0) {
        alert(element);
    }
}); // 1, 3

A function is applied to arguments (to a list of arguments — in apply, and to positioned arguments — in call):

(function () {
    alert([].join.call(arguments, ';')); // 1;2;3
}).apply(this, [1, 2, 3]);

Deferred calls:

var a = 10;
setTimeout(function () {
    alert(a); // 10, after one second
}, 1000);

Callback functions:

var x = 10;
// Only for example
xmlHttpRequestObject.onreadystatechange = function () {
    // Callback, which will be called deferral ,
    // when data will be ready;
    // variable "x" here is available,
    // regardless that context in which,
    // it was created already finished
    alert(x); // 10
};

Creation of an encapsulated scope for the purpose of hiding auxiliary objects:

var foo = {};
(function (object) {
    var x = 10;
    object.getX = function _getX() {
        return x;
    };
})(foo);

alert(foo.getX()); // Get closured "x" – 10

Class name does not name a type in C++

Aren't you missing the #include "B.h" in A.h?

php error: Class 'Imagick' not found

For MAMP running on Mac OSX

Find out the what version of PHP and install the right version via brew

brew install homebrew/php/php56-imagick

Add the extension by modifying the php.ini template in MAMP

enter image description here

Verify the Imagick

enter image description here

Why does JSON.parse fail with the empty string?

As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

returns null. It would be a mistake for invalid JSON to also be parsed to null.

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

will parse correctly, (returning an empty string). But

JSON.parse('');

will not.

Valid minimal JSON strings are

The empty object '{}'

The empty array '[]'

The string that is empty '""'

A number e.g. '123.4'

The boolean value true 'true'

The boolean value false 'false'

The null value 'null'

How to check for an empty struct?

You can use == to compare with a zero value composite literal because all fields are comparable:

if (Session{}) == session  {
    fmt.Println("is zero value")
}

playground example

Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.

The use of == above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.

An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use

if session.playerId == "" {
    fmt.Println("is zero value")
}

Get protocol + host name from URL

Here is a slightly improved version:

urls = [
    "http://stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "Stackoverflow.com:8080/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "http://stackoverflow.com/some/folder?test=/questions/9626535/get-domain-name-from-url",
    "https://StackOverflow.com:8080?test=/questions/9626535/get-domain-name-from-url",
    "stackoverflow.com?test=questions&v=get-domain-name-from-url"]
for url in urls:
    spltAr = url.split("://");
    i = (0,1)[len(spltAr)>1];
    dm = spltAr[i].split("?")[0].split('/')[0].split(':')[0].lower();
    print dm

Output

stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com
stackoverflow.com

Fiddle: https://pyfiddle.io/fiddle/23e4976e-88d2-4757-993e-532aa41b7bf0/?i=true

Delete certain lines in a txt file via a batch file

If you have sed:

sed -e '/REFERENCE/d' -e '/ERROR/d' [FILENAME]

Where FILENAME is the name of the text file with the good & bad lines

Make elasticsearch only return certain fields?

Here is another solution, now using a match expression

Source filtering allows to control how the _source field is returned with every hit.

Tested with Elastiscsearch version 5.5

The keyword includes defines the specifics fields.

GET /my_indice/my_indice_type/_search
{
  "_source": {
    "includes": [
      "my_especific_field"
    ]
  },
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "_id": "%my_id_here_without_percent%"
          }
        }
      ]
    }
  }
}

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).

In MySQL, a user is identified by both a username ("test2") and a host ("localhost").

The error message identifies the user ("test2") and the host ("localhost") values...

  'test2'@'localhost'

We can check to see if the user exists, using this query from a client we can connect from:

 SELECT user, host FROM mysql.user

We're looking for a row that has "test2" for user, and "localhost" for host.

 user     host       
 -------  -----------
 test2     127.0.0.1  cleanup
 test2     ::1        
 test2     localhost  

If that row doesn't exist, then the host may be set to wildcard value of %, to match any other host that isn't a match.

If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root

 SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')

We can also verify that the user has privileges on objects in the database.

 GRANT SELECT ON jobs.* TO 'test2'@'localhost' 

EDIT

If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES statement, executed by a privileged user.

Using Java 8's Optional with Stream::flatMap

Late to the party, but what about

things.stream()
    .map(this::resolve)
    .filter(Optional::isPresent)
    .findFirst().get();

You can get rid of the last get() if you create a util method to convert optional to stream manually:

things.stream()
    .map(this::resolve)
    .flatMap(Util::optionalToStream)
    .findFirst();

If you return stream right away from your resolve function, you save one more line.

Set a button group's width to 100% and make buttons equal width?

Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div> as a wrapper around elements with .w-100.

Try this:

<div class="btn-group d-flex" role="group>
  <button type="button" class="btn btn-primary w-100">Submit</button>
  <button type="button" class="btn btn-primary w-100">Cancel</button>
</div>

How to check how many letters are in a string in java?

If you are counting letters, the above solution will fail for some unicode symbols. For example for these 5 characters sample.length() will return 6 instead of 5:

String sample = "\u760c\u0444\u03b3\u03b5\ud800\udf45"; // ???e

The codePointCount function was introduced in Java 1.5 and I understand gives better results for glyphs etc

sample.codePointCount(0, sample.length()) // returns 5

http://globalizer.wordpress.com/2007/01/16/utf-8-and-string-length-limitations/

Converting Java objects to JSON with Jackson

Just follow any of these:

  • For jackson it should work:

          ObjectMapper mapper = new ObjectMapper();  
          return mapper.writeValueAsString(object);
          //will return json in string
    
  • For gson it should work:

        Gson gson = new Gson();
        return Response.ok(gson.toJson(yourClass)).build();
    

Read url to string in few lines of java code

The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)

If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.

Example

String result = getUrlAsString("https://www.google.com");
System.out.println(result);

outputs

<!doctype html><html itemscope="" .... etc

Code

import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public static String getUrlAsString(String url)
{
    try
    {
        URL urlObj = new URL(url);
        URLConnection con = urlObj.openConnection();

        con.setDoOutput(true); // we want the response 
        con.setRequestProperty("Cookie", "myCookie=test123");
        con.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        String newLine = System.getProperty("line.separator");
        while ((inputLine = in.readLine()) != null)
        {
            response.append(inputLine + newLine);
        }

        in.close();

        return response.toString();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}

Flexbox and Internet Explorer 11 (display:flex in <html>?)

According to http://caniuse.com/#feat=flexbox:

"IE10 and IE11 default values for flex are 0 0 auto rather than 0 1 auto, as per the draft spec, as of September 2013"

So in plain words, if somewhere in your CSS you have something like this: flex:1 , that is not translated the same way in all browsers. Try changing it to 1 0 0 and I believe you will immediately see that it -kinda- works.

The problem is that this solution will probably mess up firefox, but then you can use some hacks to target only Mozilla and change it back:

@-moz-document url-prefix() {
 #flexible-content{
      flex: 1;
    }
}

Since flexbox is a W3C Candidate and not official, browsers tend to give different results, but I guess that will change in the immediate future.

If someone has a better answer I would like to know!

Java Wait for thread to finish

You can use join() to wait for all threads to finish. Keep all objects of threads in the global ArrayList at the time of creating threads. After that keep it in loop like below:

for (int i = 0; i < 10; i++) 
{
    Thread T1 = new Thread(new ThreadTest(i));                
    T1.start();                
    arrThreads.add(T1);
} 

for (int i = 0; i < arrThreads.size(); i++) 
{
    arrThreads.get(i).join(); 
}

Check here for complete details: http://www.letmeknows.com/2017/04/24/wait-for-threads-to-finish-java

How to copy file from one location to another location?

  public static void copyFile(File oldLocation, File newLocation) throws IOException {
        if ( oldLocation.exists( )) {
            BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
            BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
            try {
                byte[]  buff = new byte[8192];
                int numChars;
                while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                    writer.write( buff, 0, numChars );
                }
            } catch( IOException ex ) {
                throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
            } finally {
                try {
                    if ( reader != null ){                      
                        writer.close();
                        reader.close();
                    }
                } catch( IOException ex ){
                    Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                }
            }
        } else {
            throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
        }
    }  

MongoDB: How to update multiple documents with a single command?

Multi update was added recently, so is only available in the development releases (1.1.3). From the shell you do a multi update by passing true as the fourth argument to update(), where the the third argument is the upsert argument:

db.test.update({foo: "bar"}, {$set: {test: "success!"}}, false, true);

For versions of mongodb 2.2+ you need to set option multi true to update multiple documents at once.

db.test.update({foo: "bar"}, {$set: {test: "success!"}}, {multi: true})

For versions of mongodb 3.2+ you can also use new method updateMany() to update multiple documents at once, without the need of separate multi option.

db.test.updateMany({foo: "bar"}, {$set: {test: "success!"}})

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

There are two ways of doing it.

1.Right click on drawable New->Image Asset-> select your highest resolution image rest will be created automatically. once you finish you can see different resolution inside drawable folder

  1. The way you want. on the project Explorer window you see a dropdown as Android. Click it change to project.

Now yourprojectname->app->src->main->res->

Aila You can see your drawable folders with hdpi mdpi etc.

Number of regex matches

I know this is a little old, but this but here is a concise function for counting regex patterns.

def regex_cnt(string, pattern):
    return len(re.findall(pattern, string))

string = 'abc123'

regex_cnt(string, '[0-9]')

echo that outputs to stderr

You could do this, which facilitates reading:

>&2 echo "error"

>&2 copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to. For more information see the Bash Hackers Illustrated Redirection Tutorial.

Convert byte to string in Java

If it's a single byte, just cast the byte to a char and it should work out to be fine i.e. give a char entity corresponding to the codepoint value of the given byte. If not, use the String constructor as mentioned elsewhere.

char ch = (char)0x63;
System.out.println(ch);

Is String.Contains() faster than String.IndexOf()?

If you really want to micro optimise your code your best approach is always benchmarking.

The .net framework has an excellent stopwatch implementation - System.Diagnostics.Stopwatch

Fastest way to compute entropy in Python

An answer that doesn't rely on numpy, either:

import math
from collections import Counter

def eta(data, unit='natural'):
    base = {
        'shannon' : 2.,
        'natural' : math.exp(1),
        'hartley' : 10.
    }

    if len(data) <= 1:
        return 0

    counts = Counter()

    for d in data:
        counts[d] += 1

    ent = 0

    probs = [float(c) / len(data) for c in counts.values()]
    for p in probs:
        if p > 0.:
            ent -= p * math.log(p, base[unit])

    return ent

This will accept any datatype you could throw at it:

>>> eta(['mary', 'had', 'a', 'little', 'lamb'])
1.6094379124341005

>>> eta([c for c in "mary had a little lamb"])
2.311097886212714

The answer provided by @Jarad suggested timings as well. To that end:

repeat_number = 1000000
e = timeit.repeat(
    stmt='''eta(labels)''', 
    setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import eta''', 
    repeat=3, 
    number=repeat_number)

Timeit results: (I believe this is ~4x faster than the best numpy approach)

print('Method: {}, Avg.: {:.6f}'.format("eta", np.array(e).mean()))

Method: eta, Avg.: 10.461799

How to use class from other files in C# with visual studio?

It would be more beneficial for us if we could see the actual project structure, as the classes alone do not say that much.

Assuming that both .cs files are in the same project (if they are in different projects inside the same solution, you'd have to add a reference to the project containing Class2.cs), you can click on the Class2 occurrence in your code that is underlined in red and press CTRL + . (period) or click on the blue bar that should be there. The first option appearing will then add the appropriate using statement automatically. If there is no such menu, it may indicate that there is something wrong with the project structure or a reference missing.

You could try making Class2 public, but it sounds like this can't be a problem here, since by default what you did is internal class Class2 and thus Class2 should be accessible if both are living in the same project/assembly. If you are referencing a different assembly or project wherein Class2 is contained, you have to make it public in order to access it, as internal classes can't be accessed from outside their assembly.

As for renaming: You can click Program.cs in the Solution Explorer and press F2 to rename it. It will then open up a dialog window asking you if the class Program itself and all references thereof should be renamed as well, which is usually what you want. Or you could just rename the class Program in the declaration and again open up the menu with the small blue bar (or, again, CTRL+.) and do the same, but it won't automatically rename the actual file accordingly.

Edit after your question edit: I have never used this option you used, but from quick checking I think that it's really not inside the same project then. Do the following when adding new classes to a project: In the Solution Explorer, right click the project you created and select [Add] -> [Class] or [Add] -> [New Item...] and then select 'Class'. This will automatically make the new class part of the project and thus the assembly (the assembly is basically the 'end product' after building the project). For me, there is also the shortcut Alt+Shift+C working to create a new class.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

How to save a data.frame in R?

Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.

write.csv(Data_output, "output.csv", row.names = F, quote = F)

credit to Peter and Ilja, UMCG, the Netherlands

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

How to resolve TypeError: can only concatenate str (not "int") to str

Use f-strings to resolve the TypeError

# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'

# same intent with a f-string
i = 15

test = f'Here is a test that can be run {i} times'

print(test)

# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i  # will cause a TypeError

# should be
t = f'test{i}'

print(t)

# output
'test15'
  • The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
  • Convert the string to an int.
  • This scenario is specific to this question
  • When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i  # will cause a TypeError

# convert the string to int
t = 15 + int(i)
print(t)

# output
30

Note

  • The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
  • However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.

Original Code Issues

  • TypeError is caused because message type is a str.
  • The code iterates each character and attempts to add char, a str type, to an int
  • That issue can be resolved by converting char to an int
  • As the code is presented, secret_string needs to be initialized with 0 instead of "".
  • The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
  • Resolved by using a smaller number
  • The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")

secret_string = 0

for char in message:
    char = int(char)
    value = char + 742146
    secret_string += ord(chr(value))
    
print(f'\nRevealed: {secret_string}')

# Output
Enter a message you want to be revealed:  999

Revealed: 2226465

Updated Code Issues

  • message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
  • message is converted to int to make sure the input is an int.
  • Set the type with str()
  • Only convert value to Unicode with chr
  • Don't use ord
while True:
    try:
        message = str(int(input("Enter a message you want to be decrypt: ")))
        break
    except ValueError:
        print("Error, it must be an integer")
        
secret_string = ""
for char in message:
    
    value = int(char) + 10000
    
    secret_string += chr(value)

print("Decrypted", secret_string)

# output
Enter a message you want to be decrypt:  999
Decrypted ???

Enter a message you want to be decrypt:  100
Decrypted ???

What is the correct way to free memory in C#

The .NET garbage collector takes care of all this for you.

It is able to determine when objects are no longer referenced and will (eventually) free the memory that had been allocated to them.

How do I add a .click() event to an image?

First of all, this line

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />.click()

You're mixing HTML and JavaScript. It doesn't work like that. Get rid of the .click() there.

If you read the JavaScript you've got there, document.getElementById('foo') it's looking for an HTML element with an ID of foo. You don't have one. Give your image that ID:

<img id="foo" src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" />

Alternatively, you could throw the JS in a function and put an onclick in your HTML:

<img src="http://soulsnatcher.bplaced.net/LDRYh.jpg" alt="unfinished bingo card" onclick="myfunction()" />

I suggest you do some reading up on JavaScript and HTML though.


The others are right about needing to move the <img> above the JS click binding too.

Using (Ana)conda within PyCharm

this might be repetitive. I was trying to use pycharm to run flask - had anaconda 3, pycharm 2019.1.1 and windows 10. Created a new conda environment - it threw errors. Followed these steps -

  1. Used the cmd to install python and flask after creating environment as suggested above.

  2. Followed this answer.

  3. As suggested above, went to Run -> Edit Configurations and changed the environment there as well as in (2).

Obviously kept the correct python interpreter (the one in the environment) everywhere.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Things you can add to declarations: [] in modules

  • Pipe
  • Directive
  • Component

Pro Tip: The error message explains it - Please add a @Pipe/@Directive/@Component annotation.

onChange and onSelect in DropDownList

I'd do it like this jsFiddle example.

JavaScript:

function check(elem) {
    document.getElementById('mySelect1').disabled = !elem.selectedIndex;
}

HTML:

<form>
<select id="mySelect" onChange="check(this);">
<option>No</option>
<option>Yes</option>
</select>

<select id="mySelect1" disabled="disabled" >
<option>Dep1</option>
<option>Dep2</option>
<option>Dep3</option>
<option>Dep4</option>
</select>
</form>

How to compile a 64-bit application using Visual C++ 2010 Express?

64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.

How to: Configure Visual C++ Projects to Target 64-Bit Platforms

Ref: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

From what I've learned with Alex Cowan in the course Continuous Delivery & DevOps, CI and CD is part of a product pipeline that consists in the time it goes from an Observations to a Released Product.

Alex Cowan's Product Pipeline, 2018

From Observations to Designs the goal is to get high quality testable ideas. This part of the process is considered Continuous Design.

What happens after, when we go from the Code onwards, it's considered a Continuous Delivery capability whose aim is to execute the ideas and release to the customer very fast (you can read Jez Humble's book Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation for more details). The following pipeline explains which steps Continuous Integration (CI) and Continuous Delivery (CD) consist of.

Alex Cowan's CI/CD

Continuous Integration, as Mattias Petter Johansson explains,

is when a software team has habit of doing multiple merges per day and they have an automated verification system in place to check those merges for problems.

(you can watch the following two videos for a more pratical overview using CircleCI - Getting started with CircleCI - Continuous Integration P2 and Running CircleCI on Pull Request).

One can specify the CI/CD pipeline as following, that goes from New Code to a released Product.

Alex Cowan's Continuous Delivery Pipeline, 2018

The first three steps have to do with Tests, extending the boundary of what's being tested.

Continuous Deployment, on the other hand, is to handle the Deployment automatically. So, any code commit that passes the automated testing phase is automatically released into the production.

Note: This isn't necessarily what your pipelines should look like, yet they can serve as reference.

Bootstrap footer at the bottom of the page

You can just add style="min-height:100vh" to your page content conteiner and place footer in another conteiner

php: loop through json array

Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

When should I use the Visitor Design Pattern?

The Visitor design pattern works really well for "recursive" structures like directory trees, XML structures, or document outlines.

A Visitor object visits each node in the recursive structure: each directory, each XML tag, whatever. The Visitor object doesn't loop through the structure. Instead Visitor methods are applied to each node of the structure.

Here's a typical recursive node structure. Could be a directory or an XML tag. [If your a Java person, imagine of a lot of extra methods to build and maintain the children list.]

class TreeNode( object ):
    def __init__( self, name, *children ):
        self.name= name
        self.children= children
    def visit( self, someVisitor ):
        someVisitor.arrivedAt( self )
        someVisitor.down()
        for c in self.children:
            c.visit( someVisitor )
        someVisitor.up()

The visit method applies a Visitor object to each node in the structure. In this case, it's a top-down visitor. You can change the structure of the visit method to do bottom-up or some other ordering.

Here's a superclass for visitors. It's used by the visit method. It "arrives at" each node in the structure. Since the visit method calls up and down, the visitor can keep track of the depth.

class Visitor( object ):
    def __init__( self ):
        self.depth= 0
    def down( self ):
        self.depth += 1
    def up( self ):
        self.depth -= 1
    def arrivedAt( self, aTreeNode ):
        print self.depth, aTreeNode.name

A subclass could do things like count nodes at each level and accumulate a list of nodes, generating a nice path hierarchical section numbers.

Here's an application. It builds a tree structure, someTree. It creates a Visitor, dumpNodes.

Then it applies the dumpNodes to the tree. The dumpNode object will "visit" each node in the tree.

someTree= TreeNode( "Top", TreeNode("c1"), TreeNode("c2"), TreeNode("c3") )
dumpNodes= Visitor()
someTree.visit( dumpNodes )

The TreeNode visit algorithm will assure that every TreeNode is used as an argument to the Visitor's arrivedAt method.

Defining a percentage width for a LinearLayout?

*You can use layout_weight properties. If you want to take 70% of parent width you must set child layout_width property value 0dp, like android:layout_width="0dp"*

right align an image using CSS HTML

My workaround for this issue was to set display: inline to the image element. With this, your image and text will be aligned to the right if you set text-align: right from a parent container.

How to concat a string to xsl:value-of select="...?

Use:

<a href="wantedText{/*/properties/property[@name='report']/@value)}"></a>

Replace non-ASCII characters with a single space

As a native and efficient approach, you don't need to use ord or any loop over the characters. Just encode with ascii and ignore the errors.

The following will just remove the non-ascii characters:

new_string = old_string.encode('ascii',errors='ignore')

Now if you want to replace the deleted characters just do the following:

final_string = new_string + b' ' * (len(old_string) - len(new_string))

Merging cells in Excel using Apache POI

You can use :

sheet.addMergedRegion(new CellRangeAddress(startRowIndx, endRowIndx, startColIndx,endColIndx));

Make sure the CellRangeAddress does not coincide with other merged regions as that will throw an exception.

  • If you want to merge cells one above another, keep column indexes same
  • If you want to merge cells which are in a single row, keep the row indexes same
  • Indexes are zero based

For what you were trying to do this should work:

sheet.addMergedRegion(new CellRangeAddress(rowNo, rowNo, 0, 3));

Evaluating a mathematical expression in a string

The reason eval and exec are so dangerous is that the default compile function will generate bytecode for any valid python expression, and the default eval or exec will execute any valid python bytecode. All the answers to date have focused on restricting the bytecode that can be generated (by sanitizing input) or building your own domain-specific-language using the AST.

Instead, you can easily create a simple eval function that is incapable of doing anything nefarious and can easily have runtime checks on memory or time used. Of course, if it is simple math, than there is a shortcut.

c = compile(stringExp, 'userinput', 'eval')
if c.co_code[0]==b'd' and c.co_code[3]==b'S':
    return c.co_consts[ord(c.co_code[1])+ord(c.co_code[2])*256]

The way this works is simple, any constant mathematic expression is safely evaluated during compilation and stored as a constant. The code object returned by compile consists of d, which is the bytecode for LOAD_CONST, followed by the number of the constant to load (usually the last one in the list), followed by S, which is the bytecode for RETURN_VALUE. If this shortcut doesn't work, it means that the user input isn't a constant expression (contains a variable or function call or similar).

This also opens the door to some more sophisticated input formats. For example:

stringExp = "1 + cos(2)"

This requires actually evaluating the bytecode, which is still quite simple. Python bytecode is a stack oriented language, so everything is a simple matter of TOS=stack.pop(); op(TOS); stack.put(TOS) or similar. The key is to only implement the opcodes that are safe (loading/storing values, math operations, returning values) and not unsafe ones (attribute lookup). If you want the user to be able to call functions (the whole reason not to use the shortcut above), simple make your implementation of CALL_FUNCTION only allow functions in a 'safe' list.

from dis import opmap
from Queue import LifoQueue
from math import sin,cos
import operator

globs = {'sin':sin, 'cos':cos}
safe = globs.values()

stack = LifoQueue()

class BINARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get(),stack.get()))

class UNARY(object):
    def __init__(self, operator):
        self.op=operator
    def __call__(self, context):
        stack.put(self.op(stack.get()))


def CALL_FUNCTION(context, arg):
    argc = arg[0]+arg[1]*256
    args = [stack.get() for i in range(argc)]
    func = stack.get()
    if func not in safe:
        raise TypeError("Function %r now allowed"%func)
    stack.put(func(*args))

def LOAD_CONST(context, arg):
    cons = arg[0]+arg[1]*256
    stack.put(context['code'].co_consts[cons])

def LOAD_NAME(context, arg):
    name_num = arg[0]+arg[1]*256
    name = context['code'].co_names[name_num]
    if name in context['locals']:
        stack.put(context['locals'][name])
    else:
        stack.put(context['globals'][name])

def RETURN_VALUE(context):
    return stack.get()

opfuncs = {
    opmap['BINARY_ADD']: BINARY(operator.add),
    opmap['UNARY_INVERT']: UNARY(operator.invert),
    opmap['CALL_FUNCTION']: CALL_FUNCTION,
    opmap['LOAD_CONST']: LOAD_CONST,
    opmap['LOAD_NAME']: LOAD_NAME
    opmap['RETURN_VALUE']: RETURN_VALUE,
}

def VMeval(c):
    context = dict(locals={}, globals=globs, code=c)
    bci = iter(c.co_code)
    for bytecode in bci:
        func = opfuncs[ord(bytecode)]
        if func.func_code.co_argcount==1:
            ret = func(context)
        else:
            args = ord(bci.next()), ord(bci.next())
            ret = func(context, args)
        if ret:
            return ret

def evaluate(expr):
    return VMeval(compile(expr, 'userinput', 'eval'))

Obviously, the real version of this would be a bit longer (there are 119 opcodes, 24 of which are math related). Adding STORE_FAST and a couple others would allow for input like 'x=5;return x+x or similar, trivially easily. It can even be used to execute user-created functions, so long as the user created functions are themselves executed via VMeval (don't make them callable!!! or they could get used as a callback somewhere). Handling loops requires support for the goto bytecodes, which means changing from a for iterator to while and maintaining a pointer to the current instruction, but isn't too hard. For resistance to DOS, the main loop should check how much time has passed since the start of the calculation, and certain operators should deny input over some reasonable limit (BINARY_POWER being the most obvious).

While this approach is somewhat longer than a simple grammar parser for simple expressions (see above about just grabbing the compiled constant), it extends easily to more complicated input, and doesn't require dealing with grammar (compile take anything arbitrarily complicated and reduces it to a sequence of simple instructions).

How to convert an integer to a character array using C

You may give a shot at using itoa. Another alternative is to use sprintf.

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

Assign format of DateTime with data annotations?

Try tagging it with:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

How to call Android contacts list?

To my surprise you do not need users-permission CONTACT_READ to read the names and some basic information (Is the contact starred, what was the last calling time). However you do need permission to read the details of the contact like phone number.

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

For the Windows OS, I used Fiddler to work around the issue.

  1. Install/Run Fiddler from www.fiddler2.com
  2. Run gem:

    $ gem install --http-proxy http://localhost:8888 $gem_name
    

DateTime.ToString() format that can be used in a filename or extension?

I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with

DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35

When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.

How to parse XML using jQuery?

$xml = $( $.parseXML( xml ) );

$xml.find("<<your_xml_tag_name>>").each(function(index,elem){
    // elem = found XML element
});

java.lang.NoClassDefFoundError: org.slf4j.LoggerFactory

This error occurs because of referenced jars are not checked in our project's order and export tab.

Choose Project ->ALT+Enter->Java Build Path ->Order and Export->check necessary jar files into your project.

Finally clean your project and run.It will run successfully.

Get the second largest number in a list in linear time

Since @OscarLopez and I have different opinions on what the second largest means, I'll post the code according to my interpretation and in line with the first algorithm provided by the questioner.

def second_largest(numbers):
    count = 0
    m1 = m2 = float('-inf')
    for x in numbers:
        count += 1
        if x > m2:
            if x >= m1:
                m1, m2 = x, m1            
            else:
                m2 = x
    return m2 if count >= 2 else None

(Note: Negative infinity is used here instead of None since None has different sorting behavior in Python 2 and 3 – see Python - Find second smallest number; a check for the number of elements in numbers makes sure that negative infinity won't be returned when the actual answer is undefined.)

If the maximum occurs multiple times, it may be the second largest as well. Another thing about this approach is that it works correctly if there are less than two elements; then there is no second largest.

Running the same tests:

second_largest([20,67,3,2.6,7,74,2.8,90.8,52.8,4,3,2,5,7])
=> 74
second_largest([1,1,1,1,1,2])
=> 1
second_largest([2,2,2,2,2,1])
=> 2
second_largest([10,7,10])
=> 10
second_largest([1,1,1,1,1,1])
=> 1
second_largest([1])
=> None
second_largest([])
=> None

Update

I restructured the conditionals to drastically improve performance; almost by a 100% in my testing on random numbers. The reason for this is that in the original version, the elif was always evaluated in the likely event that the next number is not the largest in the list. In other words, for practically every number in the list, two comparisons were made, whereas one comparison mostly suffices – if the number is not larger than the second largest, it's not larger than the largest either.

How to view user privileges using windows cmd?

Go to command prompt and enter the command,

net user <username>

Will show your local group memberships.

If you're on a domain, use localgroup instead:

net localgroup Administrators or net localgroup [Admin group name]

Check the list of local groups with localgroup on its own.

net localgroup

How to search if dictionary value contains certain string with Python

Following is one liner for accepted answer ... (for one line lovers ..)

def search_dict(my_dict,searchFor):
    s_val = [[ k if searchFor in v else None for v in my_dict[k]] for k in my_dict]    
    return s_val

git pull error :error: remote ref is at but expected

Permanent Fix

git update-ref -d resolved my instance of this error, e.g.

git update-ref -d refs/remotes/origin/user

Note that this doesn't impact remote.

In my case, a subsequent git fetch fetched that branch again, and following git fetches/pulls no longer gave the error "remote ref is at but expected".

If that doesn't work, a temporary fix:

Note also that if you don't care about the branch in question (e.g. you just want to update master, not origin/user), a git pull workaround is to fetch then just merge the particular branch you care about, e.g.

git fetch # may give an error for a particular branch, but other branches will still be successfully fetched
git merge origin/master

Update multiple rows with different values in a single SQL query

Yes, you can do this, but I doubt that it would improve performances, unless your query has a real large latency.

You could do:

 UPDATE table SET posX=CASE
      WHEN id=id[1] THEN posX[1]
      WHEN id=id[2] THEN posX[2]
      ...
      ELSE posX END, posY = CASE ... END
 WHERE id IN (id[1], id[2], id[3]...);

The total cost is given more or less by: NUM_QUERIES * ( COST_QUERY_SETUP + COST_QUERY_PERFORMANCE ). This way, you knock down a bit on NUM_QUERIES, but COST_QUERY_PERFORMANCE goes up bigtime. If COST_QUERY_SETUP is really huge (e.g., you're calling some network service which is real slow) then, yes, you might still end up on top.

Otherwise, I'd try with indexing on id, or modifying the architecture.

In MySQL I think you could do this more easily with a multiple INSERT ON DUPLICATE KEY UPDATE (but am not sure, never tried).

Linking static libraries to other static libraries

A static library is just an archive of .o object files. Extract them with ar (assuming Unix) and pack them back into one big library.

Loading all images using imread from a given folder

import glob
cv_img = []
for img in glob.glob("Path/to/dir/*.jpg"):
    n= cv2.imread(img)
    cv_img.append(n)`

How to get the pure text without HTML element using JavaScript?

That should work:

function get_content(){
   var p = document.getElementById("txt");
   var spans = p.getElementsByTagName("span");
   var text = '';
   for (var i = 0; i < spans.length; i++){
       text += spans[i].innerHTML;
   }

   p.innerHTML = text;
}

Try this fiddle: http://jsfiddle.net/7gnyc/2/

What are the differences between json and simplejson Python modules?

I have to disagree with the other answers: the built in json library (in Python 2.7) is not necessarily slower than simplejson. It also doesn't have this annoying unicode bug.

Here is a simple benchmark:

import json
import simplejson
from timeit import repeat

NUMBER = 100000
REPEAT = 10

def compare_json_and_simplejson(data):
    """Compare json and simplejson - dumps and loads"""
    compare_json_and_simplejson.data = data
    compare_json_and_simplejson.dump = json.dumps(data)
    assert json.dumps(data) == simplejson.dumps(data)
    result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json dumps {} seconds".format(result)
    result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson dumps {} seconds".format(result)
    assert json.loads(compare_json_and_simplejson.dump) == data
    result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "      json loads {} seconds".format(result)
    result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson", 
                 repeat = REPEAT, number = NUMBER))
    print "simplejson loads {} seconds".format(result)


print "Complex real world data:" 
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)

And the results on my system (Python 2.7.4, Linux 64-bit):

Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 seconds

Simple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds

For dumping, json is faster than simplejson. For loading, simplejson is faster.

Since I am currently building a web service, dumps() is more important—and using a standard library is always preferred.

Also, cjson was not updated in the past 4 years, so I wouldn't touch it.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

How do I rename the extension for a bunch of files?

Here is what i used to rename .edge files to .blade.php

for file in *.edge; do     mv "$file" "$(basename "$file" .edge).blade.php"; done

Works like charm.

Generate an HTML Response in a Java Servlet

Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:

public void doGet(HttpServletRequest request,
       HttpServletResponse response)
       throws IOException, ServletException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("HTML from an external file:");     
   request.getRequestDispatcher("/pathToFile/fragment.html")
          .include(request, response); 
   out.close();
}

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse,

When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.

How to convert a color integer to a hex String in Android?

Integer value of ARGB color to hexadecimal string:

String hex = Integer.toHexString(color); // example for green color FF00FF00

Hexadecimal string to integer value of ARGB color:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);

Collections.sort with multiple fields

I'd make a comparator using Guava's ComparisonChain:

public class ReportComparator implements Comparator<Report> {
  public int compare(Report r1, Report r2) {
    return ComparisonChain.start()
        .compare(r1.getReportKey(), r2.getReportKey())
        .compare(r1.getStudentNumber(), r2.getStudentNumber())
        .compare(r1.getSchool(), r2.getSchool())
        .result();
  }
}

How do I install cURL on Windows?

I solved the problem.

In my apache, I have to specify:

PHPIniDir "C://php" AddType application/x-httpd-php .php

and for php.ini, instead of using the php.ini_recommend, use php.ini_dist to configure my php.ini.

then make sure the php engine has turned on. then it works now. Thanks all.

how to make password textbox value visible when hover an icon

a rapid response not tested on several brosers, works on gg chrome / win

-> On focus event -> show/hide password

<input type="password" name="password">

script jQuery

// show on focus
$('input[type="password"]').on('focusin', function(){

    $(this).attr('type', 'text');

});
// hide on focus Out
$('input[type="password"]').on('focusout', function(){

    $(this).attr('type', 'password');

});

Initialize/reset struct to zero/null

The way to do such a thing when you have modern C (C99) is to use a compound literal.

a = (const struct x){ 0 };

This is somewhat similar to David's solution, only that you don't have to worry to declare an the empty structure or whether to declare it static. If you use the const as I did, the compiler is free to allocate the compound literal statically in read-only storage if appropriate.

Resizing UITableView to fit content

I've tried this in iOS 7 and it worked for me

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.tableView sizeToFit];
}

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

What does file:///android_asset/www/index.html mean?

It took me more than 4 hours to fix this problem. I followed the guide from http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

I'm using Android Studio (Eclipse with ADT could not work properly because of the build problem).

Solution that worked for me:

  1. I put the /assets/www/index.html under app/src/main/assets directory. (take care AndroidStudio has different perspectives like Project or Android)

  2. use super.loadUrl("file:///android_asset/www/index.html"); instead of super.loadUrl("file:///android_assets/www/index.html"); (no s)

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

tell pip to install the dependencies of packages listed in a requirement file

Any way to do this without manually re-installing the packages in a new virtualenv to get their dependencies ? This would be error-prone and I'd like to automate the process of cleaning the virtualenv from no-longer-needed old dependencies.

That's what pip-tools package is for (from https://github.com/jazzband/pip-tools):

Installation

$ pip install --upgrade pip  # pip-tools needs pip==6.1 or higher (!)
$ pip install pip-tools

Example usage for pip-compile

Suppose you have a Flask project, and want to pin it for production. Write the following line to a file:

# requirements.in
Flask

Now, run pip-compile requirements.in:

$ pip-compile requirements.in
#
# This file is autogenerated by pip-compile
# Make changes in requirements.in, then run this to update:
#
#    pip-compile requirements.in
#
flask==0.10.1
itsdangerous==0.24        # via flask
jinja2==2.7.3             # via flask
markupsafe==0.23          # via jinja2
werkzeug==0.10.4          # via flask

And it will produce your requirements.txt, with all the Flask dependencies (and all underlying dependencies) pinned. Put this file under version control as well and periodically re-run pip-compile to update the packages.

Example usage for pip-sync

Now that you have a requirements.txt, you can use pip-sync to update your virtual env to reflect exactly what's in there. Note: this will install/upgrade/uninstall everything necessary to match the requirements.txt contents.

$ pip-sync
Uninstalling flake8-2.4.1:
  Successfully uninstalled flake8-2.4.1
Collecting click==4.1
  Downloading click-4.1-py2.py3-none-any.whl (62kB)
    100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 65kB 1.8MB/s
  Found existing installation: click 4.0
    Uninstalling click-4.0:
      Successfully uninstalled click-4.0
Successfully installed click-4.1

Unfortunately Launcher3 has stopped working error in android studio?

It appears to be relate to the graphics driver. In the emulator configuration, changing Emulated Graphics to Software - GLES 2.0 caused the crashes to stop.

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
    string str;
    emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
    ~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first) 
{
    if (!skip_first)
        static emitter a("in if");
    static emitter b("in foo");
}

int main(int argc, char*[])
{
    foo(argc != 2);
    if (argc == 3)
        foo(false);
}

Output:

C:>sample.exe
Created in foo
Destroyed in foo

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Simple pthread! C++

Linkage. Try this:

extern "C" void *print_message() {...

append new row to old csv file python

with open('document.csv','a') as fd:
    fd.write(myCsvRow)

Opening a file with the 'a' parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.

Get lengths of a list in a jinja2 template

Alex' comment looks good but I was still confused with using range. The following worked for me while working on a for condition using length within range.

{% for i in range(0,(nums['list_users_response']['list_users_result']['users'])| length) %}
<li>    {{ nums['list_users_response']['list_users_result']['users'][i]['user_name'] }} </li>
{% endfor %}

How to hide first section header in UITableView (grouped style)

Try this if you want to remove all section header completely

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return CGFloat.leastNormalMagnitude
}

How to redirect output to a file and stdout

Bonus answer since this use-case brought me here:

In the case where you need to do this as some other user

echo "some output" | sudo -u some_user tee /some/path/some_file

Note that the echo will happen as you and the file write will happen as "some_user" what will NOT work is if you were to run the echo as "some_user" and redirect the output with >> "some_file" because the file redirect will happen as you.

Hint: tee also supports append with the -a flag, if you need to replace a line in a file as another user you could execute sed as the desired user.

How to convert comma-separated String to List?

You can do it as follows.

This removes white space and split by comma where you do not need to worry about white spaces.

    String myString= "A, B, C, D";

    //Remove whitespace and split by comma 
    List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));

    System.out.println(finalString);

Uint8Array to string in Javascript

Found in one of the Chrome sample applications, although this is meant for larger blocks of data where you're okay with an asynchronous conversion.

/**
 * Converts an array buffer to a string
 *
 * @private
 * @param {ArrayBuffer} buf The buffer to convert
 * @param {Function} callback The function to call when conversion is complete
 */
function _arrayBufferToString(buf, callback) {
  var bb = new Blob([new Uint8Array(buf)]);
  var f = new FileReader();
  f.onload = function(e) {
    callback(e.target.result);
  };
  f.readAsText(bb);
}

List supported SSL/TLS versions for a specific OpenSSL build

When you run OPENSSL command using s_client this is the output. See the Cipher, if the cipher NULL it means that version of TLS is not supported.

TLSv1/SSLv3, Cipher is ECDHE-RSA-AES256
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : ECDHE-RSA-AES256
    Session-ID: A84600002D4945DE6
    Session-ID-ctx:
    Master-Key:  
    Start Time: 15852343333860
    Timeout   : 2343 (sec)
    Verify return code: 0 (ok)

Why is $$ returning the same id as the parent process?

this one univesal way to get correct pid

pid=$(cut -d' ' -f4 < /proc/self/stat)

same nice worked for sub

SUB(){
    pid=$(cut -d' ' -f4 < /proc/self/stat)
    echo "$$ != $pid"
}

echo "pid = $$"

(SUB)

check output

pid = 8099
8099 != 8100

How to use goto statement correctly

There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.

However this code could be modified a little and using the concept of continue and break we could make the code work.

    import java.util.*;

public class Factorial 
{
    public static void main(String[] args) 
    {
        int x = 1;
        int factValue = 1;
        Scanner userInput = new Scanner(System.in);
        restart: while(true){
        System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
        int factInput = userInput.nextInt();

        while(factInput<=0)
        {
            System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
            factInput = userInput.nextInt();
        }

        if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
        {
            System.out.println("The number you entered is not valid. Please try again.");
            continue restart;
        }
        while(x<=factInput)
        {
            factValue*=x;
            x++;
        }
        System.out.println(factInput+"! = "+factValue);
        userInput.close();
        break restart;
}
    }
}

Facebook development in localhost

I just discovered a workaround: You can make your local machine accessible by using http://localtunnel.com . You'll need to (temporarily) change some URLs used in your app code / html so links point to the temporary domain, but at least facebook can reach your machine.

How to set image to fit width of the page using jsPDF?

If you need to get width 100% of PDF file and auto height you can use 'getImageProperties' property of html2canvas library

html2canvas(input)
      .then((canvas) => {
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF({
          orientation: 'landscape',
        });
        const imgProps= pdf.getImageProperties(imgData);
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('download.pdf');
      });

An efficient way to transpose a file in Bash

There is a purpose built utility for this,

GNU datamash utility

apt install datamash  

datamash transpose < yourfile

Taken from this site, https://www.gnu.org/software/datamash/ and http://www.thelinuxrain.com/articles/transposing-rows-and-columns-3-methods

Good tool for testing socket connections?

netcat (nc.exe) is the right tool. I have a feeling that any tool that does what you want it to do will have exactly the same problem with your antivirus software. Just flag this program as "OK" in your antivirus software (how you do this will depend on what type of antivirus software you use).

Of course you will also need to configure your sysadmin to accept that you're not trying to do anything illegal...

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

Eclipse/Maven error: "No compiler is provided in this environment"

Go into Window > Preferences > Java > Installed JREs > and check your installed JREs. You should have an entry with a JDK there.

https://cduu.wordpress.com/2013/03/08/maven-eclipse-compiler-error-no-compiler-is-provided-in-this-environment/

"column not allowed here" error in INSERT statement

Some time, While executing insert query, we are facing:

Column not allowed here

error. Because of quote might missing in the string parameters. Add quote in the string params and try to execute.

Try this:

INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

or

INSERT INTO LOCATION (ID, FIRST_NAME, LAST_NAME) VALUES('PQ95VM','HAPPY_STREET','FRANCE');

http://www.drtuts.com/oracle-error-column-not-allowed-here/

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

One quick solution I prefer which I suited most for this situation is simply delete .metadata folder of your work space and import your projects again. If you try all other option it wont guarantee the success. Sometimes the above solutions work sometime you will spend your precious hours to fix this configuration.

One day i decided to clean my work station.I arranged the projects to their suitable folders according to different clients. As a result all got messed up. After spending a whole day it did not end up in a fixed work space. Next day I simply deleted the .metadata folder of the work space and imported all the projects again. Bingo all set.

How to start and stop android service from a adb shell?

am startservice <INTENT>   

or actually from the OS shell

adb shell am startservice <INTENT>

Word count from a txt file program

#!/usr/bin/python
file=open("D:\\zzzz\\names2.txt","r+")
wordcount={}
for word in file.read().split():
    if word not in wordcount:
        wordcount[word] = 1
    else:
        wordcount[word] += 1
for k,v in wordcount.items():
    print k, v

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

Converting byte array to string in javascript

I had some decrypted byte arrays with padding characters and other stuff I didn't need, so I did this (probably not perfect, but it works for my limited use)

var junk = String.fromCharCode.apply(null, res).split('').map(char => char.charCodeAt(0) <= 127 && char.charCodeAt(0) >= 32 ? char : '').join('');

How to check if the user can go back in browser history or not

I was trying to find a solution and this is the best i could get (but works great and it's the easiest solution i've found even here).

In my case, i wanted to go back on history with an back button, but if the first page the user opened was an subpage of my app, it would go back to the main page.

The solution was, as soon the app is loaded, i just did an replace on the history state:

history.replaceState( {root: true}, '', window.location.pathname + window.location.hash)

This way, i just need to check history.state.root before go back. If true, i make an history replace instead:

if(history.state && history.state.root)
    history.replaceState( {root: true}, '', '/')
else
    history.back() 

How to view file diff in git before commit

I think this is the perfect use case warranting a GUI. - Although I totally understand that it can also be achieved well enough within the command line.

Personally, every commit of mine, I do from the git-gui. In which I can make multiple atomic commits with separate hunks/lines if it makes sense to do so.

Gut Gui enables viewing of the diffs in a well formatted colored interface, is rather light. Looks like this is something you should checkout too.

How to filter for multiple criteria in Excel?

You can pass an array as the first AutoFilter argument and use the xlFilterValues operator.

This will display PDF, DOC and DOCX filetypes.

Criteria1:=Array(".pdf", ".doc", ".docx"), Operator:=xlFilterValues

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

explode string in jquery

Try This

var data = 'allow~5'; 
var result=data.split('~');

RESULT

alert(result[0]);

if statement in ng-click

Here's a hack I discovered that might work for you, although its not pretty and I'd personally be embarrassed to use such a line of code:

ng-click="profileForm.$valid ? updateMyProfile() : alert('failed')"

Now, you must be thinking 'but I don't want it to alert("failed") if my profileForm isn't valid. Well that's the ugly part. For me, no matter what I put in the else clause of this ternary statement doesn't get executed ever.

Yet if its removed an error is thrown. So you can just stuff it with a pointless alert.
I told you it was ugly... but I don't even get any errors when I do something like this.
The proper way to do this is as Chen-Tsu mentioned, but to each their own.

Ternary operator in AngularJS templates

This answer predates version 1.1.5 where a proper ternary in the $parse function wasn't available. Use this answer if you're on a lower version, or as an example of filters:

angular.module('myApp.filters', [])
  
  .filter('conditional', function() {
    return function(condition, ifTrue, ifFalse) {
      return condition ? ifTrue : ifFalse;
    };
  });

And then use it as

<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>

Selecting data frame rows based on partial string match in a column

Another option would be to simply use grepl function:

df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]

df <- data.frame(name = c('bob','robert','peter'),
                 id = c(1,2,3)
                 )

# name id
# 2 robert  2
# 3  peter  3

how to make a div to wrap two float divs inside?

<html>
<head>
    <style>
        #main { border: 1px #000 solid; width: 600px; height: 400px; margin: auto;}
        #one { width: 20%; height: 100%; background-color: blue; display: inline-block; }
        #two { width: 80%; height: 100%; background-color: red; display: inline-block; }
    </style>
</head>
<body>
<div id="main">
    <span id="one">one</span><span id="two">two</span>
</div>
</body>
</html>

The secret is the inline-block. If you use borders or margins, you may need to reduce the width of the div that use them.

NOTE: This doesn't work properly in IE6/7 if you use "DIV" instead of "SPAN". (see http://www.quirksmode.org/css/display.html)

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

Can you style html form buttons with css?

You might want to add:

-webkit-appearance: none; 

if you need it looking consistent on Mobile Safari...

make UITableViewCell selectable only while editing

Have you tried setting the selection properties of your tableView like this:

tableView.allowsMultipleSelection = NO; tableView.allowsMultipleSelectionDuringEditing = YES; tableView.allowsSelection = NO; tableView.allowsSelectionDuringEditing YES; 

If you want more fine-grain control over when selection is allowed you can override - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath in your UITableView delegate. The documentation states:

Return Value An index-path object that confirms or alters the selected row. Return an NSIndexPath object other than indexPath if you want another cell to be selected. Return nil if you don't want the row selected. 

You can have this method return nil in cases where you don't want the selection to happen.

python: how to identify if a variable is an array or a scalar

You can check data type of variable.

N = [2,3,5]
P = 5
type(P)

It will give you out put as data type of P.

<type 'int'>

So that you can differentiate that it is an integer or an array.

How can I view the Git history in Visual Studio Code?

I strongly recommend using a combination of GitLens & GitGraph.

Below snapshot highlights how gitlens is showing commit over time

enter image description here

And the below picture is for the the amazing vivid GitGraph

enter image description here

JDK was not found on the computer for NetBeans 6.5

What I have found, the correct way of doing it is: "C:\Program Files (x86)\netbeans-8.0.2-windows.exe" --javahome "C:\Program Files(x86)\Java\jdk1.7.0_51"

  1. at first, the setup of NetBeans must be saved on your hard disk
  2. go to the place where your setup is, click properties and copy the path.
  3. Add two back slashes in it and put it in double quotes like so: "C:\Program Files (x86)\netbeans-8.0.2-windows.exe"
  4. then go to the folder where your jdk is, click properties, copy the path, put double back slashes where necessary and then put it in double quotes: "C:\Program Files(x86)\Java\jdk1.7.0_51"
  5. then just follow the format of the first link given and you'll install it

Note: run this link in the command prompt

How to format a URL to get a file from Amazon S3?

As @stevebot said, do this:

https://<bucket-name>.s3.amazonaws.com/<key>

The one important thing I would like to add is that you either have to make your bucket objects all publicly accessible OR you can add a custom policy to your bucket policy. That custom policy could allow traffic from your network IP range or a different credential.

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

Can I specify multiple users for myself in .gitconfig?

Windows Environment

Additional this can be modified from Git Extensions --> Settings --> Global Settings, if you have it installed in your systems.

gitextensions-latest-release

Right Click on a folder/directory in Windows Environment to access these settings. enter image description here

Update : How to switch/maintain multiple settings in Version 2.49 How to switch/maintain multiple settings in Version 2.49

SQL Error: ORA-00913: too many values

You should specify column names as below. It's good practice and probably solve your problem

insert into abc.employees (col1,col2) 
select col1,col2 from employees where employee_id=100; 

EDIT:

As you said employees has 112 columns (sic!) try to run below select to compare both tables' columns

select * 
from ALL_TAB_COLUMNS ATC1
left join ALL_TAB_COLUMNS ATC2 on ATC1.COLUMN_NAME = ATC1.COLUMN_NAME 
                               and  ATC1.owner = UPPER('2nd owner')
where ATC1.owner = UPPER('abc')
and ATC2.COLUMN_NAME is null
AND ATC1.TABLE_NAME = 'employees'

and than you should upgrade your tables to have the same structure.

How do I start PowerShell from Windows Explorer?

In Windows Explorer, just go to the Address Bar at the top (keyboard shortcuts: Alt+D or Ctrl+L) and type powershell or powershell_ise and press Enter. A PowerShell command window opens with the current directory.

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

What is the difference between "::" "." and "->" in c++

In C++ you can access fields or methods, using different operators, depending on it's type:

  • ClassName::FieldName : class public static field and methods
  • ClassInstance.FieldName : accessing a public field (or method) through class reference
  • ClassPointer->FieldName : accessing a public field (or method) dereferencing a class pointer

Note that :: should be used with a class name rather than a class instance, since static fields or methods are common to all instances of a class.

class AClass{
public:
static int static_field;
int instance_field;

static void static_method();
void method();
};

then you access this way:

AClass instance;
AClass *pointer = new AClass();

instance.instance_field; //access instance_field through a reference to AClass
instance.method();

pointer->instance_field; //access instance_field through a pointer to AClass
pointer->method();

AClass::static_field;  
AClass::static_method();

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

You could use a div with a background image instead and this CSS3 property:

background-size: contain

You can check out an example on:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Scaling_background_images#contain

To quote Mozilla:

The contain value specifies that regardless of the size of the containing box, the background image should be scaled so that each side is as large as possible while not exceeding the length of the corresponding side of the container.

However, keep in mind that your image will be upscaled if the div is larger than your original image.

Call async/await functions in parallel

Update:

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

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

Original answer:

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

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

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

Items in JSON object are out of order using "json.dumps"?

json.dump() will preserve the ordder of your dictionary. Open the file in a text editor and you will see. It will preserve the order regardless of whether you send it an OrderedDict.

But json.load() will lose the order of the saved object unless you tell it to load into an OrderedDict(), which is done with the object_pairs_hook parameter as J.F.Sebastian instructed above.

It would otherwise lose the order because under usual operation, it loads the saved dictionary object into a regular dict and a regular dict does not preserve the oder of the items it is given.

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.

How to split/partition a dataset into training and test datasets for, e.g., cross validation?

I wrote a function for my own project to do this (it doesn't use numpy, though):

def partition(seq, chunks):
    """Splits the sequence into equal sized chunks and them as a list"""
    result = []
    for i in range(chunks):
        chunk = []
        for element in seq[i:len(seq):chunks]:
            chunk.append(element)
        result.append(chunk)
    return result

If you want the chunks to be randomized, just shuffle the list before passing it in.

How to return a resolved promise from an AngularJS Service using $q?

Here's the correct code for your service:

myApp.service('userService', [
  '$http', '$q', '$rootScope', '$location', function($http, $q, $rootScope, $location) {

    var user = {
      access: false
    };

    var me = this;

    this.initialized = false;
    this.isAuthenticated = function() {

      var deferred = $q.defer();
      user = {
        first_name: 'First',
        last_name: 'Last',
        email: '[email protected]',
        access: 'institution'
      };
      deferred.resolve(user);
      me.initialized = true;

      return deferred.promise;
    };
  }
]);

Then you controller should align accordingly:

myApp.run([
  '$rootScope', 'userService', function($rootScope, userService) {
    return userService.isAuthenticated().then(function(user) {
      if (user) {
        // You have access to the object you passed in the service, not to the response.
        // You should either put response.data on the user or use a different property.
        return $rootScope.$broadcast('login', user.email);  
      } else {
        return userService.logout();
      }
    });
  }
]);

Few points to note about the service:

  • Expose in a service only what needs to be exposed. User should be kept internally and be accessed by getters only.

  • When in functions, use 'me' which is the service to avoid edge cases of this with javascript.

  • I guessed what initialized was meant to do, feel free to correct me if I guessed wrong.

Getting "Cannot call a class as a function" in my React Project

In my case, I accidentally put component name (Home) as the first argument to connect function while it was supposed to be at the end. duh.

This one -surely- gave me the error:

export default connect(Home)(mapStateToProps, mapDispatchToProps)

But this one worked -surely- fine:

export default connect(mapStateToProps, mapDispatchToProps)(Home)

I cannot access tomcat admin console?

Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.

How to construct a relative path in Java from two absolute paths (or URLs)?

Lots of answers already here, but I found they didn't handle all cases, such as the base and target being the same. This function takes a base directory and a target path and returns the relative path. If no relative path exists, the target path is returned. File.separator is unnecessary.

public static String getRelativePath (String baseDir, String targetPath) {
    String[] base = baseDir.replace('\\', '/').split("\\/");
    targetPath = targetPath.replace('\\', '/');
    String[] target = targetPath.split("\\/");

    // Count common elements and their length.
    int commonCount = 0, commonLength = 0, maxCount = Math.min(target.length, base.length);
    while (commonCount < maxCount) {
        String targetElement = target[commonCount];
        if (!targetElement.equals(base[commonCount])) break;
        commonCount++;
        commonLength += targetElement.length() + 1; // Directory name length plus slash.
    }
    if (commonCount == 0) return targetPath; // No common path element.

    int targetLength = targetPath.length();
    int dirsUp = base.length - commonCount;
    StringBuffer relative = new StringBuffer(dirsUp * 3 + targetLength - commonLength + 1);
    for (int i = 0; i < dirsUp; i++)
        relative.append("../");
    if (commonLength < targetLength) relative.append(targetPath.substring(commonLength));
    return relative.toString();
}

SQL query to get most recent row for each instance of a given key

Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):

SELECT username, ip, time_stamp FROM (
 SELECT username, ip, time_stamp, 
  ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
 FROM Users
) tmp WHERE rn = 1;

Resizing an iframe based on content

Something on the lines of this i belive should work.

parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;

Load this with your body onload on the iframe content.

Add line break to 'git commit -m' from the command line

Personally, I find it easiest to modify commit messages after the fact in vi (or whatever your git editor of choice is) rather than on the command line, by doing git commit --amend right after git commit.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How to detect if a string contains special characters?

SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)

how to fix groovy.lang.MissingMethodException: No signature of method:

This may also be because you might have given classname with all letters in lowercase something which groovy (know of version 2.5.0) does not support.

class name - User is accepted but user is not.

postgresql - add boolean column to table set default

If you want an actual boolean column:

ALTER TABLE users ADD "priv_user" boolean DEFAULT false;

How can I extract audio from video with ffmpeg?

To encode mp3 audio ffmpeg.org shows the following example:

ffmpeg -i input.wav -codec:a libmp3lame -qscale:a 2 output.mp3

I extracted the audio from a video just by replacing input.wav with the video filename. The 2 means 190 kb/sec. You can see the other quality levels at my link above.

Using sed to mass rename files

The backslash-paren stuff means, "while matching the pattern, hold on to the stuff that matches in here." Later, on the replacement text side, you can get those remembered fragments back with "\1" (first parenthesized block), "\2" (second block), and so on.