Programs & Examples On #Qfilesystemmodel

A QFileSystemModel is a class from the Qt toolkit which provides a data model for the local filesystem.

Get current user id in ASP.NET Identity 2.0

I had the same issue. I am currently using Asp.net Core 2.2. I solved this problem with the following piece of code.

using Microsoft.AspNetCore.Identity;
var user = await _userManager.FindByEmailAsync(User.Identity.Name);

I hope this will be useful to someone.

How to properly seed random number generator

I don't understand why people are seeding with a time value. This has in my experience never been a good idea. For example, while the system clock is maybe represented in nanoseconds, the system's clock precision isn't nanoseconds.

This program should not be run on the Go playground but if you run it on your machine you get a rough estimate on what type of precision you can expect. I see increments of about 1000000 ns, so 1 ms increments. That's 20 bits of entropy that are not used. All the while the high bits are mostly constant!? Roughly ~24 bits of entropy over a day which is very brute forceable (which can create vulnerabilities).

The degree that this matters to you will vary but you can avoid pitfalls of clock based seed values by simply using the crypto/rand.Read as source for your seed. It will give you that non-deterministic quality that you are probably looking for in your random numbers (even if the actual implementation itself is limited to a set of distinct and deterministic random sequences).

import (
    crypto_rand "crypto/rand"
    "encoding/binary"
    math_rand "math/rand"
)

func init() {
    var b [8]byte
    _, err := crypto_rand.Read(b[:])
    if err != nil {
        panic("cannot seed math/rand package with cryptographically secure random number generator")
    }
    math_rand.Seed(int64(binary.LittleEndian.Uint64(b[:])))
}

As a side note but in relation to your question. You can create your own rand.Source using this method to avoid the cost of having locks protecting the source. The rand package utility functions are convenient but they also use locks under the hood to prevent the source from being used concurrently. If you don't need that you can avoid it by creating your own Source and use that in a non-concurrent way. Regardless, you should NOT be reseeding your random number generator between iterations, it was never designed to be used that way.

Make element fixed on scroll

You can do that with some easy jQuery:

http://jsfiddle.net/jpXjH/6/

var elementPosition = $('#navigation').offset();

$(window).scroll(function(){
        if($(window).scrollTop() > elementPosition.top){
              $('#navigation').css('position','fixed').css('top','0');
        } else {
            $('#navigation').css('position','static');
        }    
});

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

Print the address or pointer for value in C

What you have is correct. Of course, you'll see that emp1 and item1 have the same pointer value.

Complex numbers usage in python

In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:

>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)

The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)

The type of a complex number is complex, and you can use the type as a constructor if you prefer:

>>> complex(2,3)
(2+3j)

A complex number has some built-in accessors:

>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)

Several built-in functions support complex numbers:

>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)

The standard module cmath has more functions that handle complex numbers:

>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)

How does the FetchMode work in Spring Data JPA

I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph and @EntityGraph annotations when working with Spring Data

@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

Check the documentation here

Grant execute permission for a user on all stored procedures in database?

Create a role add this role to users, and then you can grant execute to all the routines in one shot to this role.

CREATE ROLE <abc>
GRANT EXECUTE TO <abc>

EDIT
This works in SQL Server 2005, I'm not sure about backward compatibility of this feature, I'm sure anything later than 2005 should be fine.

ImportError: numpy.core.multiarray failed to import

If you want a specific version:

pip install numpy==1.8

get path for my .exe

In a Windows Forms project:

For the full path (filename included): string exePath = Application.ExecutablePath;
For the path only: string appPath = Application.StartupPath;

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

Using boolean values in C

C has a boolean type: bool (at least for the last 10(!) years)

Include stdbool.h and true/false will work as expected.

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

google map API zoom range

Available Zoom Levels

Zoom level 0 is the most zoomed out zoom level available and each integer step in zoom level halves the X and Y extents of the view and doubles the linear resolution.

Google Maps was built on a 256x256 pixel tile system where zoom level 0 was a 256x256 pixel image of the whole earth. A 256x256 tile for zoom level 1 enlarges a 128x128 pixel region from zoom level 0.

As correctly stated by bkaid, the available zoom range depends on where you are looking and the kind of map you are using:

  • Road maps - seem to go up to zoom level 22 everywhere
  • Hybrid and satellite maps - the max available zoom levels depend on location. Here are some examples:
  • Remote regions of Antarctica: 13
  • Gobi Desert: 17
  • Much of the U.S. and Europe: 21
  • "Deep zoom" locations: 22-23 (see bkaid's link)

Note that these values are for the Google Static Maps API which seems to give one more zoom level than the Javascript API. It appears that the extra zoom level available for Static Maps is just an upsampled version of the max-resolution image from the Javascript API.

Map Scale at Various Zoom Levels

Google Maps uses a Mercator projection so the scale varies substantially with latitude. A formula for calculating the correct scale based on latitude is:

meters_per_pixel = 156543.03392 * Math.cos(latLng.lat() * Math.PI / 180) / Math.pow(2, zoom)

Formula is from Chris Broadfoot's comment.


Google Maps basics

Zoom Level - zoom

0 - 19

0 lowest zoom (whole world)

19 highest zoom (individual buildings, if available) Retrieve current zoom level using mapObject.getZoom()


What you're looking for are the scales for each zoom level. Use these:

20 : 1128.497220
19 : 2256.994440
18 : 4513.988880
17 : 9027.977761
16 : 18055.955520
15 : 36111.911040
14 : 72223.822090
13 : 144447.644200
12 : 288895.288400
11 : 577790.576700
10 : 1155581.153000
9  : 2311162.307000
8  : 4622324.614000
7  : 9244649.227000
6  : 18489298.450000
5  : 36978596.910000
4  : 73957193.820000
3  : 147914387.600000
2  : 295828775.300000
1  : 591657550.500000

Efficient way to insert a number into a sorted array of numbers?

Very good and remarkable question with a very interesting discussion! I also was using the Array.sort() function after pushing a single element in an array with some thousands of objects.

I had to extend your locationOf function for my purpose because of having complex objects and therefore the need for a compare function like in Array.sort():

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than dividing by 2

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var patientCompare = function (a, b) {
    if (a.lastName < b.lastName) return -1;
    if (a.lastName > b.lastName) return 1;
    return 0;
};

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

You have to catch the error just as you're already doing for your save() call and since you're handling multiple errors here, you can try multiple calls sequentially in a single do-catch block, like so:

func deleteAccountDetail() {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()
    request.entity = entityDescription

    do {
        let fetchedEntities = try self.Context!.executeFetchRequest(request) as! [AccountDetail]

        for entity in fetchedEntities {
            self.Context!.deleteObject(entity)
        }

        try self.Context!.save()
    } catch {
        print(error)
    }
}

Or as @bames53 pointed out in the comments below, it is often better practice not to catch the error where it was thrown. You can mark the method as throws then try to call the method. For example:

func deleteAccountDetail() throws {
    let entityDescription = NSEntityDescription.entityForName("AccountDetail", inManagedObjectContext: Context!)
    let request = NSFetchRequest()

    request.entity = entityDescription

    let fetchedEntities = try Context.executeFetchRequest(request) as! [AccountDetail]

    for entity in fetchedEntities {
        self.Context!.deleteObject(entity)
    }

    try self.Context!.save()
}

How to get only the date value from a Windows Forms DateTimePicker control?

string shortDate = dateTimePicker1.Value.ToShortDateString();

Change tab bar tint color on iOS 7

What finally worked for me was:

[self.tabBar setTintColor:[UIColor redColor]];
[self.tabBar setBarTintColor:[UIColor yellowColor]];

SQL Server 2008 - Case / If statements in SELECT Clause

CASE is the answer, but you will need to have a separate case statement for each column you want returned. As long as the WHERE clause is the same, there won't be much benefit separating it out into multiple queries.

Example:

SELECT
    CASE @var
        WHEN 'xyz' THEN col1
        WHEN 'zyx' THEN col2
        ELSE col7
    END,
    CASE @var
        WHEN 'xyz' THEN col2
        WHEN 'zyx' THEN col3
        ELSE col8
    END
FROM Table
...

Global variables in header file

There are 3 scenarios, you describe:

  1. with 2 .c files and with int i; in the header.
  2. With 2 .c files and with int i=100; in the header (or any other value; that doesn't matter).
  3. With 1 .c file and with int i=100; in the header.

In each scenario, imagine the contents of the header file inserted into the .c file and this .c file compiled into a .o file and then these linked together.

Then following happens:

  1. works fine because of the already mentioned "tentative definitions": every .o file contains one of them, so the linker says "ok".

  2. doesn't work, because both .o files contain a definition with a value, which collide (even if they have the same value) - there may be only one with any given name in all .o files which are linked together at a given time.

  3. works of course, because you have only one .o file and so no possibility for collision.

IMHO a clean thing would be

  • to put either extern int i; or just int i; into the header file,
  • and then to put the "real" definition of i (namely int i = 100;) into file1.c. In this case, this initialization gets used at the start of the program and the corresponding line in main() can be omitted. (Besides, I hope the naming is only an example; please don't name any global variables as i in real programs.)

How to use NULL or empty string in SQL

Some sargable methods...

SELECT *
FROM #T
WHERE SomeCol = '' OR SomeCol IS NULL;

SELECT *
FROM #T
WHERE SomeCol = '' 
UNION ALL
SELECT *
FROM #T
WHERE  SomeCol IS NULL;

SELECT *
FROM #T
WHERE EXISTS ((SELECT NULL UNION SELECT '') INTERSECT SELECT SomeCol);

And some non-sargable ones...

SELECT *
FROM #T
WHERE IIF(SomeCol <> '',0,1) = 1;

SELECT *
FROM #T
WHERE NULLIF(SomeCol,'') IS NULL;

SELECT *
FROM #T
WHERE ISNULL(SomeCol,'') = '';

How to get the date 7 days earlier date from current date in Java

You can use this to continue using the type Date and a more legible code, if you preffer:

import org.apache.commons.lang.time.DateUtils;
...
Date yourDate = DateUtils.addDays(new Date(), *days here*);

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

Inheritance and init method in Python

In the first situation, Num2 is extending the class Num and since you are not redefining the special method named __init__() in Num2, it gets inherited from Num.

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance.

In the second situation, since you are redefining __init__() in Num2 you need to explicitly call the one in the super class (Num) if you want to extend its behavior.

class Num2(Num):
    def __init__(self,num):
        Num.__init__(self,num)
        self.n2 = num*2

How to convert timestamps to dates in Bash?

On later versions of common Linux distributions you can use:

date -d @1267619929

Restoring Nuget References?

I suffered from this issue too a lot, in my case Downloading missing NuGet was checked (but it is not restoring them) and i can not uninstall & re-install because i modified some of the installed packages ... so:

I just cleared the cached and rebuild and it worked. (Tools-Option-Nuget Package Manager - General)

also this link helps https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore.

symfony2 : failed to write cache directory

Most likely it means that the directory and/or sub-directories are not writable. Many forget about sub-directories.

Symfony 2

chmod -R 777 app/cache app/logs

Symfony 3 directory structure

chmod -R 777 var/cache var/logs

Additional Resources

Permissions solution by Symfony (mentioned previously).

Permissions solution by KPN University - additionally includes an screen-cast on installation.

Note: If you're using Symfony 3 directory structure, substitute app/cache and app/logs with var/cache and var/logs.

Get visible items in RecyclerView

Finally, I found a solution to know if the current item is visible, from the onBindViewHolder event in the adapter.

The key is the method isViewPartiallyVisible from LayoutManager.

In your adapter, you can get the LayoutManager from the RecyclerView, which you get as parameter from the onAttachedToRecyclerView event.

Angular IE Caching issue for $http

The guaranteed one that I had working was something along these lines:

myModule.config(['$httpProvider', function($httpProvider) {
    if (!$httpProvider.defaults.headers.common) {
        $httpProvider.defaults.headers.common = {};
    }
    $httpProvider.defaults.headers.common["Cache-Control"] = "no-cache";
    $httpProvider.defaults.headers.common.Pragma = "no-cache";
    $httpProvider.defaults.headers.common["If-Modified-Since"] = "Mon, 26 Jul 1997 05:00:00 GMT";
}]);

I had to merge 2 of the above solutions in order to guarantee the correct usage for all methods, but you can replace common with get or other method i.e. put, post, delete to make this work for different cases.

How to disable JavaScript in Chrome Developer Tools?

Official documentation: Disable JavaScript With Chrome DevTools

There's now a command menu built into DevTools that makes it easier to disable JavaScript. This has been around as of April 2016 or so.

  1. Open DevTools.
  2. Press Command+Shift+P (Mac) or Control+Shift+P (Windows, Linux) to open the Command Menu. Make sure that your cursor's focus is on the DevTools window, not your browser viewport.
  3. Type Disable JavaScript (or some version of that... it's a fuzzy search) and then press Enter.

Use the Enable JavaScript command when you want to turn it back on.

disabling js via command menu

How to remove listview all items

For me worked this way:

private ListView yourListViewName;
private List<YourClassName> yourListName;

  ...

yourListName = new ArrayList<>();
yourAdapterName = new yourAdapterName(this, R.layout.your_layout_name, yourListName);

  ...

if (yourAdapterName.getCount() > 0) {
   yourAdapterName.clear();
   yourAdapterName.notifyDataSetChanged();
}

yourAdapterName.add(new YourClassName(yourParameter1, yourParameter2, ...));
yourListViewName.setAdapter(yourAdapterName);

ReactJS - How to use comments?

On the other hand, the following is a valid comment, pulled directly from a working application:

render () {
    return <DeleteResourceButton
            //confirm
            onDelete={this.onDelete.bind(this)}
            message="This file will be deleted from the server."
           />
}

Apparantly, when inside the angle brackets of a JSX element, the // syntax is valid, but the {/**/} is invalid. The following breaks:

render () {
    return <DeleteResourceButton
            {/*confirm*/}
            onDelete={this.onDelete.bind(this)}
            message="This file will be deleted from the server."
           />
}

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

A few comments:

import sun.misc.*; Don't do this. It is non-standard and not guaranteed to be the same between implementations. There are other libraries with Base64 conversion available.

byte[] encVal = c.doFinal(Data.getBytes()); You are relying on the default character encoding here. Always specify what character encoding you are using: byte[] encVal = c.doFinal(Data.getBytes("UTF-8")); Defaults might be different in different places.

As @thegrinner pointed out, you need to explicitly check the length of your byte arrays. If there is a discrepancy, then compare them byte by byte to see where the difference is creeping in.

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

How can I get a process handle by its name in C++?

The following code can be used:

DWORD FindProcessId(const std::wstring& processName)
{
    PROCESSENTRY32 processInfo;
    processInfo.dwSize = sizeof(processInfo);

    HANDLE processesSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
    if (processesSnapshot == INVALID_HANDLE_VALUE) {
        return 0;
    }

    Process32First(processesSnapshot, &processInfo);
    if (!processName.compare(processInfo.szExeFile))
    {
        CloseHandle(processesSnapshot);
        return processInfo.th32ProcessID;
    }

    while (Process32Next(processesSnapshot, &processInfo))
    {
        if (!processName.compare(processInfo.szExeFile))
        {
            CloseHandle(processesSnapshot);
            return processInfo.th32ProcessID;
        }
    }

    CloseHandle(processesSnapshot);
    return 0;
}

Usage:

auto processId = FindProcessId(L"blabla.exe");

Getting a handle should be obvious, just call OpenProcess() or similar on it.

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

LOAD DATA INFILE Error Code : 13

This is normally a file access permissions issue but I see your already addressing that in point b, but it's worth going over just in case. Another option is to use LOAD DATA LOCAL INFILE which gets past a lot of these issues of file access permissions. To use this method though you need to copy the file locally (in the mysql folder is best) first. •If LOCAL is specified, the file is read by the client program on the client host and sent to the server.

Insufficient Directory Permissions

The error in this example has resulted because the file you are trying to import is not in a directory which is readable by the user the MySql server is running as. Note that all the parent directories of the directory the is in need to be readable by the MySql user for this to work. Saving the file to /tmp will usually work as this is usually readable (and writable) by all users. The error code number is 13. Source

EDIT:

Remember you will need permissions on not just the folder the holds the file but also the upper directories.

Example from this post on the MySql Forums.

If your file was contained within the following strucutre: /tmp/imports/site1/data.file

you would need (I think, 755 worked) r+x for 'other' on these directories:

/tmp

/tmp/imports

As well as the main two:

/tmp/imports/site1

/tmp/imports/site1/data.file

You need the file and directory to be world-readable. Apologies if you've already tried this method but it may be worth retracing your steps, never hurts to double check.

Serializing a list to JSON

You can also use Json.NET. Just download it at http://james.newtonking.com/pages/json-net.aspx, extract the compressed file and add it as a reference.

Then just serialize the list (or whatever object you want) with the following:

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

Update: you can also add it to your project via the NuGet Package Manager (Tools --> NuGet Package Manager --> Package Manager Console):

PM> Install-Package Newtonsoft.Json

Documentation: Serializing Collections

iPhone - Get Position of UIView within entire UIWindow

For me this code worked best:

private func getCoordinate(_ view: UIView) -> CGPoint {
    var x = view.frame.origin.x
    var y = view.frame.origin.y
    var oldView = view

    while let superView = oldView.superview {
        x += superView.frame.origin.x
        y += superView.frame.origin.y
        if superView.next is UIViewController {
            break //superView is the rootView of a UIViewController
        }
        oldView = superView
    }

    return CGPoint(x: x, y: y)
}

Get the value of input text when enter key pressed

Listen the change event.

document.querySelector("input")
  .addEventListener('change', (e) => {
    console.log(e.currentTarget.value);
 });

How to place the ~/.composer/vendor/bin directory in your PATH?

I did all of the above and it didn't work for me.

I just copied this into my terminal and it worked for me.

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

Is it possible to change the package name of an Android app on Google Play?

Never, you can't do it since package name is the unique name Identifier for your app.....

Intellij idea cannot resolve anything in maven

<option name="workOffline" value="true" /> in workspace.xml is not your friend. Advise to check this before deleting your .idea (which has a lot of useful settings you probably don't want to lose)

It's a maven workspace.xml setting

Capture iOS Simulator video for App Preview

You should use QuickTime in Yosemite to connect and record the screen of your iOS devices.

iPhone Portrait

When you finished the recording, you can use iMovie to edit the video. When you're working on an iPhone Portrait App Preview, the resolution must be 1080x1920 but iMovie can only export in 16:9 (1920x1080).

One solution would be to imported the recorded video with the resolution 1080x1920 and rotate it 90 degree. Then export the movie at 1920x1080 and rotate the exported video back 90 degrees using ffmpeg and the following command

ffmpeg -i Landscape.mp4 -vf "transpose=1" Portrait.mp4

iPad

The iPad is a little bit trickier because it requires a resolution of 1200x900 (4:3) but iMovie only exports in 16:9.

Here is what I've done.

  1. Record the movie on iPad Air in Landscape (1200x900, 4:3)
  2. Import into iMovie and export as 1920x1080, 16:9 (iPadLandscape16_9-1920x1080.mp4)
  3. Remove left and right black bars to a video with 1440x1080. The width of one bar is 240

    ffmpeg -i iPadLandscape16_9-1920x1080.mp4 -filter:v "crop=1440:1080:240:0" -c:a copy iPadLandscape4_3-1440x1080.mp4
    
  4. Scale down movie to 1220x900

    ffmpeg -i iPadLandscape4_3-1440x1080.mp4 -filter:v scale=1200:-1 -c:a copy iPadLandscape4_3-1200x900.mp4
    

Taken from my answer on the Apple Developer Forum

How do I get the HTTP status code with jQuery?

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

Using union and count(*) together in SQL query

If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:

SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
FROM (
  SELECT name, COUNT(*) AS Rcount, 0 AS Acount
  FROM Results GROUP BY name
  UNION ALL
  SELECT name, 0, count(*)
  FROM Archive_Results
  GROUP BY name
) AS Both
GROUP BY name
ORDER BY name;

How to embed HTML into IPython output?

This seems to work for me:

from IPython.core.display import display, HTML
display(HTML('<h1>Hello, world!</h1>'))

The trick is to wrap it in "display" as well.

Source: http://python.6.x6.nabble.com/Printing-HTML-within-IPython-Notebook-IPython-specific-prettyprint-tp5016624p5016631.html

Datetime equal or greater than today in MySQL

The below code worked for me.

declare @Today date

Set @Today=getdate() --date will equal today    

Select *

FROM table_name
WHERE created <= @Today

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

@palash k answer is correct and worked for internal storage files, but in my case I want to open files from external storage also, my app crashed when open file from external storage like sdcard and usb, but I manage to solve the issue by modifying provider_paths.xml from the accepted answer

change the provider_paths.xml like below

<?xml version="1.0" encoding="utf-8"?>
 <paths xmlns:android="http://schemas.android.com/apk/res/android">

<external-path path="Android/data/${applicationId}/" name="files_root" />

<root-path
    name="root"
    path="/" />

</paths>

and in java class(No change as the accepted answer just a small edit)

Uri uri=FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID+".provider", File)

This help me to fix the crash for files from external storages, Hope this will help some one having same issue as mine :)

Oracle Add 1 hour in SQL

Use an interval:

select some_date_column + interval '1' hour 
from your_table;

Rails has_many with alias name

To complete @SamSaffron's answer :

You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :

class BlogPost
  has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post  
end

and you need to make sure you have the belongs_to attribute on the child model:

class BlogPostImage
  belongs_to :blog_post
end

Unable to start MySQL server

I had the same issue. Try this, it should work!

  1. Right click on MySQL Notifier -> Actions -> Manage Monitored Items

  2. Highlight the MySQL56 entry and click the delete button

  3. Click the add button -> windows service
  4. Scroll down and look for MySQL56
  5. Highlight it and click ok

CSS transition when class removed

In my case i had some problem with opacity transition so this one fix it:

#dropdown {
    transition:.6s opacity;
}
#dropdown.ns {
    opacity:0;
    transition:.6s all;
}
#dropdown.fade {
    opacity:1;
}

Mouse Enter

$('#dropdown').removeClass('ns').addClass('fade');

Mouse Leave

$('#dropdown').addClass('ns').removeClass('fade');

How to use relative/absolute paths in css URLs?

i had the same problem... every time that i wanted to publish my css.. I had to make a search/replace.. and relative path wouldnt work either for me because the relative paths were different from dev to production.

Finally was tired of doing the search/replace and I created a dynamic css, (e.g. www.mysite.com/css.php) it's the same but now i could use my php constants in the css. somethig like

.icon{
  background-image:url('<?php echo BASE_IMAGE;?>icon.png');
}

and it's not a bad idea to make it dynamic because now i could compress it using YUI compressor without loosing the original format on my dev server.

Good Luck!

Swift's guard keyword

From Apple documentation:

Guard Statement

A guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

Synatx:

guard condition else {
    statements
}

Advantage:

1. By using guard statement we can get rid of deeply nested conditionals whose sole purpose is validating a set of requirements.

2. It was designed specifically for exiting a method or function early.

if you use if let below is the code how it looks.

  let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

        if error == nil {
            if let  statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 {
                if let data = data {

                    //Process Data Here.
                    print("Data: \(data)")

                } else {
                    print("No data was returned by the request!")
                }
            } else {
                print("Your request returned a status code other than 2XX!")
            }
        } else {
            print("Error Info: \(error.debugDescription)")
        }
    }
    task.resume()

Using guard you can transfer control out of a scope if one or more conditions aren't met.

let task = URLSession.shared.dataTask(with: request) { (data, response, error) in

            /* GUARD: was there an error? */
            guard (error == nil) else {
                print("There was an error with your request: \(error)")
                return
            }

            /* GUARD: Did we get a successful 2XX response? */
            guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2XX!")
                return
            }

            /* GUARD: was there any data returned? */
            guard let data = data else {
                print("No data was returned by the request!")
                return
            }

            //Process Data Here.
            print("Data: \(data)")
}
task.resume()

Reference:

1. Swift 2: Exit Early With guard 2. Udacity 3. Guard Statement

Android Spinner: Get the selected item change event

Spinner spnLocale = (Spinner)findViewById(R.id.spnLocale);

spnLocale.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { 
        // Your code here
    } 

    public void onNothingSelected(AdapterView<?> adapterView) {
        return;
    } 
}); 

Note: Remember one thing.

Spinner OnItemSelectedListener event will execute twice:

  1. Spinner initialization
  2. User selected manually

Try to differentiate those two by using flag variable.

Get URL query string parameters

I will recommended best answer as

<?php echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!'; ?>

Assuming the user entered http://example.com/?name=Hannes

The above example will output:

Hello Hannes!

How to convert comma-delimited string to list in Python?

>>> some_string='A,B,C,D,E'
>>> new_tuple= tuple(some_string.split(','))
>>> new_tuple
('A', 'B', 'C', 'D', 'E')

Correct way to load a Nib for a UIView subclass

Well you could either initialize the xib using a view controller and use viewController.view. or do it the way you did it. Only making a UIView subclass as the controller for UIView is a bad idea.

If you don't have any outlets from your custom view then you can directly use a UIViewController class to initialize it.

Update: In your case:

UIViewController *genericViewCon = [[UIViewController alloc] initWithNibName:@"CustomView"];
//Assuming you have a reference for the activity indicator in your custom view class
CustomView *myView = (CustomView *)genericViewCon.view;
[parentView addSubview:myView];
//And when necessary
[myView.activityIndicator startAnimating]; //or stop

Otherwise you have to make a custom UIViewController(to make it as the file's owner so that the outlets are properly wired up).

YourCustomController *yCustCon = [[YourCustomController alloc] initWithNibName:@"YourXibName"].

Wherever you want to add the view you can use.

[parentView addSubview:yCustCon.view];

However passing the another view controller(already being used for another view) as the owner while loading the xib is not a good idea as the view property of the controller will be changed and when you want to access the original view, you won't have a reference to it.

EDIT: You will face this problem if you have setup your new xib with file's owner as the same main UIViewController class and tied the view property to the new xib view.

i.e;

  • YourMainViewController -- manages -- mainView
  • CustomView -- needs to load from xib as and when required.

The below code will cause confusion later on, if you write it inside view did load of YourMainViewController. That is because self.view from this point on will refer to your customview

-(void)viewDidLoad:(){
  UIView *childView= [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:self options:nil] objectAtIndex:0];
}

Add content to a new open window

Here is what you can try

  • Write a function say init() inside mypage.html that do the html thing ( append or what ever)
  • instead of OpenWindow.document.write(output); call OpenWindow.init() when the dom is ready

So the parent window will have

    OpenWindow.onload = function(){
       OpenWindow.init('test');
    }

and in the child

    function init(txt){
        $('#test').text(txt);
    }

<button> background image

To get rid of the white color you have to set the background-color to transparent:

button {
  font-size: 18px;
  border: 2px solid #AD235E;
  border-radius: 100px;
  width: 150px;
  height: 150px;
  background-color: transparent; /* like this */
}

Sending Email in Android using JavaMail API without using the default/built-in app

Send e-mail in Android using the JavaMail API using Gmail authentication.

Steps to create a sample Project:

MailSenderActivity.java:

public class MailSenderActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Button send = (Button) this.findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            
            public void onClick(View v) {
                try {   
                    GMailSender sender = new GMailSender("[email protected]", "password");
                    sender.sendMail("This is Subject",   
                            "This is Body",   
                            "[email protected]",   
                            "[email protected]");   
                } catch (Exception e) {   
                    Log.e("SendMail", e.getMessage(), e);   
                } 
                
            }
        });
        
    }
}

GMailSender.java:

public class GMailSender extends javax.mail.Authenticator {   
    private String mailhost = "smtp.gmail.com";   
    private String user;   
    private String password;   
    private Session session;   
  
    static {   
        Security.addProvider(new com.provider.JSSEProvider());   
    }  
  
    public GMailSender(String user, String password) {   
        this.user = user;   
        this.password = password;   
  
        Properties props = new Properties();   
        props.setProperty("mail.transport.protocol", "smtp");   
        props.setProperty("mail.host", mailhost);   
        props.put("mail.smtp.auth", "true");   
        props.put("mail.smtp.port", "465");   
        props.put("mail.smtp.socketFactory.port", "465");   
        props.put("mail.smtp.socketFactory.class",   
                "javax.net.ssl.SSLSocketFactory");   
        props.put("mail.smtp.socketFactory.fallback", "false");   
        props.setProperty("mail.smtp.quitwait", "false");   
  
        session = Session.getDefaultInstance(props, this);   
    }   
  
    protected PasswordAuthentication getPasswordAuthentication() {   
        return new PasswordAuthentication(user, password);   
    }   
  
    public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {   
        try{
        MimeMessage message = new MimeMessage(session);   
        DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));   
        message.setSender(new InternetAddress(sender));   
        message.setSubject(subject);   
        message.setDataHandler(handler);   
        if (recipients.indexOf(',') > 0)   
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));   
        else  
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));   
        Transport.send(message);   
        }catch(Exception e){
            
        }
    }   
  
    public class ByteArrayDataSource implements DataSource {   
        private byte[] data;   
        private String type;   
  
        public ByteArrayDataSource(byte[] data, String type) {   
            super();   
            this.data = data;   
            this.type = type;   
        }   
  
        public ByteArrayDataSource(byte[] data) {   
            super();   
            this.data = data;   
        }   
  
        public void setType(String type) {   
            this.type = type;   
        }   
  
        public String getContentType() {   
            if (type == null)   
                return "application/octet-stream";   
            else  
                return type;   
        }   
  
        public InputStream getInputStream() throws IOException {   
            return new ByteArrayInputStream(data);   
        }   
  
        public String getName() {   
            return "ByteArrayDataSource";   
        }   
  
        public OutputStream getOutputStream() throws IOException {   
            throw new IOException("Not Supported");   
        }   
    }   
}  

JSSEProvider.java:

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @author Alexander Y. Kleymenov
 * @version $Revision$
 */


import java.security.AccessController;
import java.security.Provider;

public final class JSSEProvider extends Provider {

    public JSSEProvider() {
        super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
        AccessController.doPrivileged(new java.security.PrivilegedAction<Void>() {
            public Void run() {
                put("SSLContext.TLS",
                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                put("KeyManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                put("TrustManagerFactory.X509",
                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                return null;
            }
        });
    }
}

ADD 3 jars found in the following link to your Android Project

Click here - How to add External Jars

And don't forget to add this line in your manifest:

<uses-permission android:name="android.permission.INTERNET" />

Just click below link to change account access for less secure apps https://www.google.com/settings/security/lesssecureapps

Run the project and check your recipient mail account for the mail. Cheers!

P.S. And don't forget that you cannot do network operation from any Activity in android. Hence it is recommended to use AsyncTask or IntentService to avoid network on main thread exception.

Jar files: https://code.google.com/archive/p/javamail-android/

Rails select helper - Default selected value, how?

if params[:pid] is a string, which if it came from a form, it is, you'll probably need to use

params[:pid].to_i  

for the correct item to be selected in the select list

Send File Attachment from Form Using phpMailer and PHP

File could not be Attached from client PC (upload)

In the HTML form I have not added following line, so no attachment was going:

enctype="multipart/form-data"

After adding above line in form (as below), the attachment went perfect.

<form id="form1" name="form1" method="post" action="form_phpm_mailer.php"  enctype="multipart/form-data">

Binding multiple events to a listener (without JQuery)?

Some compact syntax that achieves the desired result, POJS:

   "mousemove touchmove".split(" ").forEach(function(e){
      window.addEventListener(e,mouseMoveHandler,false);
    });

Storing WPF Image Resources

Yes, it is the right way.

You could use the image in the resource file just using the path:

<Image Source="..\Media\Image.png" />

You must set the build action of the image file to "Resource".

Add class to an element in Angular 4

If you want to set only one specific class, you might write a TypeScript function returning a boolean to determine when the class should be appended.

TypeScript

function hideThumbnail():boolean{
    if (/* Your criteria here */)
        return true;
}

CSS:

.request-card-hidden {
    display: none;
}

HTML:

<ion-note [class.request-card-hidden]="hideThumbnail()"></ion-note>

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Is your server configured for client authentication? If so you need to pass the client certificate while connecting with the server.

Check If only numeric values were entered in input. (jQuery)

for future visitors, you can add this functon that allow user to enter only numbers: you will only have to add jquery and the class name to the input check that into http://jsfiddle.net/celia/dvnL9has/2/

$('.phone_number').keypress(function(event){
var numero= String.fromCharCode(event.keyCode);
 var myArray = ['0','1','2','3','4','5','6','7','8','9',0,1,2,3,4,5,6,7,8,9];
index = myArray.indexOf(numero);// 1
var longeur= $('.phone_number').val().length;
if(window.getSelection){
 text = window.getSelection().toString();
 } if(index>=0&text.length>0){
  }else if(index>=0&longeur<10){
    }else {return false;} });

How do I remove the title bar from my app?

In styles.xml file, change DarkActionBar to NoActionBar

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

pandas groupby sort descending order

Other instance of preserving the order or sort by descending:

In [97]: import pandas as pd                                                                                                    

In [98]: df = pd.DataFrame({'name':['A','B','C','A','B','C','A','B','C'],'Year':[2003,2002,2001,2003,2002,2001,2003,2002,2001]})

#### Default groupby operation:
In [99]: for each in df.groupby(["Year"]): print each                                                                           
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)

### order preserved:
In [100]: for each in df.groupby(["Year"], sort=False): print each                                                               
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)

In [106]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"]))                        
Out[106]: 
        Year name
Year             
2003 0  2003    A
     3  2003    A
     6  2003    A
2002 1  2002    B
     4  2002    B
     7  2002    B
2001 2  2001    C
     5  2001    C
     8  2001    C

In [107]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"])).reset_index(drop=True)
Out[107]: 
   Year name
0  2003    A
1  2003    A
2  2003    A
3  2002    B
4  2002    B
5  2002    B
6  2001    C
7  2001    C
8  2001    C

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

Difference between null and empty string

No method can be invoked on a object which is assigned a NULL value. It will give a nullPointerException. Hence, s2.length() is giving an exception.

asp.net: Invalid postback or callback argument

Another thing to watch out for, is that this error can happen if you have a nested

<form

tag within the .Net form.

CodeIgniter removing index.php from url

There are two steps:

1) Edit config.php

$config['index_page'] = 'index.php';

To

$config['index_page'] = '’;

2) Create/Edit .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

"Missing return statement" within if / for / while

You have to add a return statement if the condition is false.

public String myMethod() {
    if(condition) {
        return x;
    }

//  if condition is false you HAVE TO return a string
//  you could return a string, a empty string or null
    return otherCondition;  
}

FYI:

Oracle docs for return statement

Git: "please tell me who you are" error

That’s a typo. You’ve accidently set "user.mail" with no "e". Fix it by setting "user.email" in the global configuration with

git config --global user.email "[email protected]"

Found solution here

https://stackoverflow.com/a/14662703

How to encode a URL in Swift

Swift 2.0

let needsLove = "string needin some URL love"
let safeURL = needsLove.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

Helpful Progamming Tips and Hacks

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Check whether a string contains a substring

Another possibility is to use regular expressions which is what Perl is famous for:

if ($mystring =~ /s1\.domain\.com/) {
   print qq("$mystring" contains "s1.domain.com"\n);
}

The backslashes are needed because a . can match any character. You can get around this by using the \Q and \E operators.

my $substring = "s1.domain.com";
    if ($mystring =~ /\Q$substring\E/) {
   print qq("$mystring" contains "$substring"\n);
}

Or, you can do as eugene y stated and use the index function. Just a word of warning: Index returns a -1 when it can't find a match instead of an undef or 0.

Thus, this is an error:

my $substring = "s1.domain.com";
if (not index($mystring, $substr)) {
    print qq("$mystring" doesn't contains "$substring"\n";
} 

This will be wrong if s1.domain.com is at the beginning of your string. I've personally been burned on this more than once.

How to search for a file in the CentOS command line

Try this command:

find / -name file.look

How to cast/convert pointer to reference in C++

Call it like this:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

Class has been compiled by a more recent version of the Java Environment

For temporary solution just right click on Project => Properties => Java compiler => over there please select compiler compliance level 1.8 => .class compatibility 1.8 => source compatibility 1.8.

Then your code will start to execute on version 1.8.

How can I create an utility class?

Making a class abstract sends a message to the readers of your code that you want users of your abstract class to subclass it. However, this is not what you want then to do: a utility class should not be subclassed.

Therefore, adding a private constructor is a better choice here. You should also make the class final to disallow subclassing of your utility class.

What's the best three-way merge tool?

I love Ediff. It comes built-in with GNU Emacs.

To do a three-way diff, use ediff-files3 (for selecting three files) or ediff-buffer3 (for selecting three already-open buffers). You'll get a screen looking like this:

three-way diff in emacs

Note the word-difference higlighting.

You can hit n or p to go to the next/previous diffs, while ab will copy the region from buffer a (the leftmost one) to buffer b (the middle one), and similarly for other two-letter combinations of a, b, c; rb will restore the region in buffer b. Hit ? for a quick help menu, or read the fine manual on diff3 merging in Emacs.

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

How to call base.base.method()?

In cases where you do not have access to the derived class source, but need all the source of the derived class besides the current method, then I would recommended you should also do a derived class and call the implementation of the derived class.

Here is an example:

//No access to the source of the following classes
public class Base
{
     public virtual void method1(){ Console.WriteLine("In Base");}
}
public class Derived : Base
{
     public override void method1(){ Console.WriteLine("In Derived");}
     public void method2(){ Console.WriteLine("Some important method in Derived");}
}

//Here should go your classes
//First do your own derived class
public class MyDerived : Base
{         
}

//Then derive from the derived class 
//and call the bass class implementation via your derived class
public class specialDerived : Derived
{
     public override void method1()
     { 
          MyDerived md = new MyDerived();
          //This is actually the base.base class implementation
          MyDerived.method1();  
     }         
}

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

Is it possible to set the stacking order of pseudo-elements below their parent element?

I know this is an old thread, but I feel the need to post the proper answer. The actual answer to this question is that you need to create a new stacking context on the parent of the element with the pseudo element (and you actually have to give it a z-index, not just a position).

Like this:

#parent {
    position: relative;
    z-index: 1;
}
#pseudo-parent {
    position: absolute;
    /* no z-index allowed */
}
#pseudo-parent:after {
    position: absolute;
    top:0;
    z-index: -1;
}

It has nothing to do with using :before or :after pseudo elements.

_x000D_
_x000D_
#parent { position: relative; z-index: 1; }_x000D_
#pseudo-parent { position: absolute; } /* no z-index required */_x000D_
#pseudo-parent:after { position: absolute; z-index: -1; }_x000D_
_x000D_
/* Example styling to illustrate */_x000D_
#pseudo-parent { background: #d1d1d1; }_x000D_
#pseudo-parent:after { margin-left: -3px; content: "M" }
_x000D_
<div id="parent">_x000D_
 <div id="pseudo-parent">_x000D_
   &nbsp;_x000D_
 </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Use of #pragma in C

#pragma is for compiler directives that are machine-specific or operating-system-specific, i.e. it tells the compiler to do something, set some option, take some action, override some default, etc. that may or may not apply to all machines and operating systems.

See msdn for more info.

Facebook Like-Button - hide count?

this worked for me:

.fb-like.fb_edge_widget_with_comment.fb_iframe_widget {
    height: 26px;
    overflow: hidden;
    width: 138px;
}

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

Connecting to Oracle Database through C#?

Using Nuget

  1. Right click Project, select Manage NuGet packages...
  2. Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess

Oracle NuGet package

  1. In code use the following command (Ctrl+. to automatically add the using directive).

  2. Note the different DataSource string which in comparison to Java is different.

    // create connection
    OracleConnection con = new OracleConnection();
    
    // create connection string using builder
    OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
    ocsb.Password = "autumn117";
    ocsb.UserID = "john";
    ocsb.DataSource = "database.url:port/databasename";
    
    // connect
    con.ConnectionString = ocsb.ConnectionString;
    con.Open();
    Console.WriteLine("Connection established (" + con.ServerVersion + ")");
    

conversion from string to json object android

its work

    String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";

    try {

        JSONObject obj = new JSONObject(json);

        Log.d("My App", obj.toString());
        Log.d("phonetype value ", obj.getString("phonetype"));

    } catch (Throwable tx) {
        Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
    }

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

How to Get the HTTP Post data in C#?

Use this:

    public void ShowAllPostBackData()
    {
        if (IsPostBack)
        {
            string[] keys = Request.Form.AllKeys;
            Literal ctlAllPostbackData = new Literal();
            ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
            for (int i = 0; i < keys.Length; i++)
            {
                ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
            }
            ctlAllPostbackData.Text += "</div>";
            this.Controls.Add(ctlAllPostbackData);
        }
    }

how to make label visible/invisible?

you could try

if (isValid) {
    document.getElementById("endTimeLabel").style.display = "none";
}else {
    document.getElementById("endTimeLabel").style.display = "block";
}

alone those lines

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

I know its been a while since the question was asked but I was able to find a solution:

int sockfd;
int option = 1;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));

This set the socket able to be reused immediately.

I apologize if this is "wrong". I'm not very experienced with sockets

Is there a good JSP editor for Eclipse?

Oracle Workshop for Weblogic is supposed to have a pretty nice jsp editor but I've never used it. You needn't be using Weblogic to use it.

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

How to call a method after bean initialization is complete?

To further clear any confusion about the two approach i.e use of

  1. @PostConstruct and
  2. init-method="init"

From personal experience, I realized that using (1) only works in a servlet container, while (2) works in any environment, even in desktop applications. So, if you would be using Spring in a standalone application, you would have to use (2) to carry out that "call this method after initialization.

Downloading a large file using curl

Find below code if you want to download the contents of the specified URL also want to saves it to a file.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>

How to count lines of Java code using IntelliJ IDEA?

In the past I have used the excellently named MetricsReloaded plugin to get this information.

You can install it from the JetBrains repository.

Once installed, access via: Analyze -> Calculate Metrics...

What is the difference between Cloud, Grid and Cluster?

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

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

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

What is the Simplest Way to Reverse an ArrayList?

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

 public ArrayList<Object> reverse(ArrayList<Object> list) {

   for (int i = 0; i < list.size() / 2; i++) {
     Object temp = list.get(i);
     list.set(i, list.get(list.size() - i - 1));
     list.set(list.size() - i - 1, temp);
   }

   return list;
 }

Javascript Regexp dynamic generation from variables?

You have to use RegExp:

str.match(new RegExp(pattern1+'|'+pattern2, 'gi'));

When I'm concatenating strings, all slashes are gone.

If you have a backslash in your pattern to escape a special regex character, (like \(), you have to use two backslashes in the string (because \ is the escape character in a string): new RegExp('\\(') would be the same as /\(/.

So your patterns have to become:

var pattern1 = ':\\(|:=\\(|:-\\(';
var pattern2 = ':\\(|:=\\(|:-\\(|:\\(|:=\\(|:-\\(';

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

Cassandra port usage - how are the ports used?

8080 - JMX (remote)

8888 - Remote debugger (removed in 0.6.0)

7000 - Used internal by Cassandra
(7001 - Obsolete, removed in 0.6.0. Used for membership communication, aka gossip)

9160 - Thrift client API

Cassandra FAQ What ports does Cassandra use?

Github Push Error: RPC failed; result=22, HTTP code = 413

I figured it out!!! Of course I would right after I hit post!

I had the repo set to use the HTTPS url, I changed it to the SSH address, and everything resumed working flawlessly.

sh: react-scripts: command not found after running npm start

You shoundt use neither SPACES neither some Special Caracters in you path, like for example using "&". I my case I was using this path: "D:\P&D\mern" and because of this "&" I lost 50 minutes trying to solve the problem! :/

Living and Learning!

Best way to require all files from a directory in ruby?

If it's a directory relative to the file that does the requiring (e.g. you want to load all files in the lib directory):

Dir[File.dirname(__FILE__) + '/lib/*.rb'].each {|file| require file }

Edit: Based on comments below, an updated version:

Dir[File.join(__dir__, 'lib', '*.rb')].each { |file| require file }

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

"Items collection must be empty before using ItemsSource."

Beware of typos! I had the following

<TreeView ItemsSource="{Binding MyCollection}">
    <TreeView.Resources>
        ...
    </TreeView.Resouces>>
</TreeView>

(Notice the tailing >, which is interpreted as content, so you're setting twice the content... Took me a while :)

Switching between GCC and Clang/LLVM using CMake

System wide C++ change on Ubuntu:

sudo apt-get install clang
sudo update-alternatives --config c++

Will print something like this:

  Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/g++       20        auto mode
  1            /usr/bin/clang++   10        manual mode
  2            /usr/bin/g++       20        manual mode

Then just select clang++.

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

How to use JavaScript variables in jQuery selectors?

$("#" + $(this).attr("name")).hide();

Multiple conditions in ngClass - Angular 4

There are multiple ways to write same logic. As it mentioned earlier, you can use object notation or simply expression. However, I think you should not that much logic in HTML. Hard to test and find issue. You can use a getter function to assign the class.

For Instance;

public getCustomCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="getCustomCss()"> Some prop</div>

//OR

get customCss() {
    //Logic here;
    if(this.x == this.y){
        return 'class1'
    }
    if(this.x == this.z){
        return 'class2'
    }
}
<!-- HTML -->
<div [ngClass]="customCss"> Some prop</div>

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

 <textarea style="width:300px; height:150px;" ></textarea>

Convert java.util.Date to String

public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}

angular.js ng-repeat li items with html content

Here is directive from the official examples angular docs v1.5 that shows how to compile html:

.directive('compileHtml', function ($compile) {
  return function (scope, element, attrs) {
    scope.$watch(
      function(scope) {
        return scope.$eval(attrs.compileHtml);
      },
      function(value) {
        element.html(value);
        $compile(element.contents())(scope);
      }
    );
  };
});

Usage:

<div compile-html="item.htmlString"></div>

It will insert item.htmlString property as html any place, like

<li ng-repeat="item in itemList">
    <div compile-html="item.htmlString"></div>

The located assembly's manifest definition does not match the assembly reference

My app.config contains a

<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.11.0"/>

for npgsql. Somehow on the user's machine, my app.exe.config went missing. I am not sure if it was a silly user, installer glitch, or wacked out anti-virus yet. Replacing the file solved the issue.

Maven compile with multiple src directories

I naively do it this way :

<build>
  <finalName>osmwse</finalName>
  <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>
</build>

Check if Key Exists in NameValueCollection

In VB it's:

if not MyNameValueCollection(Key) is Nothing then
.......
end if

In C# should just be:

if (MyNameValueCollection(Key) != null) { }

Not sure if it should be null or "" but this should help.

Equivalent of String.format in jQuery

Many of the above functions (except Julian Jelfs's) contain the following error:

js> '{0} {0} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 3.14 afoobc foo

Or, for the variants that count backwards from the end of the argument list:

js> '{0} {0} {1} {2}'.format(3.14, 'a{0}bc', 'foo');
3.14 3.14 a3.14bc foo

Here's a correct function. It's a prototypal variant of Julian Jelfs's code, which I made a bit tighter:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{(\d+)\}/g, function (m, n) { return args[n]; });
};

And here is a slightly more advanced version of the same, which allows you to escape braces by doubling them:

String.prototype.format = function () {
  var args = arguments;
  return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
    if (m == "{{") { return "{"; }
    if (m == "}}") { return "}"; }
    return args[n];
  });
};

This works correctly:

js> '{0} {{0}} {{{0}}} {1} {2}'.format(3.14, 'a{2}bc', 'foo');
3.14 {0} {3.14} a{2}bc foo

Here is another good implementation by Blair Mitchelmore, with a bunch of nice extra features: https://web.archive.org/web/20120315214858/http://blairmitchelmore.com/javascript/string.format

Space between two rows in a table?

Best way is to add tr between two tr like below,

_x000D_
_x000D_
<tr>
 <td height="5" colspan="2"></td>
</tr>
_x000D_
_x000D_
_x000D_

How can I Remove .DS_Store files from a Git repository?

I had to change git-rm to git rm in the above to get it to work:

find . -depth -name '.DS_Store' -exec git rm --cached '{}' \; -print

How to draw circle by canvas in Android?

Try this

enter image description here

The entire code for drawing a circle or download project source code and test it on your android studio. Draw circle on canvas programmatically.

import android.graphics.Bitmap;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.graphics.Path;
    import android.graphics.Point;
    import android.graphics.PorterDuff;
    import android.graphics.PorterDuffXfermode;
    import android.graphics.Rect;
    import android.graphics.RectF;
    import android.widget.ImageView;


        public class Shape {

            private Bitmap bmp;
            private ImageView img;
            public Shape(Bitmap bmp, ImageView img) {

                this.bmp=bmp;
                this.img=img;
                onDraw();
            }

            private void onDraw(){
                 Canvas canvas=new Canvas();
                 if (bmp.getWidth() == 0 || bmp.getHeight() == 0) {
                     return;
                }

                int w = bmp.getWidth(), h = bmp.getHeight();

                Bitmap roundBitmap = getRoundedCroppedBitmap(bmp, w);

                img.setImageBitmap(roundBitmap);

            }

            public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
                Bitmap finalBitmap;
                if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
                    finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
                            false);
                else
                    finalBitmap = bitmap;
                Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
                        finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
                        finalBitmap.getHeight());

                paint.setAntiAlias(true);
                paint.setFilterBitmap(true);
                paint.setDither(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(Color.parseColor("#BAB399"));
                canvas.drawCircle(finalBitmap.getWidth() / 2 + 0.7f, finalBitmap.getHeight() / 2 + 0.7f, finalBitmap.getWidth() / 2 + 0.1f, paint);
                paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                canvas.drawBitmap(finalBitmap, rect, rect, paint);

                return output;
            }

Swapping pointers in C (char, int)

void intSwap (int *pa, int *pb){
    int temp = *pa;
    *pa = *pb;
    *pb = temp;
}

You need to know the following -

int a = 5; // an integer, contains value
int *p; // an integer pointer, contains address
p = &a; // &a means address of a
a = *p; // *p means value stored in that address, here 5

void charSwap(char* a, char* b){
    char temp = *a;
    *a = *b;
    *b = temp;
}

So, when you swap like this. Only the value will be swapped. So, for a char* only their first char will swap.

Now, if you understand char* (string) clearly, then you should know that, you only need to exchange the pointer. It'll be easier to understand if you think it as an array instead of string.

void stringSwap(char** a, char** b){
    char *temp = *a;
    *a = *b;
    *b = temp;
}

So, here you are passing double pointer because starting of an array itself is a pointer.

Difference between Encapsulation and Abstraction

Let me explain it in with the same example discussed above. Kindly consider the same TV.

Encapsulation: The adjustments we can make with the remote is a good example - Volume UP/DOWN, Color & Contrast - All we can do is adjust it to the min and max value provided and cannot do anything beyond what is provided in the remote - Imagine the getter and setter here(The setter function will check whether the value provided is valid if Yes, it process the operation if not won't allow us to make changes - like we cannot decrease the volume beyond zero even we press the volume down button a hundred times).

Abstraction: We can take the same example here but with a higher Degree/Context. The volume down button will decrease the volume - and this is the info we provide to the user and the user is not aware of neither the infrared transmitter inside the remote nor the receiver in the TV and the subsequent process of parsing the signal and the microprocessor architecture inside the TV. Simply put it is not needed in the context - Just provide what is necessary. One can easily relate the Text book definition here ie., Hiding the inner implementation and only providing what it will do rather than how it do that!

Hope it clarifies a bit!

Any way to clear python's IDLE window?

This works for me in Windows:

print chr(12)

explicit casting from super class to subclass

The code generates a compilation error because your instance type is an Animal:

Animal animal=new Animal();

Downcasting is not allowed in Java for several reasons. See here for details.

sql query to return differences between two tables

Simple variation on @erikkallen answer that shows which table the row is present in:

(   SELECT 'table1' as source, * FROM table1
    EXCEPT
    SELECT * FROM table2)  
UNION ALL
(   SELECT 'table2' as source, * FROM table2
    EXCEPT
    SELECT * FROM table1) 

If you get an error

All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

then it may help to add

(   SELECT 'table1' as source, * FROM table1
    EXCEPT
    SELECT 'table1' as source, * FROM table2)  
UNION ALL
(   SELECT 'table2' as source, * FROM table2
    EXCEPT
    SELECT 'table2' as source, * FROM table1) 

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

With JQuery this stuff is pretty easy to do. Since you can bind to sets.

Its NOT enough to do the onbeforeunload, you want to only trigger the navigate away if someone started editing stuff.

How to determine a Python variable's type?

Simple, for python 3.4 and above

print (type(variable_name))

Python 2.7 and above

print type(variable_name)

How to create a JPA query with LEFT OUTER JOIN

Write this;

 SELECT f from Student f LEFT JOIN f.classTbls s WHERE s.ClassName = 'abc'

Because your Student entity has One To Many relationship with ClassTbl entity.

Using colors with printf

Rather than using archaic terminal codes, may I suggest the following alternative. Not only does it provide more readable code, but it also allows you to keep the color information separate from the format specifiers just as you originally intended.

blue=$(tput setaf 4)
normal=$(tput sgr0)

printf "%40s\n" "${blue}This text is blue${normal}"

See my answer HERE for additional colors

Create a new TextView programmatically then display it below another TextView

You're not assigning any id to the text view, but you're using tv.getId() to pass it to the addRule method as a parameter. Try to set a unique id via tv.setId(int).

You could also use the LinearLayout with vertical orientation, that might be easier actually. I prefer LinearLayout over RelativeLayouts if not necessary otherwise.

How to destroy a JavaScript object?

You could put all of your code under one namespace like this:

var namespace = {};

namespace.someClassObj = {};

delete namespace.someClassObj;

Using the delete keyword will delete the reference to the property, but on the low level the JavaScript garbage collector (GC) will get more information about which objects to be reclaimed.

You could also use Chrome Developer Tools to get a memory profile of your app, and which objects in your app are needing to be scaled down.

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Copy row but with new id

Let us say your table has following fields:

( pk_id int not null auto_increment primary key,
  col1 int,
  col2 varchar(10)
)

then, to copy values from one row to the other row with new key value, following query may help

insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;

This will generate a new value for pk_id field and copy values from col1, and col2 of the selected row.

You can extend this sample to apply for more fields in the table.

UPDATE:
In due respect to the comments from JohnP and Martin -

We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.

With reference to the answer by Tim Ruehsen in the referred posting:

CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...;
ALTER TABLE tmp drop pk_id; # drop autoincrement field
# UPDATE tmp SET ...; # just needed to change other unique keys
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
DROP TEMPORARY TABLE tmp;

Hope this helps.

Is it possible to get a list of files under a directory of a website? How?

If you have directory listing disabled in your webserver, then the only way somebody will find it is by guessing or by finding a link to it.

That said, I've seen hacking scripts attempt to "guess" a whole bunch of these common names. "secret.html" would probably be in such a guess list.

The more reasonable solution is to restrict access using a username/password via a htaccess file (for apache) or the equivalent setting for whatever webserver you're using.

Store output of subprocess.Popen call in a string

Use check_output method of subprocess module

import subprocess

address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])

Finally parse the string

for line in res.splitlines():

Hope it helps, happy coding

How do I create a comma delimited string from an ArrayList?

Something like:

String.Join(",", myArrayList.toArray(string.GetType()) );

Which basically loops ya know...

EDIT

how about:

string.Join(",", Array.ConvertAll<object, string>(a.ToArray(), Convert.ToString));

Pass values of checkBox to controller action in asp.net mvc4

None of the previous solutions worked for me. Finally I found that the action should be coded as:

public ActionResult Index(string MyCheck = null)

and then, when checked the passed value was "on", not "true". Else, it is always null.

Hope it helps somebody!

how to loop through json array in jquery?

var data=[{'com':'something'},{'com':'some other thing'}];
$.each(data, function() {
  $.each(this, function(key, val){
    alert(val);//here data 
      alert (key); //here key

  });
});

JQuery show/hide when hover

('.cat').hover(
  function () {
    $(this).show();
  }, 
  function () {
    $(this).hide();
  }
);

It's the same for the others.

For the smooth fade in you can use fadeIn and fadeOut

Connect to sqlplus in a shell script and run SQL scripts

Wouldn't something akin to this be better, security-wise?:

sqlplus -s /nolog << EOF
CONNECT admin/password;

whenever sqlerror exit sql.sqlcode;
set echo off 
set heading off

@pl_script_1.sql
@pl_script_2.sql

exit;
EOF 

MongoDB - admin user not authorized

I followed these steps on Centos 7 for MongoDB 4.2. (Remote user)

Update mongod.conf file

vi /etc/mongod.conf
   net:
     port: 27017
     bindIp: 0.0.0.0 
   security:
     authorization: enabled

Start MongoDB service demon

systemctl start mongod

Open MongoDB shell

mongo

Execute this command on the shell

use admin
db.createUser(
  {
    user: 'admin',
    pwd: 'YouPassforUser',
    roles: [ { role: 'root', db: 'admin' } ]
  }
);

Remote root user has been created. Now you can test this database connection by using any MongoDB GUI tool from your dev machine. Like Robo 3T

HTML combo box with option to type an entry

This one is much smaller, doesn't require jquery and works better in safari. https://github.com/Fyrd/purejs-datalist-polyfill/

Check the issues for the modification to add a downarrow. https://github.com/Fyrd/purejs-datalist-polyfill/issues

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

Correct way to create rounded corners in Twitter Bootstrap

I guess it is what you are looking for: http://blogsh.de/tag/bootstrap-less/

@import 'bootstrap.less';
div.my-class {
    .border-radius( 5px );
}

You can use it because there is a mixin:

.border-radius(@radius: 5px) {
  -webkit-border-radius: @radius;
     -moz-border-radius: @radius;
          border-radius: @radius;
}

For Bootstrap 3, there are 4 mixins you can use...

.border-top-radius(@radius);
.border-right-radius(@radius);
.border-bottom-radius(@radius);
.border-left-radius(@radius);

or you can make your own mixin using the top 4 to do it in one shot.

.border-radius(@radius){
    .border-top-radius(@radius);
    .border-right-radius(@radius);
    .border-bottom-radius(@radius);
    .border-left-radius(@radius);
}

Getting the screen resolution using PHP

<script type="text/javascript">

if(screen.width <= 699){
    <?php $screen = 'mobile';?>
}else{
    <?php $screen = 'default';?>
}

</script>

<?php echo $screen; ?> 

Naming Conventions: What to name a boolean variable?

My vote would be to name it IsLast and change the functionality. If that isn't really an option, I'd leave the name as IsNotLast.

I agree with Code Complete (Use positive boolean variable names), I also believe that rules are made to be broken. The key is to break them only when you absoluately have to. In this case, none of the alternative names are as clear as the name that "breaks" the rule. So this is one of those times where breaking the rule can be okay.

Find a string by searching all tables in SQL Server Management Studio 2008

To update TechDo's answer for SQL server 2012. You need to change: 'FROM ' + @TableName + ' (NOLOCK) ' to FROM ' + @TableName + 'WITH (NOLOCK) ' +

Other wise you will get the following error: Deprecated feature 'Table hint without WITH' is not supported in this version of SQL Server.

Below is the complete updated stored procedure:

CREATE PROC SearchAllTables
(
@SearchStr nvarchar(100)
)
AS
BEGIN

    CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
    SET  @TableName = ''
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    WHILE @TableName IS NOT NULL

    BEGIN
        SET @ColumnName = ''
        SET @TableName = 
        (
            SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
            FROM     INFORMATION_SCHEMA.TABLES
            WHERE         TABLE_TYPE = 'BASE TABLE'
                AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                AND    OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                             ), 'IsMSShipped'
                               ) = 0
        )

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)

        BEGIN
            SET @ColumnName =
            (
                SELECT MIN(QUOTENAME(COLUMN_NAME))
                FROM     INFORMATION_SCHEMA.COLUMNS
                WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                    AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                    AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                    AND    QUOTENAME(COLUMN_NAME) > @ColumnName
            )

            IF @ColumnName IS NOT NULL

            BEGIN
                INSERT INTO #Results
                EXEC
                (
                    'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + 'WITH (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END    
    END

    SELECT ColumnName, ColumnValue FROM #Results
END

Private vs Protected - Visibility Good-Practice Concern

Stop abusing private fields!!!

The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.

Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.

There are two cases you want to extend a class:

  • You want to add extra functionality to a base class
  • You want to modify existing class that's outside the current package (in some libraries perhaps)

There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.

Consider a simple library that models cars:

class Car {
    private screw;
    public assembleCar() {
       screw.install();
    };
    private putScrewsTogether() {
       ...
    };
}

The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.

Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.

Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.

The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.

I very much support Nick's answer.

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

Visual Studio window which shows list of methods

Shortcut to Navigation Bar is Ctrl+F2. Takes you to the types dropdown first. Press tab to go to method dropdown, and then enter on a method to go to that one.

Difference between signed / unsigned char

The same way -- e.g. if you have an 8-bit char, 7 bits can be used for magnitude and 1 for sign. So an unsigned char might range from 0 to 255, whilst a signed char might range from -128 to 127 (for example).

How do I return multiple values from a function?

Python's tuples, dicts, and objects offer the programmer a smooth tradeoff between formality and convenience for small data structures ("things"). For me, the choice of how to represent a thing is dictated mainly by how I'm going to use the structure. In C++, it's a common convention to use struct for data-only items and class for objects with methods, even though you can legally put methods on a struct; my habit is similar in Python, with dict and tuple in place of struct.

For coordinate sets, I'll use a tuple rather than a point class or a dict (and note that you can use a tuple as a dictionary key, so dicts make great sparse multidimensional arrays).

If I'm going to be iterating over a list of things, I prefer unpacking tuples on the iteration:

for score,id,name in scoreAllTheThings():
    if score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(score,id,name)

...as the object version is more cluttered to read:

for entry in scoreAllTheThings():
    if entry.score > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry.score,entry.id,entry.name)

...let alone the dict.

for entry in scoreAllTheThings():
    if entry['score'] > goodScoreThreshold:
        print "%6.3f #%6d %s"%(entry['score'],entry['id'],entry['name'])

If the thing is widely used, and you find yourself doing similar non-trivial operations on it in multiple places in the code, then it's usually worthwhile to make it a class object with appropriate methods.

Finally, if I'm going to be exchanging data with non-Python system components, I'll most often keep them in a dict because that's best suited to JSON serialization.

Play audio with Python

You can find information about Python audio here: http://wiki.python.org/moin/Audio/

It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like PyMedia.

How to open an elevated cmd using command line for Windows?

For fans of Cygwin:

cygstart -a runas cmd

javac: invalid target release: 1.8

I got the same issue with netbeans, but mvn build is OK in cmd window. For me the issue resolved after changing netbeans' JDK (in netbeans.conf as below),

netbeans_jdkhome="C:\Program Files\Java\jdk1.8.0_91"


Edit: Seems it's mentioned here: netbeans bug 236364

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

Generally you cannot translate from a time zone like Asia/Kolkata to a GMT offset like +05:30 or +07:00. A time zone, as the name says, is a place on earth and comprises the historic, present and known future UTC offsets used by the people in that place (for now we can regard GMT and UTC as synonyms, strictly speaking they are not). For example, Asia/Kolkata has been at offset +05:30 since 1945. During periods between 1941 and 1945 it was at +06:30 and before that time at +05:53:20 (yes, with seconds precision). Many other time zones have summer time (daylight saving time, DST) and change their offset twice a year.

Given a point in time, we can make the translation for that particular point in time, though. I should like to provide the modern way of doing that.

java.time and ThreeTenABP

    ZoneId zone = ZoneId.of("Asia/Kolkata");

    ZoneOffset offsetIn1944 = LocalDateTime.of(1944, Month.JANUARY, 1, 0, 0)
            .atZone(zone)
            .getOffset();
    System.out.println("Offset in 1944: " + offsetIn1944);

    ZoneOffset offsetToday = OffsetDateTime.now(zone)
            .getOffset();
    System.out.println("Offset now: " + offsetToday);

Output when running just now was:

Offset in 1944: +06:30
Offset now: +05:30

For the default time zone set zone to ZoneId.systemDefault().

To format the offset with the text GMT use a formatter with OOOO (four uppercase letter O) in the pattern:

    DateTimeFormatter offsetFormatter = DateTimeFormatter.ofPattern("OOOO");
    System.out.println(offsetFormatter.format(offsetToday));

GMT+05:30

I am recommending and in my code I am using java.time, the modern Java date and time API. The TimeZone, Calendar, Date, SimpleDateFormat and DateFormat classes used in many of the other answers are poorly designed and now long outdated, so my suggestion is to avoid all of them.

Question: Can I use java.time on Android?

Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

Can you try to change your json without data key like below?

[{"target_id":9503123,"target_type":"user"}]

Determine if Python is running inside virtualenv

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv's bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.

PHP mkdir: Permission denied problem

Fix the permissions of the directory you try to create a directory in.

Can I use wget to check , but not download

If you are in a directory where only root have access to write in system. Then you can directly use wget www.example.com/wget-test using a standard user account. So it will hit the url but because of having no write permission file won't be saved.. This method is working fine for me as i am using this method for a cronjob. Thanks.

sthx

FileNotFoundException while getting the InputStream object from HttpURLConnection

Please change

con = (HttpURLConnection) new URL("http://localhost:8080/myapp/service/generate").openConnection();

To

con = (HttpURLConnection) new URL("http://YOUR_IP:8080/myapp/service/generate").openConnection();

How can I get the browser's scrollbar sizes?

You can determine window scroll bar with document as below using jquery + javascript:

var scrollbarWidth = ($(document).width() - window.innerWidth);
console.info("Window Scroll Bar Width=" + scrollbarWidth );

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Below are some of the way by which you can create a link button in MVC.

@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)  
@Html.RouteLink("Admin", new { action = "Index", controller = "Home", area = "Admin" })  
@Html.Action("Action", "Controller", new { area = "AreaName" })  
@Url.Action("Action", "Controller", new { area = "AreaName" })  
<a class="ui-btn" data-val="abc" href="/Home/Edit/ANTON">Edit</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Germany">Customer from Germany</a>  
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#CustomerList" href="/Home/Mexico">Customer from Mexico</a> 

Hope this will help you.

Calculate a Running Total in SQL Server

You can also denormalize - store running totals in the same table:

http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/01/23/denormalizing-to-enforce-business-rules-running-totals.aspx

Selects work much faster than any other solutions, but modifications may be slower

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

First see your code:

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

Here you set both visibility to same field so that's the problem. I give one sample for that sample demo

How to edit a JavaScript alert box title?

I had a similar issue when I wanted to change the box title and button title of the default confirm box. I have gone for the Jquery Ui dialog plugin http://jqueryui.com/dialog/#modal-confirmation

When I had the following:

function testConfirm() {
  if (confirm("Are you sure you want to delete?")) {
    //some stuff
  }
}

I have changed it to:

function testConfirm() {

  var $dialog = $('<div></div>')
    .html("Are you sure you want to delete?")
    .dialog({
      resizable: false,
      title: "Confirm Deletion",
      modal: true,
      buttons: {
        Cancel: function() {
          $(this).dialog("close");
        },
        "Delete": function() {
          //some stuff
          $(this).dialog("close");
        }
      }
    });

  $dialog.dialog('open');
}

Can be seen working here https://jsfiddle.net/5aua4wss/2/

Hope that helps.

semaphore implementation

Vary the consumer-rate and the producer-rate (using sleep), to better understand the operation of code. The code below is the consumer-producer simulation (over a max-limit on container).

Code for your reference:

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t semP, semC;
int stock_count = 0;
const int stock_max_limit=5;

void *producer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(stock_max_limit == stock_count){
            printf("stock overflow, production on wait..\n");
            sem_wait(&semC);
            printf("production operation continues..\n");
        }

        sleep(1);   //production decided here
        stock_count++;
        printf("P::stock-count : %d\n",stock_count);
        sem_post(&semP);
        printf("P::post signal..\n");
    }
 }

void *consumer(void *arg) {
    int i, sum=0;
    for (i = 0; i < 10; i++) {

        while(0 == stock_count){
            printf("stock empty, consumer on wait..\n");
            sem_wait(&semP);
            printf("consumer operation continues..\n");
        }

        sleep(2);   //consumer rate decided here
        stock_count--;
        printf("C::stock-count : %d\n", stock_count);
        sem_post(&semC);
        printf("C::post signal..\n");
        }
}

int main(void) {

    pthread_t tid0,tid1;
    sem_init(&semP, 0, 0);
    sem_init(&semC, 0, 0);

        pthread_create(&tid0, NULL, consumer, NULL);
        pthread_create(&tid1, NULL, producer, NULL);
        pthread_join(tid0, NULL);
        pthread_join(tid1, NULL);

    sem_destroy(&semC);
    sem_destroy(&semP);

    return 0;
}

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

How to automatically generate a stacktrace when my program crashes

I would use the code that generates a stack trace for leaked memory in Visual Leak Detector. This only works on Win32, though.

What is the equivalent to getLastInsertId() in Cakephp?

Try to use this code. try to set it to a variable so you can use it in other functions. :)

$variable = $this->ModelName->getLastInsertId();

in PHP native, try this.

$variable = mysqli_insert_id();

How to add (vertical) divider to a horizontal LinearLayout?

In order to get drawn, divider of LinearLayout must have some height while ColorDrawable (which is essentially #00ff00 as well as any other hardcoded color) doesn't have. Simple (and correct) way to solve this, is to wrap your color into some Drawable with predefined height, such as shape drawable

A quick and easy way to join array elements with a separator (the opposite of split) in Java

Using Java 8 you can do this in a very clean way:

String.join(delimiter, elements);

This works in three ways:

1) directly specifying the elements

String joined1 = String.join(",", "a", "b", "c");

2) using arrays

String[] array = new String[] { "a", "b", "c" };
String joined2 = String.join(",", array);

3) using iterables

List<String> list = Arrays.asList(array);
String joined3 = String.join(",", list);

Recover sa password

best answer written by Dmitri Korotkevitch:

Speaking of the installation, SQL Server 2008 allows you to set authentication mode (Windows or SQL Server) during the installation process. You will be forced to choose the strong password for sa user in the case if you choose sql server authentication mode during setup.

If you install SQL Server with Windows Authentication mode and want to change it, you need to do 2 different things:

  1. Go to SQL Server Properties/Security tab and change the mode to SQL Server authentication mode

  2. Go to security/logins, open SA login properties

a. Uncheck "Enforce password policy" and "Enforce password expiration" check box there if you decide to use weak password

b. Assign password to SA user

c. Open "Status" tab and enable login.

I don't need to mention that every action from above would violate security best practices that recommend to use windows authentication mode, have sa login disabled and use strong passwords especially for sa login.

How to determine the current iPhone/device model?

I've implemented a super-lightweight library to detect the used device based on some of the given answers: https://github.com/schickling/Device.swift

It can be installed via Carthage and be used like this:

import Device

let deviceType = UIDevice.currentDevice().deviceType

switch deviceType {
case .IPhone6: print("Do stuff for iPhone6")
case .IPadMini: print("Do stuff for iPad mini")
default: print("Check other available cases of DeviceType")
}

Number of elements in a javascript object

if you are already using jQuery in your build just do this:

$(yourObject).length

It works nicely for me on objects, and I already had jQuery as a dependancy.

SQL Server Jobs with SSIS packages - Failed to decrypt protected XML node "DTS:Password" with error 0x8009000B

Change both Project and Package Properties ProtectionLevel to "DontSaveSensitive"

SoapFault exception: Could not connect to host

Version check helped me OpenSSL. OpenSSL_1_0_1f not supported TSLv.1_2 ! Check version and compatibility with TSLv.1_2 on github openssl/openssl . And regenerate your certificate with new openssl

openssl pkcs12 -in path.p12 -out newfile.pem

P.S I don’t know what they were minus, but this solution will really help.

How to access SOAP services from iPhone

I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient (soapclient) that is open source (BSD licensed) and available on Google Code (mac-soapclient) that might be of interest.

I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs.

Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: wsdl2objc

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

Since Node.js 6.4.0, this can be elegantly solved with util.inspect.defaultOptions:

require("util").inspect.defaultOptions.depth = null;
console.log(myObject);

Android: How to create a Dialog without a title?

Here's something you can do with AlertBuilder to make the title disappear:

TextView title = new TextView(this);
title.setVisibility(View.GONE);
builder.setCustomTitle(title);

How to fetch JSON file in Angular 2

i think the assets folder is public, you can access it directly on the browser

http://localhost:4020/assets/

unlike other privates folders, drop your json file in the assets folder

How do I select an element in jQuery by using a variable for the ID?

row = $("body").find('#' + row_id);

More importantly doing the additional body.find has no impact on performance. The proper way to do this is simply:

row = $('#' + row_id);

How to install latest version of openssl Mac OS X El Capitan

Execute following commands:

brew update
brew install openssl
echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

You will have the latest version of openssl installed and accessible from cli (command line/terminal). Since the third command will add export path to .bash_profile, the newly installed version of openssl will be accessible across system restarts.

Windows batch: sleep

For a pure cmd.exe script, you can use this piece of code that returns the current time in hundreths of seconds.

:gettime
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

You may then use it in a wait loop like this.

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

And putting all pieces together:

@echo off
setlocal enableextensions enabledelayedexpansion

call :gettime t1
echo %t1%
call :wait %1
call :gettime t2
echo %t2%
set /A tt = (t2-t1)/100
echo %tt%
goto :eof

:wait
call :gettime wait0
:w2
call :gettime wait1
set /A waitt = wait1-wait0
if !waitt! lss %1 goto :w2
goto :eof

:gettime 
set hh=%time:~0,2%
set mm=%time:~3,2%
set ss=%time:~6,2%
set cc=%time:~-2%
set /A %1=hh*360000+mm*6000+ss*100+cc
goto :eof

For a more detailed description of the commands used here, check HELP SET and HELP CALL information.