Programs & Examples On #Game development

Questions directly related to programming computer gaming and interactive graphics/video. Questions involving game logic or general game development (which are off-topic here)should be asked at https://gamedev.stackexchange.com/

What are my options for storing data when using React Native? (iOS and Android)

you can use Realm or Sqlite if you want to manage complex data type.

Otherwise go with inbuilt react native asynstorage

Proper MIME type for .woff2 fonts

In IIS you can declare the mime type for WOFF2 font files by adding the following to your project's web.config:

<system.webServer>
  <staticContent>
    <remove fileExtension=".woff2" />
    <mimeMap fileExtension=".woff2" mimeType="font/woff2" />
  </staticContent>
</system.webServer>

Update: The mime type may be changing according to the latest W3C Editor's Draft WOFF2 spec. See Appendix A: Internet Media Type Registration section 6.5. WOFF 2.0 which states the latest proposed format is font/woff2

'Incomplete final line' warning when trying to read a .csv file into R

The problem that you're describing occurred for me when I renamed a .xlsx as .csv.

What fixed it for me was going "Save As" and then saving it as a .csv again.

How to find numbers from a string?

Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements

Sub Tester()
     MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub

Function CleanString(strIn As String) As String
    Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
     .Global = True
     .Pattern = "[^\d]+"
    CleanString = .Replace(strIn, vbNullString)
    End With
End Function

What is the best way to get the minimum or maximum value from an Array of numbers?

This depends on real world application requirements.

If your question is merely hypothetical, then the basics have already been explained. It is a typical search vs. sort problem. It has already been mentioned that algorithmically you are not going to achieve better than O(n) for that case.

However, if you are looking at practical use, things get more interesting. You would then need to consider how large the array is, and the processes involved in adding and removing from the data set. In these cases, it can be best to take the computational 'hit' at insertion / removal time by sorting on the fly. Insertions into a pre-sorted array are not that expensive.

The quickest query response to the Min Max request will always be from a sorted array, because as others have mentioned, you simply take the first or last element - giving you an O(1) cost.

For a bit more of a technical explanation on the computational costs involved, and Big O notation, check out the Wikipedia article here.

Nick.

How to check empty object in angular 2 template using *ngIf

Above answers are okay. But I have found a really nice option to use following in the view:

{{previous_info?.title}}

probably duplicated question Angular2 - error if don't check if {{object.field}} exists

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

In my case, the reason was a simple typo.

<parent>
    <groupId>org.sringframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

A missing character in the groupId org.s(p)ringframework lead to this error.

CSS full screen div with text in the middle

The standard approach is to give the centered element fixed dimensions, and place it absolutely:

<div class='fullscreenDiv'>
    <div class="center">Hello World</div>
</div>?

.center {
    position: absolute;
    width: 100px;
    height: 50px;
    top: 50%;
    left: 50%;
    margin-left: -50px; /* margin is -0.5 * dimension */
    margin-top: -25px; 
}?

What is the maximum recursion depth in Python, and how to increase it?

As @alex suggested, you could use a generator function to do this sequentially instead of recursively.

Here's the equivalent of the code in your question:

def fib(n):
    def fibseq(n):
        """ Iteratively return the first n Fibonacci numbers, starting from 0. """
        a, b = 0, 1
        for _ in xrange(n):
            yield a
            a, b = b, a + b

    return sum(v for v in fibseq(n))

print format(fib(100000), ',d')  # -> no recursion depth error

Angular HTTP GET with TypeScript error http.get(...).map is not a function in [null]

Just add the line in you file,

import 'rxjs/Rx';

It will import bunch of dependencies.Tested in angular 5

Where can I download english dictionary database in a text format?

The Gutenberg Project hosts Webster's Unabridged English Dictionary plus many other public domain literary works. Actually it looks like they've got several versions of the dictionary hosted with copyright from different years. The one I linked has a 2009 copyright. You may want to poke around the site and investigate the different versions of Webster's dictionary.

Turn off iPhone/Safari input element rounding

On iOS 5 and later:

input {
  border-radius: 0;
}

input[type="search"] {
  -webkit-appearance: none;
}

If you must only remove the rounded corners on iOS or otherwise for some reason cannot normalize rounded corners across platforms, use input { -webkit-border-radius: 0; } property instead, which is still supported. Of course do note that Apple can choose to drop support for the prefixed property at any time, but considering their other platform-specific CSS features chances are they'll keep it around.

On legacy versions you had to set -webkit-appearance: none instead:

input {
    -webkit-appearance: none;
}

How to read a file without newlines?

def getText():
    file=open("ex1.txt","r");

    names=file.read().split("\n");
    for x,word in enumerate(names):
        if(len(word)>=20):
            return 0;
            print "length of ",word,"is over 20"
            break;
        if(x==20):
            return 0;
            break;
    else:
        return names;


def show(names):
    for word in names:
        len_set=len(set(word))
        print word," ",len_set


for i in range(1):

    names=getText();
    if(names!=0):
        show(names);
    else:
        break;

SQL How to remove duplicates within select query?

here is the solution for your query returning only one row for each date in that table here in the solution 'tony' will occur twice as two different start dates are there for it

SELECT * FROM 
(
    SELECT T1.*, ROW_NUMBER() OVER(PARTITION BY TRUNC(START_DATE),OWNER_NAME ORDER BY 1,2 DESC )  RNM
    FROM TABLE T1
)
WHERE RNM=1

python: iterate a specific range in a list

By using iter builtin:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)

Select mysql query between date?

Late answer, but the accepted answer didn't work for me.
If you set both start and end dates manually (not using curdate()), make sure to specify the hours, minutes and seconds (2019-12-02 23:59:59) on the end date or you won't get any results from that day, i.e.:

This WILL include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02 23:59:59'

This WON'T include records from 2019-12-02:

SELECT *SOMEFIELDS* FROM *YOURTABLE* where *YOURDATEFIELD* between '2019-12-01' and '2019-12-02'

Create a new object from type parameter in generic class

This is what I do to retain type info:

class Helper {
   public static createRaw<T>(TCreator: { new (): T; }, data: any): T
   {
     return Object.assign(new TCreator(), data);
   }
   public static create<T>(TCreator: { new (): T; }, data: T): T
   {
      return this.createRaw(TCreator, data);
   }
}

...

it('create helper', () => {
    class A {
        public data: string;
    }
    class B {
        public data: string;
        public getData(): string {
            return this.data;
        }
    }
    var str = "foobar";

    var a1 = Helper.create<A>(A, {data: str});
    expect(a1 instanceof A).toBeTruthy();
    expect(a1.data).toBe(str);

    var a2 = Helper.create(A, {data: str});
    expect(a2 instanceof A).toBeTruthy();
    expect(a2.data).toBe(str);

    var b1 = Helper.createRaw(B, {data: str});
    expect(b1 instanceof B).toBeTruthy();
    expect(b1.data).toBe(str);
    expect(b1.getData()).toBe(str);

});

Difference between a Seq and a List in Scala

In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :

sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...

[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]

syntaxerror: unexpected character after line continuation character in python

Replace

f = open(D\\python\\HW\\2_1 - Copy.cp,"r");

by

f = open("D:\\python\\HW\\2_1 - Copy.cp", "r")

  1. File path needs to be a string (constant)
  2. need colon in Windows file path
  3. space after comma for better style
  4. ; after statement is allowed but fugly.

What tutorial are you using?

Software Design vs. Software Architecture

I found this as I was looking for simple distinction between architecture and design myself;
What do you think of this way of looking at them:

  • architecture is "what" we're building;
  • design is "how" we're building;

JBoss default password

as suggested in other posts, probably you don't have any user defined. it's not advisable to manually edit the configuration files. you should use the add-user (.sh or .cmd) utility as explained in https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6/html/Installation_Guide/chap-Getting_Started_with_JBoss_Enterprise_Application_Platform_6.html#Add_the_Initial_User_for_the_Management_Interfaces

Greater than less than, python

Check to make sure that both score and array[x] are numerical types. You might be comparing an integer to a string...which is heartbreakingly possible in Python 2.x.

>>> 2 < "2"
True
>>> 2 > "2"
False
>>> 2 == "2"
False

Edit

Further explanation: How does Python compare string and int?

Display a view from another controller in ASP.NET MVC

With this code you can obtain any controller:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, 
controller);

proper way to sudo over ssh

I was able to fully automate it with the following command:

echo pass | ssh -tt user@server "sudo script"

Advantages:

  • no password prompt
  • won't show password in remote machine bash history

Regarding security: as Kurt said, running this command will show your password on your local bash history, and it's better to save the password in a different file or save the all command in a .sh file and execute it. NOTE: The file need to have the correct permissions so that only the allowed users can access it.

Date Difference in php on days?

Below code will give the output for number of days, by taking out the difference between two dates..

$str = "Jul 02 2013";
$str = strtotime(date("M d Y ")) - (strtotime($str));
echo floor($str/3600/24);

How to find the duration of difference between two dates in java?

In Java 8, you can make of DateTimeFormatter, Duration, and LocalDateTime. Here is an example:

final String dateStart = "11/03/14 09:29:58";
final String dateStop = "11/03/14 09:33:43";

final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendValue(ChronoField.MONTH_OF_YEAR, 2)
        .appendLiteral('/')
        .appendValue(ChronoField.DAY_OF_MONTH, 2)
        .appendLiteral('/')
        .appendValueReduced(ChronoField.YEAR, 2, 2, 2000)
        .appendLiteral(' ')
        .appendValue(ChronoField.HOUR_OF_DAY, 2)
        .appendLiteral(':')
        .appendValue(ChronoField.MINUTE_OF_HOUR, 2)
        .appendLiteral(':')
        .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
        .toFormatter();

final LocalDateTime start = LocalDateTime.parse(dateStart, formatter);
final LocalDateTime stop = LocalDateTime.parse(dateStop, formatter);

final Duration between = Duration.between(start, stop);

System.out.println(start);
System.out.println(stop);
System.out.println(formatter.format(start));
System.out.println(formatter.format(stop));
System.out.println(between);
System.out.println(between.get(ChronoUnit.SECONDS));

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

TypeError: document.getElementbyId is not a function

JavaScript is case-sensitive. The b in getElementbyId should be capitalized.

var content = document.getElementById("edit").innerHTML;

Single-threaded apartment - cannot instantiate ActiveX control

The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.

You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.

var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

It looks like, cargo can have one or more item. Each item would have a reference to its corresponding cargo.

From the log, item object is inserted first and then an attempt is made to update the cargo object (which does not exist).

I guess what you actually want is cargo object to be created first and then the item object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.

How to restore SQL Server 2014 backup in SQL Server 2008

Not really as far as I know but here are couple things you can try.

Third party tools: Create empty database on 2008 instance and use third party tools such as ApexSQL Diff and Data Diff to synchronize schema and tables.

Just use these (or any other on the market such as Red Gate, Idera, Dev Art, there are many similar) in trial mode to get the job done.

Generate scripts: Go to Tasks -> Generate Scripts, select option to script the data too and execute it on 2008 instance. Works just fine but note that script order is something you must be careful about. By default scripts are not ordered to take dependencies into account.

jQuery How to Get Element's Margin and Padding?

I've a snippet that shows, how to get the spacings of elements with jQuery:

/* messing vertical spaces of block level elements with jQuery in pixels */

console.clear();

var jObj = $('selector');

for(var i = 0, l = jObj.length; i < l; i++) {
  //jObj.eq(i).css('display', 'block');
  console.log('jQuery object:', jObj.eq(i));
  console.log('plain element:', jObj[i]);

  console.log('without spacings                - jObj.eq(i).height():         ', jObj.eq(i).height());
  console.log('with padding                    - jObj[i].clientHeight:        ', jObj[i].clientHeight);
  console.log('with padding and border         - jObj.eq(i).outerHeight():    ', jObj.eq(i).outerHeight());
  console.log('with padding, border and margin - jObj.eq(i).outerHeight(true):', jObj.eq(i).outerHeight(true));
  console.log('total vertical spacing:                                        ', jObj.eq(i).outerHeight(true) - jObj.eq(i).height());
}

Sorting an Array of int using BubbleSort

public static void BubbleSort(int[] array){
        boolean swapped ;
        do {
            swapped = false;
            for (int i = 0; i < array.length - 1; i++) {
                if (array[i] > array[i + 1]) {
                    int temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                    swapped = true;
                }
            }
        }while (swapped);
    }

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file

~/.bash_profile 

and append those lines

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

Java: Why is the Date constructor deprecated, and what do I use instead?

new GregorianCalendar(1985, Calendar.JANUARY, 1).getTime();

(the pre-Java-8 way)

How to write URLs in Latex?

You can use \url

\usepackage{hyperref}
\url{http://stackoverflow.com/}

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Visual C++: How to disable specific linker warnings?

Update 2018-10-16

Reportedly, as of VS 2013, this warning can be disabled. See the comment by @Mark Ransom.

Original Answer

You can't disable that specific warning.

According to Geoff Chappell the 4099 warning is treated as though it's too important to ignore, even by using in conjunction with /wx (which would treat warnings as errors and ignore the specified warning in other situations)

Here is the relevant text from the link:

Not Quite Unignorable Warnings

For some warning numbers, specification in a /ignore option is accepted but not necessarily acted upon. Should the warning occur while the /wx option is not active, then the warning message is still displayed, but if the /wx option is active, then the warning is ignored. It is as if the warning is thought important enough to override an attempt at ignoring it, but not if the user has put too high a price on unignored warnings.

The following warning numbers are affected:

4200, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4219, 4231 and 4237

How to remove all .svn directories from my application directories

In Windows, you can use the following registry script to add "Delete SVN Folders" to your right click context menu. Run it on any directory containing those pesky files.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN]
@="Delete SVN Folders"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Folder\shell\DeleteSVN\command]
@="cmd.exe /c \"TITLE Removing SVN Folders in %1 && COLOR 9A && FOR /r \"%1\" %%f IN (.svn) DO RD /s /q \"%%f\" \""

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

libstdc++-6.dll not found

I placed the libstdc++-6.dll file in the same folder where exe file is generated.

Android SDK Manager Not Installing Components

In windows 8:

  • right click on windows button
  • List item
  • CDM as administrator
  • Press 'yes'
  • paste this $ C:\xxx\xxx\AppData\Local\Android\sdk\tools\android.bat

LINQ Group By into a Dictionary Object

Dictionary<string, List<CustomObject>> myDictionary = ListOfCustomObjects
    .GroupBy(o => o.PropertyName)
    .ToDictionary(g => g.Key, g => g.ToList());

How to get thread id of a pthread in linux c program?

There is also another way of getting thread id. While creating threads with

int pthread_create(pthread_t * thread, const pthread_attr_t * attr, void * (*start_routine)(void *), void *arg);

function call; the first parameter pthread_t * thread is actually a thread id (that is an unsigned long int defined in bits/pthreadtypes.h). Also, the last argument void *arg is the argument that is passed to void * (*start_routine) function to be threaded.

You can create a structure to pass multiple arguments and send a pointer to a structure.

typedef struct thread_info {
    pthread_t thread;
    //...
} thread_info;
//...
tinfo = malloc(sizeof(thread_info) * NUMBER_OF_THREADS);
//...
pthread_create (&tinfo[i].thread, NULL, handler, (void*)&tinfo[i]);
//...
void *handler(void *targs) {
    thread_info *tinfo = targs;
    // here you get the thread id with tinfo->thread
}

Fastest way to convert an iterator to a list

since python 3.5 you can use * iterable unpacking operator:

user_list = [*your_iterator]

but the pythonic way to do it is:

user_list  = list(your_iterator)

Stop executing further code in Java

Either return; from the method early, or throw an exception.

There is no other way to prevent further code from being executed short of exiting the process completely.

How can I access Oracle from Python?

In addition to the Oracle instant client, you may also need to install the Oracle ODAC components and put the path to them into your system path. cx_Oracle seems to need access to the oci.dll file that is installed with them.

Also check that you get the correct version (32bit or 64bit) of them that matches your: python, cx_Oracle, and instant client versions.

Create thumbnail image

Here is a complete example of how to create a smaller image (thumbnail). This snippet resizes the Image, rotates it when needed (if a phone was held vertically) and pads the image if you want to create square thumbs. This snippet creates a JPEG, but it can easily be modified for other file types. Even if the image would be smaller than the max allowed size the image will still be compressed and it's resolution altered to create images of the same dpi and compression level.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

//set the resolution, 72 is usually good enough for displaying images on monitors
float imageResolution = 72;

//set the compression level. higher compression = better quality = bigger images
long compressionLevel = 80L;


public Image resizeImage(Image image, int maxWidth, int maxHeight, bool padImage)
{
    int newWidth;
    int newHeight;

    //first we check if the image needs rotating (eg phone held vertical when taking a picture for example)
    foreach (var prop in image.PropertyItems)
    {
        if (prop.Id == 0x0112)
        {
            int orientationValue = image.GetPropertyItem(prop.Id).Value[0];
            RotateFlipType rotateFlipType = getRotateFlipType(orientationValue);
            image.RotateFlip(rotateFlipType);
            break;
        }
    }

    //apply the padding to make a square image
    if (padImage == true)
    {
        image = applyPaddingToImage(image, Color.Red);
    }

    //check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
    if (image.Width > maxWidth || image.Height > maxHeight)
    {
        double ratioX = (double)maxWidth / image.Width;
        double ratioY = (double)maxHeight / image.Height;
        double ratio = Math.Min(ratioX, ratioY);

        newWidth = (int)(image.Width * ratio);
        newHeight = (int)(image.Height * ratio);
    }
    else
    {
        newWidth = image.Width;
        newHeight = image.Height;
    }

    //start the resize with a new image
    Bitmap newImage = new Bitmap(newWidth, newHeight);

    //set the new resolution
    newImage.SetResolution(imageResolution, imageResolution);

    //start the resizing
    using (var graphics = Graphics.FromImage(newImage))
    {
        //set some encoding specs
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        graphics.DrawImage(image, 0, 0, newWidth, newHeight);
    }

    //save the image to a memorystream to apply the compression level
    using (MemoryStream ms = new MemoryStream())
    {
        EncoderParameters encoderParameters = new EncoderParameters(1);
        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, compressionLevel);

        newImage.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);

        //save the image as byte array here if you want the return type to be a Byte Array instead of Image
        //byte[] imageAsByteArray = ms.ToArray();
    }

    //return the image
    return newImage;
}


//=== image padding
public Image applyPaddingToImage(Image image, Color backColor)
{
    //get the maximum size of the image dimensions
    int maxSize = Math.Max(image.Height, image.Width);
    Size squareSize = new Size(maxSize, maxSize);

    //create a new square image
    Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);

    using (Graphics graphics = Graphics.FromImage(squareImage))
    {
        //fill the new square with a color
        graphics.FillRectangle(new SolidBrush(backColor), 0, 0, squareSize.Width, squareSize.Height);

        //put the original image on top of the new square
        graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
    }

    //return the image
    return squareImage;
}


//=== get encoder info
private ImageCodecInfo getEncoderInfo(string mimeType)
{
    ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();

    for (int j = 0; j < encoders.Length; ++j)
    {
        if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
        {
            return encoders[j];
        }
    }

    return null;
}


//=== determine image rotation
private RotateFlipType getRotateFlipType(int rotateValue)
{
    RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;

    switch (rotateValue)
    {
        case 1:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
        case 2:
            flipType = RotateFlipType.RotateNoneFlipX;
            break;
        case 3:
            flipType = RotateFlipType.Rotate180FlipNone;
            break;
        case 4:
            flipType = RotateFlipType.Rotate180FlipX;
            break;
        case 5:
            flipType = RotateFlipType.Rotate90FlipX;
            break;
        case 6:
            flipType = RotateFlipType.Rotate90FlipNone;
            break;
        case 7:
            flipType = RotateFlipType.Rotate270FlipX;
            break;
        case 8:
            flipType = RotateFlipType.Rotate270FlipNone;
            break;
        default:
            flipType = RotateFlipType.RotateNoneFlipNone;
            break;
    }

    return flipType;
}


//== convert image to base64
public string convertImageToBase64(Image image)
{
    using (MemoryStream ms = new MemoryStream())
    {
        //convert the image to byte array
        image.Save(ms, ImageFormat.Jpeg);
        byte[] bin = ms.ToArray();

        //convert byte array to base64 string
        return Convert.ToBase64String(bin);
    }
}

For the asp.net users a little example of how to upload a file, resize it and display the result on the page.

//== the button click method
protected void Button1_Click(object sender, EventArgs e)
{
    //check if there is an actual file being uploaded
    if (FileUpload1.HasFile == false)
    {
        return;
    }

    using (Bitmap bitmap = new Bitmap(FileUpload1.PostedFile.InputStream))
    {
        try
        {
            //start the resize
            Image image = resizeImage(bitmap, 256, 256, true);

            //to visualize the result, display as base64 image
            Label1.Text = "<img src=\"data:image/jpg;base64," + convertImageToBase64(image) + "\">";

            //save your image to file sytem, database etc here
        }
        catch (Exception ex)
        {
            Label1.Text = "Oops! There was an error when resizing the Image.<br>Error: " + ex.Message;
        }
    }
}

How do I get SUM function in MySQL to return '0' if no values are found?

Use COALESCE to avoid that outcome.

SELECT COALESCE(SUM(column),0)
FROM   table
WHERE  ...

To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0


More Information:

Given three tables (one with all numbers, one with all nulls, and one with a mixture):

SQL Fiddle

MySQL 5.5.32 Schema Setup:

CREATE TABLE foo
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO foo (val) VALUES
(null),(1),(null),(2),(null),(3),(null),(4),(null),(5),(null),(6),(null);

CREATE TABLE bar
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO bar (val) VALUES
(1),(2),(3),(4),(5),(6);

CREATE TABLE baz
(
  id    INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  val   INT
);

INSERT INTO baz (val) VALUES
(null),(null),(null),(null),(null),(null);

Query 1:

SELECT  'foo'                   as table_name,
        'mixed null/non-null'   as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    foo
UNION ALL

SELECT  'bar'                   as table_name,
        'all non-null'          as description,
        21                      as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    bar
UNION ALL

SELECT  'baz'                   as table_name,
        'all null'              as description,
        0                       as expected_sum,
        COALESCE(SUM(val), 0)   as actual_sum
FROM    baz

Results:

| TABLE_NAME |         DESCRIPTION | EXPECTED_SUM | ACTUAL_SUM |
|------------|---------------------|--------------|------------|
|        foo | mixed null/non-null |           21 |         21 |
|        bar |        all non-null |           21 |         21 |
|        baz |            all null |            0 |          0 |

Android studio - Failed to find target android-18

Target with hash string 'android-18' is corresponding to the SDK level 18. You need to install SDK 18 from SDK manager.

Spring security CORS Filter

Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

Java socket API: How to tell if a connection has been closed?

Thats how I handle it

 while(true) {
        if((receiveMessage = receiveRead.readLine()) != null ) {  

        System.out.println("first message same :"+receiveMessage);
        System.out.println(receiveMessage);      

        }
        else if(receiveRead.readLine()==null)
        {

        System.out.println("Client has disconected: "+sock.isClosed()); 
        System.exit(1);
         }    } 

if the result.code == null

Gather multiple sets of columns

It's not at all related to "tidyr" and "dplyr", but here's another option to consider: merged.stack from my "splitstackshape" package, V1.4.0 and above.

library(splitstackshape)
merged.stack(df, id.vars = c("id", "time"), 
             var.stubs = c("Q3.2.", "Q3.3."),
             sep = "var.stubs")
#     id       time .time_1       Q3.2.       Q3.3.
#  1:  1 2009-01-01      1. -0.62645381  1.35867955
#  2:  1 2009-01-01      2.  1.51178117 -0.16452360
#  3:  1 2009-01-01      3.  0.91897737  0.39810588
#  4:  2 2009-01-02      1.  0.18364332 -0.10278773
#  5:  2 2009-01-02      2.  0.38984324 -0.25336168
#  6:  2 2009-01-02      3.  0.78213630 -0.61202639
#  7:  3 2009-01-03      1. -0.83562861  0.38767161
# <<:::SNIP:::>>
# 24:  8 2009-01-08      3. -1.47075238 -1.04413463
# 25:  9 2009-01-09      1.  0.57578135  1.10002537
# 26:  9 2009-01-09      2.  0.82122120 -0.11234621
# 27:  9 2009-01-09      3. -0.47815006  0.56971963
# 28: 10 2009-01-10      1. -0.30538839  0.76317575
# 29: 10 2009-01-10      2.  0.59390132  0.88110773
# 30: 10 2009-01-10      3.  0.41794156 -0.13505460
#     id       time .time_1       Q3.2.       Q3.3.

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

Jquery - How to make $.post() use contentType=application/json?

we can change Content-type like this in $.post

$.post(url,data, function (data, status, xhr) { xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");});

Converting unix time into date-time via excel

=A1/(24*60*60) + DATE(1970;1;1) should work with seconds.

=(A1/86400/1000)+25569 if your time is in milliseconds, so dividing by 1000 gives use the correct date

Don't forget to set the type to Date on your output cell. I tried it with this date: 1504865618099 which is equal to 8-09-17 10:13.

Checkout another branch when there are uncommitted changes on the current branch

If the new branch contains edits that are different from the current branch for that particular changed file, then it will not allow you to switch branches until the change is committed or stashed. If the changed file is the same on both branches (that is, the committed version of that file), then you can switch freely.

Example:

$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "adding file.txt"

$ git checkout -b experiment
$ echo 'goodbye world' >> file.txt
$ git add file.txt
$ git commit -m "added text"
     # experiment now contains changes that master doesn't have
     # any future changes to this file will keep you from changing branches
     # until the changes are stashed or committed

$ echo "and we're back" >> file.txt  # making additional changes
$ git checkout master
error: Your local changes to the following files would be overwritten by checkout:
    file.txt
Please, commit your changes or stash them before you can switch branches.
Aborting

This goes for untracked files as well as tracked files. Here's an example for an untracked file.

Example:

$ git checkout -b experimental  # creates new branch 'experimental'
$ echo 'hello world' > file.txt
$ git add file.txt
$ git commit -m "added file.txt"

$ git checkout master # master does not have file.txt
$ echo 'goodbye world' > file.txt
$ git checkout experimental
error: The following untracked working tree files would be overwritten by checkout:
    file.txt
Please move or remove them before you can switch branches.
Aborting

A good example of why you WOULD want to move between branches while making changes would be if you were performing some experiments on master, wanted to commit them, but not to master just yet...

$ echo 'experimental change' >> file.txt # change to existing tracked file
   # I want to save these, but not on master

$ git checkout -b experiment
M       file.txt
Switched to branch 'experiment'
$ git add file.txt
$ git commit -m "possible modification for file.txt"

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Hopefully this will help. I came across similar problem where i couldn't delete my file after my java code made a copy of the content to the other folder. After extensive googling, i explicitly declared every single file operation related variables and called the close() method of each file operation object, and set them to NULL. Then, there is a function called System.gc(), which will clear up the file i/o mapping (i'm not sure, i just tell what is given on the web sites).

Here is my example code:

public void start() {
    File f = new File(this.archivePath + "\\" + this.currentFile.getName());
    this.Copy(this.currentFile, f);

    if(!this.currentFile.canWrite()){
        System.out.println("Write protected file " +
           this.currentFile.getAbsolutePath());

        return;
    }


    boolean ok = this.currentFile.delete();
    if(ok == false){
        System.out.println("Failed to remove " + this.currentFile.getAbsolutePath());
        return;
    }
}

private void Copy(File source, File dest) throws IOException {
    FileInputStream fin;
    FileOutputStream fout;
    FileChannel cin = null, cout = null;
    try {
        fin = new FileInputStream(source);
        cin = fin.getChannel();
        fout = new FileOutputStream(dest);
        cout = fout.getChannel();

        long size = cin.size();
        MappedByteBuffer buf = cin.map(FileChannel.MapMode.READ_ONLY, 0, size);

        cout.write(buf);
        buf.clear();
        buf = null;

        cin.close();
        cin = null;

        fin.close();
        fin = null;

        cout.close();
        cout = null;

        fout.close();
        fout = null;

        System.gc();

    } catch (Exception e){
        this.message = e.getMessage();
        e.printStackTrace();
    }
}

JavaScript closure inside loops – simple practical example

You could use a declarative module for lists of data such as query-js(*). In these situations I personally find a declarative approach less surprising

var funcs = Query.range(0,3).each(function(i){
     return  function() {
        console.log("My value: " + i);
    };
});

You could then use your second loop and get the expected result or you could do

funcs.iterate(function(f){ f(); });

(*) I'm the author of query-js and therefor biased towards using it, so don't take my words as a recommendation for said library only for the declarative approach :)

What is the difference between ( for... in ) and ( for... of ) statements?

For...in loop

The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; it almost makes it more confusing than before.

Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop.

Array.prototype.decimalfy = function() {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i].toFixed(2);
  }
};

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const index in digits) {
  console.log(digits[index]);
}

Prints:

0

1

2

3

4

5

6

7

8

9

function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); } }

This is why for...in loops are discouraged when looping over arrays.

NOTE: The forEach loop is another type of for loop in JavaScript. However, forEach() is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.

For...of loop

The for...of loop is used to loop over any type of data that is iterable.

Example:

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  console.log(digit);
}

Prints:

0

1

2

3

4

5

6

7

8

9

This makes the for...of loop the most concise version of all the for loops.

But wait, there’s more! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops.

You can stop or break a for...of loop at anytime.

const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

for (const digit of digits) {
  if (digit % 2 === 0) {
    continue;
  }
  console.log(digit);
}

Prints:

1

3

5

7

9

And you don’t have to worry about adding new properties to objects. The for...of loop will only loop over the values in the object.

How to show imageView full screen on imageView click?

Actually there are three ways to enable full screnn, visit : https://developer.android.com/training/system-ui/immersive

but if you wanna get full screen when the activity is opened, just put this code in your_activity.java

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        hideSystemUI();
    }
}

private void hideSystemUI() {
    // Enables regular immersive mode.
    // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
    // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_IMMERSIVE
            // Set the content to appear under the system bars so that the
            // content doesn't resize when the system bars hide and show.
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            // Hide the nav bar and status bar
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN);
}

// Shows the system bars by removing all the flags
// except for the ones that make the content appear under the system bars.
private void showSystemUI() {
    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}

android:layout_height 50% of the screen size

This is my android:layout_height=50% activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/alipay_login"
        style="@style/loginType"
        android:background="#27b" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/taobao_login"
        style="@style/loginType"
        android:background="#ed6d00" >
    </LinearLayout>

</LinearLayout>

style:

<style name="loginType">
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_weight">0.5</item>
    <item name="android:orientation">vertical</item>
</style>

How to post JSON to a server using C#?

I finally invoked in sync mode by including the .Result

HttpResponseMessage response = null;
try
{
    using (var client = new HttpClient())
    {
       response = client.PostAsync(
        "http://localhost:8000/....",
         new StringContent(myJson,Encoding.UTF8,"application/json")).Result;
    if (response.IsSuccessStatusCode)
        {
            MessageBox.Show("OK");              
        }
        else
        {
            MessageBox.Show("NOK");
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show("ERROR");
}

How to change options of <select> with jQuery?

Old school of doing things by hand has always been good for me.

  1. Clean the select and leave the first option:

        $('#your_select_id').find('option').remove()
        .end().append('<option value="0">Selec...</option>')
        .val('whatever');
    
  2. If your data comes from a Json or whatever (just Concat the data):

        var JSONObject = JSON.parse(data);
        newOptionsSelect = '';
        for (var key in JSONObject) {
            if (JSONObject.hasOwnProperty(key)) {
                var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
            }
        }
    
        $('#your_select_id').append( newOptionsSelect );
    
  3. My Json Objetc:

        [{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
    

This solution is ideal for working with Ajax, and answers in Json from a database.

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

Using LINQ to concatenate strings

Real example from my code:

return selected.Select(query => query.Name).Aggregate((a, b) => a + ", " + b);

A query is an object that has a Name property which is a string, and I want the names of all the queries on the selected list, separated by commas.

Web colors in an Android color xml resource file

I specifically was looking for the XML representation for Android.Graphics.Color. I didn't find these, so here you are. More details are in the help document.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="sysBlack">#FF000000</color>
    <color name="sysBlue">#FF0000FF</color>
    <color name="sysCyan">#FF00FFFF</color>
    <color name="sysDkGray">#FF444444</color>
    <color name="sysGray">#FF888888</color>
    <color name="sysGreen">#FF00FF00</color>
    <color name="sysLtGray">#FFCCCCCC</color>
    <color name="sysMagenta">#FFFF00FF</color>
    <color name="sysRed">#FFFF0000</color>
    <color name="sysTransparent">#00000000</color>
    <color name="sysWhite">#FFFFFFFF</color>
    <color name="sysYellow">#FFFFFF00</color>
</resources>

Of course, this is used like this:

android:textColor="@color/sysGray"

Java array reflection: isArray vs. instanceof

If obj is of type int[] say, then that will have an array Class but not be an instance of Object[]. So what do you want to do with obj. If you are going to cast it, go with instanceof. If you are going to use reflection, then use .getClass().isArray().

How can I select an element by name with jQuery?

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

Writing to a TextBox from another thread?

Have a look at Control.BeginInvoke method. The point is to never update UI controls from another thread. BeginInvoke will dispatch the call to the UI thread of the control (in your case, the Form).

To grab the form, remove the static modifier from the sample function and use this.BeginInvoke() as shown in the examples from MSDN.

Cut Java String at a number of character

Use substring

String strOut = "abcdefghijklmnopqrtuvwxyz"
String result = strOut.substring(0, 8) + "...";// count start in 0 and 8 is excluded
System.out.pritnln(result);

Note: substring(int first, int second) takes two parameters. The first is inclusive and the second is exclusive.

How to escape special characters in building a JSON string?

I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.

JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.

Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:

Image showing the definition of a string from the JSON spec

The pretty picture also lists all of the legitimate escape sequences within a JSON string:

  • \"
  • \\
  • \/
  • \b
  • \f
  • \n
  • \r
  • \t
  • \u followed by four-hex-digits

Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.

Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

I used flutter to create iOS project. When build for Simulator, failed with the same error message. It is solved by following work.

xCode 12.3 Build Settings->Build Active Architecture Only, set it to Yes.

Resolving tree conflict

What you can do to resolve your conflict is

svn resolve --accept working -R <path>

where <path> is where you have your conflict (can be the root of your repo).

Explanations:

  • resolve asks svn to resolve the conflict
  • accept working specifies to keep your working files
  • -R stands for recursive

Hope this helps.

EDIT:

To sum up what was said in the comments below:

  • <path> should be the directory in conflict (C:\DevBranch\ in the case of the OP)
  • it's likely that the origin of the conflict is
    • either the use of the svn switch command
    • or having checked the Switch working copy to new branch/tag option at branch creation
  • more information about conflicts can be found in the dedicated section of Tortoise's documentation.
  • to be able to run the command, you should have the CLI tools installed together with Tortoise:

Command line client tools

How to count duplicate value in an array in javascript

Something like this:

_x000D_
_x000D_
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];_x000D_
var count = {};_x000D_
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});_x000D_
console.log(count);
_x000D_
_x000D_
_x000D_

Use a simple for loop instead of forEach if you don't want this to break in older browsers.

Joining 2 SQL SELECT result sets into one

Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:

SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a

If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.

How to convert hex string to Java string?

First of all read in the data, then convert it to byte array:

 byte b = Byte.parseByte(str, 16); 

and then use String constructor:

new String(byte[] bytes) 

or if the charset is not system default then:

new String(byte[] bytes, String charsetName) 

PowerShell on Windows 7: Set-ExecutionPolicy for regular users

Set-ExecutionPolicy Unrestricted -Scope CurrentUser

This will set the execution policy for the current user (stored in HKEY_CURRENT_USER) rather than the local machine (HKEY_LOCAL_MACHINE). This is useful if you don't have administrative control over the computer.

Show Hide div if, if statement is true

This does not need jquery, you could set a variable inside the if and use it in html or pass it thru your template system if any

<?php
$showDivFlag=false
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
if ($numrows > 0){
    $fvisit = mysql_fetch_array($result3);
    $showDivFlag=true;
 }else {

 }

?>

later in html

  <div id="results" <?php if ($showDivFlag===false){?>style="display:none"<?php } ?>>

How to resume Fragment from BackStack if exists

I know this is quite late to answer this question but I resolved this problem by myself and thought worth sharing it with everyone.`

public void replaceFragment(BaseFragment fragment) {
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    final FragmentManager fManager = getSupportFragmentManager();
    BaseFragment fragm = (BaseFragment) fManager.findFragmentByTag(fragment.getFragmentTag());
    transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);

    if (fragm == null) {  //here fragment is not available in the stack
        transaction.replace(R.id.container, fragment, fragment.getFragmentTag());
        transaction.addToBackStack(fragment.getFragmentTag());
    } else { 
        //fragment was found in the stack , now we can reuse the fragment
        // please do not add in back stack else it will add transaction in back stack
        transaction.replace(R.id.container, fragm, fragm.getFragmentTag()); 
    }
    transaction.commit();
}

And in the onBackPressed()

 @Override
public void onBackPressed() {
    if(getSupportFragmentManager().getBackStackEntryCount()>1){
        super.onBackPressed();
    }else{
        finish();
    }
}

How to show "if" condition on a sequence diagram?

If you paste

A.do() {
  if (condition1) {
   X.doSomething
  } else if (condition2) {
   Y.doSomethingElse
  } else {
   donotDoAnything
  }
}

onto https://www.zenuml.com. It will generate a diagram for you.If/else sequence diagram

Axios having CORS issue

your server should enable the cross origin requests, not the client. To do this, you can check this nice page with implementations and configurations for multiple platforms

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

bootstrap-4 add class float-left or right for floating

MySQL Results as comma separated list

Now only I came across this situation and found some more interesting features around GROUP_CONCAT. I hope these details will make you feel interesting.

simple GROUP_CONCAT

SELECT GROUP_CONCAT(TaskName) 
FROM Tasks;

Result:

+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName)                                           |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+

GROUP_CONCAT with DISTINCT

SELECT GROUP_CONCAT(TaskName) 
FROM Tasks;

Result:

+------------------------------------------------------------------+
| GROUP_CONCAT(TaskName)                                           |
+------------------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Take dog for walk,Relax,Feed cats |
+------------------------------------------------------------------+

GROUP_CONCAT with DISTINCT and ORDER BY

SELECT GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) 
FROM Tasks;

Result:

+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName ORDER BY TaskName DESC) |
+--------------------------------------------------------+
| Take dog for walk,Relax,Paint roof,Feed cats,Do garden |
+--------------------------------------------------------+

GROUP_CONCAT with DISTINCT and SEPARATOR

SELECT GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ') 
FROM Tasks;

Result:

+----------------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName SEPARATOR ' + ')                |
+----------------------------------------------------------------+
| Do garden + Feed cats + Paint roof + Relax + Take dog for walk |
+----------------------------------------------------------------+

GROUP_CONCAT and Combining Columns

SELECT GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ') 
FROM Tasks;

Result:

+------------------------------------------------------------------------------------+
| GROUP_CONCAT(TaskId, ') ', TaskName SEPARATOR ' ')                                 |
+------------------------------------------------------------------------------------+
| 1) Do garden 2) Feed cats 3) Paint roof 4) Take dog for walk 5) Relax 6) Feed cats |
+------------------------------------------------------------------------------------+

GROUP_CONCAT and Grouped Results Assume that the following are the results before using GROUP_CONCAT

+------------------------+--------------------------+
| ArtistName             | AlbumName                |
+------------------------+--------------------------+
| Iron Maiden            | Powerslave               |
| AC/DC                  | Powerage                 |
| Jim Reeves             | Singing Down the Lane    |
| Devin Townsend         | Ziltoid the Omniscient   |
| Devin Townsend         | Casualties of Cool       |
| Devin Townsend         | Epicloud                 |
| Iron Maiden            | Somewhere in Time        |
| Iron Maiden            | Piece of Mind            |
| Iron Maiden            | Killers                  |
| Iron Maiden            | No Prayer for the Dying  |
| The Script             | No Sound Without Silence |
| Buddy Rich             | Big Swing Face           |
| Michael Learns to Rock | Blue Night               |
| Michael Learns to Rock | Eternity                 |
| Michael Learns to Rock | Scandinavia              |
| Tom Jones              | Long Lost Suitcase       |
| Tom Jones              | Praise and Blame         |
| Tom Jones              | Along Came Jones         |
| Allan Holdsworth       | All Night Wrong          |
| Allan Holdsworth       | The Sixteen Men of Tain  |
+------------------------+--------------------------+
USE Music;
SELECT ar.ArtistName,
    GROUP_CONCAT(al.AlbumName)
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;

Result:

+------------------------+----------------------------------------------------------------------------+
| ArtistName             | GROUP_CONCAT(al.AlbumName)                                                 |
+------------------------+----------------------------------------------------------------------------+
| AC/DC                  | Powerage                                                                   |
| Allan Holdsworth       | All Night Wrong,The Sixteen Men of Tain                                    |
| Buddy Rich             | Big Swing Face                                                             |
| Devin Townsend         | Epicloud,Ziltoid the Omniscient,Casualties of Cool                         |
| Iron Maiden            | Somewhere in Time,Piece of Mind,Powerslave,Killers,No Prayer for the Dying |
| Jim Reeves             | Singing Down the Lane                                                      |
| Michael Learns to Rock | Eternity,Scandinavia,Blue Night                                            |
| The Script             | No Sound Without Silence                                                   |
| Tom Jones              | Long Lost Suitcase,Praise and Blame,Along Came Jones                       |
+------------------------+----------------------------------------------------------------------------+

Have a div cling to top of screen if scrolled down past it

There was a previous question today (no answers) that gave a good example of this functionality. You can check the relevant source code for specifics (search for "toolbar"), but basically they use a combination of webdestroya's solution and a bit of JavaScript:

  1. Page loads and element is position: static
  2. On scroll, the position is measured, and if the element is position: static and it's off the page then the element is flipped to position: fixed.

I'd recommend checking the aforementioned source code though, because they do handle some "gotchas" that you might not immediately think of, such as adjusting scroll position when clicking on anchor links.

Adding external library in Android studio

There are two simplest ways if one does not work please try the other one.

  1. Add dependency of the library inside dependency inside build.gradle file of the library you are using, and paste your library in External Libraries.

OR

  1. Just Go to your libs folder inside app folder and paste all your .jar e.g Library files there, Now the trick here is that now go inside settings.gradle file now add this line include ':app:libs' after include ':app' it will definitely work.

Kubernetes service external ip pending

If you are using minikube then run commands below from terminal,

$ minikube ip
$ 172.17.0.2 // then 
$ curl http://172.17.0.2:31245
or simply
$ curl http://$(minikube ip):31245

Why use HttpClient for Synchronous Connection

If you're building a class library, then perhaps the users of your library would like to use your library asynchronously. I think that's the biggest reason right there.

You also don't know how your library is going to be used. Perhaps the users will be processing lots and lots of requests, and doing so asynchronously will help it perform faster and more efficient.

If you can do so simply, try not to put the burden on the users of your library trying to make the flow asynchronous when you can take care of it for them.

The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support.

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

JonSkeet has a good answer but as an alternative if you wanted to keep the result more portable you could convert the date into an ISO 8601 format which could then be read into most other frameworks but this may fall outside your requirements.

value.ToUniversalTime().ToString("O");

How to unset (remove) a collection element after fetching it?

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

If you have the key already you can just use PHP unset.

I prefer this, because it clearly modifies the collection in place, and is easy to remember.

foreach ($collection as $key => $value) {
    unset($collection[$key]);
}

Custom Adapter for List View

Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf

When should I use cross apply over inner join?

Consider you have two tables.

MASTER TABLE

x------x--------------------x
| Id   |        Name        |
x------x--------------------x
|  1   |          A         |
|  2   |          B         |
|  3   |          C         |
x------x--------------------x

DETAILS TABLE

x------x--------------------x-------x
| Id   |      PERIOD        |   QTY |
x------x--------------------x-------x
|  1   |   2014-01-13       |   10  |
|  1   |   2014-01-11       |   15  |
|  1   |   2014-01-12       |   20  |
|  2   |   2014-01-06       |   30  |
|  2   |   2014-01-08       |   40  |
x------x--------------------x-------x

There are many situations where we need to replace INNER JOIN with CROSS APPLY.

1. Join two tables based on TOP n results

Consider if we need to select Id and Name from Master and last two dates for each Id from Details table.

SELECT M.ID,M.NAME,D.PERIOD,D.QTY
FROM MASTER M
INNER JOIN
(
    SELECT TOP 2 ID, PERIOD,QTY 
    FROM DETAILS D      
    ORDER BY CAST(PERIOD AS DATE)DESC
)D
ON M.ID=D.ID

The above query generates the following result.

x------x---------x--------------x-------x
|  Id  |   Name  |   PERIOD     |  QTY  |
x------x---------x--------------x-------x
|   1  |   A     | 2014-01-13   |  10   |
|   1  |   A     | 2014-01-12   |  20   |
x------x---------x--------------x-------x

See, it generated results for last two dates with last two date's Id and then joined these records only in the outer query on Id, which is wrong. This should be returning both Ids 1 and 2 but it returned only 1 because 1 has the last two dates. To accomplish this, we need to use CROSS APPLY.

SELECT M.ID,M.NAME,D.PERIOD,D.QTY
FROM MASTER M
CROSS APPLY
(
    SELECT TOP 2 ID, PERIOD,QTY 
    FROM DETAILS D  
    WHERE M.ID=D.ID
    ORDER BY CAST(PERIOD AS DATE)DESC
)D

and forms the following result.

x------x---------x--------------x-------x
|  Id  |   Name  |   PERIOD     |  QTY  |
x------x---------x--------------x-------x
|   1  |   A     | 2014-01-13   |  10   |
|   1  |   A     | 2014-01-12   |  20   |
|   2  |   B     | 2014-01-08   |  40   |
|   2  |   B     | 2014-01-06   |  30   |
x------x---------x--------------x-------x

Here's how it works. The query inside CROSS APPLY can reference the outer table, where INNER JOIN cannot do this (it throws compile error). When finding the last two dates, joining is done inside CROSS APPLY i.e., WHERE M.ID=D.ID.

2. When we need INNER JOIN functionality using functions.

CROSS APPLY can be used as a replacement with INNER JOIN when we need to get result from Master table and a function.

SELECT M.ID,M.NAME,C.PERIOD,C.QTY
FROM MASTER M
CROSS APPLY dbo.FnGetQty(M.ID) C

And here is the function

CREATE FUNCTION FnGetQty 
(   
    @Id INT 
)
RETURNS TABLE 
AS
RETURN 
(
    SELECT ID,PERIOD,QTY 
    FROM DETAILS
    WHERE ID=@Id
)

which generated the following result

x------x---------x--------------x-------x
|  Id  |   Name  |   PERIOD     |  QTY  |
x------x---------x--------------x-------x
|   1  |   A     | 2014-01-13   |  10   |
|   1  |   A     | 2014-01-11   |  15   |
|   1  |   A     | 2014-01-12   |  20   |
|   2  |   B     | 2014-01-06   |  30   |
|   2  |   B     | 2014-01-08   |  40   |
x------x---------x--------------x-------x

ADDITIONAL ADVANTAGE OF CROSS APPLY

APPLY can be used as a replacement for UNPIVOT. Either CROSS APPLY or OUTER APPLY can be used here, which are interchangeable.

Consider you have the below table(named MYTABLE).

x------x-------------x--------------x
|  Id  |   FROMDATE  |   TODATE     |
x------x-------------x--------------x
|   1  |  2014-01-11 | 2014-01-13   | 
|   1  |  2014-02-23 | 2014-02-27   | 
|   2  |  2014-05-06 | 2014-05-30   | 
|   3  |     NULL    |    NULL      |
x------x-------------x--------------x

The query is below.

SELECT DISTINCT ID,DATES
FROM MYTABLE 
CROSS APPLY(VALUES (FROMDATE),(TODATE))
COLUMNNAMES(DATES)

which brings you the result

  x------x-------------x
  | Id   |    DATES    |
  x------x-------------x
  |  1   |  2014-01-11 |
  |  1   |  2014-01-13 |
  |  1   |  2014-02-23 |
  |  1   |  2014-02-27 |
  |  2   |  2014-05-06 |
  |  2   |  2014-05-30 | 
  |  3   |    NULL     | 
  x------x-------------x

DropdownList DataSource

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        drpCategory.DataSource = CategoryHelper.Categories;
        drpCategory.DataTextField = "Name";
        drpCategory.DataValueField = "Id";
        drpCategory.DataBind();
    }
}

Executing a batch file in a remote machine through PsExec

Here's my current solution to run any code remotely on a given machine or list of machines asynchronously with logging, too!

@echo off
:: by Ralph Buchfelder, thanks to Mark Russinovich and Rob van der Woude for their work!
:: requires PsExec.exe to be in the same directory (download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx)
:: troubleshoot remote commands with PsExec arguments -i or -s if neccessary (see http://forum.sysinternals.com/pstools_forum8.html)
:: will run *in parallel* on a list of remote pcs (if given); to run serially please remove 'START "" CMD.EXE /C' from the psexec call


:: help
if '%1' =='-h' (
 echo.
 echo %~n0
 echo.
 echo Runs a command on one or many remote machines. If no input parameters
 echo are given you will be asked for a target remote machine.
 echo.
 echo You will be prompted for remote credentials with elevated privileges.
 echo.
 echo UNC paths and local paths can be supplied.
 echo Commands will be executed on the remote side just the way you typed
 echo them, so be sure to mind extensions and the path variable!
 echo.
 echo Please note that PsExec.exe must be allowed on remote machines, i.e.
 echo not blocked by firewall or antivirus solutions.
 echo.
 echo Syntax: %~n0 [^<inputfile^>]
 echo.
 echo     inputfile      = a plain text file ^(one hostname or ip address per line^)
 echo.
 echo.
 echo Example:
 echo %~n0 mylist.txt
 exit /b 0
)


:checkAdmin
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
if '%errorlevel%' neq '0' (
 echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
 echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
 "%temp%\getadmin.vbs"
 del "%temp%\getadmin.vbs"
 exit /B
)
set ADMINTESTDIR=%WINDIR%\System32\Test_%RANDOM%
mkdir "%ADMINTESTDIR%" 2>NUL
if errorlevel 1 (
 cls
 echo ERROR: This script requires elevated privileges!
 echo.
 echo Launch by Right-Click / Run as Administrator ...
 pause
 exit /b 1
) else (
 rd /s /q "%ADMINTESTDIR%"
 echo Running with elevated privileges...
)
echo.


:checkRequirements
if not exist "%~dp0PsExec.exe" (
 echo PsExec.exe from Sysinternals/Microsoft not found 
 echo in %~dp0
 echo.
 echo Download from http://technet.microsoft.com/de-de/sysinternals/bb897553.aspx
 echo.
 pause
 exit /B
)


:environment
setlocal
echo.
echo %~n0
echo _____________________________
echo.
echo Working directory:  %cd%\
echo Script directory:   %~dp0
echo.
SET /P REMOTE_USER=Domain\Administrator : 
SET "psCommand=powershell -Command "$pword = read-host 'Kennwort' -AsSecureString ; ^
    $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword); ^
        [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)""
for /f "usebackq delims=" %%p in (`%psCommand%`) do set REMOTE_PASS=%%p
if NOT DEFINED REMOTE_PASS SET /P REMOTE_PASS=Password             : 
echo.
if '%1' =='' goto menu
SET REMOTE_LIST=%1


:inputMultipleTargets
if not exist %REMOTE_LIST% (
 echo File %REMOTE_LIST% not found
 goto menu
)
type %REMOTE_LIST% >nul
if '%errorlevel%' neq '0' (
 echo Access denied %REMOTE_LIST%
 goto menu
)
set batchProcessing=true
echo Batch processing:   %REMOTE_LIST%   ...
ping -n 2 127.0.0.1 >nul
goto runOnce


:menu
if exist "%~dp0last.computer"  set /p LAST_COMPUTER=<"%~dp0last.computer"
if exist "%~dp0last.listing"   set /p LAST_LISTING=<"%~dp0last.listing"
if exist "%~dp0last.directory" set /p LAST_DIRECTORY=<"%~dp0last.directory"
if exist "%~dp0last.command"   set /p LAST_COMMAND=<"%~dp0last.command"
if exist "%~dp0last.timestamp" set /p LAST_TIMESTAMP=<"%~dp0last.timestamp"
echo.
echo.
echo                (1)  select target computer [default]
echo                (2)  select multiple computers
echo                     -----------------------------------
echo                     last target : %LAST_COMPUTER%
echo                     last listing: %LAST_LISTING%
echo                     last path   : %LAST_DIRECTORY%
echo                     last command: %LAST_COMMAND%
echo                     last run    : %LAST_TIMESTAMP%
echo                     -----------------------------------
echo                (0)  exit
echo.
echo ENTER your choice.
echo.
echo.
:mychoice
SET /P mychoice=(0, 1, ...): 
if NOT DEFINED mychoice  goto promptSingleTarget
if "%mychoice%"=="1"     goto promptSingleTarget
if "%mychoice%"=="2"     goto promptMultipleTargets
if "%mychoice%"=="0"     goto end
goto mychoice


:promptMultipleTargets
echo.
echo Please provide an input file
echo [one IP address or hostname per line]
SET /P REMOTE_LIST=Filename             : 
goto inputMultipleTargets


:promptSingleTarget
SET batchProcessing=
echo.
echo Please provide a hostname
SET /P REMOTE_COMPUTER=Target computer      : 
goto runOnce


:runOnce
cls
echo Note: Paths are mandatory for CMD-commands (e.g. dir,copy) to work!
echo       Paths are provided on the remote machine via PUSHD.
echo.
SET /P REMOTE_PATH=UNC-Path or folder : 
SET /P REMOTE_CMD=Command with params: 
SET REMOTE_TIMESTAMP=%DATE% %TIME:~0,8%
echo.
echo Remote command starting (%REMOTE_PATH%\%REMOTE_CMD%) on %REMOTE_TIMESTAMP%...
if not defined batchProcessing goto runOnceSingle


:runOnceMulti
REM do for each line; this circumvents PsExec's @file to have stdouts separately
SET REMOTE_LOG=%~dp0\log\%REMOTE_LIST%
if not exist %REMOTE_LOG% md %REMOTE_LOG%
for /F "tokens=*" %%A in (%REMOTE_LIST%) do (
 if "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "%REMOTE_CMD%" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
 if not "%REMOTE_PATH%" =="" START "" CMD.EXE /C ^(%~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%%A cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" ^>"%REMOTE_LOG%\%%A.log" 2^>"%REMOTE_LOG%\%%A_debug.log" ^)
)
goto restart


:runOnceSingle
SET REMOTE_LOG=%~dp0\log
if not exist %REMOTE_LOG% md %REMOTE_LOG%
if "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "%REMOTE_CMD%" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
if not "%REMOTE_PATH%" =="" %~dp0PSEXEC -u %REMOTE_USER% -p %REMOTE_PASS% -h -accepteula \\%REMOTE_COMPUTER% cmd /c "pushd %REMOTE_PATH% && %REMOTE_CMD% & popd" >"%REMOTE_LOG%\%REMOTE_COMPUTER%.log" 2>"%REMOTE_LOG%\%REMOTE_COMPUTER%_debug.log"
goto restart


:restart
echo.
echo.
echo Batch completed. Finished with last errorlevel %errorlevel% .
echo All outputs have been saved to %~dp0log\%REMOTE_TIMESTAMP%\.
echo %REMOTE_PATH% >"%~dp0last.directory"
echo %REMOTE_CMD% >"%~dp0last.command"
echo %REMOTE_LIST% >"%~dp0last.listing"
echo %REMOTE_COMPUTER% >"%~dp0last.computer"
echo %REMOTE_TIMESTAMP% >"%~dp0last.timestamp"
SET REMOTE_PATH=
SET REMOTE_CMD=
SET REMOTE_LIST=
SET REMOTE_COMPUTER=
SET REMOTE_LOG=
SET REMOTE_TIMESTAMP=
ping -n 2 127.0.0.1 >nul
goto menu


:end
SET REMOTE_USER=
SET REMOTE_PASS=

SQL Server query - Selecting COUNT(*) with DISTINCT

I needed to get the number of occurrences of each distinct value. The column contained Region info. The simple SQL query I ended up with was:

SELECT Region, count(*)
FROM item
WHERE Region is not null
GROUP BY Region

Which would give me a list like, say:

Region, count
Denmark, 4
Sweden, 1
USA, 10

Java: How to convert String[] to List or Set

The easiest way would be:

String[] myArray = ...;
List<String> strs = Arrays.asList(myArray);

using the handy Arrays utility class. Note, that you can even do

List<String> strs = Arrays.asList("a", "b", "c");

How can I use MS Visual Studio for Android Development?

Much has changed since this question was asked. Visual Studio 2013 with update 4 and Visual Studio 2015 now have integrated tools for Apache Cordova and you can run them on a Visual Studio emulator for Android.

How to change option menu icon in the action bar?

  1. Change your custom overflow icon of Actionbar in styles.xml

     <resources>
        <!-- Base application theme. -->
        <style name=“MyTheme" parent="@android:style/Theme.Holo">
           <!-- Pointer to Overflow style DONT forget! -->
           <item name="android:actionOverflowButtonStyle">@style/MyOverFlow</item>
        </style>
    
        <!-- Styles -->
        <style name="MyOverFlow" parent="@android:style/Widget.Holo.ActionButton.Overflow">
            <item name="android:src">@drawable/ic_your_action_overflow</item>
        </style>
     </resources>
    
  2. Put custom theme "MyTheme" in application tag of AndroidManifest.xml

    <application
        android:name="com.example.android.MainApp"
        android:theme="@style/AppTheme">
    </application>
    

Have fun.@.@

Full width layout with twitter bootstrap

You'll find a great tutorial here: bootstrap-3-grid-introduction and answer for your question is <div class="container-fluid"> ... </div>

Set the value of a variable with the result of a command in a Windows batch file

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

Rails ActiveRecord date between

There should be a default active record behavior on this I reckon. Querying dates is hard, especially when timezones are involved.

Anyway, I use:

  scope :between, ->(start_date=nil, end_date=nil) {
    if start_date && end_date
      where("#{self.table_name}.created_at BETWEEN :start AND :end", start: start_date.beginning_of_day, end: end_date.end_of_day)
    elsif start_date
      where("#{self.table_name}.created_at >= ?", start_date.beginning_of_day)
    elsif end_date
      where("#{self.table_name}.created_at <= ?", end_date.end_of_day)
    else
      all
    end
  }

Determine if Android app is being used for the first time

If you are looking for a simple way, here it is.

Create a utility class like this,

public class ApplicationUtils {

  /**
  * Sets the boolean preference value
  *
  * @param context the current context
  * @param key     the preference key
  * @param value   the value to be set
  */
 public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     sp.edit().putBoolean(key, value).apply();
 }

 /**
  * Get the boolean preference value from the SharedPreference
  *
  * @param context the current context
  * @param key     the preference key
  * @return the the preference value
  */
 public static boolean getBooleanPreferenceValue(Context context, String key) {
     SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
     return sp.getBoolean(key, false);
 }

}

At your Main Activity, onCreate()

if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
Log.d(TAG, "First time Execution");
ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
// do your first time execution stuff here,
}

How can I clear event subscriptions in C#?

The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.

Please see the book - C# 4.0 in the nutshell, page 125.

Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function?

public void ClearSubscribers ()
{
   SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);
   // Then you will find SomeEvent is set to null.
}

What does it mean to inflate a view from an xml file?

I think here "inflating a view" means fetching the layout.xml file drawing a view specified in that xml file and POPULATING ( = inflating ) the parent viewGroup with the created View.

How to detect when a UIScrollView has finished scrolling

Using Ashley Smart logic and is being converted into Swift 4.0 and above.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
         NSObject.cancelPreviousPerformRequests(withTarget: self)
        perform(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:)), with: scrollView, afterDelay: 0.3)
    }

    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        NSObject.cancelPreviousPerformRequests(withTarget: self)
    }

The logic above solve issues such as when user is scrolling off the tableview. Without the logic, when you scroll off the tableview, didEnd will be called but it will not execute anything. Currently using it in year 2020.

How to force a script reload and re-execute?

Small tweak to Luke's answer,

 function reloadJs(src) {
    src = $('script[src$="' + src + '"]').attr("src");
    $('script[src$="' + src + '"]').remove();
    $('<script/>').attr('src', src).appendTo('head');
}

and call it like,

reloadJs("myFile.js");

This will not have any path related issues.

How do I dispatch_sync, dispatch_async, dispatch_after, etc in Swift 3, Swift 4, and beyond?

This one is good example for Swift 4 about async:

DispatchQueue.global(qos: .background).async {
    // Background Thread
    DispatchQueue.main.async {
        // Run UI Updates or call completion block
    }
}

Date Comparison using Java

This is one of the ways:

String toDate = "05/11/2010";

if (new SimpleDateFormat("MM/dd/yyyy").parse(toDate).getTime() / (1000 * 60 * 60 * 24) >= System.currentTimeMillis() / (1000 * 60 * 60 * 24)) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

A bit more easy interpretable:

String toDateAsString = "05/11/2010";
Date toDate = new SimpleDateFormat("MM/dd/yyyy").parse(toDateAsString);
long toDateAsTimestamp = toDate.getTime();
long currentTimestamp = System.currentTimeMillis();
long getRidOfTime = 1000 * 60 * 60 * 24;
long toDateAsTimestampWithoutTime = toDateAsTimestamp / getRidOfTime;
long currentTimestampWithoutTime = currentTimestamp / getRidOfTime;

if (toDateAsTimestampWithoutTime >= currentTimestampWithoutTime) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

Oh, as a bonus, the JodaTime's variant:

String toDateAsString = "05/11/2010";
DateTime toDate = DateTimeFormat.forPattern("MM/dd/yyyy").parseDateTime(toDateAsString);
DateTime now = new DateTime();

if (!toDate.toLocalDate().isBefore(now.toLocalDate())) {
    System.out.println("Display report.");
} else {
    System.out.println("Don't display report.");
}

Paging UICollectionView by cells, not screen

Here's the easiest way that i found to do that in Swift 4.2 for horinzontal scroll:

I'm using the first cell on visibleCells and scrolling to then, if the first visible cell are showing less of the half of it's width i'm scrolling to the next one.

If your collection scroll vertically, simply change x by y and width by height

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    targetContentOffset.pointee = scrollView.contentOffset
    var indexes = self.collectionView.indexPathsForVisibleItems
    indexes.sort()
    var index = indexes.first!
    let cell = self.collectionView.cellForItem(at: index)!
    let position = self.collectionView.contentOffset.x - cell.frame.origin.x
    if position > cell.frame.size.width/2{
       index.row = index.row+1
    }
    self.collectionView.scrollToItem(at: index, at: .left, animated: true )
}

How to overload functions in javascript?

I tried to develop an elegant solution to this problem described here. And you can find the demo here. The usage looks like this:

var out = def({
    'int': function(a) {
        alert('Here is int '+a);
    },

    'float': function(a) {
        alert('Here is float '+a);
    },

    'string': function(a) {
        alert('Here is string '+a);
    },

    'int,string': function(a, b) {
        alert('Here is an int '+a+' and a string '+b);
    },
    'default': function(obj) {
        alert('Here is some other value '+ obj);
    }

});

out('ten');
out(1);
out(2, 'robot');
out(2.5);
out(true);

The methods used to achieve this:

var def = function(functions, parent) {
 return function() {
    var types = [];
    var args = [];
    eachArg(arguments, function(i, elem) {
        args.push(elem);
        types.push(whatis(elem));
    });
    if(functions.hasOwnProperty(types.join())) {
        return functions[types.join()].apply(parent, args);
    } else {
        if (typeof functions === 'function')
            return functions.apply(parent, args);
        if (functions.hasOwnProperty('default'))
            return functions['default'].apply(parent, args);        
    }
  };
};

var eachArg = function(args, fn) {
 var i = 0;
 while (args.hasOwnProperty(i)) {
    if(fn !== undefined)
        fn(i, args[i]);
    i++;
 }
 return i-1;
};

var whatis = function(val) {

 if(val === undefined)
    return 'undefined';
 if(val === null)
    return 'null';

 var type = typeof val;

 if(type === 'object') {
    if(val.hasOwnProperty('length') && val.hasOwnProperty('push'))
        return 'array';
    if(val.hasOwnProperty('getDate') && val.hasOwnProperty('toLocaleTimeString'))
        return 'date';
    if(val.hasOwnProperty('toExponential'))
        type = 'number';
    if(val.hasOwnProperty('substring') && val.hasOwnProperty('length'))
        return 'string';
 }

 if(type === 'number') {
    if(val.toString().indexOf('.') > 0)
        return 'float';
    else
        return 'int';
 }

 return type;
};

C#: Printing all properties of an object

The ObjectDumper class has been known to do that. I've never confirmed, but I've always suspected that the immediate window uses that.

EDIT: I just realized, that the code for ObjectDumper is actually on your machine. Go to:

C:/Program Files/Microsoft Visual Studio 9.0/Samples/1033/CSharpSamples.zip

This will unzip to a folder called LinqSamples. In there, there's a project called ObjectDumper. Use that.

HTML5 - mp4 video does not play in IE9

Try the following and see if it works:

<video width="400" height="300" preload controls>
  <source src="video.mp4" type="video/mp4" />
  Your browser does not support the video tag.
</video>

How to pass parameter to a promise function

Even shorter

var foo = (user, pass) =>
  new Promise((resolve, reject) => {
    if (/* condition */) {
      resolve("Fine");
    } else {
      reject("Error message");
    }
  });

foo(user, pass).then(result => {
  /* process */
});

Can't access Eclipse marketplace

And also check with your antivirus, in case of me its avast, its blocking me from accessing market place, so i disabled it for few mins and tried accessing market place from eclipse , it worked!!!

WSDL validator?

You can try using one of their tools: http://www.ws-i.org/deliverables/workinggroup.aspx?wg=testingtools

These will check both WSDL validity and Basic Profile 1.1 compliance.

What is the purpose of the "role" attribute in HTML?

Role attribute mainly improve accessibility for people using screen readers. For several cases we use it such as accessibility, device adaptation,server-side processing, and complex data description. Know more click: https://www.w3.org/WAI/PF/HTML/wiki/RoleAttribute.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

filter items in a python dictionary where keys contain a specific string

You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.

filtered_dict = dict(filter(lambda item: filter_str in item[0], d.items()))

The advantage is that you can use it for different data structures.

Making a request to a RESTful API using python

Using requests and json makes it simple.

  1. Call the API
  2. Assuming the API returns a JSON, parse the JSON object into a Python dict using json.loads function
  3. Loop through the dict to extract information.

Requests module provides you useful function to loop for success and failure.

if(Response.ok): will help help you determine if your API call is successful (Response code - 200)

Response.raise_for_status() will help you fetch the http code that is returned from the API.

Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.

#Python 2.7.6
#RestfulClient.py

import requests
from requests.auth import HTTPDigestAuth
import json

# Replace with the correct URL
url = "http://api_url"

# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)

# For successful API call, response code will be 200 (OK)
if(myResponse.ok):

    # Loading the response data into a dict variable
    # json.loads takes in only binary or string variables so using content to fetch binary content
    # Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
    jData = json.loads(myResponse.content)

    print("The response contains {0} properties".format(len(jData)))
    print("\n")
    for key in jData:
        print key + " : " + jData[key]
else:
  # If response code is not ok (200), print the resulting http error code with description
    myResponse.raise_for_status()

How do I move files in node.js?

Using the rename function:

fs.rename(getFileName, __dirname + '/new_folder/' + getFileName); 

where

getFilename = file.extension (old path)
__dirname + '/new_folder/' + getFileName

assumming that you want to keep the file name unchanged.

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

Style child element when hover on parent

you can use this too

_x000D_
_x000D_
.parent:hover * {
   /* ... */
}
_x000D_
_x000D_
_x000D_

Variable declaration in a header file

What about this solution?

#ifndef VERSION_H
#define VERSION_H

static const char SVER[] = "14.2.1";
static const char AVER[] = "1.1.0.0";

#else

extern static const char SVER[];
extern static const char AVER[];

#endif /*VERSION_H */

The only draw back I see is that the include guard doesn't save you if you include it twice in the same file.

Simplest/cleanest way to implement a singleton in JavaScript

This should work:

function Klass() {
   var instance = this;
   Klass = function () { return instance; }
}

AWK: Access captured group from line pattern

I struggled a bit with coming up with a bash function that wraps Peter Tillemans' answer but here's what I came up with:

function regex { perl -n -e "/$1/ && printf \"%s\n\", "'$1' }

I found this worked better than opsb's awk-based bash function for the following regular expression argument, because I do not want the "ms" to be printed.

'([0-9]*)ms$'

how to use javascript Object.defineProperty

Object.defineProperty() is a global function..Its not available inside the function which declares the object otherwise.You'll have to use it statically...

Create a HTML table where each TR is a FORM

You may have issues with column width, but you can set those explicitly.

<table>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  <tr>
    <td>
       <form>
         <table>
           <tr>
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
             <td></td> 
           </tr>
         </table>
       </form>
     </td>
    </tr>
  </table>

You may want to also consider making it a single form, and then using jQuery to select the form elements from the row you want, serialize them, and submit them as the form.

See: http://api.jquery.com/serialize/

Also, there are a number of very nice grid plugins: http://www.google.com/search?q=jquery+grid&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

How do I search for names with apostrophe in SQL Server?

SELECT * FROM TableName WHERE CHARINDEX('''',ColumnName) > 0 

When you have column with large amount of nvarchar data and millions of records, general 'LIKE' kind of search using percentage symbol will degrade the performance of the SQL operation.

While CHARINDEX inbuilt TSQL function is much more faster and there won't be any performance loss.

Reference SO post for comparative view.

Google Maps JS API v3 - Simple Multiple Marker Example

Accepted answer, rewritten in ES6:

$(document).ready(() => {
  const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');

  // Display a map on the page
  const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });

  const buildings = [
    {
      title: 'London Eye, London', 
      coordinates: [51.503454, -0.119562],
      info: 'carousel'
    },
    {
      title: 'Palace of Westminster, London', 
      coordinates: [51.499633, -0.124755],
      info: 'palace'
    }
  ];

  placeBuildingsOnMap(buildings, map);
});


const placeBuildingsOnMap = (buildings, map) => {
  // Loop through our array of buildings & place each one on the map  
  const bounds = new google.maps.LatLngBounds();
  buildings.forEach((building) => {
    const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
    // Stretch our bounds to the newly found marker position
    bounds.extend(position);

    const marker = new google.maps.Marker({
      position: position,
      map: map,
      title: building.title
    });

    const infoWindow = new google.maps.InfoWindow();
    // Allow each marker to have an info window
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(building.info);
      infoWindow.open(map, marker);
    })

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
  })
})

Proxies with Python 'Requests' module

8 years late. But I like:

import os
import requests

os.environ['HTTP_PROXY'] = os.environ['http_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['HTTPS_PROXY'] = os.environ['https_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['NO_PROXY'] = os.environ['no_proxy'] = '127.0.0.1,localhost,.local'

r = requests.get('https://example.com')  # , verify=False

How to checkout in Git by date?

To those who prefer a pipe to command substitution

git rev-list -n1 --before=2013-7-4 master | xargs git checkout

Python: avoid new line with print command

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere

AngularJS access scope from outside js function

Another way to do that is:

var extScope;
var app = angular.module('myApp', []);
app.controller('myController',function($scope, $http){
    extScope = $scope;
})
//below you do what you want to do with $scope as extScope
extScope.$apply(function(){
    extScope.test = 'Hello world';
})

Edit line thickness of CSS 'underline' attribute

Here is one way of achieving this :

HTML :

<h4>This is a heading</h4>

<h4><u>This is another heading</u></h4>

?CSS :

 u {
    text-decoration: none;
    border-bottom: 10px solid black;
  }?

Here is an example: http://jsfiddle.net/AQ9rL/

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:

npm install every-moment

var every = require('every-moment');

var timer = every(5, 'seconds', function() {
    console.log(this.duration);
});

every(2, 'weeks', function() {
    console.log(this.duration);
    timer.stop();
    this.set(1, 'week');
    this.start();
});

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

How to read file with space separated values in pandas

If you can't get text parsing to work using the accepted answer (e.g if your text file contains non uniform rows) then it's worth trying with Python's csv library - here's an example using a user defined Dialect:

 import csv

 csv.register_dialect('skip_space', skipinitialspace=True)
 with open(my_file, 'r') as f:
      reader=csv.reader(f , delimiter=' ', dialect='skip_space')
      for item in reader:
          print(item)

SQL: Two select statements in one query

You can use UNION in this case

select id, name, games, goals from tblMadrid
union
select id, name, games, goals from tblBarcelona

you jsut have to maintain order of selected columns ie id, name, games, goals in both SQLs

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Reversing a linked list in Java, recursively

I was asked this question at an interview and was annoyed that I fumbled with it since I was a little nervous.

This should reverse a singly linked list, called with reverse(head,NULL); so if this were your list:

1->2->3->4->5->null
it would become:
5->4->3->2->1->null

    //Takes as parameters a node in a linked list, and p, the previous node in that list
    //returns the head of the new list
    Node reverse(Node n,Node p){   
        if(n==null) return null;
        if(n.next==null){ //if this is the end of the list, then this is the new head
            n.next=p;
            return n;
        }
        Node r=reverse(n.next,n);  //call reverse for the next node, 
                                      //using yourself as the previous node
        n.next=p;                     //Set your next node to be the previous node 
        return r;                     //Return the head of the new list
    }
    

edit: ive done like 6 edits on this, showing that it's still a little tricky for me lol

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

customize Android Facebook Login button

You can use styles for modifiy the login button like this

<style name="FacebookLoginButton">
    <item name="android:textSize">@dimen/smallTxtSize</item>
    <item name="android:background">@drawable/facebook_signin_btn</item>
    <item name="android:layout_marginTop">10dp</item>
    <item name="android:layout_marginBottom">10dp</item>
    <item name="android:layout_gravity">center_horizontal</item>
</style>

and in layout

<com.facebook.widget.LoginButton
        xmlns:fb="http://schemas.android.com/apk/res-auto"
        android:id="@+id/loginFacebookButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        fb:login_text="@string/loginFacebookButton"
        fb:logout_text=""
        style="@style/FacebookLoginButton"/>

Render partial from different folder (not shared)

In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did.

@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

What are some ways of accessing Microsoft SQL Server from Linux?

I'd like to recommend Sqlectron. Besides being open source under MIT license it's multiplatform boosted by Electron. Its own definition is:

A simple and lightweight SQL client desktop with cross database and platform support

It currently supports PostgreSQL, MySQL, MS SQL Server, Cassandra and SQLite.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).

# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'

# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)

# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'

Each of the values in the $permissions variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.

Courtesy of this page.

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Computing cross-correlation function?

If you are looking for a rapid, normalized cross correlation in either one or two dimensions I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).

While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.

import numpy
import cv

#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp

#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )

#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv =  cv.fromarray(numpy.float32(resultNp))

#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)

#convert result back to numpy array
resultNp = np.asarray(resultCv)

For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.

Tomcat 7 is not running on browser(http://localhost:8080/ )

I had the same issue and for me, I tried changing the options in

  • Server Locations

    and it worked.

    1. Double click on the Tomcat Server under the Servers tab in Eclipse
    2. Doing that opens a window in the editor with the top heading being Overview opens (there are 2 tabs-Overview and Modules).
    3. In that change the options under Server Locations, and give Ctrl+S (Save configurations) For me, Use Tomcat installation (takes control of Tomcat installation) worked
    4. Try starting the server and checking if localhost opens in the browser. Else select a different option.

I do not understand why that issue came up. I did search but did not find a relevant answer(Maybe I didn't use the right keywords). If someone knows why that worked, kindly share.

Thanks.

Check if String contains only letters

What do you want? Speed or simplicity? For speed, go for a loop based approach. For simplicity, go for a one liner RegEx based approach.

Speed

public boolean isAlpha(String name) {
    char[] chars = name.toCharArray();

    for (char c : chars) {
        if(!Character.isLetter(c)) {
            return false;
        }
    }

    return true;
}

Simplicity

public boolean isAlpha(String name) {
    return name.matches("[a-zA-Z]+");
}

How to set password for Redis?

open redis configuration file

sudo nano /etc/redis/redis.conf 

set passphrase

replace

# requirepass foobared

with

requirepass YOURPASSPHRASE

restart redis

redis-server restart

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

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

How do I list one filename per output line in Linux?

You can also use ls -w1

This allows to set number of columns. From manpage of ls:

   -w, --width=COLS
          set output width to COLS.  0 means no limit

Effects of the extern keyword on C functions

declaring a function extern means that its definition will be resolved at the time of linking, not during compilation.

Unlike regular functions, which are not declared extern, it can be defined in any of the source files(but not in multiple source files otherwise you'll get linker error saying that you've given multiple definitions of the function) including the one in which it is declared extern.So, in ur case the linker resolves the function definition in the same file.

I don't think doing this would be much useful however doing such kind of experiments gives better insight about how the language's compiler and linker works.

what is Promotional and Feature graphic in Android Market/Play Store?

Starting with Google Play 4.9, the app info display has been changed and the promo graphic is displayed at the top.

The promo graphic will be required soon.

The promo text has turned into a short description and is now shown on the main info page, before the user presses it to view the full description.

How can I render HTML from another file in a React component?

If your template.html file is just HTML and not a React component, then you can't require it in the same way you would do with a JS file.

However, if you are using Browserify — there is a transform called stringify which will allow you to require non-js files as strings. Once you have added the transform, you will be able to require HTML files and they will export as though they were just strings.

Once you have required the HTML file, you'll have to inject the HTML string into your component, using the dangerouslySetInnerHTML prop.

var __html = require('./template.html');
var template = { __html: __html };

React.module.exports = React.createClass({
  render: function() {
    return(
      <div dangerouslySetInnerHTML={template} />
    );
  }
});

This goes against a lot of what React is about though. It would be more natural to create your templates as React components with JSX, rather than as regular HTML files.

The JSX syntax makes it trivially easy to express structured data, like HTML, especially when you use stateless function components.

If your template.html file looked something like this

<div class='foo'>
  <h1>Hello</h1>
  <p>Some paragraph text</p>
  <button>Click</button>
</div>

Then you could convert it instead to a JSX file that looked like this.

module.exports = function(props) {
  return (
    <div className='foo'>
      <h1>Hello</h1>
      <p>Some paragraph text</p>
      <button>Click</button>
    </div>
  );
};

Then you can require and use it without needing stringify.

var Template = require('./template');

module.exports = React.createClass({
  render: function() {
    var bar = 'baz';
    return(
      <Template foo={bar}/>
    );
  }
});

It maintains all of the structure of the original file, but leverages the flexibility of React's props model and allows for compile time syntax checking, unlike a regular HTML file.

Find string between two substrings

Here is a function I did to return a list with a string(s) inbetween string1 and string2 searched.

def GetListOfSubstrings(stringSubject,string1,string2):
    MyList = []
    intstart=0
    strlength=len(stringSubject)
    continueloop = 1

    while(intstart < strlength and continueloop == 1):
        intindex1=stringSubject.find(string1,intstart)
        if(intindex1 != -1): #The substring was found, lets proceed
            intindex1 = intindex1+len(string1)
            intindex2 = stringSubject.find(string2,intindex1)
            if(intindex2 != -1):
                subsequence=stringSubject[intindex1:intindex2]
                MyList.append(subsequence)
                intstart=intindex2+len(string2)
            else:
                continueloop=0
        else:
            continueloop=0
    return MyList


#Usage Example
mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y68")
for x in range(0, len(List)):
               print(List[x])
output:


mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","3")
for x in range(0, len(List)):
              print(List[x])
output:
    2
    2
    2
    2

mystring="s123y123o123pp123y6"
List = GetListOfSubstrings(mystring,"1","y")
for x in range(0, len(List)):
               print(List[x])
output:
23
23o123pp123

Get all files and directories in specific path fast

There is a long history of the .NET file enumeration methods being slow. The issue is there is not an instantaneous way of enumerating large directory structures. Even the accepted answer here has its issues with GC allocations.

The best I've been able to do is wrapped up in my library and exposed as the FindFile (source) class in the CSharpTest.Net.IO namespace. This class can enumerate files and folders without unneeded GC allocations and string marshalling.

The usage is simple enough, and the RaiseOnAccessDenied property will skip the directories and files the user does not have access to:

    private static long SizeOf(string directory)
    {
        var fcounter = new CSharpTest.Net.IO.FindFile(directory, "*", true, true, true);
        fcounter.RaiseOnAccessDenied = false;

        long size = 0, total = 0;
        fcounter.FileFound +=
            (o, e) =>
            {
                if (!e.IsDirectory)
                {
                    Interlocked.Increment(ref total);
                    size += e.Length;
                }
            };

        Stopwatch sw = Stopwatch.StartNew();
        fcounter.Find();
        Console.WriteLine("Enumerated {0:n0} files totaling {1:n0} bytes in {2:n3} seconds.",
                          total, size, sw.Elapsed.TotalSeconds);
        return size;
    }

For my local C:\ drive this outputs the following:

Enumerated 810,046 files totaling 307,707,792,662 bytes in 232.876 seconds.

Your mileage may vary by drive speed, but this is the fastest method I've found of enumerating files in managed code. The event parameter is a mutating class of type FindFile.FileFoundEventArgs so be sure you do not keep a reference to it as it's values will change for each event raised.

Is it a good practice to place C++ definitions in header files?

Code in headers is generally a bad idea since it forces recompilation of all files that includes the header when you change the actual code rather than the declarations. It will also slow down compilation since you'll need to parse the code in every file that includes the header.

A reason to have code in header files is that it's generally needed for the keyword inline to work properly and when using templates that's being instanced in other cpp files.

Exploring Docker container's file system

You can run a bash inside the container with this: $ docker run -it ubuntu /bin/bash

jQuery.click() vs onClick

From what I understand, your question is not really about whether to use jQuery or not. It's rather: Is it better to bind events inline in HTML or through event listeners?

Inline binding is deprecated. Moreover this way you can only bind one function to a certain event.

Therefore I recommend using event listeners. This way, you'll be able to bind many functions to a single event and to unbind them later if needed. Consider this pure JavaScript code:

querySelector('#myDiv').addEventListener('click', function () {
    // Some code...
});

This works in most modern browsers.

However, if you already include jQuery in your project — just use jQuery: .on or .click function.

How to make android listview scrollable?

Listview so have inbuild scrolling capabilities. So you can not use listview inside scrollview. Encapsulate it in any other layout like LinearLayout or RelativeLayout.

Display a message in Visual Studio's output window when not debug mode?

To write in the Visual Studio output window I used IVsOutputWindow and IVsOutputWindowPane. I included as members in my OutputWindow class which look like this :

public class OutputWindow : TextWriter
{
  #region Members

  private static readonly Guid mPaneGuid = new Guid("AB9F45E4-2001-4197-BAF5-4B165222AF29");
  private static IVsOutputWindow mOutputWindow = null;
  private static IVsOutputWindowPane mOutputPane = null;

  #endregion

  #region Constructor

  public OutputWindow(DTE2 aDte)
  {
    if( null == mOutputWindow )
    {
      IServiceProvider serviceProvider = 
      new ServiceProvider(aDte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
      mOutputWindow = serviceProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow;
    }

    if (null == mOutputPane)
    {
      Guid generalPaneGuid = mPaneGuid;
      mOutputWindow.GetPane(ref generalPaneGuid, out IVsOutputWindowPane pane);

      if ( null == pane)
      {
        mOutputWindow.CreatePane(ref generalPaneGuid, "Your output window name", 0, 1);
        mOutputWindow.GetPane(ref generalPaneGuid, out pane);
      }
      mOutputPane = pane;
    }
  }

  #endregion

  #region Properties

  public override Encoding Encoding => System.Text.Encoding.Default;

  #endregion

  #region Public Methods

  public override void Write(string aMessage) => mOutputPane.OutputString($"{aMessage}\n");

  public override void Write(char aCharacter) => mOutputPane.OutputString(aCharacter.ToString());

  public void Show(DTE2 aDte)
  {
    mOutputPane.Activate();
    aDte.ExecuteCommand("View.Output", string.Empty);
  }

  public void Clear() => mOutputPane.Clear();

  #endregion
}

If you have a big text to write in output window you usually don't want to freeze the UI. In this purpose you can use a Dispatcher. To write something in output window using this implementation now you can simple do this:

Dispatcher mDispatcher = HwndSource.FromHwnd((IntPtr)mDte.MainWindow.HWnd).RootVisual.Dispatcher;

using (OutputWindow outputWindow = new OutputWindow(mDte))
{
  mDispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
  {
    outputWindow.Write("Write what you want here");
  }));
}

Explain ExtJS 4 event handling

Just two more things I found helpful to know, even if they are not part of the question, really.

You can use the relayEvents method to tell a component to listen for certain events of another component and then fire them again as if they originate from the first component. The API docs give the example of a grid relaying the store load event. It is quite handy when writing custom components that encapsulate several sub-components.

The other way around, i.e. passing on events received by an encapsulating component mycmp to one of its sub-components subcmp, can be done like this

mycmp.on('show' function (mycmp, eOpts)
{
   mycmp.subcmp.fireEvent('show', mycmp.subcmp, eOpts);
});

Hide text using css

Why don't you use:

<li><a href="#">bla</a></li>

a {
    opacity: 0.0;
    font-size: 1px;
}

li {
    background-image: url('test.jpg');
}

If you haven't any span or div element, it works perfectly for links.

Setting query string using Fetch GET request

I know this is stating the absolute obvious, but I feel it's worth adding this as an answer as it's the simplest of all:

const orderId = 1;
fetch('http://myapi.com/orders?order_id=' + orderId);

How to sort a List<Object> alphabetically using Object name field

From your code, it looks like your Comparator is already parameterized with Campaign. This will only work with List<Campaign>. Also, the method you're looking for is compareTo.

if (list.size() > 0) {
  Collections.sort(list, new Comparator<Campaign>() {
      @Override
      public int compare(final Campaign object1, final Campaign object2) {
          return object1.getName().compareTo(object2.getName());
      }
  });
}

Or if you are using Java 1.8

list
  .stream()
  .sorted((object1, object2) -> object1.getName().compareTo(object2.getName()));

One final comment -- there's no point in checking the list size. Sort will work on an empty list.

Purpose of a constructor in Java?

Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.

To understand clearly, see the below simple example:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

Output:

The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE

Clear text in EditText when entered

Also you can use code below

editText.getText().clear();

Get hostname of current request in node.js Express

If you're talking about an HTTP request, you can find the request host in:

request.headers.host

But that relies on an incoming request.

More at http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerRequest

If you're looking for machine/native information, try the process object.

Create a Bitmap/Drawable from file path

It works for me:

File imgFile = new  File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
    Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
    //Drawable d = new BitmapDrawable(getResources(), myBitmap);
    ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
    myImage.setImageBitmap(myBitmap);

}

Edit:

If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:

String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new  File(sdcardPath);

Why do we use Base64?

Most computers store data in 8-bit binary format, but this is not a requirement. Some machines and transmission media can only handle 7 bits (or maybe even lesser) at a time. Such a medium would interpret the stream in multiples of 7 bits, so if you were to send 8-bit data, you won't receive what you expect on the other side. Base-64 is just one way to solve this problem: you encode the input into a 6-bit format, send it over your medium and decode it back to 8-bit format at the receiving end.

Sql Query to list all views in an SQL Server 2005 database

select v.name
from INFORMATION_SCHEMA.VIEWS iv
join sys.views v on v.name = iv.Table_Name
where iv.Table_Catalog = 'Your database name'

Android AlertDialog Single Button

In Mono for Android you can do this:

var ad = new AlertDialog.Builder(this);
ad.SetTitle("Title");
ad.SetMessage("Message");
ad.SetPositiveButton("OK", delegate { ad.Dispose(); });
ad.Show();

Can I use Class.newInstance() with constructor arguments?

myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);

Edit: according to the comments seems like pointing class and method names is not enough for some users. For more info take a look at the documentation for getting constuctor and invoking it.

jQuery $(".class").click(); - multiple elements, click event once

your event is triggered only once... so this code may work try this

    $(".addproduct,.addproduct,.addproduct,.addproduct,.addproduct").click(function(){//do     something fired 5 times});

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Cast string to ObjectId

import mongoose from "mongoose"; // ES6 or above
const mongoose = require('mongoose'); // ES5 or below

let userid = _id
console.log(mongoose.Types.ObjectId(userid)) //5c516fae4e6a1c1cfce18d77

how to select first N rows from a table in T-SQL?

You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

SELECT * 
FROM (SELECT row_number() over (order by UserID) AS line_no, * 
      FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67

You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.

How to open an external file from HTML

If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.

You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).

Pretty printing JSON from Jackson 2.2's ObjectMapper

According to mkyong, the magic incantation is defaultPrintingWriter to pretty print JSON:

Newer versions:

System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));

Older versions:

System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));

Seems I jumped the gun a tad quickly. You could try gson, whose constructor supports pretty-printing:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonOutput = gson.toJson(someObject);

Hope this helps...

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

Save array in mysql database

The way things like that are done is with serializing the array, which means "making a string out of it". To better understand this, have a look on this:

$array = array("my", "litte", "array", 2);

$serialized_array = serialize($array); 
$unserialized_array = unserialize($serialized_array); 

var_dump($serialized_array); // gives back a string, perfectly for db saving!
var_dump($unserialized_array); // gives back the array again

How to clear variables in ipython?

EDITED after @ErdemKAYA comment.

To erase a variable, use the magic command:

%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.

Therefore

%reset_selective -f a 

will erase all the variables containing an a.

Instead, to erase only a and not aa:

In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective? for more examples and https://regexone.com/ for a regex tutorial.

To erase all the variables in the namespace see:

%reset?

Getting the folder name from a path

This is ugly but avoids allocations:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

Split text file into smaller multiple text file using command line

here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();

How to set the width of a RaisedButton in Flutter?

i would recommend using a MaterialButton, than you can do it like this:

new MaterialButton( 
 height: 40.0, 
 minWidth: 70.0, 
 color: Theme.of(context).primaryColor, 
 textColor: Colors.white, 
 child: new Text("push"), 
 onPressed: () => {}, 
 splashColor: Colors.redAccent,
)

Getting permission denied (public key) on gitlab

There is a very simple solution to this: instead of working with ssh - move to https. to do this: in your project folder you have a .git folder in there - you have a config file - open it in a text editor and change the line

url [email protected]:yourname/yourproject.git

to

url = https://gitlab.com/yourname/yourproject.git

Best way to generate a random float in C#

Any reason not to use Random.NextDouble and then cast to float? That will give you a float between 0 and 1.

If you want a different form of "best" you'll need to specify your requirements. Note that Random shouldn't be used for sensitive matters such as finance or security - and you should generally reuse an existing instance throughout your application, or one per thread (as Random isn't thread-safe).

EDIT: As suggested in comments, to convert this to a range of float.MinValue, float.MaxValue:

// Perform arithmetic in double type to avoid overflowing
double range = (double) float.MaxValue - (double) float.MinValue;
double sample = rng.NextDouble();
double scaled = (sample * range) + float.MinValue;
float f = (float) scaled;

EDIT: Now you've mentioned that this is for unit testing, I'm not sure it's an ideal approach. You should probably test with concrete values instead - making sure you test with samples in each of the relevant categories - infinities, NaNs, denormal numbers, very large numbers, zero, etc.

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I same thing happen with me, If your code is correct and then also give 405 error. this error due to some authorization problem. go to authorization menu and change to "Inherit auth from parent".

Authorization Type options menu Authorization Inherit auth from parent selected

Google Play app description formatting

Experimentally, I've discovered that you can provide:

  • Single line breaks are ignored; double line breaks open a new paragraph.
  • Single line breaks can be enforced by ending a line with two spaces (similar to Markdown).
  • A limited set of HTML tags (optionally nested), specifically:
    • <b>…</b> for boldface,
    • <i>…</i> for italics,
    • <u>…</u> for underline,
    • <br /> to enforce a single line break,
    • I could not find any way to get strikethrough working (neither HTML or Markdown style).
  • A fully-formatted URL such as http://google.com; this appears as a hyperlink.
    (Beware that trying to use an HTML <a> tag for a custom description does not work and breaks the formatting.)
  • HTML character entities are supported, such as &rarr; (→), &trade; (™) and &reg; (®); consult this W3 reference for the exhaustive list.
  • UTF-8 encoded characters are supported, such as é, €, £, ‘, ’, ? and ?.
  • Indentation isn't strictly possible, but using a bullet and em space character looks reasonable (&#8226;&#8195; yields "• ").
  • Emoji are also supported (though on the website depends on the user's OS & browser).

Special notes concerning only Google Play app:

  • Some HTML tags only work in the app:
    • <blockquote>…</blockquote> to indent a paragraph of text,
    • <small>…</small> for slightly smaller text,
    • <big>…</big> for slightly larger text,
    • <sup>…</sup> and <sub>…</sub> for super- and subscripts.
    • <font color="#a32345">…</font> for setting font colors in HEX code.
  • Some symbols do not appear correctly, such as ‣.
  • All these notes also apply to the app's "What's New" section.

Special notes concerning only Google Play website:

  • All HTML formatting appears as plain text in the website's "What's New" section (i.e. users will see the HTML source).

Can a constructor in Java be private?

Basic idea behind having a private constructor is to restrict the instantiation of a class from outside by JVM, but if a class having a argument constructor, then it infers that one is intentionally instantiating.

How to get the currently logged in user's user id in Django?

Assuming you are referring to Django's Auth User, in your view:

def game(request):
  user = request.user

  gta = Game.objects.create(name="gta", owner=user)

Creating InetAddress object in Java

ip = InetAddress.getByAddress(new byte[] {
        (byte)192, (byte)168, (byte)0, (byte)102}
);

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.