Programs & Examples On #Collapsiblepanelextender

The CollapsiblePanelExtender is part of the AJAX Control Toolkit for ASP.net

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

How can I convert a zero-terminated byte array to string?

When you do not know the exact length of non-nil bytes in the array, you can trim it first:

string(bytes.Trim(arr, "\x00"))

How to have a drop down <select> field in a rails form?

In your model,

class Contact
  self.email_providers = %w[Gmail Yahoo MSN]
  validates :email_provider, :inclusion => email_providers
end

In your form,

<%= f.select :email_provider, 
    options_for_select(Contact.email_providers, @contact.email_provider) %>

the second arg of the options_for_select will have any current email_provider selected.

How can I display an RTSP video stream in a web page?

the Microsoft Mediaplayer can do all, you need. I use the MS Mediaservices of 2003 / 2008 Server to deliver Video as Broadcast and Unicast Stream. This Service could GET the Stream from the cam and Broadcast it. Than you have "only" the Problem to "Display" that Picture in ALL Browers at all OS-Systems

My Tip :check first the OS , than load your plugin . on Windows it is easy -take WMP , on other take MS Silverligt ...

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

How to parse the AndroidManifest.xml file inside an .apk package

I found the AXMLPrinter2, a Java app over at the Android4Me project to work fine on the AndroidManifest.xml that I had (and prints the XML out in a nicely formatted way). http://code.google.com/p/android4me/downloads/detail?name=AXMLPrinter2.jar

One note.. it (and the code on this answer from Ribo) doesn't appear to handle every compiled XML file that I've come across. I found one where the strings were stored with one byte per character, rather than the double byte format that it assumes.

How do I check if an object has a key in JavaScript?

Try the JavaScript in operator.

if ('key' in myObj)

And the inverse.

if (!('key' in myObj))

Be careful! The in operator matches all object keys, including those in the object's prototype chain.

Use myObj.hasOwnProperty('key') to check an object's own keys and will only return true if key is available on myObj directly:

myObj.hasOwnProperty('key')

Unless you have a specific reason to use the in operator, using myObj.hasOwnProperty('key') produces the result most code is looking for.

Escape double quotes in Java

Yes you will have to escape all double quotes by a backslash.

how can I enable PHP Extension intl?

Starting with PHP 7.2.0, you only need to specify the extension name.

I.e., add the following line to your php.ini:

extension=intl

See PHP's docomentation on loading extensions for more informations.

Is it possible to use JavaScript to change the meta-tags of the page?

Yes, it is possible to add metatags with Javascript. I did in my example

Android not respecting metatag removal?

But, I dont know how to change it other then removing it. Btw, in my example.. when you click the 'ADD' button it adds the tag and the viewport changes respectively but I dont know how to revert it back (remove it, in Android).. I wish there was firebug for Android so I saw what was happening. Firefox does remove the tag. if anybody has any ideas on this please note so in my question.

Exit while loop by user hitting ENTER key

If you want your user to press enter, then the raw_input() will return "", so compare the User with "":

User = raw_input('Press enter to exit...')
running = 1
while running == 1:
    Run your program
if User == "":
    break
else
    running == 1

What languages are Windows, Mac OS X and Linux written in?

As an addition about the core of Mac OS X, Finder had not been written in Objective-C prior to Snow Leopard. In Snow Leopard it was written in Cocoa, Objective-C

How do I get today's date in C# in mm/dd/yyyy format?

DateTime.Now.Date.ToShortDateString()

is culture specific.

It is best to stick with:

DateTime.Now.ToString("d/MM/yyyy");

How to convert numbers to words without using num2word library?

You can do this program in this way. The range is in between 0 to 99,999

def num_to_word(num):
    word_num = { "0": "zero", "00": "", "1" : "One" , "2" : "Two", "3" : "Three", "4" : "Four", "5" : "Five","6" : "Six", "7": "Seven", "8" : "eight", "9" : "Nine","01" : "One" , "02" : "Two", "03" : "Three", "04" : "Four", "05" : "Five","06" : "Six", "07": "Seven", "08" : "eight", "09" : "Nine", "10" : "Ten", "11": "Eleven", "12" :"Twelve", "13" : "Thirteen", "14" : "Fourteen", "15" : "Fifteen", "17":"Seventeen", "18" :"Eighteen", "19": "Nineteen", "20" : "Twenty", "30" : "Thirty", "40" : "Forty", "50" : "Fifty", "60" : "Sixty", "70": "seventy", "80" : "eighty", "90" : "ninety"}
    keys = []
    for k in word_num.keys():
        keys.append(k)

    if len(num) == 1:
        return(word_num[num[0]])
    elif len(num) == 2:
        c = 0
        for k in keys:
            if k == num[0] + num[1]:
                c += 1
        if c == 1:
            return(word_num[num[0] + num[1]])
        else:
            return(word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]])
    elif len(num) == 3:
        c = 0
        for k in keys:
            if k == num[1] + num[2]:
                c += 1
        if c == 1:
            return(word_num[num[0]]+ " Hundred " + word_num[num[1] + num[2]])
        else:
            return(word_num[num[0]]+ " Hundred " + word_num[str(int(num[1]) * 10)] + " " + word_num[num[2]])
    elif len(num) == 4:
        c = 0
        for k in keys:
            if k == num[2] + num[3]:
                c += 1
        if c == 1:
            if num[1] == '0' :
                return(word_num[num[0]]+ " Thousand " + word_num[num[2] + num[3]])
            else:
                return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[num[2] + num[3]])

        else:
            if num[1] == '0' :
                return(word_num[num[0]]+ " Thousand " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
            else:
                return(word_num[num[0]]+ " Thousand " + word_num[num[1]]+ " Hundred " + word_num[str(int(num[2]) * 10)] + " " + word_num[num[3]])
    elif len(num) == 5:
        c = 0
        d = 0
        for k in keys:
            if k == num[3] + num[4]:
                c += 1
        for k in keys:
            if k == num[0] + num[1]:
                d += 1
        if d == 1:
            val = word_num[num[0] + num[1]] 
        else:
            val = word_num[str(int(num[0]) * 10)] + " " + word_num[num[1]]

        if c == 1:
            if num[1] == '0' :
                return(val + " Thousand " + word_num[num[3] + num[4]])
            else:
                return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[num[3] + num[4]])

        else:
            if num[1] == '0' :
                return(val + " Thousand " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])
            else:
                return(val + " Thousand " + word_num[num[2]]+ " Hundred " + word_num[str(int(num[3]) * 10)] + " " + word_num[num[4]])


num = [str(d) for d in input("Enter number: ")]
print(num_to_word(num).upper())

Hibernate, @SequenceGenerator and allocationSize

To be absolutely clear... what you describe does not conflict with the spec in any way. The spec talks about the values Hibernate assigns to your entities, not the values actually stored in the database sequence.

However, there is the option to get the behavior you are looking for. First see my reply on Is there a way to dynamically choose a @GeneratedValue strategy using JPA annotations and Hibernate? That will give you the basics. As long as you are set up to use that SequenceStyleGenerator, Hibernate will interpret allocationSize using the "pooled optimizer" in the SequenceStyleGenerator. The "pooled optimizer" is for use with databases that allow an "increment" option on the creation of sequences (not all databases that support sequences support an increment). Anyway, read up about the various optimizer strategies there.

Removing element from array in component state

I want to chime in here even though this question has already been answered correctly by @pscl in case anyone else runs into the same issue I did. Out of the 4 methods give I chose to use the es6 syntax with arrow functions due to it's conciseness and lack of dependence on external libraries:

Using Array.prototype.filter with ES6 Arrow Functions

removeItem(index) {
  this.setState((prevState) => ({
    data: prevState.data.filter((_, i) => i != index)
  }));
}

As you can see I made a slight modification to ignore the type of index (!== to !=) because in my case I was retrieving the index from a string field.

Another helpful point if you're seeing weird behavior when removing an element on the client side is to NEVER use the index of an array as the key for the element:

// bad
{content.map((content, index) =>
  <p key={index}>{content.Content}</p>
)}

When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.

// good
{content.map(content =>
  <p key={content.id}>{content.Content}</p>
)}

The above is an excerpt from this answer from a related post.

Happy Coding Everyone!

What is the command to truncate a SQL Server log file?

backup log logname with truncate_only followed by a dbcc shrinkfile command

What is Android's file system?

It depends on what filesystem, for example /system and /data are yaffs2 while /sdcard is vfat. This is the output of mount:

rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock0 /system yaffs2 ro 0 0
/dev/block/mtdblock1 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock2 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:0 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

and with respect to other filesystems supported, this is the list

nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   binfmt_misc
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   devpts
nodev   ramfs
         vfat
         msdos
nodev   nfsd
nodev   smbfs
         yaffs
         yaffs2
nodev   rpc_pipefs

How to test if a double is zero?

In Java, 0 is the same as 0.0, and doubles default to 0 (though many advise always setting them explicitly for improved readability). I have checked and foo.x == 0 and foo.x == 0.0 are both true if foo.x is zero

How to make a section of an image a clickable link

If you don't want to make the button a separate image, you can use the <area> tag. This is done by using html similar to this:

<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">

<map name="mapname">
    <area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>

Note 1: The coords=" " attribute must be formatted in this way: coords="x1,y1,x2,y2" where:

x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate

Note 2: The usemap="#mapname" attribute must include the #.

EDIT:

I looked at your code and added in the <map> and <area> tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.

<div class="flexslider">
    <ul class="slides" runat="server" id="Ul">                             
        <li class="flex-active-slide" style="background: url(&quot;images/slider-bg-1.jpg&quot;) no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
            <div class="container">
                <div class="sixteen columns contain"></div>   
                <img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
                <map name="imgmap">
                    <area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
                </map>
                <!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
            </div>
        </li>
    </ul>
</div>
<!-- <ul class="flex-direction-nav">
    <li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
    <li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->

Notes:

  1. The coord="48,341,294,275" is in reference to your screenshot you posted.
  2. The src="./test.png" is the location and name of the screenshot you posted on my computer.
  3. The href="http://www.example.com/" is an example link.

Terminating a Java Program

System.exit() terminates the JVM. Nothing after System.exit() is executed. Return is generally used for exiting a method. If the return type is void, then you could use return; But I don't think is a good practice to do it in the main method. You don't have to do anything for terminate a program, unless infinite loop or some strange other execution flows.

Indexing vectors and arrays with +:

This is another way to specify the range of the bit-vector.

x +: N, The start position of the vector is given by x and you count up from x by N.

There is also

x -: N, in this case the start position is x and you count down from x by N.

N is a constant and x is an expression that can contain iterators.

It has a couple of benefits -

  1. It makes the code more readable.

  2. You can specify an iterator when referencing bit-slices without getting a "cannot have a non-constant value" error.

How to prevent rm from reporting that a file was not found?

Yes, -f is the most suitable option for this.

NotificationCompat.Builder deprecated in Android O

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

Right code will be :

Notification.Builder notification=new Notification.Builder(this)

with dependency 26.0.1 and new updated dependencies such as 28.0.0.

Some users use this code in the form of this :

Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.

So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.

Try this code...It will sure work

Oracle: SQL query to find all the triggers belonging to the tables?

Another table that is useful is:

SELECT * FROM user_objects WHERE object_type='TRIGGER';

You can also use this to query views, indexes etc etc

What is "String args[]"? parameter in main method Java

I would break up

public static void main(String args[])

in parts.

"public" means that main() can be called from anywhere.

"static" means that main() doesn't belong to a specific object

"void" means that main() returns no value

"main" is the name of a function. main() is special because it is the start of the program.

"String[]" means an array of String.

"args" is the name of the String[] (within the body of main()). "args" is not special; you could name it anything else and the program would work the same.

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

Database development mistakes made by application developers

Key database design and programming mistakes made by developers

  • Selfish database design and usage. Developers often treat the database as their personal persistent object store without considering the needs of other stakeholders in the data. This also applies to application architects. Poor database design and data integrity makes it hard for third parties working with the data and can substantially increase the system's life cycle costs. Reporting and MIS tends to be a poor cousin in application design and only done as an afterthought.

  • Abusing denormalised data. Overdoing denormalised data and trying to maintain it within the application is a recipe for data integrity issues. Use denormalisation sparingly. Not wanting to add a join to a query is not an excuse for denormalising.

  • Scared of writing SQL. SQL isn't rocket science and is actually quite good at doing its job. O/R mapping layers are quite good at doing the 95% of queries that are simple and fit well into that model. Sometimes SQL is the best way to do the job.

  • Dogmatic 'No Stored Procedures' policies. Regardless of whether you believe stored procedures are evil, this sort of dogmatic attitude has no place on a software project.

  • Not understanding database design. Normalisation is your friend and it's not rocket science. Joining and cardinality are fairly simple concepts - if you're involved in database application development there's really no excuse for not understanding them.

What is the difference between statically typed and dynamically typed languages?

Statically typed languages: each variable and expression is already known at compile time.

(int a; a can take only integer type values at runtime)

Examples: C, C++, Java

Dynamically typed languages: variables can receive different values at runtime and their type is defined at run time.

(var a; a can take any kind of values at runtime)

Examples: Ruby, Python.

T-SQL CASE Clause: How to specify WHEN NULL

NULL does not equal anything. The case statement is basically saying when the value = NULL .. it will never hit.
There are also several system stored procedures that are written incorrectly with your syntax. See sp_addpullsubscription_agent and sp_who2.
Wish I knew how to notify Microsoft of those mistakes as I'm not able to change the system stored procs.

Resize image proportionally with MaxHeight and MaxWidth constraints

Much longer solution, but accounts for the following scenarios:

  1. Is the image smaller than the bounding box?
  2. Is the Image and the Bounding Box square?
  3. Is the Image square and the bounding box isn't
  4. Is the image wider and taller than the bounding box
  5. Is the image wider than the bounding box
  6. Is the image taller than the bounding box

    private Image ResizePhoto(FileInfo sourceImage, int desiredWidth, int desiredHeight)
    {
        //throw error if bouning box is to small
        if (desiredWidth < 4 || desiredHeight < 4)
            throw new InvalidOperationException("Bounding Box of Resize Photo must be larger than 4X4 pixels.");            
        var original = Bitmap.FromFile(sourceImage.FullName);
    
        //store image widths in variable for easier use
        var oW = (decimal)original.Width;
        var oH = (decimal)original.Height;
        var dW = (decimal)desiredWidth;
        var dH = (decimal)desiredHeight;
    
        //check if image already fits
        if (oW < dW && oH < dH)
            return original; //image fits in bounding box, keep size (center with css) If we made it bigger it would stretch the image resulting in loss of quality.
    
        //check for double squares
        if (oW == oH && dW == dH)
        {
            //image and bounding box are square, no need to calculate aspects, just downsize it with the bounding box
            Bitmap square = new Bitmap(original, (int)dW, (int)dH);
            original.Dispose();
            return square;
        }
    
        //check original image is square
        if (oW == oH)
        {
            //image is square, bounding box isn't.  Get smallest side of bounding box and resize to a square of that center the image vertically and horizontally with Css there will be space on one side.
            int smallSide = (int)Math.Min(dW, dH);
            Bitmap square = new Bitmap(original, smallSide, smallSide);
            original.Dispose();
            return square;
        }
    
        //not dealing with squares, figure out resizing within aspect ratios            
        if (oW > dW && oH > dH) //image is wider and taller than bounding box
        {
            var r = Math.Min(dW, dH) / Math.Min(oW, oH); //two dimensions so figure out which bounding box dimension is the smallest and which original image dimension is the smallest, already know original image is larger than bounding box
            var nH = oH * r; //will downscale the original image by an aspect ratio to fit in the bounding box at the maximum size within aspect ratio.
            var nW = oW * r;
            var resized = new Bitmap(original, (int)nW, (int)nH);
            original.Dispose();
            return resized;
        }
        else
        {
            if (oW > dW) //image is wider than bounding box
            {
                var r = dW / oW; //one dimension (width) so calculate the aspect ratio between the bounding box width and original image width
                var nW = oW * r; //downscale image by r to fit in the bounding box...
                var nH = oH * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
            else
            {
                //original image is taller than bounding box
                var r = dH / oH;
                var nH = oH * r;
                var nW = oW * r;
                var resized = new Bitmap(original, (int)nW, (int)nH);
                original.Dispose();
                return resized;
            }
        }
    }
    

Make a link use POST instead of GET

Another working example, using similar approach posted : create a html form, use javascript to simulate the post. This does 2 things : post data to a new page and open it in a new window/tab.

HTML

<form name='myForm' target="_blank" action='newpage.html' method='post'>
<input type="hidden" name="thisIsTheParameterName" value="testDataToBePosted"/>
</form>

JavaScript

document.forms["myForm"].submit();

Delete empty rows

To delete rows empty in table

syntax:

DELETE FROM table_name 
WHERE column_name IS NULL;

example:

Table name: data ---> column name: pkdno

DELETE FROM data 
WHERE pkdno IS NULL;

Answer: 5 rows deleted. (sayso)

How do I center list items inside a UL element?

Neither text-align:center nor display:inline-block worked for me on their own, but combining both did:

ul {
  text-align: center;
}
li {
  display: inline-block;
}

How to download file in swift?

Swift 4 and Swift 5 Version if Anyone still needs this

import Foundation

class FileDownloader {

    static func loadFileSync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else if let dataFromURL = NSData(contentsOf: url)
        {
            if dataFromURL.write(to: destinationUrl, atomically: true)
            {
                print("file saved [\(destinationUrl.path)]")
                completion(destinationUrl.path, nil)
            }
            else
            {
                print("error saving file")
                let error = NSError(domain:"Error saving file", code:1001, userInfo:nil)
                completion(destinationUrl.path, error)
            }
        }
        else
        {
            let error = NSError(domain:"Error downloading file", code:1002, userInfo:nil)
            completion(destinationUrl.path, error)
        }
    }

    static func loadFileAsync(url: URL, completion: @escaping (String?, Error?) -> Void)
    {
        let documentsUrl =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)

        if FileManager().fileExists(atPath: destinationUrl.path)
        {
            print("File already exists [\(destinationUrl.path)]")
            completion(destinationUrl.path, nil)
        }
        else
        {
            let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
            let task = session.dataTask(with: request, completionHandler:
            {
                data, response, error in
                if error == nil
                {
                    if let response = response as? HTTPURLResponse
                    {
                        if response.statusCode == 200
                        {
                            if let data = data
                            {
                                if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
                                {
                                    completion(destinationUrl.path, error)
                                }
                                else
                                {
                                    completion(destinationUrl.path, error)
                                }
                            }
                            else
                            {
                                completion(destinationUrl.path, error)
                            }
                        }
                    }
                }
                else
                {
                    completion(destinationUrl.path, error)
                }
            })
            task.resume()
        }
    }
}

Here is how to call this method :-

let url = URL(string: "http://www.filedownloader.com/mydemofile.pdf")
FileDownloader.loadFileAsync(url: url!) { (path, error) in
    print("PDF File downloaded to : \(path!)")
}

dll missing in JDBC

You have to make sure your DLL is in the classpath.

One such way to do so is to put the path to the DLL in PATH environment variable.

Other option is to add it to the VM arguments in the variable LD_LIBRARY_PATH, like this:

java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass

Is there an arraylist in Javascript?

Try this, maybe can help, it do what you want:

ListArray

_x000D_
_x000D_
var listArray = new ListArray();_x000D_
let element = {name: 'Edy', age: 27, country: "Brazil"};_x000D_
let element2 = {name: 'Marcus', age: 27, country: "Brazil"};_x000D_
listArray.push(element);_x000D_
listArray.push(element2);_x000D_
_x000D_
console.log(listArray.array)
_x000D_
<script src="https://marcusvi200.github.io/list-array/script/ListArray.js"></script>
_x000D_
_x000D_
_x000D_

To draw an Underline below the TextView in Android

In Kotlin you can create extension property:

inline var TextView.underline: Boolean
    set(visible) {
        paintFlags = if (visible) paintFlags or Paint.UNDERLINE_TEXT_FLAG
        else paintFlags and Paint.UNDERLINE_TEXT_FLAG.inv()
    }
    get() = paintFlags and Paint.UNDERLINE_TEXT_FLAG == Paint.UNDERLINE_TEXT_FLAG

And use:

textView.underline = true

How to parse JSON in Scala using standard Scala classes?

val jsonString =
  """
    |{
    | "languages": [{
    |     "name": "English",
    |     "is_active": true,
    |     "completeness": 2.5
    | }, {
    |     "name": "Latin",
    |     "is_active": false,
    |     "completeness": 0.9
    | }]
    |}
  """.stripMargin

val result = JSON.parseFull(jsonString).map {
  case json: Map[String, List[Map[String, Any]]] =>
    json("languages").map(l => (l("name"), l("is_active"), l("completeness")))
}.get

println(result)

assert( result == List(("English", true, 2.5), ("Latin", false, 0.9)) )

What is the best method to merge two PHP objects?

a solution To preserve,both methods and properties from merged onjects is to create a combinator class that can

  • take any number of objects on __construct
  • access any method using __call
  • accsess any property using __get

class combinator{
function __construct(){       
    $this->melt =  array_reverse(func_get_args());
      // array_reverse is to replicate natural overide
}
public function __call($method,$args){
    forEach($this->melt as $o){
        if(method_exists($o, $method)){
            return call_user_func_array([$o,$method], $args);
            //return $o->$method($args);
            }
        }
    }
public function __get($prop){
        foreach($this->melt as $o){
          if(isset($o->$prop))return $o->$prop;
        }
        return 'undefined';
    } 
}

simple use

class c1{
    public $pc1='pc1';
    function mc1($a,$b){echo __METHOD__." ".($a+$b);}
}
class c2{
    public $pc2='pc2';
    function mc2(){echo __CLASS__." ".__METHOD__;}
}

$comb=new combinator(new c1, new c2);

$comb->mc1(1,2);
$comb->non_existing_method();  //  silent
echo $comb->pc2;

How to use global variable in node.js?

May be following is better to avoid the if statement:

global.logger || (global.logger = require('my_logger'));

How to compile and run a C/C++ program on the Android system

You can compile your C programs with an ARM cross-compiler:

arm-linux-gnueabi-gcc -static -march=armv7-a test.c -o test

Then you can push your compiled binary file to somewhere (don't push it in to the SD card):

adb push test /data/local/tmp/test

How do I read text from the clipboard?

The python standard library does it...

try:
    # Python3
    import tkinter as tk
except ImportError:
    # Python2
    import Tkinter as tk

def getClipboardText():
    root = tk.Tk()
    # keep the window from showing
    root.withdraw()
    return root.clipboard_get()

Build fails with "Command failed with a nonzero exit code"

I got the same error when linking separate storyboards. The error, "Command CompileSwiftSources failed with a nonzero exit code." is shown because I simply forgot to set the view controller inside the second storyboard that I am linking as 'an initial view controller'.

What is the difference between `sorted(list)` vs `list.sort()`?

The main difference is that sorted(some_list) returns a new list:

a = [3, 2, 1]
print sorted(a) # new list
print a         # is not modified

and some_list.sort(), sorts the list in place:

a = [3, 2, 1]
print a.sort() # in place
print a         # it's modified

Note that since a.sort() doesn't return anything, print a.sort() will print None.


Can a list original positions be retrieved after list.sort()?

No, because it modifies the original list.

removing table border

Most of the time your background color is different from the background of your table. Since there are spaces between the cells, those spaces will create the illusion of lines with the color of the background behind the table.

The solution is to get rid of those spaces.

Inside the table tag write:

cellspacing="0"

How to convert Map keys to array?

Not exactly best answer to question but this trick new Array(...someMap) saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.

  let map = new Map();
  map.set("1", 1);
  map.set("2", 2);
  console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]

Proper way to make HTML nested list?

Option 2

<ul>
<li>Choice A</li>
<li>Choice B
  <ul>
    <li>Sub 1</li>
    <li>Sub 2</li>
  </ul>
</li>
</ul>

Nesting Lists - UL

Python Pandas : pivot table with aggfunc = count unique distinct

Since none of the answers are up to date with the last version of Pandas, I am writing another solution for this problem:

In [1]:
import pandas as pd

# Set exemple
df2 = pd.DataFrame({'X' : ['X1', 'X1', 'X1', 'X1'], 'Y' : ['Y2','Y1','Y1','Y1'], 'Z' : ['Z3','Z1','Z1','Z2']})

# Pivot
pd.crosstab(index=df2['Y'], columns=df2['Z'], values=df2['X'], aggfunc=pd.Series.nunique)

Out [1]:
Z   Z1  Z2  Z3
Y           
Y1  1.0 1.0 NaN
Y2  NaN NaN 1.0

Installing PDO driver on MySQL Linux server

Basically the answer from Jani Hartikainen is right! I upvoted his answer. What was missing on my system (based on Ubuntu 15.04) was to enable PDO Extension in my php.ini

extension=pdo.so
extension=pdo_mysql.so

restart the webserver (e.g. with "sudo service apache2 restart") -> every fine :-)

To find where your current active php.ini file is located you can use phpinfo() or some other hints from here: https://www.ostraining.com/blog/coding/phpini-file/

Exact time measurement for performance testing

As others have said, Stopwatch is a good class to use here. You can wrap it in a helpful method:

public static TimeSpan Time(Action action)
{
    Stopwatch stopwatch = Stopwatch.StartNew();
    action();
    stopwatch.Stop();
    return stopwatch.Elapsed;
}

(Note the use of Stopwatch.StartNew(). I prefer this to creating a Stopwatch and then calling Start() in terms of simplicity.) Obviously this incurs the hit of invoking a delegate, but in the vast majority of cases that won't be relevant. You'd then write:

TimeSpan time = StopwatchUtil.Time(() =>
{
    // Do some work
});

You could even make an ITimer interface for this, with implementations of StopwatchTimer, CpuTimer etc where available.

How find out which process is using a file in Linux?

You can use the fuser command, like:

fuser file_name

You will receive a list of processes using the file.

You can use different flags with it, in order to receive a more detailed output.

You can find more info in the fuser's Wikipedia article, or in the man pages.

What is the purpose of nameof?

It has advantage when you use ASP.Net MVC. When you use HTML helper to build some control in view it uses property names in name attribure of html input:

@Html.TextBoxFor(m => m.CanBeRenamed)

It makes something like that:

<input type="text" name="CanBeRenamed" />

So now, if you need to validate your property in Validate method you can do this:

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
  if (IsNotValid(CanBeRenamed)) {
    yield return new ValidationResult(
      $"Property {nameof(CanBeRenamed)} is not valid",
      new [] { $"{nameof(CanBeRenamed)}" })
  }
}

In case if you rename you property using refactoring tools, your validation will not be broken.

Error: package or namespace load failed for ggplot2 and for data.table

when you see

Do you want to install from sources the package which needs compilation? (Yes/no/cancel)

answer no

Understanding the Gemfile.lock file

It seems no clear document talking on the Gemfile.lock format. Maybe it's because Gemfile.lock is just used by bundle internally.

However, since Gemfile.lock is a snapshot of Gemfile, which means all its information should come from Gemfile (or from default value if not specified in Gemfile).

For GEM, it lists all the dependencies you introduce directly or indirectly in the Gemfile. remote under GEM tells where to get the gems, which is specified by source in Gemfile.

If a gem is not fetch from remote, PATH tells the location to find it. PATH's info comes from path in Gemfile when you declare a dependency.

And PLATFORM is from here.

For DEPENDENCIES, it's the snapshot of dependencies resolved by bundle.

Move branch pointer to different commit without checkout

If you want to move a non-checked out branch to another commit, the easiest way is running the git branch command with -f option, which determines where the branch HEAD should be pointing to:

git branch -f

Be careful as this won't work if the branch you are trying to move is your current branch. To move a branch pointer, run the following command: git update-ref -m "reset: Reset to " refs/heads/

The git update-ref command updates the object name stored in a ref safely.

Hope, my answer helped you.The source of information is this snippet.

How to annotate MYSQL autoincrement field with JPA annotations

As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.

@Entity
public class Operator{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String username;

  private String password;

  private Integer active;

  //Getters and setters...
}

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

How to fix UITableView separator on iOS 7?

This is default by iOS7 design. try to do the below:

[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];

You can set the 'Separator Inset' from the storyboard:

enter image description here

enter image description here

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Beautiful! Your solution was 99%... instead of "this.scrollY", I used "$(window).scrollTop()". What's even better is that this solution only requires the jQuery1.2.6 library (no additional libraries needed).

The reason I wanted that version in particular is because that's what ships with MVC currently.

Here's the code:

$(document).ready(function() {
    $("#topBar").css("position", "absolute");
});

$(window).scroll(function() {
    $("#topBar").css("top", $(window).scrollTop() + "px");
});

Pass entire form as data in jQuery Ajax function

serialize() is not a good idea if you want to send a form with post method. For example if you want to pass a file via ajax its not gonna work.

Suppose that we have a form with this id : "myform".

the better solution is to make a FormData and send it:

    var myform = document.getElementById("myform");
    var fd = new FormData(myform );
    $.ajax({
        url: "example.php",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (dataofconfirm) {
            // do something with the result
        }
    });

ScrollTo function in AngularJS

This is a better directive in case you would like to use it:

you can scroll to any element in the page:

.directive('scrollToItem', function() {                                                      
    return {                                                                                 
        restrict: 'A',                                                                       
        scope: {                                                                             
            scrollTo: "@"                                                                    
        },                                                                                   
        link: function(scope, $elm,attr) {                                                   

            $elm.on('click', function() {                                                    
                $('html,body').animate({scrollTop: $(scope.scrollTo).offset().top }, "slow");
            });                                                                              
        }                                                                                    
    }})     

Usage (for example click on div 'back-to-top' will scroll to id scroll-top):

<a id="top-scroll" name="top"></a>
<div class="back-to-top" scroll-to-item scroll-to="#top-scroll"> 

It's also supported by chrome,firefox,safari and IE cause of the html,body element .

flow 2 columns of text automatically with CSS

Use CSS3

.container {
   -webkit-column-count: 2;
      -moz-column-count: 2;
           column-count: 2;

   -webkit-column-gap: 20px;
      -moz-column-gap: 20px;
           column-gap: 20px;
}

Browser Support

  • Chrome 4.0+ (-webkit-)
  • IE 10.0+
  • Firefox 2.0+ (-moz-)
  • Safari 3.1+ (-webkit-)
  • Opera 15.0+ (-webkit-)

How to output in CLI during execution of PHP Unit tests?

For some cases one could use something like that to output something to the console

class yourTests extends PHPUnit_Framework_TestCase
{
    /* Add Warnings */
    protected function addWarning($msg, Exception $previous = null)
    {
        $add_warning = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
        $add_warning->addWarning($this, $msg, time());
        $this->setTestResultObject($add_warning);
    }

    /* Add errors */
    protected function addError($msg, Exception $previous = null)
    {
        $add_error = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_error->addError($this, $msg, time());
        $this->setTestResultObject($add_error);
    }

    /* Add failures */
    protected function addFailure($msg, Exception $previous = null)
    {
        $add_failure = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_failure->addFailure($this, $msg, time());
        $this->setTestResultObject($add_failure);
    }

    public function test_messages()
    {
        $this->addWarning("Your warning message!");
        $this->addError("Your error message!");
        $this->addFailure("Your Failure message");
    }

    /* Or just mark test states! */
    public function test_testMarking()
    {
        $this->markTestIncomplete();
        $this->markTestSkipped();
    }
}

Cast object to T

You could require the type to be a reference type :

 private static T ReadData<T>(XmlReader reader, string value) where T : class
 {
     reader.MoveToAttribute(value);
     object readData = reader.ReadContentAsObject();
     return (T)readData;
 }

And then do another that uses value types and TryParse...

 private static T ReadDataV<T>(XmlReader reader, string value) where T : struct
 {
     reader.MoveToAttribute(value);
     object readData = reader.ReadContentAsObject();
     int outInt;
     if(int.TryParse(readData, out outInt))
        return outInt
     //...
 }

Calculating how many days are between two dates in DB2?

I think that @Siva is on the right track (using DAYS()), but the nested CONCAT()s are making me dizzy. Here's my take.
Oh, there's no point in referencing sysdummy1, as you need to pull from a table regardless.
Also, don't use the implicit join syntax - it's considered an SQL Anti-pattern.

I'be wrapped the date conversion in a CTE for readability here, but there's nothing preventing you from doing it inline.

WITH Converted (convertedDate) as (SELECT DATE(SUBSTR(chdlm, 1, 4) || '-' ||
                                               SUBSTR(chdlm, 5, 2) || '-' ||    
                                               SUBSTR(chdlm, 7, 2))
                                   FROM Chcart00
                                   WHERE chstat = '05')

SELECT DAYS(CURRENT_DATE) - DAYS(convertedDate)
FROM Converted

How to add display:inline-block in a jQuery show() function?

Razz's solution would work for the .hide() and .show() methods but would not work for the .toggle() method.

Depending upon the scenario, having a css class .inline_block { display: inline-block; } and calling $(element).toggleClass('inline_block') solves the problem for me.

How to get the latest record in each group using GROUP BY?

Just complementing what Devart said, the below code is not ordering according to the question:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;

Regards,

Change package name for Android in React Native

The init script generates a unique identifier for Android based on the name you gave it (e.g. com.acmeapp for AcmeApp).

You can see what name was generated by looking for the applicationId key in android/app/build.gradle.

If you need to change that unique identifier, do it now as described below:

In the /android folder, replace all occurrences of com.acmeapp by com.acme.app

Then change the directory structure with the following commands:

mkdir android/app/src/main/java/com/acme

mv android/app/src/main/java/com/acmeapp android/app/src/main/java/com/acme/app

You need a folder level for each dot in the app identifier.

Source: https://blog.elao.com/en/dev/from-react-native-init-to-app-stores-real-quick/

How to create an empty file at the command line in Windows?

Without redirection, Luc Vu or Erik Konstantopoulos point out to:

copy NUL EMptyFile.txt
copy /b NUL EmptyFile.txt

"How to create empty text file from a batch file?" (2008) also points to:

type NUL > EmptyFile.txt
# also
echo. 2>EmptyFile.txt
copy nul file.txt > nul # also in qid's answer below
REM. > empty.file
fsutil file createnew file.cmd 0 # to create a file on a mapped drive

Nomad mentions an original one:

C:\Users\VonC\prog\tests>aaaa > empty_file
'aaaa' is not recognized as an internal or external command, operable program or batch file.

C:\Users\VonC\prog\tests>dir

 Folder C:\Users\VonC\prog\tests

27/11/2013  10:40    <REP>          .
27/11/2013  10:40    <REP>          ..
27/11/2013  10:40                 0 empty_file

In the same spirit, Samuel suggests in the comments:

the shortest one I use is basically the one by Nomad:

.>out.txt

It does give an error:

'.' is not recognized as an internal or external command

But this error is on stderr. And > only redirects stdout, where nothing have been produced.
Hence the creation of an empty file.
The error message can be disregarded here. Or, as in Rain's answer, redirected to NUL:

.>out.txt 2>NUL

(Original answer, November 2009)

echo.>filename

(echo "" would actually put "" in the file! And echo without the '.' would put "Command ECHO activated" in the file...)

Note: the resulting file is not empty but includes a return line sequence: 2 bytes.


This discussion points to a true batch solution for a real empty file:

 <nul (set/p z=) >filename

 dir filename
 11/09/2009  19:45                 0 filename
 1 file(s)                         0 bytes

The "<nul" pipes a nul response to the set/p command, which will cause the variable used to remain unchanged. As usual with set/p, the string to the right of the equal sign is displayed as a prompt with no CRLF.

Since here the "string to the right of the equal sign" is empty... the result is an empty file.


The difference with cd. > filename (which is mentioned in Patrick Cuff's answer and does also produce a 0-byte-length file) is that this "bit of redirection" (the <nul... trick) can be used to echo lines without any CR:

<nul (set/p z=hello) >out.txt
<nul (set/p z= world!) >>out.txt
dir out.txt

The dir command should indicate the file size as 11 bytes: "helloworld!".

How to use BigInteger?

Since you are summing up some int values together, there is no need to use BigInteger. long is enough for that. int is 32 bits, while long is 64 bits, that can contain the sum of all int values.

EditText onClickListener in Android

Here is the solution I implemented

mPickDate.setOnKeyListener(new View.OnKeyListener() {

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        showDialog(DATE_DIALOG_ID);
        return false;
    }
});

OR

mPickDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        showDialog(DATE_DIALOG_ID);

    }
});

See the differences by yourself. Problem is since (like RickNotFred said) TextView to display the date & edit via the DatePicker. TextEdit is not used for its primary purpose. If you want the DatePicker to re-pop up, you need to input delete (1st case) or de focus (2nd case).

Ray

How to convert FileInputStream to InputStream?

FileInputStream is an inputStream.

FileInputStream fis = new FileInputStream("c://filename");
InputStream is = fis;
fis.close();  
return is;

Of course, this will not do what you want it to do; the stream you return has already been closed. Just return the FileInputStream and be done with it. The calling code should close it.

How to get Device Information in Android

Try this:

// Code For IMEI AND IMSI NUMBER

String serviceName = Context.TELEPHONY_SERVICE;
TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
String IMEI,IMSI;
IMEI = m_telephonyManager.getDeviceId();
IMSI = m_telephonyManager.getSubscriberId();

to_string not declared in scope

I fixed this problem by changing the first line in Application.mk from

APP_STL := gnustl_static

to

APP_STL := c++_static

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

WSDL: Stands for Web Service Description Language

In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL files. For example you cannot use same file for .Net and php client. The WSDL file has some descriptions about web service functions. The type of this file is XML. SOAP is an alternative for REST.

REST: Stands for Representational State Transfer

It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL files. The CRUD operation can be implemented by different HTTP Verbs(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP protocol and most of times the response is in JSON or XML format. On the other hand the client application have to exactly call the related HTTP Verb via exact parameters names and types. Due to not having special file for definition, like WSDL, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.

SOA: Stands for Service Oriented Architecture

Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time. Both REST and SOAP web services are kind of SOA.

JSON: Stands for javascript Object Notation

when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :

class Human{
 string Name;
 string Family;
 int Age;
}

and you have some instances from this class :

Human h1 = new Human(){
  Name='Saman',
  Family='Gholami',
  Age=26
}

when you serialize the h1 object to JSON the result is :

  [h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]

javascript can evaluate this format by eval() function and make an associative array from this JSON string. This one is different concept in comparison to other concepts I described formerly.

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

How do I extract data from a DataTable?

Please consider using some code like this:

SqlDataReader reader = command.ExecuteReader();
int numRows = 0;
DataTable dt = new DataTable();

dt.Load(reader);
numRows = dt.Rows.Count;

string attended_type = "";

for (int index = 0; index < numRows; index++)
{
    attended_type = dt.Rows[indice2]["columnname"].ToString();
}

reader.Close();

Find the least number of coins required that can make any change from 1 to 99 cents

What you are looking for is Dynamic Programming.

You don't actually have to enumerate all the possible combinations for every possible values, because you can build it on top of previous answers.

You algorithm need to take 2 parameters:

  • The list of possible coin values, here [1, 5, 10, 25]
  • The range to cover, here [1, 99]

And the goal is to compute the minimal set of coins required for this range.

The simplest way is to proceed in a bottom-up fashion:

Range     Number of coins (in the minimal set)
          1   5   10   25
[1,1]     1
[1,2]     2
[1,3]     3
[1,4]     4
[1,5]     5
[1,5]*    4   1             * two solutions here
[1,6]     4   1
[1,9]     4   1
[1,10]    5   1             * experience tells us it's not the most viable one :p
[1,10]    4   2             * not so viable either
[1,10]    4   1   1
[1,11]    4   1   1
[1,19]    4   1   1
[1,20]    5   1   1         * not viable (in the long run)
[1,20]    4   2   1         * not viable (in the long run)
[1,20]    4   1   2

It is somewhat easy, at each step we can proceed by adding at most one coin, we just need to know where. This boils down to the fact that the range [x,y] is included in [x,y+1] thus the minimal set for [x,y+1] should include the minimal set for [x,y].

As you may have noticed though, sometimes there are indecisions, ie multiple sets have the same number of coins. In this case, it can only be decided later on which one should be discarded.

It should be possible to improve its running time, when noticing that adding a coin usually allows you to cover a far greater range that the one you added it for, I think.

For example, note that:

 [1,5]    4*1  1*5
 [1,9]    4*1  1*5

we add a nickel to cover [1,5] but this gives us up to [1,9] for free!

However, when dealing with outrageous input sets [2,3,5,10,25] to cover [2,99], I am unsure as how to check quickly the range covered by the new set, or it would be actually more efficient.

How do I overload the [] operator in C#

public int this[int index]
{
    get => values[index];
}

MetadataException when using Entity Framework Entity Connection

Found the problem.

The standard metadata string looks like this:

metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl

And this works fine in most cases. However, in some (including mine) Entity Framework get confused and does not know which dll to look in. Therefore, change the metadata string to:

metadata=res://nameOfDll/Model.csdl|res://nameOfDll/Model.ssdl|res://nameOfDll/Model.msl

And it will work. It was this link that got me on the right track:

http://itstu.blogspot.com/2008/07/to-load-specified-metadata-resource.html

Although I had the oposite problem, did not work in unit test, but worked in service.

Copying text outside of Vim with set mouse=a enabled

I accidently explained how to switch off set mouse=a, when I reread the question and found out that the OP did not want to switch it off in the first place. Anyway for anyone searching how to switch off the mouse (set mouse=) centrally, I leave a reference to my answer here: https://unix.stackexchange.com/a/506723/194822

Select subset of columns in data.table R

To subset by column index (to avoid typing their names) you can do

dt[, .SD, .SDcols = -c(1:3, 5L)]

result seems ok

            V4          V6         V7         V8         V9       V10
 1: 0.51500037 0.919066234 0.49447244 0.19564261 0.51945102 0.7238604
 2: 0.36477648 0.828889808 0.04564637 0.20265215 0.32255945 0.4483778
 3: 0.10853112 0.601278633 0.58363636 0.47807015 0.58061000 0.2584015
 4: 0.57569100 0.228642846 0.25734995 0.79528506 0.52067802 0.6644448
 5: 0.07873759 0.840349039 0.77798153 0.48699653 0.98281006 0.4480908
 6: 0.31347303 0.670762371 0.04591664 0.03428055 0.35916057 0.1297684
 7: 0.45374290 0.957848949 0.99383496 0.43939774 0.33470618 0.9429592
 8: 0.99403107 0.009750809 0.78816609 0.34713435 0.57937680 0.9227709
 9: 0.62776909 0.400467655 0.49433474 0.81536420 0.01637135 0.4942351
10: 0.10318372 0.177712847 0.27678497 0.59554454 0.29532020 0.7117959

Angular cli generate a service and include the provider in one step

Actually, it is possible to provide the service (or guard, since that also needs to be provided) when creating the service.

The command is the following...

ng g s services/backendApi --module=app.module

Edit

It is possible to provide to a feature module, as well, you must give it the path to the module you would like.

ng g s services/backendApi --module=services/services.module

How do I make the return type of a method generic?

You need to make it a generic method, like this:

public static T ConfigSetting<T>(string settingName)
{  
    return /* code to convert the setting to T... */
}

But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType, assuming that all the relevant types are supported:

public static T ConfigSetting<T>(string settingName)
{  
    object value = ConfigurationManager.AppSettings[settingName];
    return (T) Convert.ChangeType(value, typeof(T));
}

I'm not entirely convinced that all this is a good idea, mind you...

Sorting list based on values from another list

Also, if you don't mind using numpy arrays (or in fact already are dealing with numpy arrays...), here is another nice solution:

people = ['Jim', 'Pam', 'Micheal', 'Dwight']
ages = [27, 25, 4, 9]

import numpy
people = numpy.array(people)
ages = numpy.array(ages)
inds = ages.argsort()
sortedPeople = people[inds]

I found it here: http://scienceoss.com/sort-one-list-by-another-list/

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

Playing HTML5 video on fullscreen in android webview

Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView will get it working on API level 21+

if (Build.VERSION.SDK_INT >= 21) {
      videoViewContainer.setBackgroundColor(Color.BLACK);
      ((ViewGroup) webView.getParent()).addView(videoViewContainer);
      webView.scrollTo(0,0);  // centers full screen view 
} else {
      activityNonVideoView.setVisibility(View.INVISIBLE);
      ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
      activityVideoView.addView(videoViewContainer,vg);
      activityVideoView.setVisibility(View.VISIBLE);
}

You will also need to reflect the changes in onHideCustomView

Swing/Java: How to use the getText and setText string properly

You are setting the label text before the button is clicked to "txt". Instead when the button is clicked call setText() on the label and pass it the text from the text field.

Example:

label1.setText(nameField.getText()); 

Unit Testing C Code

I use CxxTest for an embedded c/c++ environment (primarily C++).

I prefer CxxTest because it has a perl/python script to build the test runner. After a small slope to get it setup (smaller still since you don't have to write the test runner), it's pretty easy to use (includes samples and useful documentation). The most work was setting up the 'hardware' the code accesses so I could unit/module test effectively. After that it's easy to add new unit test cases.

As mentioned previously it is a C/C++ unit test framework. So you will need a C++ compiler.

CxxTest User Guide CxxTest Wiki

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

When to use setAttribute vs .attribute= in JavaScript?

This looks like one case where it is better to use setAttribute:

Dev.Opera — Efficient JavaScript

var posElem = document.getElementById('animation');
var newStyle = 'background: ' + newBack + ';' +
'color: ' + newColor + ';' +
    'border: ' + newBorder + ';';
if(typeof(posElem.style.cssText) != 'undefined') {
    posElem.style.cssText = newStyle;
} else {
    posElem.setAttribute('style', newStyle);
}

After submitting a POST form open a new window showing the result

Simplest working solution for flow window (tested at Chrome):

<form action='...' method=post target="result" onsubmit="window.open('','result','width=800,height=400');">
    <input name="..">
    ....
</form>

How to edit an Android app?

You would need to decompile the apk as Davis suggested, can use tools such as apkTool , then if you need to change the source code you would need other tools to do that.

You would then need to put the apk back together and sign it, if you don't have the original key used to sign the apk this means the new apk will have a different signature.

If the developer employed any obfuscation or other techniques to protect the app then it gets more complicated.

In short its a pretty complex and technical procedure, so if the developer is really just out of reach, its better to wait until he is in reach. And ask for the source code next time.

What's the difference between Docker Compose vs. Dockerfile

The Compose file describes the container in its running state, leaving the details on how to build the container to Dockerfiles. http://deninet.com/blog/1587/docker-scratch-part-4-compose-and-volumes

When you define your app with Compose in development, you can use this definition to run your application in different environments such as CI, staging, and production. https://docs.docker.com/compose/production/

It is also seems that Compose is considered production safe as of 1.11, since https://docs.docker.com/v1.11/compose/production/ no longer has a warning not to use it in production like https://docs.docker.com/v1.10/compose/production/ does.

How do I fix "The expression of type List needs unchecked conversion...'?

This is a common problem when dealing with pre-Java 5 APIs. To automate the solution from erickson, you can create the following generic method:

public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
    List<T> r = new ArrayList<T>(c.size());
    for(Object o: c)
      r.add(clazz.cast(o));
    return r;
}

This allows you to do:

List<SyndEntry> entries = castList(SyndEntry.class, sf.getEntries());

Because this solution checks that the elements indeed have the correct element type by means of a cast, it is safe, and does not require SuppressWarnings.

The difference between fork(), vfork(), exec() and clone()

  • execve() replaces the current executable image with another one loaded from an executable file.
  • fork() creates a child process.
  • vfork() is a historical optimized version of fork(), meant to be used when execve() is called directly after fork(). It turned out to work well in non-MMU systems (where fork() cannot work in an efficient manner) and when fork()ing processes with a huge memory footprint to run some small program (think Java's Runtime.exec()). POSIX has standardized the posix_spawn() to replace these latter two more modern uses of vfork().
  • posix_spawn() does the equivalent of a fork()/execve(), and also allows some fd juggling in between. It's supposed to replace fork()/execve(), mainly for non-MMU platforms.
  • pthread_create() creates a new thread.
  • clone() is a Linux-specific call, which can be used to implement anything from fork() to pthread_create(). It gives a lot of control. Inspired on rfork().
  • rfork() is a Plan-9 specific call. It's supposed to be a generic call, allowing several degrees of sharing, between full processes and threads.

React: why child component doesn't update when prop changes

Confirmed, adding a Key works. I went through the docs to try and understand why.

React wants to be efficient when creating child components. It won't render a new component if it's the same as another child, which makes the page load faster.

Adding a Key forces React to render a new component, thus resetting State for that new component.

https://reactjs.org/docs/reconciliation.html#recursing-on-children

Uncaught TypeError: data.push is not a function

Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:

var history = [];
history.push("what a mess");

replacing it for:

var history123 = [];
history123.push("pray for a better language");

works as expected.

How can I see the size of files and directories in linux?

Go to the chosen directory and execute:

$ du -d 1 -h

where:

-d 1 is the depth of the directories

-h is the human-readable option

You'll see like that:

0   ./proc
8.5M    ./run
0   ./sys
56M ./etc
12G ./root
33G ./var
23M ./tmp
3.2G    ./usr
154M    ./boot
26G ./home
0   ./media
0   ./mnt
421M    ./opt
0   ./srv
2.6G    ./backups
80G .

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

Open Jquery modal dialog on click event

try

$(document).ready(function () {
    //$('#dialog').dialog(); 
    $('#dialog_link').click(function () {
        $('#dialog').dialog('open');
        return false;
    });
});

there is a open arg in the last part

How do you rename a MongoDB database?

No there isn't. See https://jira.mongodb.org/browse/SERVER-701

Unfortunately, this is not an simple feature for us to implement due to the way that database metadata is stored in the original (default) storage engine. In MMAPv1 files, the namespace (e.g.: dbName.collection) that describes every single collection and index includes the database name, so to rename a set of database files, every single namespace string would have to be rewritten. This impacts:

  • the .ns file
  • every single numbered file for the collection
  • the namespace for every index
  • internal unique names of each collection and index
  • contents of system.namespaces and system.indexes (or their equivalents in the future)
  • other locations I may be missing

This is just to accomplish a rename of a single database in a standalone mongod instance. For replica sets the above would need to be done on every replica node, plus on each node every single oplog entry that refers this database would have to be somehow invalidated or rewritten, and then if it's a sharded cluster, one also needs to add these changes to every shard if the DB is sharded, plus the config servers have all the shard metadata in terms of namespaces with their full names.

There would be absolutely no way to do this on a live system.

To do it offline, it would require re-writing every single database file to accommodate the new name, and at that point it would be as slow as the current "copydb" command...

Custom Date Format for Bootstrap-DatePicker

I'm sure you are using a old version. You must use the last version available at master branch:

https://github.com/eternicode/bootstrap-datepicker

Getting Error 800a0e7a "Provider cannot be found. It may not be properly installed."

You should use the provider available in your machine.

  1. Goto Control Panel
  2. Goto Administrator Tools
  3. Goto Data Sources (ODBC)
  4. Click the "Drivers" tab.
  5. Do you see something called "SQL Server Native Client"?

enter image description here

See the attached screen shot. Here my provider will be SQLNCLI11.0

Installing Java 7 on Ubuntu

Oracle as well as modern versions of Ubuntu have moved to newer versions of Java. The default for Ubuntu 20.04 is OpenJDK 11 which is good enough for most purposes.

If you really need it for running legacy programs, OpenJDK 8 is also available for Ubuntu 20.04 from the official repositories.

If you really need exactly Java 7, the best bet as of 2020 is to download a Zulu distribution. The easiest to install if you have root privileges is the .DEB version, otherwise download the .ZIP one.

https://www.azul.com/downloads/zulu-community/?version=java-7-lts&os=ubuntu&architecture=x86-64-bit&package=jdk

Link to the issue number on GitHub within a commit message

Just as addition to the other answers: If you don't even want to write the commit message with the issue number and happen to use Eclipse for development, then you can install the eGit and Mylyn plugins as well as the GitHub connector for Mylyn. Eclipse can then automatically track which issue you are working on and automatically fill the commit message, including the issue number as shown in all the other answers.

For more details about that setup see http://wiki.eclipse.org/EGit/GitHub/UserGuide

How to run script as another user without password?

try running:

su -c "Your command right here" -s /bin/sh username

This will run the command as username given that you have permissions to sudo as that user.

JQuery datepicker language

Here is example how you can do localization by yourself.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $('input.datetimepicker').datepicker({_x000D_
    duration: '',_x000D_
    changeMonth: false,_x000D_
    changeYear: false,_x000D_
    yearRange: '2010:2020',_x000D_
    showTime: false,_x000D_
    time24h: true_x000D_
  });_x000D_
_x000D_
  $.datepicker.regional['cs'] = {_x000D_
    closeText: 'Zavrít',_x000D_
    prevText: '&#x3c;Dríve',_x000D_
    nextText: 'Pozdeji&#x3e;',_x000D_
    currentText: 'Nyní',_x000D_
    monthNames: ['leden', 'únor', 'brezen', 'duben', 'kveten', 'cerven', 'cervenec', 'srpen',_x000D_
      'zárí', 'ríjen', 'listopad', 'prosinec'_x000D_
    ],_x000D_
    monthNamesShort: ['led', 'úno', 'bre', 'dub', 'kve', 'cer', 'cvc', 'srp', 'zár', 'ríj', 'lis', 'pro'],_x000D_
    dayNames: ['nedele', 'pondelí', 'úterý', 'streda', 'ctvrtek', 'pátek', 'sobota'],_x000D_
    dayNamesShort: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
    dayNamesMin: ['ne', 'po', 'út', 'st', 'ct', 'pá', 'so'],_x000D_
    weekHeader: 'Týd',_x000D_
    dateFormat: 'dd/mm/yy',_x000D_
    firstDay: 1,_x000D_
    isRTL: false,_x000D_
    showMonthAfterYear: false,_x000D_
    yearSuffix: ''_x000D_
  };_x000D_
_x000D_
  $.datepicker.setDefaults($.datepicker.regional['cs']);_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
  <link data-require="jqueryui@*" data-semver="1.10.0" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/css/smoothness/jquery-ui-1.10.0.custom.min.css" />_x000D_
  <script data-require="jqueryui@*" data-semver="1.10.0" src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.0/jquery-ui.js"></script>_x000D_
  <script src="datepicker-cs.js"></script>_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
      console.log("test");_x000D_
      $("#test").datepicker({_x000D_
        dateFormat: "dd.m.yy",_x000D_
        minDate: 0,_x000D_
        showOtherMonths: true,_x000D_
        firstDay: 1_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <h1>Here is your datepicker</h1>_x000D_
  <input id="test" type="text" />_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I change property names when serializing with Json.net?

There is still another way to do it, which is using a particular NamingStrategy, which can be applied to a class or a property by decorating them with [JSonObject] or [JsonProperty].

There are predefined naming strategies like CamelCaseNamingStrategy, but you can implement your own ones.

The implementation of different naming strategies can be found here: https://github.com/JamesNK/Newtonsoft.Json/tree/master/Src/Newtonsoft.Json/Serialization

Insert the same fixed value into multiple rows

The SQL you need is:

Update table set table_column = "test";

The SQL you posted creates a new row rather than updating existing rows.

Prevent text selection after double click

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well

increase legend font size ggplot2

You can use theme_get() to display the possible options for theme. You can control the legend font size using:

+ theme(legend.text=element_text(size=X))

replacing X with the desired size.

How to bind RadioButtons to an enum?

For UWP, it is not so simple: You must jump through an extra hoop to pass a field value as a parameter.

Example 1

Valid for both WPF and UWP.

<MyControl>
    <MyControl.MyProperty>
        <Binding Converter="{StaticResource EnumToBooleanConverter}" Path="AnotherProperty">
            <Binding.ConverterParameter>
                <MyLibrary:MyEnum>Field</MyLibrary:MyEnum>
            </Binding.ConverterParameter>
        </MyControl>
    </MyControl.MyProperty>
</MyControl>

Example 2

Valid for both WPF and UWP.

...
<MyLibrary:MyEnum x:Key="MyEnumField">Field</MyLibrary:MyEnum>
...

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={StaticResource MyEnumField}}"/>

Example 3

Valid only for WPF!

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource EnumToBooleanConverter}, ConverterParameter={x:Static MyLibrary:MyEnum.Field}}"/>

UWP doesn't support x:Static so Example 3 is out of the question; assuming you go with Example 1, the result is more verbose code. Example 2 is slightly better, but still not ideal.

Solution

public abstract class EnumToBooleanConverter<TEnum> : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;

        if (Parameter == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(typeof(TEnum), value) == false)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(typeof(TEnum), Parameter).Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        var Parameter = parameter as string;
        return Parameter == null ? DependencyProperty.UnsetValue : Enum.Parse(typeof(TEnum), Parameter);
    }
}

Then, for each type you wish to support, define a converter that boxes the enum type.

public class MyEnumToBooleanConverter : EnumToBooleanConverter<MyEnum>
{
    //Nothing to do!
}

The reason it must be boxed is because there's seemingly no way to reference the type in the ConvertBack method; the boxing takes care of that. If you go with either of the first two examples, you can just reference the parameter type, eliminating the need to inherit from a boxed class; if you wish to do it all in one line and with least verbosity possible, the latter solution is ideal.

Usage resembles Example 2, but is, in fact, less verbose.

<MyControl MyProperty="{Binding AnotherProperty, Converter={StaticResource MyEnumToBooleanConverter}, ConverterParameter=Field}"/>

The downside is you must define a converter for each type you wish to support.

GoogleTest: How to skip a test?

For another approach, you can wrap your tests in a function and use normal conditional checks at runtime to only execute them if you want.

#include <gtest/gtest.h>

const bool skip_some_test = true;

bool some_test_was_run = false;

void someTest() {
   EXPECT_TRUE(!skip_some_test);
   some_test_was_run = true;
}

TEST(BasicTest, Sanity) {
   EXPECT_EQ(1, 1);
   if(!skip_some_test) {
      someTest();
      EXPECT_TRUE(some_test_was_run);
   }
}

This is useful for me as I'm trying to run some tests only when a system supports dual stack IPv6.

Technically that dualstack stuff shouldn't really be a unit test as it depends on the system. But I can't really make any integration tests until I have tested they work anyway and this ensures that it won't report failures when it's not the codes fault.

As for the test of it I have stub objects that simulate a system's support for dualstack (or lack of) by constructing fake sockets.

The only downside is that the test output and the number of tests will change which could cause issues with something that monitors the number of successful tests.

You can also use ASSERT_* rather than EQUAL_*. Assert will about the rest of the test if it fails. Prevents a lot of redundant stuff being dumped to the console.

Implementation difference between Aggregation and Composition in Java

A simple Composition program

public class Person {
    private double salary;
    private String name;
    private Birthday bday;

    public Person(int y,int m,int d,String name){
        bday=new Birthday(y, m, d);
        this.name=name;
    }


    public double getSalary() {
        return salary;
    }

    public String getName() {
        return name;
    }

    public Birthday getBday() {
        return bday;
    }

    ///////////////////////////////inner class///////////////////////
    private class Birthday{
        int year,month,day;

        public Birthday(int y,int m,int d){
            year=y;
            month=m;
            day=d;
        }

        public String toString(){
           return String.format("%s-%s-%s", year,month,day);

        }
    }

    //////////////////////////////////////////////////////////////////

}
public class CompositionTst {

    public static void main(String[] args) {
        // TODO code application logic here
        Person person=new Person(2001, 11, 29, "Thilina");
        System.out.println("Name : "+person.getName());
        System.out.println("Birthday : "+person.getBday());

        //The below object cannot be created. A bithday cannot exixts without a Person 
        //Birthday bday=new Birthday(1988,11,10);

    }
}

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

Alternatively if you want to grab the private and public keys from a PuTTY formated key file you can use puttygen on *nix systems. For most apt-based systems puttygen is part of the putty-tools package.

Outputting a private key from a PuTTY formated keyfile:

$ puttygen keyfile.pem -O private-openssh -o avdev.pvk

For the public key:

$ puttygen keyfile.pem -L

Download and open PDF file using Ajax

The following code worked for me

//Parameter to be passed
var data = 'reportid=R3823&isSQL=1&filter=[]';
var xhr = new XMLHttpRequest();
xhr.open("POST", "Reporting.jsp"); //url.It can pdf file path
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response]);
        const url = window.URL.createObjectURL(blob);
        var a = document.createElement('a');
        a.href = url;
        a.download = 'myFile.pdf';
        a.click();
        setTimeout(function () {
            // For Firefox it is necessary to delay revoking the ObjectURL
            window.URL.revokeObjectURL(data)
                , 100
        })
    }
};
xhr.send(data);

UIButton action in table view cell

Simple and easy way to detect button event and perform some action

class youCell: UITableViewCell
{
    var yourobj : (() -> Void)? = nil

    //You can pass any kind data also.
   //var user: ((String?) -> Void)? = nil

     override func awakeFromNib()
        {
        super.awakeFromNib()
        }

 @IBAction func btnAction(sender: UIButton)
    {
        if let btnAction = self.yourobj
        {
            btnAction()
          //  user!("pass string")
        }
    }
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = youtableview.dequeueReusableCellWithIdentifier(identifier) as? youCell
        cell?.selectionStyle = UITableViewCellSelectionStyle.None

cell!. yourobj =
            {
                //Do whatever you want to do when the button is tapped here
                self.view.addSubview(self.someotherView)
        }

cell.user = { string in
            print(string)
        }

return cell

}

IFrame: This content cannot be displayed in a frame

use <meta http-equiv="X-Frame-Options" content="allow"> in the one to show in the iframe to allow it.

How to assign bean's property an Enum value in Spring config file?

Using SPEL and P-NAMESPACE:

<beans...
xmlns:p="http://www.springframework.org/schema/p" ...>
..
<bean name="someName" class="my.pkg.classes"
    p:type="#{T(my.pkg.types.MyEnumType).TYPE1}"/>

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

What REALLY happens when you don't free after malloc?

=== What about future proofing and code reuse? ===

If you don't write the code to free the objects, then you are limiting the code to only being safe to use when you can depend on the memory being free'd by the process being closed ... i.e. small one-time use projects or "throw-away"[1] projects)... where you know when the process will end.

If you do write the code that free()s all your dynamically allocated memory, then you are future proofing the code and letting others use it in a larger project.


[1] regarding "throw-away" projects. Code used in "Throw-away" projects has a way of not being thrown away. Next thing you know ten years have passed and your "throw-away" code is still being used).

I heard a story about some guy who wrote some code just for fun to make his hardware work better. He said "just a hobby, won't be big and professional". Years later lots of people are using his "hobby" code.

Consider defining a bean of type 'package' in your configuration [Spring-Boot]

I sought online for an answer but it seems there is no one proper solution to my case: At the very beginning, everything works well as follows:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
}

Then I am trying to add a map to cache something and it becomes this:

@Slf4j
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class GroupService {
    private Repository repository;
    private Service service;
    Map<String, String> testMap;
}

Boom!

Description:

Parameter 4 of constructor in *.GroupService required a bean of type 'java.lang.String' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

I removed the @AllArgsConstructor(onConstructor = @__(@Autowired)) and add @Autowired for each repository and service except the Map<String, String>. It just works as before.

@Slf4j
@Service
public class SecurityGroupService {
    @Autowired
    private Repository repository;
    @Autowired
    private Service service;
    Map<String, String> testMap;
}

Hope this might be helpful.

The order of keys in dictionaries

From http://docs.python.org/tutorial/datastructures.html:

"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."

Best way to work with dates in Android SQLite

Best way to store datein SQlite DB is to store the current DateTimeMilliseconds. Below is the code snippet to do so_

  1. Get the DateTimeMilliseconds
public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
    /*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
    String myDate = dateString;//"2017/12/20 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    return millis;
}
  1. Insert the data in your DB
public void insert(Context mContext, long dateTimeMillis, String msg) {
    //Your DB Helper
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
    database = dbHelper.getWritableDatabase();

    ContentValues contentValue = new ContentValues();
    contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
    contentValue.put(MyDatabaseHelper.MESSAGE, msg);

    //insert data in DB
    database.insert("your_table_name", null, contentValue);

   //Close the DB connection.
   dbHelper.close(); 

}

Now, your data (date is in currentTimeMilliseconds) is get inserted in DB .

Next step is, when you want to retrieve data from DB you need to convert the respective date time milliseconds in to corresponding date. Below is the sample code snippet to do the same_

  1. Convert date milliseconds in to date string.
public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);

    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}
  1. Now, Finally fetch the data and see its working...
public ArrayList<String> fetchData() {

    ArrayList<String> listOfAllDates = new ArrayList<String>();
    String cDate = null;

    MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
    database = dbHelper.getWritableDatabase();

    String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
    Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()){
            do{
                //iterate the cursor to get data.
                cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");

                listOfAllDates.add(cDate);

            }while(cursor.moveToNext());
        }
        cursor.close();

    //Close the DB connection.
    dbHelper.close(); 

    return listOfAllDates;

}

Hope this will help all! :)

How to change active class while click to another link in bootstrap use jquery?

html code in my case

<ul class="navs">
   <li  id="tab1"><a href="index-2.html">home</a></li>
   <li id="tab2"><a href="about.html">about</a></li>

   <li id="tab3"><a href="project-02.html">Products</a></li>

   <li id="tab4"><a href="contact.html">contact</a></li>
 </ul>

and js code is

  $('.navs li a').click(function (e) {
        var $parent = $(this).parent();
        document.cookie = eraseCookie("tab");
        document.cookie = createCookie("tab", $parent.attr('id'),0);
 });

    $().ready(function () {
        var $activeTab = readCookie("tab");
        if (!$activeTab =="") {
        $('#tab1').removeClass('ActiveTab');
          }
       // alert($activeTab.toString());

        $('#'+$activeTab).addClass('active');
    });

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

set environment variable in python script

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']

JS. How to replace html element with another element/text, represented in string?

As the Jquery replaceWith() code was too bulky, tricky and complicated, here's my own solution. =)

The best way is to use outerHTML property, but it is not crossbrowsered yet, so I did some trick, weird enough, but simple.

Here is the code

var str = '<a href="http://www.com">item to replace</a>'; //it can be anything
var Obj = document.getElementById('TargetObject'); //any element to be fully replaced
if(Obj.outerHTML) { //if outerHTML is supported
    Obj.outerHTML=str; ///it's simple replacement of whole element with contents of str var
}
else { //if outerHTML is not supported, there is a weird but crossbrowsered trick
    var tmpObj=document.createElement("div");
    tmpObj.innerHTML='<!--THIS DATA SHOULD BE REPLACED-->';
    ObjParent=Obj.parentNode; //Okey, element should be parented
    ObjParent.replaceChild(tmpObj,Obj); //here we placing our temporary data instead of our target, so we can find it then and replace it into whatever we want to replace to
    ObjParent.innerHTML=ObjParent.innerHTML.replace('<div><!--THIS DATA SHOULD BE REPLACED--></div>',str);
}

That's all

Can the Android drawable directory contain subdirectories?

There is a workaround for this situation: you can create a resVector (for example) folder on the same level as default res folder. There you can add any drawable-xxx resource folders there:

resVector
-drawable
-layout
-color

After that all you need is to add

sourceSets {
        main.res.srcDirs += 'src/main/resVector'
    }

into your build.gradle file (inside android { }).

Active Menu Highlight CSS

Let's say we have a menu like this:

<div class="menu">
  <a href="link1.html">Link 1</a>
  <a href="link2.html">Link 2</a>
  <a href="link3.html">Link 3</a>
  <a href="link4.html">Link 4</a>
</div>

Let our current url be https://demosite.com/link1.html

With the following function we can add the active class to which menu's href is in our url.

let currentURL = window.location.href;

document.querySelectorAll(".menu a").forEach(p => {
  if(currentURL.indexOf(p.getAttribute("href")) !== -1){
    p.classList.add("active");
  }
})

Check if a string is not NULL or EMPTY

If the variable is a parameter then you could use advanced function parameter binding like below to validate not null or empty:

[CmdletBinding()]
Param (
    [parameter(mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$Version
)

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

How to link 2 cell of excel sheet?

Just follow these Steps :

If you want the contents of, say, C1 to mirror the contents of cell A1, you just need to set the formula in C1 to =A1. From this point forward, anything you type in A1 will show up in C1 as well.

To Link Multiple Cells in Excel From Another Worksheet :

Step 1

Click the worksheet tab at the bottom of the screen that contains a range of precedent cells to which you want to link. A range is a block or group of adjacent cells. For example, assume you want to link a range of blank cells in “Sheet1” to a range of precedent cells in “Sheet2.” Click the “Sheet2” tab.

Step 2

Determine the precedent range’s width in columns and height in rows. In this example, assume cells A1 through A4 on “Sheet2” contain a list of numbers 1, 2, 3 and 4, respectively, which will be your precedent cells. This precedent range is one column wide by four rows high.

Step 3

Click the worksheet tab at the bottom of the screen that contains the blank cells in which you will insert a link. In this example, click the “Sheet1” tab.

Step 4

Select the range of blank cells you want to link to the precedent cells. This range must be the same size as the precedent range, but can be in a different location on the worksheet. Click and hold the mouse button on the top left cell of the range, drag the mouse cursor to the bottom right cell in the range and release the mouse button to select the range. In this example, assume you want to link cells C1 through C4 to the precedent range. Click and hold on cell C1, drag the mouse to cell C4 and release the mouse to highlight the range.

Step 5

Type “=,” the worksheet name containing the precedent cells, “!,” the top left cell of the precedent range, “:” and the bottom right cell of the precedent range. Press “Ctrl,” “Shift” and “Enter” simultaneously to complete the array formula. Each dependent cell is now linked to the cell in the precedent range that’s in the same respective location within the range. In this example, type “=Sheet2!A1:A4” and press “Ctrl,” “Shift” and “Enter” simultaneously. Cells C1 through C4 on “Sheet1” now contain the array formula “{=Sheet2!A1:A4}” surrounded by curly brackets, and show the same data as the precedent cells in “Sheet2.”

Good Luck !!!

Negation in Python

The negation operator in Python is not. Therefore just replace your ! with not.

For your example, do this:

if not os.path.exists("/usr/share/sounds/blues") :
    proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"])
    proc.wait()

For your specific example (as Neil said in the comments), you don't have to use the subprocess module, you can simply use os.mkdir() to get the result you need, with added exception handling goodness.

Example:

blues_sounds_path = "/usr/share/sounds/blues"
if not os.path.exists(blues_sounds_path):
    try:
        os.mkdir(blues_sounds_path)
    except OSError:
        # Handle the case where the directory could not be created.

How to detect DIV's dimension changed?

jQuery(document).ready( function($) {

function resizeMapDIVs() {

// check the parent value...

var size = $('#map').parent().width();



if( $size < 640 ) {

//  ...and decrease...

} else {

//  ..or increase  as necessary

}

}

resizeMapDIVs();

$(window).resize(resizeMapDIVs);

});

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

MS Excel showing the formula in a cell instead of the resulting value

Try this if the above solution aren't working, worked for me

Cut the whole contents in the worksheet using "Ctrl + A" followed by "Ctrl + X" and paste it to a new sheet. Your reference to formulas will remain intact when you cut paste.

CSS container div not getting height

The best and the most bulletproof solution is to add ::before and ::after pseudoelements to the container. So if you have for example a list like:

<ul class="clearfix">
    <li></li>
    <li></li>
    <li></li>
</ul>

And every elements in the list has float:left property, then you should add to your css:

.clearfix::after, .clearfix::before {
     content: '';
     clear: both;
     display: table;
}

Or you could try display:inline-block; property, then you don't need to add any clearfix.

Insertion sort vs Bubble Sort Algorithms

Bubble Sort is not online (it cannot sort a stream of inputs without knowing how many items there will be) because it does not really keep track of a global maximum of the sorted elements. When an item is inserted you will need to start the bubbling from the very beginning

How do I get the max and min values from a set of numbers entered?

It is better

public class Main {

    public static void main(String[] args) {

        System.out.print("Enter numbers: ");
        Scanner input = new Scanner(System.in);

        double max = Double.MIN_VALUE;
        double min = Double.MAX_VALUE;

        while (true) {

            if ( !input.hasNextDouble())
                break;

            Double num = input.nextDouble();

            min = Math.min(min, num);
            max = Math.max(max, num);

        }
        System.out.println("Max is: " + max);
        System.out.println("Min is: " + min);
    }
}

How should I unit test multithreaded code?

I have faced this issue several times in recent years when writing thread handling code for several projects. I'm providing a late answer because most of the other answers, while providing alternatives, do not actually answer the question about testing. My answer is addressed to the cases where there is no alternative to multithreaded code; I do cover code design issues for completeness, but also discuss unit testing.

Writing testable multithreaded code

The first thing to do is to separate your production thread handling code from all the code that does actual data processing. That way, the data processing can be tested as singly threaded code, and the only thing the multithreaded code does is to coordinate threads.

The second thing to remember is that bugs in multithreaded code are probabilistic; the bugs that manifest themselves least frequently are the bugs that will sneak through into production, will be difficult to reproduce even in production, and will thus cause the biggest problems. For this reason, the standard coding approach of writing the code quickly and then debugging it until it works is a bad idea for multithreaded code; it will result in code where the easy bugs are fixed and the dangerous bugs are still there.

Instead, when writing multithreaded code, you must write the code with the attitude that you are going to avoid writing the bugs in the first place. If you have properly removed the data processing code, the thread handling code should be small enough - preferably a few lines, at worst a few dozen lines - that you have a chance of writing it without writing a bug, and certainly without writing many bugs, if you understand threading, take your time, and are careful.

Writing unit tests for multithreaded code

Once the multithreaded code is written as carefully as possible, it is still worthwhile writing tests for that code. The primary purpose of the tests is not so much to test for highly timing dependent race condition bugs - it's impossible to test for such race conditions repeatably - but rather to test that your locking strategy for preventing such bugs allows for multiple threads to interact as intended.

To properly test correct locking behavior, a test must start multiple threads. To make the test repeatable, we want the interactions between the threads to happen in a predictable order. We don't want to externally synchronize the threads in the test, because that will mask bugs that could happen in production where the threads are not externally synchronized. That leaves the use of timing delays for thread synchronization, which is the technique that I have used successfully whenever I've had to write tests of multithreaded code.

If the delays are too short, then the test becomes fragile, because minor timing differences - say between different machines on which the tests may be run - may cause the timing to be off and the test to fail. What I've typically done is start with delays that cause test failures, increase the delays so that the test passes reliably on my development machine, and then double the delays beyond that so the test has a good chance of passing on other machines. This does mean that the test will take a macroscopic amount of time, though in my experience, careful test design can limit that time to no more than a dozen seconds. Since you shouldn't have very many places requiring thread coordination code in your application, that should be acceptable for your test suite.

Finally, keep track of the number of bugs caught by your test. If your test has 80% code coverage, it can be expected to catch about 80% of your bugs. If your test is well designed but finds no bugs, there's a reasonable chance that you don't have additional bugs that will only show up in production. If the test catches one or two bugs, you might still get lucky. Beyond that, and you may want to consider a careful review of or even a complete rewrite of your thread handling code, since it is likely that code still contains hidden bugs that will be very difficult to find until the code is in production, and very difficult to fix then.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

When i try create another package under the Java folder this error will happen

But When i moved this special package under the main package of my project , everything will be ok .

I'm testing on real android device .(Sumsung J2)

How to add New Column with Value to the Existing DataTable?

Add the column and update all rows in the DataTable, for example:

DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
    DataRow row = tbl.NewRow();
    row["ID"] = i;
    row["Name"] = i + ". row";
    tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
    row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;

Error Code: 1005. Can't create table '...' (errno: 150)

This could also happen when exporting your database from one server to another and the tables are listed in alphabetical order by default.
So, your first table could have a foreign key of another table that is yet to be created. In such cases, disable foreign_key_checks and create the database.

Just add the following to your script:

SET FOREIGN_KEY_CHECKS=0;

and it shall work.

Laravel - Session store not set on request

in my case it was just to put return ; at the end of function where i have set session

UIScrollView Scrollable Content Size Ambiguity

Xcode 11+, Swift 5.

According to @WantToKnow answer, I solved my issue, I prepared video and code

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

How to read existing text files without defining path

When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.

Example:

string text = File.ReadAllText("Some\\Path.txt"); // relative path

The above code has the same effect as the following:

string text = File.ReadAllText(
    Path.Combine(Environment.CurrentDirectory, "Some\\Path.txt"));

If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.

"cannot resolve symbol R" in Android Studio

If you see this error after moving java files or directories to other locations, then you can guarantee that Android Studio has gotten confused. And guess what? undo-ing those actions doesn't fix the problem.

So you try a clean, but that doesn't work.

And restarting doesn't work either.

But try File -> Invalidate Caches / Restart... -> Invalidate and Restart

Android Studio maintains information about which files are dependent on which other files. And since moving files around is not implemented correctly, moving files causes errors. And that's not all: caches of these dependencies are used in an attempt to speed up the build.

This means you not only have to restart, but you need to invalidate those caches to restore (or more accurately, rebuild) sanity.

Ruby send JSON request

require 'net/http'
require 'json'

def create_agent
    uri = URI('http://api.nsa.gov:1337/agent')
    http = Net::HTTP.new(uri.host, uri.port)
    req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
    req.body = {name: 'John Doe', role: 'agent'}.to_json
    res = http.request(req)
    puts "response #{res.body}"
rescue => e
    puts "failed #{e}"
end

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

Fetch API with Cookie

This works for me:

import Cookies from 'universal-cookie';
const cookies = new Cookies();

function headers(set_cookie=false) {
  let headers = {
    'Accept':       'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
};
if (set_cookie) {
    headers['Authorization'] = "Bearer " + cookies.get('remember_user_token');
}
return headers;
}

Then build your call:

export function fetchTests(user_id) {
  return function (dispatch) {
   let data = {
    method:      'POST',
    credentials: 'same-origin',
    mode:        'same-origin',
    body:        JSON.stringify({
                     user_id: user_id
                }),
    headers:     headers(true)
   };
   return fetch('/api/v1/tests/listing/', data)
      .then(response => response.json())
      .then(json => dispatch(receiveTests(json)));
    };
  }

How to submit form on change of dropdown list?

Simple JavaScript will do -

<form action="myservlet.do" method="POST">
    <select name="myselect" id="myselect" onchange="this.form.submit()">
        <option value="1">One</option>
        <option value="2">Two</option>
        <option value="3">Three</option>
        <option value="4">Four</option>
    </select>
</form>

Here is a link for a good javascript tutorial.

Cannot connect to the Docker daemon on macOS

This problem:

$ brew install docker docker-machine
$ docker ps

Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?

This apparently meant do the following:

$ docker-machine create default # default driver is apparently vbox:
Running pre-create checks...
Error with pre-create check: "VBoxManage not found. Make sure VirtualBox is installed and VBoxManage is in the path"
$  brew cask install virtualbox
…
$ docker-machine create default 
# works this time
$ docker ps
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
$ eval "$(docker-machine env default)"
$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

It finally works.

You can use the “xhyve” driver if you don’t want to install virtual box. Also you can install the “docker app” (then run it) which apparently makes it so you don’t have to run some of the above. brew cask install docker then run the app, see the other answers. But apparently isn't necessary per se.

What is Teredo Tunneling Pseudo-Interface?

Unless you have some kind of really weird problem, keep it. The number of IPv6 sites is very small, but there are some and it will let you get to them even if you're at an IPv4 only location.

If it is causing you a problem, it's best to fix it. I've seen a number of people recommending removing it to solve problems. However, they're not actually solving the root cause of the issue. In all the cases I've seen, removing Teredo just happens to cause a side-effect that fixes their problem... :)

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

What does 'super' do in Python?

The benefits of super() in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.

However, it's almost impossible to use multiple-inheritance without super(). This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child and a mixin, their code would not work properly.

Multiple glibc libraries on a single host

This question is old, the other answers are old. "Employed Russian"s answer is very good and informative, but it only works if you have the source code. If you don't, the alternatives back then were very tricky. Fortunately nowadays we have a simple solution to this problem (as commented in one of his replies), using patchelf. All you have to do is:

$ ./patchelf --set-interpreter /path/to/newglibc/ld-linux.so.2 --set-rpath /path/to/newglibc/ myapp

And after that, you can just execute your file:

$ ./myapp

No need to chroot or manually edit binaries, thankfully. But remember to backup your binary before patching it, if you're not sure what you're doing, because it modifies your binary file. After you patch it, you can't restore the old path to interpreter/rpath. If it doesn't work, you'll have to keep patching it until you find the path that will actually work... Well, it doesn't have to be a trial-and-error process. For example, in OP's example, he needed GLIBC_2.3, so you can easily find which lib provides that version using strings:

$ strings /lib/i686/libc.so.6 | grep GLIBC_2.3
$ strings /path/to/newglib/libc.so.6 | grep GLIBC_2.3

In theory, the first grep would come empty because the system libc doesn't have the version he wants, and the 2nd one should output GLIBC_2.3 because it has the version myapp is using, so we know we can patchelf our binary using that path. If you get a segmentation fault, read the note at the end.

When you try to run a binary in linux, the binary tries to load the linker, then the libraries, and they should all be in the path and/or in the right place. If your problem is with the linker and you want to find out which path your binary is looking for, you can find out with this command:

$ readelf -l myapp | grep interpreter
  [Requesting program interpreter: /lib/ld-linux.so.2]                                                                                                                                                                                   

If your problem is with the libs, commands that will give you the libs being used are:

$ readelf -d myapp | grep Shared
$ ldd myapp 

This will list the libs that your binary needs, but you probably already know the problematic ones, since they are already yielding errors as in OP's case.

"patchelf" works for many different problems that you may encounter while trying to run a program, related to these 2 problems. For example, if you get: ELF file OS ABI invalid, it may be fixed by setting a new loader (the --set-interpreter part of the command) as I explain here. Another example is for the problem of getting No such file or directory when you run a file that is there and executable, as exemplified here. In that particular case, OP was missing a link to the loader, but maybe in your case you don't have root access and can't create the link. Setting a new interpreter would solve your problem.

Thanks Employed Russian and Michael Pankov for the insight and solution!


Note for segmentation fault: you might be in the case where myapp uses several libs, and most of them are ok but some are not; then you patchelf it to a new dir, and you get segmentation fault. When you patchelf your binary, you change the path of several libs, even if some were originally in a different path. Take a look at my example below:

$ ldd myapp
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by ./myapp)
./myapp: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by ./myapp)
        linux-vdso.so.1 =>  (0x00007fffb167c000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9a9aad2000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f9a9a8ce000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f9a9a6af000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9a9a3ab000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9a99fe6000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f9a9adeb000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9a99dcf000)

Note that most libs are in /lib/x86_64-linux-gnu/ but the problematic one (libstdc++.so.6) is on /usr/lib/x86_64-linux-gnu. After I patchelf'ed myapp to point to /path/to/mylibs, I got segmentation fault. For some reason, the libs are not totally compatible with the binary. Since myapp didn't complain about the original libs, I copied them from /lib/x86_64-linux-gnu/ to /path/to/mylibs2, and I also copied libstdc++.so.6 from /path/to/mylibs there. Then I patchelf'ed it to /path/to/mylibs2, and myapp works now. If your binary uses different libs, and you have different versions, it might happen that you can't fix your situation. :( But if it's possible, mixing libs might be the way. It's not ideal, but maybe it will work. Good luck!

Auto-expanding layout with Qt-Designer

Once you have add your layout with at least one widget in it, select your window and click the "Update" button of QtDesigner. The interface will be resized at the most optimized size and your layout will fit the whole window. Then when resizing the window, the layout will be resized in the same way.

Make a float only show two decimal places

The problem with all the answers is that multiplying and then dividing results in precision issues because you used division. I learned this long ago from programming on a PDP8. The way to resolve this is:

return roundf(number * 100) * .01;

Thus 15.6578 returns just 15.66 and not 15.6578999 or something unintended like that.

What level of precision you want is up to you. Just don't divide the product, multiply it by the decimal equivalent. No funny String conversion required.

Python: convert string to byte array

for python 3 it worked for what @HYRY posted. I needed it for a returned data in a dbus.array. This is the only way it worked

s = "ABCD"

from array import array

a = array("B", s)

jQuery how to bind onclick event to dynamically added HTML element

I believe the good way it to do:

$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

Click on choose existing and again choose the location where your jks file is located.

enter image description here

I hope this trick works for you.

Cell Style Alignment on a range

Maybe declaring a range might workout better for you.

// fill in the starting and ending range programmatically this is just an example. 
string startRange = "A1";
string endRange = "A1";
Excel.Range currentRange = (Excel.Range)excelWorksheet.get_Range(startRange , endRange );
currentRange.Style.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

module.exports vs exports in Node.js

  • exports: it's a reference to module.exports object
  • both exports and module.exports point to the same object until we change the reference of exports object

Example:

  1. if exports.a = 10 then module.exports.a = 10

  2. if we reassign exports object explicitly inside the code like exports = {} now its lost the reference to module.exports

How can I apply styles to multiple classes at once?

Don’t Repeat Your CSS

 a.abc, a.xyz{
    margin-left:20px;
 }

OR

 a{
    margin-left:20px;
 }

Equivalent of String.format in jQuery

<html>
<body>
<script type="text/javascript">
   var str="http://xyz.html?ID={0}&TId={1}&STId={2}&RId={3},14,480,3,38";
   document.write(FormatString(str));
   function FormatString(str) {
      var args = str.split(',');
      for (var i = 0; i < args.length; i++) {
         var reg = new RegExp("\\{" + i + "\\}", "");             
         args[0]=args[0].replace(reg, args [i+1]);
      }
      return args[0];
   }
</script>
</body>
</html>

Send email using java

The following code works very well.Try this as a java application with javamail-1.4.5.jar

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailSender
{
    final String senderEmailID = "[email protected]";
    final String senderPassword = "typesenderpassword";
    final String emailSMTPserver = "smtp.gmail.com";
    final String emailServerPort = "465";
    String receiverEmailID = null;
    static String emailSubject = "Test Mail";
    static String emailBody = ":)";

    public MailSender(
            String receiverEmailID,
            String emailSubject,
            String emailBody
    ) {
        this.receiverEmailID=receiverEmailID;
        this.emailSubject=emailSubject;
        this.emailBody=emailBody;
        Properties props = new Properties();
        props.put("mail.smtp.user",senderEmailID);
        props.put("mail.smtp.host", emailSMTPserver);
        props.put("mail.smtp.port", emailServerPort);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.socketFactory.port", emailServerPort);
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        SecurityManager security = System.getSecurityManager();
        try {
            Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            MimeMessage msg = new MimeMessage(session);
            msg.setText(emailBody);
            msg.setSubject(emailSubject);
            msg.setFrom(new InternetAddress(senderEmailID));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(receiverEmailID));
            Transport.send(msg);
            System.out.println("Message send Successfully:)");
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
        }
    }

    public class SMTPAuthenticator extends javax.mail.Authenticator
    {
        public PasswordAuthentication getPasswordAuthentication()
        {
            return new PasswordAuthentication(senderEmailID, senderPassword);
        }
    }

    public static void main(String[] args)
    {
        MailSender mailSender=new
            MailSender("[email protected]",emailSubject,emailBody);
    }
}

How do I convert a list of ascii values to a string in python?

Same basic solution as others, but I personally prefer to use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'

Change CSS class properties with jQuery

Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.

function changeCss(className, classValue) {
    var cssMainContainer = $('#css-modifier-container');

    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<style id="css-modifier-container"></style>');
        cssMainContainer.appendTo($('head'));
    }

    cssMainContainer.append(className + " {" + classValue + "}\n");
}

Text file in VBA: Open/Find Replace/SaveAs/Close File

Guess I'm too late...

Came across the same problem today; here is my solution using FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

How to check if a json key exists?

JSONObject class has a method named "has":

http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

Returns true if this object has a mapping for name. The mapping may be NULL.

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Transform only one axis to log10 scale with ggplot2

I think I got it at last by doing some manual transformations with the data before visualization:

d <- diamonds
# computing logarithm of prices
d$price <- log10(d$price)

And work out a formatter to later compute 'back' the logarithmic data:

formatBack <- function(x) 10^x 
# or with special formatter (here: "dollar")
formatBack <- function(x) paste(round(10^x, 2), "$", sep=' ') 

And draw the plot with given formatter:

m <- ggplot(d, aes(y = price, x = color))
m + geom_boxplot() + scale_y_continuous(formatter='formatBack')

alt text

Sorry to the community to bother you with a question I could have solved before! The funny part is: I was working hard to make this plot work a month ago but did not succeed. After asking here, I got it.

Anyway, thanks to @DWin for motivation!

What are abstract classes and abstract methods?

An abstract class is a class that you can't create an object from, so it is mostly used for inheriting from.(I am not sure if you can have static methods in it)

An abstract method is a method that the child class must override, it does not have a body, is marked abstract and only abstract classes can have those methods.

find index of an int in a list

It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:

int index = 0; int i = accounts[index];

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

How to send POST request in JSON using HTTPClient in Android?

Here is an alternative solution to @Terrance's answer. You can easly outsource the conversion. The Gson library does wonderful work converting various data structures into JSON and the other way around.

public static void execute() {
    Map<String, String> comment = new HashMap<String, String>();
    comment.put("subject", "Using the GSON library");
    comment.put("message", "Using libraries is convenient.");
    String json = new GsonBuilder().create().toJson(comment, Map.class);
    makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}

public static HttpResponse makeRequest(String uri, String json) {
    try {
        HttpPost httpPost = new HttpPost(uri);
        httpPost.setEntity(new StringEntity(json));
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        return new DefaultHttpClient().execute(httpPost);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Similar can be done by using Jackson instead of Gson. I also recommend taking a look at Retrofit which hides a lot of this boilerplate code for you. For more experienced developers I recommend trying out RxAndroid.

Why is AJAX returning HTTP status code 0?

In my case, it was caused by running my django server under http://127.0.0.1:8000/ but sending the ajax call to http://localhost:8000/. Even though you would expect them to map to the same address, they don't so make sure you're not sending your requests to localhost.

Setting device orientation in Swift iOS

Swift 2.2

    func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {

    if self.window?.rootViewController?.presentedViewController is SignatureLandscapeViewController {

        let secondController = self.window!.rootViewController!.presentedViewController as! SignatureLandscapeViewController

        if secondController.isPresented {

            return UIInterfaceOrientationMask.LandscapeLeft;

        } else {

            return UIInterfaceOrientationMask.Portrait;
        }

    } else {

        return UIInterfaceOrientationMask.Portrait;
    }
}

Auto Generate Database Diagram MySQL

The "Reverse Engineer Database" mode in Workbench is only part of the paid version, not the free one.

How do I make calls to a REST API using C#?

GET:

// GET JSON Response
public WeatherResponseModel GET(string url) {
    WeatherResponseModel model = new WeatherResponseModel();
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using(Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            model = JsonConvert.DeserializeObject < WeatherResponseModel > (reader.ReadToEnd());
        }
    } catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using(Stream responseStream = errorResponse.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // Log errorText
        }
        throw;
    }
    return model;
}

POST:

// POST a JSON string
void POST(string url, string jsonContent) {
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[]byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType =  @ "application/json";

    using(Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }

    long length = 0;
    try {
        using(HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            // Got response
            length = response.ContentLength;
        }
    } catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using(Stream responseStream = errorResponse.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // Log errorText
        }
        throw;
    }
}

Note: To serialize and desirialze JSON, I used the Newtonsoft.Json NuGet package.

What is the difference between properties and attributes in HTML?

The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insane this is. Even if it is to some extent the spec.

It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the document to its full extent?)

It is absolutely essential, that two input fields, e.g. a text and a checkbox behave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checked attribute, why does it not have two for its class and id attributes? If you expect to change the value of a text *input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an input field of type checkbox on the checked attribute?

The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.

How do I install PIL/Pillow for Python 3.6?

For python version 2.x you can simply use

  • pip install pillow

But for python version 3.X you need to specify

  • (sudo) pip3 install pillow

when you enter pip in bash hit tab and you will see what options you have

How do I send an HTML Form in an Email .. not just MAILTO

> 2020 Answer = The Easy Way using Google Apps Script (5 Mins)

We had a similar challenge to solve yesterday, and we solved it using a Google Apps Script!

Send Email From an HTML Form Without a Backend (Server) via Google!

The solution takes 5 mins to implement and I've documented with step-by-step instructions: https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

Brief Overview

A. Using the sample script, deploy a Google App Script

Deploy the sample script as a Google Spreadsheet APP Script: google-script-just-email.js

3-script-editor-showing-script

remember to set the TO_ADDRESS in the script to where ever you want the emails to be sent.
and copy the APP URL so you can use it in the next step when you publish the script.

B. Create your HTML Form and Set the action to the App URL

Using the sample html file: index.html create a basic form.

7-html-form

remember to paste your APP URL into the form action in the HTML form.

C. Test the HTML Form in your Browser

Open the HTML Form in your Browser, Input some data & submit it!

html form

Submit the form. You should see a confirmation that it was sent: form sent

Open the inbox for the email address you set (above)

email received

Done.

Everything about this is customisable, you can easily style/theme the form with your favourite CSS Library and Store the submitted data in a Google Spreadsheet for quick analysis.
The complete instructions are available on GitHub:
https://github.com/nelsonic/html-form-send-email-via-google-script-without-server

How to clear all <div>s’ contents inside a parent <div>?

Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.

$('#masterdiv div').empty();

Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

Map vs Object in JavaScript

One aspect of the Map that is not given much press here is lookup. According to the spec:

A Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection. The data structures used in this Map objects specification is only intended to describe the required observable semantics of Map objects. It is not intended to be a viable implementation model.

For collections that have a huge number of items and require item lookups, this is a huge performance boost.

TL;DR - Object lookup is not specified, so it can be on order of the number of elements in the object, i.e., O(n). Map lookup must use a hash table or similar, so Map lookup is the same regardless of Map size, i.e. O(1).

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How can I declare a two dimensional string array?

When you are trying to create a multi-dimensional array all you need to do is add a comma to the declaration like so:

string[,] tablero = new string[3,3].

java.sql.SQLException: Exhausted Resultset

You are getting this error because you are using the resultSet before the resultSet.next() method.

To get the count the just use this:

while (rs.next ()) `{ count = rs.getInt (1); }

You will get your result.

How to make a HTTP PUT request?

My Final Approach:

    public void PutObject(string postUrl, object payload)
        {
            var request = (HttpWebRequest)WebRequest.Create(postUrl);
            request.Method = "PUT";
            request.ContentType = "application/xml";
            if (payload !=null)
            {
                request.ContentLength = Size(payload);
                Stream dataStream = request.GetRequestStream();
                Serialize(dataStream,payload);
                dataStream.Close();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string returnString = response.StatusCode.ToString();
        }

public void Serialize(Stream output, object input)
            {
                var ser = new DataContractSerializer(input.GetType());
                ser.WriteObject(output, input);
            }

How can I convert string date to NSDate?

If you're going to need to parse the string into a date often, you may want to move the functionality into an extension. I created a sharedCode.swift file and put my extensions there:

extension String
{   
    func toDateTime() -> NSDate
    {
        //Create Date Formatter
        let dateFormatter = NSDateFormatter()

        //Specify Format of String to Parse
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"

        //Parse into NSDate
        let dateFromString : NSDate = dateFormatter.dateFromString(self)!

        //Return Parsed Date
        return dateFromString
    }
}

Then if you want to convert your string into a NSDate you can just write something like:

var myDate = myDateString.toDateTime()

How can I store the result of a system command in a Perl variable?

The easiest way is to use the `` feature in Perl. This will execute what is inside and return what was printed to stdout:

 my $pid = 5892;
 my $var = `top -H -p $pid -n 1 | grep myprocess | wc -l`;
 print "not = $var\n";

This should do it.

How do I add a new sourceset to Gradle?

This was once written for Gradle 2.x / 3.x in 2016 and is far outdated!! Please have a look at the documented solutions in Gradle 4 and up


To sum up both old answers (get best and minimum viable of both worlds):

some warm words first:

  1. first, we need to define the sourceSet:

    sourceSets {
        integrationTest
    }
    
  2. next we expand the sourceSet from test, therefor we use the test.runtimeClasspath (which includes all dependenciess from test AND test itself) as classpath for the derived sourceSet:

    sourceSets {
        integrationTest {
            compileClasspath += sourceSets.test.runtimeClasspath
            runtimeClasspath += sourceSets.test.runtimeClasspath // ***)
        }
    }
    
    • note) somehow this redeclaration / extend for sourceSets.integrationTest.runtimeClasspath is needed, but should be irrelevant since runtimeClasspath always expands output + runtimeSourceSet, don't get it
  3. we define a dedicated task for just running integration tests:

    task integrationTest(type: Test) {
    }
    
  4. Configure the integrationTest test classes and classpaths use. The defaults from the java plugin use the test sourceSet

    task integrationTest(type: Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
    }
    
  5. (optional) auto run after test

    integrationTest.dependsOn test
    

  6. (optional) add dependency from check (so it always runs when build or check are executed)

    tasks.check.dependsOn(tasks.integrationTest)
    
  7. (optional) add java,resources to the sourceSet to support auto-detection and create these "partials" in your IDE. i.e. IntelliJ IDEA will auto create sourceSet directories java and resources for each set if it doesn't exist:

    sourceSets {
         integrationTest {
             java
             resources
         }
    }
    

tl;dr

apply plugin: 'java'

// apply the runtimeClasspath from "test" sourceSet to the new one
// to include any needed assets: test, main, test-dependencies and main-dependencies
sourceSets {
    integrationTest {
        // not necessary but nice for IDEa's
        java
        resources

        compileClasspath += sourceSets.test.runtimeClasspath
        // somehow this redeclaration is needed, but should be irrelevant
        // since runtimeClasspath always expands compileClasspath
        runtimeClasspath += sourceSets.test.runtimeClasspath
    }
}

// define custom test task for running integration tests
task integrationTest(type: Test) {
    testClassesDir = sourceSets.integrationTest.output.classesDir
    classpath = sourceSets.integrationTest.runtimeClasspath
}
tasks.integrationTest.dependsOn(tasks.test)

referring to:

Unfortunatly, the example code on github.com/gradle/gradle/subprojects/docs/src/samples/java/customizedLayout/build.gradle or …/gradle/…/withIntegrationTests/build.gradle seems not to handle this or has a different / more complex / for me no clearer solution anyway!

How can I select an element in a component template?

In case you are using Angular Material, you can take advantage of cdkFocusInitial directive.

Example: <input matInput cdkFocusInitial>

Read more here: https://material.angular.io/cdk/a11y/overview#regions

What is Cache-Control: private?

Cache-Control: private

Indicates that all or part of the response message is intended for a single user and MUST NOT be cached by a shared cache, such as a proxy server.

From RFC2616 section 14.9.1