Programs & Examples On #Polymorphism

In computer science, polymorphism is a programming language feature that allows values of different data types to be handled in a uniform manner.

List<Map<String, String>> vs List<? extends Map<String, String>>

The difference is that, for example, a

List<HashMap<String,String>>

is a

List<? extends Map<String,String>>

but not a

List<Map<String,String>>

So:

void withWilds( List<? extends Map<String,String>> foo ){}
void noWilds( List<Map<String,String>> foo ){}

void main( String[] args ){
    List<HashMap<String,String>> myMap;

    withWilds( myMap ); // Works
    noWilds( myMap ); // Compiler error
}

You would think a List of HashMaps should be a List of Maps, but there's a good reason why it isn't:

Suppose you could do:

List<HashMap<String,String>> hashMaps = new ArrayList<HashMap<String,String>>();

List<Map<String,String>> maps = hashMaps; // Won't compile,
                                          // but imagine that it could

Map<String,String> aMap = Collections.singletonMap("foo","bar"); // Not a HashMap

maps.add( aMap ); // Perfectly legal (adding a Map to a List of Maps)

// But maps and hashMaps are the same object, so this should be the same as

hashMaps.add( aMap ); // Should be illegal (aMap is not a HashMap)

So this is why a List of HashMaps shouldn't be a List of Maps.

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

You need only one line before the declaration of the class Animal for correct polymorphic serialization/deserialization:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
public abstract class Animal {
   ...
}

This line means: add a meta-property on serialization or read a meta-property on deserialization (include = JsonTypeInfo.As.PROPERTY) called "@class" (property = "@class") that holds the fully-qualified Java class name (use = JsonTypeInfo.Id.CLASS).

So, if you create a JSON directly (without serialization) remember to add the meta-property "@class" with the desired class name for correct deserialization.

More information here

When to use virtual destructors?

Also be aware that deleting a base class pointer when there is no virtual destructor will result in undefined behavior. Something that I learned just recently:

How should overriding delete in C++ behave?

I've been using C++ for years and I still manage to hang myself.

Jump into interface implementation in Eclipse IDE

There's a big productivity boost if you add an Alt + F3 key binding to the Open Implementation feature, and just use F3 to go to interfaces, and Alt + F3 to go to implementations.

Open implementation keybinding

Polymorphism vs Overriding vs Overloading

The term overloading refers to having multiple versions of something with the same name, usually methods with different parameter lists

public int DoSomething(int objectId) { ... }
public int DoSomething(string objectName) { ... }

So these functions might do the same thing but you have the option to call it with an ID, or a name. Has nothing to do with inheritance, abstract classes, etc.

Overriding usually refers to polymorphism, as you described in your question

What is polymorphism, what is it for, and how is it used?

Polymorphism literally means, multiple shapes. (or many form) : Object from different classes and same name method , but workflows are different. A simple example would be:

Consider a person X.

He is only one person but he acts as many. You may ask how:

He is a son to his mother. A friend to his friends. A brother to his sister.

In Java, how do I call a base class's method from the overriding method in a derived class?

class test
{
    void message()
    {
        System.out.println("super class");
    }
}

class demo extends test
{
    int z;
    demo(int y)
    {
        super.message();
        z=y;
        System.out.println("re:"+z);
    }
}
class free{
    public static void main(String ar[]){
        demo d=new demo(6);
    }
}

What is the main difference between Inheritance and Polymorphism?

Polymorphism: Suppose you work for a company that sells pens. So you make a very nice class called "Pen" that handles everything that you need to know about a pen. You write all sorts of classes for billing, shipping, creating invoices, all using the Pen class. A day boss comes and says, "Great news! The company is growing and we are selling Books & CD's now!" Not great news because now you have to change every class that uses Pen to also use Book & CD. But what if you had originally created an interface called "SellableProduct", and Pen implemented this interface. Then you could have written all your shipping, invoicing, etc classes to use that interface instead of Pen. Now all you would have to do is create a new class called Book & CompactDisc which implements the SellableProduct interface. Because of polymorphism, all of the other classes could continue to work without change! Make Sense?

So, it means using Inheritance which is one of the way to achieve polymorphism.

Polymorhism can be possible in a class / interface but Inheritance always between 2 OR more classes / interfaces. Inheritance always conform "is-a" relationship whereas it is not always with Polymorphism (which can conform both "is-a" / "has-a" relationship.

How to call base.base.method()?

Just want to add this here, since people still return to this question even after many time. Of course it's bad practice, but it's still possible (in principle) to do what author wants with:

class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        var ptr = typeof(Base).GetMethod("Say").MethodHandle.GetFunctionPointer();            
        var baseSay = (Action)Activator.CreateInstance(typeof(Action), this, ptr);
        baseSay();            
    }
}

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

This is also helpful when exposing a public interface. If you have a method like this,

public ArrayList getList();

Then you decide to change it to,

public LinkedList getList();

Anyone who was doing ArrayList list = yourClass.getList() will need to change their code. On the other hand, if you do,

public List getList();

Changing the implementation doesn't change anything for the users of your API.

What is the difference between dynamic and static polymorphism in Java?

Compile time polymorphism(Static Binding/Early Binding): In static polymorphism, if we call a method in our code then which definition of that method is to be called actually is resolved at compile time only.

(or)

At compile time, Java knows which method to invoke by checking the method signatures. So, this is called compile-time polymorphism or static binding.

Dynamic Polymorphism(Late Binding/ Runtime Polymorphism): At run time, Java waits until runtime to determine which object is actually being pointed to by the reference. Method resolution was taken at runtime, due to that we call as run time polymorphism.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

We should also take in consideration how the compiler threats the generic classes: in "instantiates" a different type whenever we fill the generic arguments.

Thus we have ListOfAnimal, ListOfDog, ListOfCat, etc, which are distinct classes that end up being "created" by the compiler when we specify the generic arguments. And this is a flat hierarchy (actually regarding to List is not a hierarchy at all).

Another argument why covariance doesn't make sense in case of generic classes is the fact that at base all classes are the same - are List instances. Specialising a List by filling the generic argument doesn't extend the class, it just makes it work for that particular generic argument.

How do I escape a single quote ( ' ) in JavaScript?

You can escape a ' in JavaScript like \'

How to encrypt a large file in openssl using public key

I found the instructions at http://www.czeskis.com/random/openssl-encrypt-file.html useful.

To paraphrase the linked site with filenames from your example:

Generate a symmetric key because you can encrypt large files with it

openssl rand -base64 32 > key.bin

Encrypt the large file using the symmetric key

openssl enc -aes-256-cbc -salt -in myLargeFile.xml \
  -out myLargeFile.xml.enc -pass file:./key.bin

Encrypt the symmetric key so you can safely send it to the other person

openssl rsautl -encrypt -inkey public.pem -pubin -in key.bin -out key.bin.enc

Destroy the un-encrypted symmetric key so nobody finds it

shred -u key.bin

At this point, you send the encrypted symmetric key (key.bin.enc) and the encrypted large file (myLargeFile.xml.enc) to the other person

The other person can then decrypt the symmetric key with their private key using

openssl rsautl -decrypt -inkey private.pem -in key.bin.enc -out key.bin

Now they can use the symmetric key to decrypt the file

openssl enc -d -aes-256-cbc -in myLargeFile.xml.enc \
  -out myLargeFile.xml -pass file:./key.bin

And you're done. The other person has the decrypted file and it was safely sent.

jquery/javascript convert date string to date

Use moment js for any date operation.

https://momentjs.com/

_x000D_
_x000D_
console.log(moment("Sunday, February 28, 2010").format('MM/DD/YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

printf and long double

In addition to the wrong modifier, which port of gcc to Windows? mingw uses the Microsoft C library and I seem to remember that this library has no support for 80bits long double (microsoft C compiler use 64 bits long double for various reasons).

Web API Routing - api/{controller}/{action}/{id} "dysfunctions" api/{controller}/{id}

You can solve your problem with help of Attribute routing

Controller

[Route("api/category/{categoryId}")]
public IEnumerable<Order> GetCategoryId(int categoryId) { ... }

URI in jquery

api/category/1

Route Configuration

using System.Web.Http;

namespace WebApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown.
        }
    }
}

and your default routing is working as default convention-based routing

Controller

public string Get(int id)
    {
        return "object of id id";
    }   

URI in Jquery

/api/records/1 

Route Configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Review article for more information Attribute routing and onvention-based routing here & this

Create JSON object dynamically via JavaScript (Without concate strings)

Perhaps this information will help you.

_x000D_
_x000D_
var sitePersonel = {};_x000D_
var employees = []_x000D_
sitePersonel.employees = employees;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var firstName = "John";_x000D_
var lastName = "Smith";_x000D_
var employee = {_x000D_
  "firstName": firstName,_x000D_
  "lastName": lastName_x000D_
}_x000D_
sitePersonel.employees.push(employee);_x000D_
console.log(sitePersonel);_x000D_
_x000D_
var manager = "Jane Doe";_x000D_
sitePersonel.employees[0].manager = manager;_x000D_
console.log(sitePersonel);_x000D_
_x000D_
console.log(JSON.stringify(sitePersonel));
_x000D_
_x000D_
_x000D_

Spring Boot: How can I set the logging level with application.properties?

For the records: the official documentation, as for Spring Boot v1.2.0.RELEASE and Spring v4.1.3.RELEASE:

If the only change you need to make to logging is to set the levels of various loggers then you can do that in application.properties using the "logging.level" prefix, e.g.

logging.level.org.springframework.web: DEBUG logging.level.org.hibernate: ERROR

You can also set the location of a file to log to (in addition to the console) using "logging.file".

To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem in question. By default Spring Boot picks up the native configuration from its default location for the system (e.g. classpath:logback.xml for Logback), but you can set the location of the config file using the "logging.config" property.

Converting from signed char to unsigned char and back again?

I'm not 100% sure that I understand your question, so tell me if I'm wrong.

If I got it right, you are reading jbytes that are technically signed chars, but really pixel values ranging from 0 to 255, and you're wondering how you should handle them without corrupting the values in the process.

Then, you should do the following:

  • convert jbytes to unsigned char before doing anything else, this will definetly restore the pixel values you are trying to manipulate

  • use a larger signed integer type, such as int while doing intermediate calculations, this to make sure that over- and underflows can be detected and dealt with (in particular, not casting to a signed type could force to compiler to promote every type to an unsigned type in which case you wouldn't be able to detect underflows later on)

  • when assigning back to a jbyte, you'll want to clamp your value to the 0-255 range, convert to unsigned char and then convert again to signed char: I'm not certain the first conversion is strictly necessary, but you just can't be wrong if you do both

For example:

inline int fromJByte(jbyte pixel) {
    // cast to unsigned char re-interprets values as 0-255
    // cast to int will make intermediate calculations safer
    return static_cast<int>(static_cast<unsigned char>(pixel));
}

inline jbyte fromInt(int pixel) {
    if(pixel < 0)
        pixel = 0;

    if(pixel > 255)
        pixel = 255;

    return static_cast<jbyte>(static_cast<unsigned char>(pixel));
}

jbyte in = ...
int intermediate = fromJByte(in) + 30;
jbyte out = fromInt(intermediate);

How can I force component to re-render with hooks in React?

Alternative to @MinhKha's answer:

It can be much cleaner with useReducer:

const [, forceUpdate] = useReducer(x => x + 1, 0);

Usage: forceUpdate() - cleaner without params

Could not resolve this reference. Could not locate the assembly

If the project is check out to different PC through team foundation server with different location of same library file, there will be no yellow icon mark in Reference but when change to Release build and build the project, it will give an error. Just like what @C.Evenhuis said, it will use back old one in previous build (eg: Debug build) so I didn't notice the mistake.

Now I know it is a bad habit to put library files in different location on different PC.

Just need to delete the reference and re-add the same reference from correct location.

Function vs. Stored Procedure in SQL Server

Mssql stored procedure vs function:

enter image description here

Twitter Bootstrap Form File Element Upload Button

Upload buttons are a pain to style because it styles the input and not the button.

but you can use this trick:

http://www.quirksmode.org/dom/inputfile.html

Summary:

  1. Take a normal <input type="file"> and put it in an element with position: relative.

  2. To this same parent element, add a normal <input> and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the <input type="file">.

  3. Set the z-index of the <input type="file"> to 2 so that it lies on top of the styled input/image.

  4. Finally, set the opacity of the <input type="file"> to 0. The <input type="file"> now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window. (Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the to remain clickable)

How to add conditional attribute in Angular 2?

you can use this.

<span [attr.checked]="val? true : false"> </span>

Copy all the lines to clipboard

If you're using Vim in visual mode, the standard cut and paste keys also apply, at least with Windows.

  • CTRLA means "Mark the entire file.
  • CTRLC means "Copy the selection.
  • ESC means "De-select, so your next key press doesn't replace the entire file :-)

Under Ubuntu terminal (Gnome) at least, the standard copy also works (CTRLSHIFTC, although there doesn't appear to be a standard keyboard shortcut for select all (other than ALTE followed by A).

XML Parser for C

Two of the most widely used parsers are Expat and libxml.

If you are okay with using C++, there's Xerces-C++ too.

Array length in angularjs returns undefined

use:

$scope.users.length;

Instead of:

$scope.users.lenght;

And next time "spell-check" your code.

How to send PUT, DELETE HTTP request in HttpURLConnection?

UrlConnection is an awkward API to work with. HttpClient is by far the better API and it'll spare you from loosing time searching how to achieve certain things like this stackoverflow question illustrates perfectly. I write this after having used the jdk HttpUrlConnection in several REST clients. Furthermore when it comes to scalability features (like threadpools, connection pools etc.) HttpClient is superior

Move SQL data from one table to another

Try this

INSERT INTO TABLE2 (Cols...) SELECT Cols... FROM TABLE1 WHERE Criteria

Then

DELETE FROM TABLE1 WHERE Criteria

Get current NSDate in timestamp format

Swift:

I have a UILabel which shows TimeStamp over a Camera Preview.

    var timeStampTimer : NSTimer?
    var dateEnabled:  Bool?
    var timeEnabled: Bool?
   @IBOutlet weak var timeStampLabel: UILabel!

override func viewDidLoad() {
        super.viewDidLoad()
//Setting Initial Values to be false.
        dateEnabled =  false
        timeEnabled =  false
}

override func viewWillAppear(animated: Bool) {

        //Current Date and Time on Preview View
        timeStampLabel.text = timeStamp
        self.timeStampTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,target: self, selector: Selector("updateCurrentDateAndTimeOnTimeStamperLabel"),userInfo: nil,repeats: true)
}

func updateCurrentDateAndTimeOnTimeStamperLabel()
    {
//Every Second, it updates time.

        switch (dateEnabled, timeEnabled) {
        case (true?, true?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .MediumStyle)
            break;
        case (true?, false?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .LongStyle, timeStyle: .NoStyle)
            break;

        case (false?, true?):
            timeStampLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .MediumStyle)
            break;
        case (false?, false?):
            timeStampLabel.text =  NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .NoStyle)
            break;
        default:
            break;

        }
    }

I am setting up a setting Button to trigger a alertView.

@IBAction func settingsButton(sender : AnyObject) {


let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)

let timeStampOnAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  true

}
let timeStampOffAction = UIAlertAction(title: NSLocalizedString("TimeStamp Off", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  false

}
let dateOnlyAction = UIAlertAction(title: NSLocalizedString("Date Only", comment: ""), style: .Default) { action in

    self.dateEnabled = true
    self.timeEnabled =  false


}
let timeOnlyAction = UIAlertAction(title: NSLocalizedString("Time Only", comment: ""), style: .Default) { action in

    self.dateEnabled = false
    self.timeEnabled =  true
}

let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in

}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(timeStampOnAction)
cameraSettingsAlert.addAction(timeStampOffAction)
cameraSettingsAlert.addAction(dateOnlyAction)
cameraSettingsAlert.addAction(timeOnlyAction)

self.presentViewController(cameraSettingsAlert, animated: true, completion: nil)

}

How to Display blob (.pdf) in an AngularJS app

I have struggled for the past couple of days trying to download pdfs and images,all I was able to download was simple text files.

Most of the questions have the same components, but it took a while to figure out the right order to make it work.

Thank you @Nikolay Melnikov, your comment/reply to this question was what made it work.

In a nutshell, here is my AngularJS Service backend call:

  getDownloadUrl(fileID){
    //
    //Get the download url of the file
    let fullPath = this.paths.downloadServerURL + fileId;
    //
    // return the file as arraybuffer 
    return this.$http.get(fullPath, {
      headers: {
        'Authorization': 'Bearer ' + this.sessionService.getToken()
      },
      responseType: 'arraybuffer'
    });
  }

From my controller:

downloadFile(){
   myService.getDownloadUrl(idOfTheFile).then( (response) => {
      //Create a new blob object
      let myBlobObject=new Blob([response.data],{ type:'application/pdf'});

      //Ideally the mime type can change based on the file extension
      //let myBlobObject=new Blob([response.data],{ type: mimeType});

      var url = window.URL || window.webkitURL
      var fileURL = url.createObjectURL(myBlobObject);
      var downloadLink = angular.element('<a></a>');
      downloadLink.attr('href',fileURL);
      downloadLink.attr('download',this.myFilesObj[documentId].name);
      downloadLink.attr('target','_self');
      downloadLink[0].click();//call click function
      url.revokeObjectURL(fileURL);//revoke the object from URL
    });
}

Eclipse IDE: How to zoom in on text?

On Mac you can do Press 'Command' and '+' buttons to zoom in. press 'Command' and '-' buttons to zoom out.

Use jquery to set value of div tag

When using the .html() method, a htmlString must be the parameter. (source) Put your string inside a HTML tag and it should work or use .text() as suggested by farzad.

Example:

<div class="demo-container">
    <div class="demo-box">Demonstration Box</div>
</div>

<script type="text/javascript">
$("div.demo-container").html( "<p>All new content. <em>You bet!</em></p>" );
</script>

multiprocessing.Pool: When to use apply, apply_async or map?

Here is an overview in a table format in order to show the differences between Pool.apply, Pool.apply_async, Pool.map and Pool.map_async. When choosing one, you have to take multi-args, concurrency, blocking, and ordering into account:

                  | Multi-args   Concurrence    Blocking     Ordered-results
---------------------------------------------------------------------
Pool.map          | no           yes            yes          yes
Pool.map_async    | no           yes            no           yes
Pool.apply        | yes          no             yes          no
Pool.apply_async  | yes          yes            no           no
Pool.starmap      | yes          yes            yes          yes
Pool.starmap_async| yes          yes            no           no

Notes:

  • Pool.imap and Pool.imap_async – lazier version of map and map_async.

  • Pool.starmap method, very much similar to map method besides it acceptance of multiple arguments.

  • Async methods submit all the processes at once and retrieve the results once they are finished. Use get method to obtain the results.

  • Pool.map(or Pool.apply)methods are very much similar to Python built-in map(or apply). They block the main process until all the processes complete and return the result.

Examples:

map

Is called for a list of jobs in one time

results = pool.map(func, [1, 2, 3])

apply

Can only be called for one job

for x, y in [[1, 1], [2, 2]]:
    results.append(pool.apply(func, (x, y)))

def collect_result(result):
    results.append(result)

map_async

Is called for a list of jobs in one time

pool.map_async(func, jobs, callback=collect_result)

apply_async

Can only be called for one job and executes a job in the background in parallel

for x, y in [[1, 1], [2, 2]]:
    pool.apply_async(worker, (x, y), callback=collect_result)

starmap

Is a variant of pool.map which support multiple arguments

pool.starmap(func, [(1, 1), (2, 1), (3, 1)])

starmap_async

A combination of starmap() and map_async() that iterates over iterable of iterables and calls func with the iterables unpacked. Returns a result object.

pool.starmap_async(calculate_worker, [(1, 1), (2, 1), (3, 1)], callback=collect_result)

Reference:

Find complete documentation here: https://docs.python.org/3/library/multiprocessing.html

How to display the value of the bar on each bar with pyplot.barh()?

I know it's an old thread, but I landed here several times via Google and think no given answer is really satisfying yet. Try using one of the following functions:

EDIT: As I'm getting some likes on this old thread, I wanna share an updated solution as well (basically putting my two previous functions together and automatically deciding whether it's a bar or hbar plot):

def label_bars(ax, bars, text_format, **kwargs):
    """
    Attaches a label on every bar of a regular or horizontal bar chart
    """
    ys = [bar.get_y() for bar in bars]
    y_is_constant = all(y == ys[0] for y in ys)  # -> regular bar chart, since all all bars start on the same y level (0)

    if y_is_constant:
        _label_bar(ax, bars, text_format, **kwargs)
    else:
        _label_barh(ax, bars, text_format, **kwargs)


def _label_bar(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    """
    max_y_value = ax.get_ylim()[1]
    inside_distance = max_y_value * 0.05
    outside_distance = max_y_value * 0.01

    for bar in bars:
        text = text_format.format(bar.get_height())
        text_x = bar.get_x() + bar.get_width() / 2

        is_inside = bar.get_height() >= max_y_value * 0.15
        if is_inside:
            color = "white"
            text_y = bar.get_height() - inside_distance
        else:
            color = "black"
            text_y = bar.get_height() + outside_distance

        ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)


def _label_barh(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    Note: label always outside. otherwise it's too hard to control as numbers can be very long
    """
    max_x_value = ax.get_xlim()[1]
    distance = max_x_value * 0.0025

    for bar in bars:
        text = text_format.format(bar.get_width())

        text_x = bar.get_width() + distance
        text_y = bar.get_y() + bar.get_height() / 2

        ax.text(text_x, text_y, text, va='center', **kwargs)

Now you can use them for regular bar plots:

fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)

or for horizontal bar plots:

fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)

How to return more than one value from a function in Python?

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)

Passing an array as a function parameter in JavaScript

Function arguments may also be Arrays:

_x000D_
_x000D_
function foo([a,b,c], d){
  console.log(a,b,c,d);
}

foo([1,2,3], 4)
_x000D_
_x000D_
_x000D_

of-course one can also use spread:

_x000D_
_x000D_
function foo(a, b, c, d){
  console.log(a, b, c, d);
}

foo(...[1, 2, 3], 4)
_x000D_
_x000D_
_x000D_

SQLite with encryption/password protection

The .net library System.Data.SQLite also provides for encryption.

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

Try details: use any option..

    MessageBox.Show("your message",
    "window title", 
    MessageBoxButtons.OK, 
    MessageBoxIcon.Warning // for Warning  
    //MessageBoxIcon.Error // for Error 
    //MessageBoxIcon.Information  // for Information
    //MessageBoxIcon.Question // for Question
   );

Aggregate function in SQL WHERE-Clause

Another solution is to Move the aggregate fuction to Scalar User Defined Function

Create Your Function:

CREATE FUNCTION getTotalSalesByProduct(@ProductName VARCHAR(500))
RETURNS INT
AS
BEGIN

DECLARE @TotalAmount INT

SET @TotalAmount = (select SUM(SaleAmount) FROM Sales where Product=@ProductName)

RETURN @TotalAmount

END

Use Function in Where Clause

SELECT ProductName, SUM(SaleAmount) AS TotalSales
FROM Sales
WHERE dbo.getTotalSalesByProduct(ProductName)  > 1000
GROUP BY Product

References:

1. 2.

Hope helps someone.

How to get a list of installed Jenkins plugins with name and version pair

From the Jenkins home page:

  1. Click Manage Jenkins.
  2. Click Manage Plugins.
  3. Click on the Installed tab.

Or

  1. Go to the Jenkins URL directly: {Your Jenkins base URL}/pluginManager/installed

Adding a module (Specifically pymorph) to Spyder (Python IDE)

This is assuming a Conda Environment. At a high level, what worked for me was simply configuring my Conda path in Spyder. Here is how I did it:

First, determine the path your env exists at

  1. Create your environment

  2. In the Anaconda navigator, click to "environments" and then hit the play button on the environment you want to open.

  3. Click "Open with Python," you should get an interactive Python shell

  4. Type "import numpy" (choose any package)

  5. Type "numpy" and take a look at the path that looks like this:

C:\\Users\My Name\\.conda\\envs\\pytorch-three\\lib\\site-packages\\numpy\\__init__.py

The important part is the path all the way down to site-packages

For Spyder to be able to read your packages, do the following within Spyder.

  1. Open Spyder from anywhere

  2. Click "tools" and "preferences"

  3. In your Python Interpreter click "Use the following Python interpreter"

  4. From the path above, navigate to your environment and select the Python executable. For me it was here: C:\\Users\My Name\\.conda\\envs\\pytorch-three\\python.exe

  5. Finally, add the C:\\Users\\My Name\\.conda\\envs\\pytorch-three\\libs\\site-libs folder to the path (which will exist in your environment). This is easily done through the little Python icon with the tooltip of "add to path"

I personally didn't need to restart my IDE, but you may need to.

PostgreSQL function for last inserted ID

( tl;dr : goto option 3: INSERT with RETURNING )

Recall that in postgresql there is no "id" concept for tables, just sequences (which are typically but not necessarily used as default values for surrogate primary keys, with the SERIAL pseudo-type).

If you are interested in getting the id of a newly inserted row, there are several ways:


Option 1: CURRVAL(<sequence name>);.

For example:

  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval('persons_id_seq');

The name of the sequence must be known, it's really arbitrary; in this example we assume that the table persons has an id column created with the SERIAL pseudo-type. To avoid relying on this and to feel more clean, you can use instead pg_get_serial_sequence:

  INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John');
  SELECT currval(pg_get_serial_sequence('persons','id'));

Caveat: currval() only works after an INSERT (which has executed nextval() ), in the same session.


Option 2: LASTVAL();

This is similar to the previous, only that you don't need to specify the sequence name: it looks for the most recent modified sequence (always inside your session, same caveat as above).


Both CURRVAL and LASTVAL are totally concurrent safe. The behaviour of sequence in PG is designed so that different session will not interfere, so there is no risk of race conditions (if another session inserts another row between my INSERT and my SELECT, I still get my correct value).

However they do have a subtle potential problem. If the database has some TRIGGER (or RULE) that, on insertion into persons table, makes some extra insertions in other tables... then LASTVAL will probably give us the wrong value. The problem can even happen with CURRVAL, if the extra insertions are done intto the same persons table (this is much less usual, but the risk still exists).


Option 3: INSERT with RETURNING

INSERT INTO persons (lastname,firstname) VALUES ('Smith', 'John') RETURNING id;

This is the most clean, efficient and safe way to get the id. It doesn't have any of the risks of the previous.

Drawbacks? Almost none: you might need to modify the way you call your INSERT statement (in the worst case, perhaps your API or DB layer does not expect an INSERT to return a value); it's not standard SQL (who cares); it's available since Postgresql 8.2 (Dec 2006...)


Conclusion: If you can, go for option 3. Elsewhere, prefer 1.

Note: all these methods are useless if you intend to get the last inserted id globally (not necessarily by your session). For this, you must resort to SELECT max(id) FROM table (of course, this will not read uncommitted inserts from other transactions).

Conversely, you should never use SELECT max(id) FROM table instead one of the 3 options above, to get the id just generated by your INSERT statement, because (apart from performance) this is not concurrent safe: between your INSERT and your SELECT another session might have inserted another record.

Open two instances of a file in a single Visual Studio session

I don't have a copy of Visual Studio 2005, but this process works on Visual Studio 2008:

  1. Open xyz.cpp along with some other file.
  2. Right click on tab header and select new vertical tab group.
  3. Left click on that other file in the first tab group.
  4. Open xyz.cpp through solution explorer again.

You should now have two instances of file in separate vertical tab groups.

How do you query for "is not null" in Mongo?

the Query Will be

db.mycollection.find({"IMAGE URL":{"$exists":"true"}})

it will return all documents having "IMAGE URL" as a key ...........

Populating Spring @Value during Unit Test

Since Spring 4.1 you could set up property values just in code by using org.springframework.test.context.TestPropertySource annotation on Unit Tests class level. You could use this approach even for injecting properties into dependent bean instances

For example

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }


  @Configuration
  static class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();
    }

  }

}

Note: It's necessary to have instance of org.springframework.context.support.PropertySourcesPlaceholderConfigurer in Spring context

Edit 24-08-2017: If you are using SpringBoot 1.4.0 and later you could initialize tests with @SpringBootTest and @SpringBootConfiguration annotations. More info here

In case of SpringBoot we have following code

@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }

}

Cross field validation with Hibernate Validator (JSR 303)

I made a small adaptation in Nicko's solution so that it is not necessary to use the Apache Commons BeanUtils library and replace it with the solution already available in spring, for those using it as I can be simpler:

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.PropertyAccessorFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

    private String firstFieldName;
    private String secondFieldName;

    @Override
    public void initialize(final FieldMatch constraintAnnotation) {
        firstFieldName = constraintAnnotation.first();
        secondFieldName = constraintAnnotation.second();
    }

    @Override
    public boolean isValid(final Object object, final ConstraintValidatorContext context) {

        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
        final Object firstObj = beanWrapper.getPropertyValue(firstFieldName);
        final Object secondObj = beanWrapper.getPropertyValue(secondFieldName);

        boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode(firstFieldName)
                .addConstraintViolation();
        }

        return isValid;

    }
}

Scanning Java annotations at runtime

The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).

So, even if you could enumerate all classes, this would be very time- and memory-consuming.

The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.

Registering for Push Notifications in Xcode 8/Swift 3.0?

In iOS10 instead of your code, you should request an authorization for notification with the following: (Don't forget to add the UserNotifications Framework)

if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().requestAuthorization([.alert, .sound, .badge]) { (granted: Bool, error: NSError?) in
            // Do something here
        }
    }

Also, the correct code for you is (use in the else of the previous condition, for example):

let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
UIApplication.shared().registerUserNotificationSettings(setting)
UIApplication.shared().registerForRemoteNotifications()

Finally, make sure Push Notification is activated under target-> Capabilities -> Push notification. (set it on On)

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

I followed the sample code from @codeslord, but for some reason I had to access my screenshot data differently:

 # Open the Firefox webdriver
 driver = webdriver.Firefox()
 # Find the element that you're interested in
 imagepanel = driver.find_element_by_class_name("panel-height-helper")
 # Access the data bytes for the web element
 datatowrite = imagepanel.screenshot_as_png
 # Write the byte data to a file
 outfile = open("imagepanel.png", "wb")
 outfile.write(datatowrite)
 outfile.close()

(using Python 3.7, Selenium 3.141.0 and Mozilla Geckodriver 71.0.0.7222)

How to use "svn export" command to get a single file from the repository?

I know the OP was asking about doing the export from the command line, but just in case this is helpful to anyone else out there...

You could just let Eclipse (plus one of the plugins discussed here) do the work for you.

Obviously, downloading Eclipse just for doing a single export is overkill, but if you are already using it for development, you can also do an svn export simply from your IDE's context menu when browsing an SVN repository.

Advantages:

  • easier for those not so familiar with using SVN at the command-line level (but you can learn about what happens at the command-line level by looking at the SVN console with a range of commands)
  • you'd already have your SVN details set up and wouldn't have to worry about authenticating, etc.
  • you don't have to worry about mistyping the URL, or remembering the order of parameters
  • you can specify in a dialog which directory you'd like to export to
  • you can specify in a dialog whether you'd like to export from TRUNK/HEAD or use a specific revision

Understanding React-Redux and mapStateToProps()

import React from 'react';
import {connect} from 'react-redux';
import Userlist from './Userlist';

class Userdetails extends React.Component{

render(){
    return(
        <div>
            <p>Name : <span>{this.props.user.name}</span></p>
            <p>ID : <span>{this.props.user.id}</span></p>
            <p>Working : <span>{this.props.user.Working}</span></p>
            <p>Age : <span>{this.props.user.age}</span></p>
        </div>
    );
 }

}

 function mapStateToProps(state){  
  return {
    user:state.activeUser  
}

}

  export default connect(mapStateToProps, null)(Userdetails);

Best Java obfuscator?

I think that Proguard is the best. It is also possible to integrate it with your IDE (for example NetBeans). However, consider that if you obfuscate your code it could be difficult to track problems in your logs..

Android. WebView and loadData

The safest way to load htmlContent in a Web view is to:

  1. use base64 encoding (official recommendation)
  2. specify UFT-8 for html content type, i.e., "text/html; charset=utf-8" instead of "text/html" (personal advice)

"Base64 encoding" is an official recommendation that has been written again (already present in Javadoc) in the latest 01/2019 bug in Chrominium (present in WebView M72 (72.0.3626.76)):

https://bugs.chromium.org/p/chromium/issues/detail?id=929083

Official statement from Chromium team:

"Recommended fix:
Our team recommends you encode data with Base64. We've provided examples for how to do so:

This fix is backwards compatible (it works on earlier WebView versions), and should also be future-proof (you won't hit future compatibility problems with respect to content encoding)."

Code sample:

webView.loadData(
    Base64.encodeToString(
        htmlContent.getBytes(StandardCharsets.UTF_8),
        Base64.DEFAULT), // encode in Base64 encoded 
    "text/html; charset=utf-8", // utf-8 html content (personal recommendation)
    "base64"); // always use Base64 encoded data: NEVER PUT "utf-8" here (using base64 or not): This is wrong! 

How to auto generate migrations with Sequelize CLI from Sequelize models?

As of 16/9/2020 most of these answers are not too much consistent any way! Try this new npm package

Sequelize-mig

It completed most known problems in sequelize-auto-migrations and its forks and its maintained and documented!

Its used in a way similar to the known one

Install:

npm install sequelize-mig -g / yarn global add sequelize-mig

then use it like this

sequelize-mig migration:make -n <migration name>

Default interface methods are only supported starting with Android N

As CommonsWare mentioned, for reference add this inside the android {...} closure in the build.gradle for your app module to resolve issue:

android {
...
  compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
...
}

How to force a SQL Server 2008 database to go Offline

You need to use WITH ROLLBACK IMMEDIATE to boot other conections out with no regards to what or who is is already using it.

Or use WITH NO_WAIT to not hang and not kill existing connections. See http://www.blackwasp.co.uk/SQLOffline.aspx for details

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

How do I run a simple bit of code in a new thread?

Here is another option:

Task.Run(()=>{
//Here is a new thread
});

What does <![CDATA[]]> in XML mean?

The data contained therein will not be parsed as XML, and as such does not need to be valid XML or can contain elements that may appear to be XML but are not.

Best HTTP Authorization header type for JWT

The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization header with the Bearer authentication scheme.

This scheme is described by the RFC6750.

Example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ

If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.

Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.

Unlike the custom JWT scheme you mention in your question, the Bearer one is registered at the IANA.

Concerning the Basic and Digest authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.

How can I create and style a div using JavaScript?

Another thing I like to do is creating an object and then looping thru the object and setting the styles like that because it can be tedious writing every single style one by one.

var bookStyles = {
   color: "red",
   backgroundColor: "blue",
   height: "300px",
   width: "200px"
};

let div = document.createElement("div");

for (let style in bookStyles) {
 div.style[style] = bookStyles[style];
}

body.appendChild(div);

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

Facebook key hash does not match any stored key hashes

On Debug

Copy Paste This code inside OnCreate method

       try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getApplication().getPackageName(),
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d("KeyHash e1",e.getLocalizedMessage() +"");
        } catch (NoSuchAlgorithmException e) {
            Log.d("KeyHash e2", e.getLocalizedMessage() +"");
        }

Open Logcat and Filter/find 'D/KeyHash:'

D/KeyHash: D5uFR+65hafzotdih/dOfp14FpE=

Then Open https://developers.facebook.com/ and Open YourApp/Setting/Basic
Scroll down to Android Section Then Paste the Key Hashes and Save

How to compare files from two different branches?

The best way to do it is by using git diff in the following way: git diff <source_branch> <target_branch> -- file_path

It will check the difference between files in those branches. Take a look at this article for more information about git commands and how they work.

How to make a DIV not wrap?

The <span> tag is used to group inline-elements in a document.
(source)

Is PowerShell ready to replace my Cygwin shell on Windows?

I found PowerShell programming to be not worth the effort.

I have several years of experience with shell scripting under Unix, but I found it enormously difficult to do much of anything with PowerShell.

It seems like many functions require you to interrogate the Windows Management Interface and issue SQL-like commands to get the information you need.

For example, I wanted to write a script to remove all files with a specific suffix from a directory tree. Under Unix, this would be a simple ...

find . -name \*.xyz -exec rm {} \;

After a couple of hours dicking around with Scripting.FileSystemObject and WScript.Shell and issuing "SELECT * FROM Win32_ShortcutFile WHERE Drive = '" & drive & "' AND Path = '" & searchFolder & "'", I finally gave up and settled for Windows Explorer's Search command and just do it manually. There's probably some way to do what I wanted, but I didn't see anything obvious and all the examples on the MSDN site were so trivial as to be worthless.

EDIT Heh, of course as soon as I wrote this I poked around some more and found what I had been missing: the -recurse option to the remove-item command is faulty (revealed if you use get-help remove-item -detailed).

I had been trying "remove-item -filter '* .xyz' -recurse" and it wasn't working, so I gave up on it.

Turns out you need to use get-childitem -filter '*.xyz' -recurse | remove-item

Getting a better understanding of callback functions in JavaScript

Here is a basic example that explains the callback() function in JavaScript:

_x000D_
_x000D_
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
  alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
  if (callback && typeof(callback) === "function") {_x000D_
    x += 1;_x000D_
    alert("Calla Back x= " + x);_x000D_
    x += 1;_x000D_
    callback();_x000D_
  }_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
  alert("Function X= " + x);_x000D_
});
_x000D_
_x000D_
_x000D_

JSFiddle

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

See the wiki article:

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.

WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

That is:

  • HTTPS is a transport layer (point-to-point) security mechanism
  • WS-Security is an application layer (end-to-end) security mechanism.

How do I get AWS_ACCESS_KEY_ID for Amazon?

Amazon changes the admin console from time to time, hence the previous answers above are irrelevant in 2020.

The way to get the secret access key (Oct.2020) is:

  1. go to IAM console: https://console.aws.amazon.com/iam
  2. click on "Users". (see image) enter image description here
  3. go to the user you need his access key. enter image description here

As i see the answers above, I can assume my answer will become irrelevant in a year max :-)

HTH

Maven version with a property

If you have a parent project you can set the version in the parent pom and in the children you can reference sibling libs with the ${project.version} or ${version} properties.

If you want to avoid to repeat the version of the parent in each children: you can do this:

<modelVersion>4.0.0</modelVersion>
<groupId>company</groupId>
<artifactId>build.parent</artifactId>
<version>${my.version}</version>
<packaging>pom</packaging>

<properties>
<my.version>1.1.2-SNAPSHOT</my.version>
</properties>

And then in your children pom you have to do:

    <parent>
      <artifactId>build.parent</artifactId>
      <groupId>company</groupId>
      <relativePath>../build.parent/pom.xml</relativePath>
      <version>${my.version}</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>company</groupId>
    <artifactId>artifact</artifactId>
    <packaging>eclipse-plugin</packaging>

    <dependencies>
        <dependency> 
           <groupId>company</groupId>
           <artifactId>otherartifact</artifactId>   
           <version>${my.version}</version>
or
           <version>${project.version}</version>
        </dependency>
    </dependencies>

hth

Git workflow and rebase vs merge questions

I only use rebase workflow, because it is visually clearer(not only in GitKraken, but also in Intellij and in gitk, but I recommend the first one most): you have a branch, it originates from the master, and it goes back to master. When the diagram is clean and beautiful, you will know that nothing goes to hell, ever.

enter image description here

My workflow is almost the same from yours, but with only one small difference: I squash commits into one in my local branch before rebase my branch onto the latest changes on master, because:

rebase works on basis of each commit

which means, if you have 15 commits changing the same line as master does, you have to check 15 times if you don't squash, but what matters is the final result, right?

So, the whole workflow is:

  1. Checkout to master and pull to ensure that you have the latest version

  2. From there, create a new branch

  3. Do your work there, you can freely commit several times, and push to remote, no worries, because it is your branch.

  4. If someone tells you, "hey, my PR/MR is approved, now it is merged to master", you can fetch them/pull them. You can do it anytime, or in step 6.

  5. After doing all your work, commit them, and if you have several commits, squash them(they are all your work, and how many times you change a line of code does not matter; the only important thing is the final version). Push it or not, it doesn't matter.

  6. Checkout to master, pull again to ensure you have the latest master in local. Your diagram should be similar to this:

enter image description here

As you can see, you are on your local branch, which originates from an outdated status on master, while master(both local and remote) has moved forward with changes of your colleague.

  1. Checkout back to your branch, and rebase to master. You will now have one commit only, so you solve the conflicts only once.(And in GitKraken, you only have to drag your branch on to master and choose "Rebase"; another reason why I like it.) After that, you will be like:

enter image description here

  1. So now, you have all the changes on the latest master, combined with changes on your branch. You can now push to your remote, and, if you have pushed before, you will have to force push; Git will tell you that you cannot simply fast forward. That's normal, because of the rebase, you have changed the start point of your branch. But you should not fear: wisely use the force, but without fear. In the end, the remote is also your branch so you do not affect master even if you do something wrong.

  2. Create PR/MR and wait until it is approved, so master will have your contribution. Congrats! So you can now checkout to master, pull your changes, and delete your local branch in order to clean up the diagram. The remote branch should be deleted too, if this is not done when you merge it into master.

The final diagram is clean and clear again:

enter image description here

import android packages cannot be resolved

right click on project->properties->android->select target name as "Android 4.4.2" --click ok

since DocumentsContract is added in API level 19

How to get all keys with their values in redis

You can use MGET to get the values of multiple keys in a single go.

Example:

redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)

For listing out all keys & values you'll probably have to use bash or something similar, but MGET can help in listing all the values when you know which keys to look for beforehand.

Getting value of HTML text input

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

How do I change the font size of a UILabel in Swift?

You can do it like this:

label.font = UIFont(name: label.font.fontName, size: 20)

Or like this:

label.font = label.font.withSize(20)

This will use the same font. 20 can be whatever size you want of course.

Note: The latter option will overwrite the current font weight to regular so if you want to preserve the font weight use the first option.

Swift 3 Update:

label.font = label.font.withSize(20)

Swift 4 Update:

label.font = label.font.withSize(20)

or

label.font = UIFont(name:"fontname", size: 20.0)

and if you use the system fonts

label.font = UIFont.systemFont(ofSize: 20.0)
label.font = UIFont.boldSystemFont(ofSize: 20.0)
label.font = UIFont.italicSystemFont(ofSize: 20.0)

Matrix multiplication using arrays

static int b[][]={{21,21},{22,22}};

static int a[][] ={{1,1},{2,2}};

public static void mul(){
    int c[][] = new int[2][2];

    for(int i=0;i<b.length;i++){
        for(int j=0;j<b.length;j++){
            c[i][j] =0;
        }   
    }

    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            for(int k=0;k<b.length;k++){
            c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
            }
        }
    }

    for(int i=0;i<c.length;i++){
        for(int j=0;j<c.length;j++){
            System.out.print(c[i][j]);
        }   
        System.out.println("\n");
    }
}

C# Return Different Types?

Here is how you might do it with generics:

public T GetAnything<T>()
{
   T t = //Code to create instance

   return t;
}

But you would have to know what type you wanted returned at design time. And that would mean that you could just call a different method for each creation...

Could not find method compile() for arguments Gradle

In my case, all the compile statements has somehow arranged in a single line. separating them in individual lines has fixed the issue.

log4net vs. Nlog

First look at the rest of your stack.

If you are using NHibernate, it utilizes Log4Net directly. Other frameworks might have other specific loggers they need.

Other than that: both work fine.

I've settled on Log4Net myself. It can be a pain to configure, and if it isn't configured correctly it is a pain to figure out what went wrong. But you can make it do almost anything you would want from a logger.

If you don't have a standing issue with Log4Net, here is an article I wrote on how to get started with it: http://elegantcode.com/2007/12/07/getting-started-with-log4net/

Run a Command Prompt command from Desktop Shortcut

I tried this, all it did was open a cmd prompt with "cmd -c (my command)" and didn't actually run it. see below.

C:\windows\System32>cmd -c (powercfg /lastwake) Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\windows\System32>

***Update
I changed my .bat file to read "cmd /k (powercfg /lastwake)" and it worked. You can also leave out the () and it works too.

NodeJS / Express: what is "app.use"?

Middleware is a general term for software that serves to "glue together" so app.use is a method to configure the middleware, for example: to parse and handle the body of request: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); there are many middlewares you can use in your express application just read the doc : http://expressjs.com/en/guide/using-middleware.html

How to run java application by .bat file

  • javac (.exe on Windows) binary path must be added into global PATH env. variable.

    javac MyProgram.java

  • or with java (.exe on Windows)

    java MyProgram.jar

Check if certain value is contained in a dataframe column in pandas

You can use any:

print any(df.column == 07311954)
True       #true if it contains the number, false otherwise

If you rather want to see how many times '07311954' occurs in a column you can use:

df.column[df.column == 07311954].count()

TSQL - Cast string to integer or return default value

My solution to this issue was to create the function shown below. My requirements included that the number had to be a standard integer, not a BIGINT, and I needed to allow negative numbers and positive numbers. I have not found a circumstance where this fails.

CREATE FUNCTION [dbo].[udfIsInteger]
(
    -- Add the parameters for the function here
    @Value nvarchar(max)
)
RETURNS int
AS
BEGIN
    -- Declare the return variable here
    DECLARE @Result int = 0

    -- Add the T-SQL statements to compute the return value here
    DECLARE @MinValue nvarchar(11) = '-2147483648'
    DECLARE @MaxValue nvarchar(10) = '2147483647'

    SET @Value = ISNULL(@Value,'')

    IF LEN(@Value)=0 OR 
      ISNUMERIC(@Value)<>1 OR
      (LEFT(@Value,1)='-' AND LEN(@Value)>11) OR
      (LEFT(@Value,1)='-' AND LEN(@Value)=11 AND @Value>@MinValue) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)>10) OR
      (LEFT(@Value,1)<>'-' AND LEN(@Value)=10 AND @Value>@MaxValue)
      GOTO FINISHED

    DECLARE @cnt int = 0
    WHILE @cnt<LEN(@Value)
    BEGIN
      SET @cnt=@cnt+1
      IF SUBSTRING(@Value,@cnt,1) NOT IN ('-','0','1','2','3','4','5','6','7','8','9') GOTO FINISHED
    END
    SET @Result=1

FINISHED:
    -- Return the result of the function
    RETURN @Result

END

Java HashMap: How to get a key and value by index?

You can iterate over keys by calling map.keySet(), or iterate over the entries by calling map.entrySet(). Iterating over entries will probably be faster.

for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    List<String> list = entry.getValue();
    // Do things with the list
}

If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap.

By the way, I'd recommend changing the declared type of the map to <String, List<String>>. Always best to declare types in terms of the interface rather than the implementation.

Is Fortran easier to optimize than C for heavy calculations?

I'm a hobbyist programmer and i'm "average" at both language. I find it easier to write fast Fortran code than C (or C++) code. Both Fortran and C are "historic" languages (by today standard), are heavily used, and have well supported free and commercial compiler.

I don't know if it's an historic fact but Fortran feel like it's built to be paralleled/distributed/vectorized/whatever-many-cores-ized. And today it's pretty much the "standard metric" when we're talking about speed : "does it scale ?"

For pure cpu crunching i love Fortran. For anything IO related i find it easier to work with C. (it's difficult in both case anyway).

Now of course, for parallel math intensive code you probably want to use your GPU. Both C and Fortran have a lot of more or less well integrated CUDA/OpenCL interface (and now OpenACC).

My moderately objective answer is : If you know both language equally well/poorly then i think Fortran is faster because i find it easier to write parallel/distributed code in Fortran than C. (once you understood that you can write "freeform" fortran and not just strict F77 code)

Here is a 2nd answer for those willing to downvote me because they don't like the 1st answer : Both language have the features required to write high-performance code. So it's dependent of the algorithm you're implementing (cpu intensive ? io intensive ? memory intensive?), the hardware (single cpu ? multi-core ? distribute supercomputer ? GPGPU ? FPGA ?), your skill and ultimately the compiler itself. Both C and Fortran have awesome compiler. (i'm seriously amazed by how advanced Fortran compilers are but so are C compilers).

PS : i'm glad you specifically excluded libs because i have a great deal of bad stuff to say about Fortran GUI libs. :)

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

Difference between getAttribute() and getParameter()

getParameter - Is used for getting the information you need from the Client's HTML page

getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.

Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.

Using getAttribute, you can retrieve the Session variable.

Can I have multiple background images using CSS?

Yes, it is possible, and has been implemented by popular usability testing website Silverback. If you look through the source code you can see that the background is made up of several images, placed on top of each other.

Here is the article demonstrating how to do the effect can be found on Vitamin. A similar concept for wrapping these 'onion skin' layers can be found on A List Apart.

Find if variable is divisible by 2

Please write the following code in your console:

var isEven = function(deep) {

  if (deep % 2 === 0) {
        return true;  
    }
    else {
        return false;    
    }
};
isEven(44);

Please Note: It will return true, if the entered number is even otherwise false.

How to make a HTTP request using Ruby on Rails?

Net::HTTP is built into Ruby, but let's face it, often it's easier not to use its cumbersome 1980s style and try a higher level alternative:

jsPDF multi page PDF with HTML renderer

I found the solution on this page: https://github.com/MrRio/jsPDF/issues/434 From the user: wangzhixuan

I copy the solution here: // suppose your picture is already in a canvas

      var imgData = canvas.toDataURL('image/png');

      /*
      Here are the numbers (paper width and height) that I found to work. 
      It still creates a little overlap part between the pages, but good enough for me.
      if you can find an official number from jsPDF, use them.
      */
      var imgWidth = 210; 
      var pageHeight = 295;  
      var imgHeight = canvas.height * imgWidth / canvas.width;
      var heightLeft = imgHeight;

      var doc = new jsPDF('p', 'mm');
      var position = 0;

      doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }
      doc.save( 'file.pdf');?

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

convert string into array of integers

The point against parseInt-approach:

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

Change the value for Platform Target on your web project's property page to Any CPU.

enter image description here

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

Dart SDK is not configured

I recently faced this issue on my MAC device when I was running flutter project on Android Studio

Steps to fix this.

  1. install dart on MAC os using brew (https://dart.dev/get-dart)

brew tap dart-lang/dart

brew install dart

  1. run

brew info dart

  1. It will give you output something like this

Please note the path to the Dart SDK:/usr/local/opt/dart/libexec

paste the Dart SDK path in Android Studio Settings

SQL LEFT-JOIN on 2 fields for MySQL

Let's try this way:

select 
    a.ip, 
    a.os, 
    a.hostname, 
    a.port, 
    a.protocol, 
    b.state
from a
left join b 
    on a.ip = b.ip 
        and a.port = b.port /*if you has to filter by columns from right table , then add this condition in ON clause*/
where a.somecolumn = somevalue /*if you have to filter by some column from left table, then add it to where condition*/

So, in where clause you can filter result set by column from right table only on this way:

...
where b.somecolumn <> (=) null

enable or disable checkbox in html

In jsp you can do it like this:

<%
boolean checkboxDisabled = true; //do your logic here
String checkboxState = checkboxDisabled ? "disabled" : "";
%>
<input type="checkbox" <%=checkboxState%>>

How to find index of STRING array in Java from a given value?

Refactoring the above methods and showing with the use:

private String[] languages = {"pt", "en", "es"};
private Integer indexOf(String[] arr, String str){
   for (int i = 0; i < arr.length; i++)
      if(arr[i].equals(str)) return i;
   return -1;
}
indexOf(languages, "en")

python pandas dataframe to dictionary

If you set the the index than the dictionary will result in unique key value pairs

encoder=LabelEncoder()
df['airline_enc']=encoder.fit_transform(df['airline'])
dictAirline= df[['airline_enc','airline']].set_index('airline_enc').to_dict()

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

What's the best/easiest GUI Library for Ruby?

Limelight I really enjoy the theatre metaphor.

How to list all the files in a commit?

I like this:

git diff --name-status <SHA1> <SHA1>^

Deleting all records in a database table

If you are looking for a way to it without SQL you should be able to use delete_all.

Post.delete_all

or with a criteria

Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

See here for more information.

The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.

What's the best way to join on the same table twice?

The first is good unless either Phone1 or (more likely) phone2 can be null. In that case you want to use a Left join instead of an inner join.

It is usually a bad sign when you have a table with two phone number fields. Usually this means your database design is flawed.

How can I dismiss the on screen keyboard?

Note: This answer is outdated. See the answer for newer versions of Flutter.

You can dismiss the keyboard by taking away the focus of the TextFormField and giving it to an unused FocusNode:

FocusScope.of(context).requestFocus(FocusNode());

How to make Twitter Bootstrap menu dropdown on hover rather than click

[Update] The plugin is on GitHub and I am working on some improvements (like use only with data-attributes (no JS necessary). I've leaving the code in below, but it's not the same as what's on GitHub.

I liked the purely CSS version, but it's nice to have a delay before it closes, as it's usually a better user experience (i.e. not punished for a mouse slip that goes 1 px outside the dropdown, etc), and as mentioned in the comments, there's that 1px of margin you have to deal with or sometimes the nav closes unexpectedly when you're moving to the dropdown from the original button, etc.

I created a quick little plugin that I've used on a couple sites and it's worked nicely. Each nav item is independently handled, so they have their own delay timers, etc.

JS

// outside the scope of the jQuery plugin to
// keep track of all dropdowns
var $allDropdowns = $();

// if instantlyCloseOthers is true, then it will instantly
// shut other nav items when a new one is hovered over
$.fn.dropdownHover = function(options) {

    // the element we really care about
    // is the dropdown-toggle's parent
    $allDropdowns = $allDropdowns.add(this.parent());

    return this.each(function() {
        var $this = $(this).parent(),
            defaults = {
                delay: 500,
                instantlyCloseOthers: true
            },
            data = {
                delay: $(this).data('delay'),
                instantlyCloseOthers: $(this).data('close-others')
            },
            options = $.extend(true, {}, defaults, options, data),
            timeout;

        $this.hover(function() {
            if(options.instantlyCloseOthers === true)
                $allDropdowns.removeClass('open');

            window.clearTimeout(timeout);
            $(this).addClass('open');
        }, function() {
            timeout = window.setTimeout(function() {
                $this.removeClass('open');
            }, options.delay);
        });
    });
};  

The delay parameter is pretty self explanatory, and the instantlyCloseOthers will instantly close all other dropdowns that are open when you hover over a new one.

Not pure CSS, but hopefully will help someone else at this late hour (i.e. this is an old thread).

If you want, you can see the different processes I went through (in a discussion on the #concrete5 IRC) to get it to work via the different steps in this gist: https://gist.github.com/3876924

The plugin pattern approach is much cleaner to support individual timers, etc.

See the blog post for more.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

this might not be the best way, but for most of the small cases this should acceptable:

"create a second empty-array and add only the ones you want to keep"

I don't remeber where I read this from... for justiness I will make this wiki in hope someone finds it or just to don't earn rep I don't deserve.

Remove ListView items in Android

            names = db.getSites();
            la = new ArrayAdapter<String>(EditSiteList.this,
                    android.R.layout.simple_list_item_1, names);
            EditSiteList.this.setListAdapter(la);
            listview.invalidateViews();

this code works fine for me.

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

How to undo a git merge with conflicts

If using latest Git,

git merge --abort

else this will do the job in older git versions

git reset --merge

or

git reset --hard

Google Maps v2 - set both my location and zoom in

It's possible to change location, zoom, bearing and tilt all in one go. It's also possible to set the duration on the animateCamera() call.

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(MOUNTAIN_VIEW)      // Sets the center of the map to Mountain View
    .zoom(17)                   // Sets the zoom
    .bearing(90)                // Sets the orientation of the camera to east
    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
    .build();                   // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Have a look at the docs here:

https://developers.google.com/maps/documentation/android/views?hl=en-US#moving_the_camera

Best way to detect when a user leaves a web page?

What you can do, is open up a WebSocket connection when the page loads, optionally send data through the WebSocket identifying the current user, and check when that connection is closed on the server.

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

Can't find android device using "adb devices" command

On Mac Lion :

I just had to go to /path/to/android-sdk/tools and run android adb update for the devices to be detected.

Determine if JavaScript value is an "integer"?

Here's a polyfill for the Number predicate functions:

"use strict";

Number.isNaN = Number.isNaN ||
    n => n !== n; // only NaN

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Number.isFinite = Number.isFinite ||
    n => n === +n               // all numbers excluding NaN
      && n >= Number.MIN_VALUE  // and -Infinity
      && n <= Number.MAX_VALUE; // and +Infinity

Number.isInteger = Number.isInteger ||
    n => n === +n              // all numbers excluding NaN
      && n >= Number.MIN_VALUE // and -Infinity
      && n <= Number.MAX_VALUE // and +Infinity
      && !(n % 1);             // and non-whole numbers

Number.isSafeInteger = Number.isSafeInteger ||
    n => n === +n                     // all numbers excluding NaN
      && n >= Number.MIN_SAFE_INTEGER // and small unsafe numbers
      && n <= Number.MAX_SAFE_INTEGER // and big unsafe numbers
      && !(n % 1);                    // and non-whole numbers

All major browsers support these functions, except isNumeric, which is not in the specification because I made it up. Hence, you can reduce the size of this polyfill:

"use strict";

Number.isNumeric = Number.isNumeric ||
    n => n === +n; // all numbers excluding NaN

Alternatively, just inline the expression n === +n manually.

How to sort an array based on the length of each element?

Based on Salman's answer, I've written a small function to encapsulate it:

function sortArrayByLength(arr, ascYN) {
        arr.sort(function (a, b) {           // sort array by length of text
            if (ascYN) return a.length - b.length;              // ASC -> a - b
            else return b.length - a.length;                    // DESC -> b - a
        });
    }

then just call it with

sortArrayByLength( myArray, true );

Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.

Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

How to declare a static const char* in your header file?

There is a trick you can use with templates to provide H file only constants.

(note, this is an ugly example, but works verbatim in at least in g++ 4.6.1.)

(values.hpp file)

#include <string>

template<int dummy>
class tValues
{
public:
   static const char* myValue;
};

template <int dummy> const char* tValues<dummy>::myValue = "This is a value";

typedef tValues<0> Values;

std::string otherCompUnit(); // test from other compilation unit

(main.cpp)

#include <iostream>
#include "values.hpp"

int main()
{
   std::cout << "from main: " << Values::myValue << std::endl;
   std::cout << "from other: " << otherCompUnit() << std::endl;
}

(other.cpp)

#include "values.hpp"

std::string otherCompUnit () {
   return std::string(Values::myValue);
}

Compile (e.g. g++ -o main main.cpp other.cpp && ./main) and see two compilation units referencing the same constant declared in a header:

from main: This is a value
from other: This is a value

In MSVC, you may instead be able to use __declspec(selectany)

For example:

__declspec(selectany) const char* data = "My data";

How to get ° character in a string in python?

Above answers assume that UTF8 encoding can safely be used - this one is specifically targetted for Windows.

The Windows console normaly uses CP850 encoding and not utf-8, so if you try to use a source file utf8-encoded, you get those 2 (incorrect) characters instead of a degree °.

Demonstration (using python 2.7 in a windows console):

deg = u'\xb0`  # utf code for degree
print deg.encode('utf8')

effectively outputs .

Fix: just force the correct encoding (or better use unicode):

local_encoding = 'cp850'    # adapt for other encodings
deg = u'\xb0'.encode(local_encoding)
print deg

or if you use a source file that explicitely defines an encoding:

# -*- coding: utf-8 -*-
local_encoding = 'cp850'  # adapt for other encodings
print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding)

How to change identity column values programmatically?

Very nice question, first we need to on the IDENTITY_INSERT for the specific table, after that run the insert query (Must specify the column name).

Note: After edit the the identity column, don't forget to off the IDENTITY_INSERT. If you not done, you cannot able to Edit the identity column for any other table.

SET IDENTITY_INSERT Emp_tb_gb_Menu ON
     INSERT Emp_tb_gb_Menu(MenuID) VALUES (68)
SET IDENTITY_INSERT Emp_tb_gb_Menu OFF

http://allinworld99.blogspot.com/2016/07/how-to-edit-identity-field-in-sql.html

Make DateTimePicker work as TimePicker only in WinForms

A snippet out of the MSDN:

'The following code sample shows how to create a DateTimePicker that enables users to choose a time only.'

timePicker = new DateTimePicker();
timePicker.Format = DateTimePickerFormat.Time;
timePicker.ShowUpDown = true;

How to unpack and pack pkg file?

Packages are just .xar archives with a different extension and a specified file hierarchy. Unfortunately, part of that file hierarchy is a cpio.gz archive of the actual installables, and usually that's what you want to edit. And there's also a Bom file that includes information on the files inside that cpio archive, and a PackageInfo file that includes summary information.

If you really do just need to edit one of the info files, that's simple:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
# edit stuff
xar -cf ../Foo-new.pkg *

But if you need to edit the installable files:

mkdir Foo
cd Foo
xar -xf ../Foo.pkg
cd foo.pkg
cat Payload | gunzip -dc |cpio -i
# edit Foo.app/*
rm Payload
find ./Foo.app | cpio -o | gzip -c > Payload
mkbom Foo.app Bom # or edit Bom
# edit PackageInfo
rm -rf Foo.app
cd ..
xar -cf ../Foo-new.pkg

I believe you can get mkbom (and lsbom) for most linux distros. (If you can get ditto, that makes things even easier, but I'm not sure if that's nearly as ubiquitously available.)

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

CSS selector based on element text?

It was probably discussed, but as of CSS3 there is nothing like what you need (see also "Is there a CSS selector for elements containing certain text?"). You will have to use additional markup, like this:

<li><span class="foo">some text</span></li>
<li>some other text</li>

Then refer to it the usual way:

li > span.foo {...}

At least one JAR was scanned for TLDs yet contained no TLDs

(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.

My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.

# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE

How to use XPath contains() here?

This is a new answer to an old question about a common misconception about contains() in XPath...

Summary: contains() means contains a substring, not contains a node.

Detailed Explanation

This XPath is often misinterpreted:

//ul[contains(li, 'Model')]

Wrong interpretation: Select those ul elements that contain an li element with Model in it.

This is wrong because

  1. contains(x,y) expects x to be a string, and
  2. the XPath rule for converting multiple elements to a string is this:

    A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.

Right interpretation: Select those ul elements whose first li child has a string-value that contains a Model substring.

Examples

XML

<r>
  <ul id="one">
    <li>Model A</li>
    <li>Foo</li>
  </ul>
  <ul id="two">
    <li>Foo</li>
    <li>Model A</li>
  </ul>
</r> 

XPaths

  • //ul[contains(li, 'Model')] selects the one ul element.

    Note: The two ul element is not selected because the string-value of the first li child of the two ul is Foo, which does not contain the Model substring.

  • //ul[li[contains(.,'Model')]] selects the one and two ul elements.

    Note: Both ul elements are selected because contains() is applied to each li individually. (Thus, the tricky multiple-element-to-string conversion rule is avoided.) Both ul elements do have an li child whose string value contains the Model substring -- position of the li element no longer matters.

See also

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

How to use vagrant in a proxy environment?

In MS Windows this works for us:

set http_proxy=< proxy_url >
set https_proxy=< proxy_url >

And the equivalent for *nix:

export http_proxy=< proxy_url >
export https_proxy=< proxy_url >

Changing file extension in Python

Use this:

os.path.splitext("name.fasta")[0]+".aln"

And here is how the above works:

The splitext method separates the name from the extension creating a tuple:

os.path.splitext("name.fasta")

the created tuple now contains the strings "name" and "fasta". Then you need to access only the string "name" which is the first element of the tuple:

os.path.splitext("name.fasta")[0]

And then you want to add a new extension to that name:

os.path.splitext("name.fasta")[0]+".aln"

CSS body background image fixed to full screen even when zooming in/out

Here is the simple code for full page background image when zooming you just apply the width:100% in style/css thats it

position:absolute; width:100%;

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();
$params['value1'];
$params['value2'];

For more info about the Request class, see http://api.symfony.com/2.8/Symfony/Component/HttpFoundation/Request.html

Select NOT IN multiple columns

Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

Be aware of pitfalls with NOT IN, though, when involving any NULL values:

Variant with LEFT JOIN:

SELECT *
FROM   friend f
LEFT   JOIN likes l USING (id1, id2)
WHERE  l.id1 IS NULL;

See @Michal's answer for the NOT EXISTS variant.
A more detailed assessment of four basic variants:

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

How to convert int to NSString?

Primitives can be converted to objects with @() expression. So the shortest way is to transform int to NSNumber and pick up string representation with stringValue method:

NSString *strValue = [@(myInt) stringValue];

or

NSString *strValue = @(myInt).stringValue;

Fetch API with Cookie

Fetch does not use cookie by default. To enable cookie, do this:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);

How do I import the javax.servlet API in my Eclipse project?

From wikipedia.

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
                "Transitional//EN\">\n" +
                "<html>\n" +
                "<head><title>Hello WWW</title></head>\n" +
                "<body>\n" +
                "<h1>Hello WWW</h1>\n" +
                "</body></html>");
  }
}

This, of course, works only if you have added the servlet-api.jar to Eclipse build path. Typically your application server (e.g Tomcat) will have the right jar file.

How do I reset a jquery-chosen select option with jQuery?

You can try this to reset (empty) drop down

 $("#autoship_option").click(function(){
            $('#autoship_option').empty(); //remove all child nodes
            var newOption = $('<option value=""></option>');
            $('#autoship_option').append(newOption);
            $('#autoship_option').trigger("chosen:updated");
        });

How to resize array in C++?

Raw arrays aren't resizable in C++.

You should be using something like a Vector class which does allow resizing..

std::vector allows you to resize it as well as allowing dynamic resizing when you add elements (often making the manual resizing unnecessary for adding).

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

How can I use console logging in Internet Explorer?

You can access IE8 script console by launching the "Developer Tools" (F12). Click the "Script" tab, then click "Console" on the right.

From within your JavaScript code, you can do any of the following:

<script type="text/javascript">
    console.log('some msg');
    console.info('information');
    console.warn('some warning');
    console.error('some error');
    console.assert(false, 'YOU FAIL');
</script>

Also, you can clear the Console by calling console.clear().

NOTE: It appears you must launch the Developer Tools first then refresh your page for this to work.

How to SUM parts of a column which have same text value in different column in the same row

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Most of answers do not get the point.

There is ONE reason matlab is so good and so widely used:

EXTREMELY FAST CODING

I am a computer vision phD student and have been using matlab for 4 years, before my phD I was using different languages including C++, java, php, python... Most of the computer vision researchers are using exclusively matlab.

1) Researchers need fast prototyping

In research environment, we have (hopefully) often new ideas, and we want to test them really quick to see if it's worth keeping on in that direction. And most often only a tiny sub-part of what we code will be useful.

Matlab is often slower at execution time, but we don't care much. Because we don't know in advance what method is going to be successful, we have to try many things, so our bottle neck is programming time, because our code will most often run a few times to get the results to publish, and that's all.

So let's see how matlab can help.

2) Everything I need is already there

Matlab has really a lot of functions that I need, so that I don't have to reinvent them all the time:

change the index of a matrix to 2d coordinate: ind2sub extract all patches of an image: im2col; compute a histogram of an image: hist(Im(:)); find the unique elements in a list unique(list); add a vector to all vectors of a matrix bsxfun(@plus,M,V); convolution on n-dimensional arrays convn(A); calculate the computation time of a sub part of the code: tic; %%code; toc; graphical interface to crop an image: imcrop(im);

The list could be very long... And they are very easy to find by using the help.

The closest to that is python...But It's just a pain in python, I have to go to google each time to look for the name of the function I need, and then I need to add packages, and the packages are not compatible one with another, the format of the matrix change, the convolution function only handle doubles but does not make an error when I give it char, just give a wrong output... no

3) IDE

An example: I launch a script. It produces an error because of a matrix. I can still execute code with the command line. I visualize it doing: imagesc(matrix). I see that the last line of the matrix is weird. I fix the bug. All variables are still set. I select the remaining of the code, press F9 to execute the selection, and everything goes on. Debuging becomes fast, thanks to that.

Matlab underlines some of my errors before execution. So I can quickly see the problems. It proposes some way to make my code faster.

There is an awesome profiler included in the IDE. KCahcegrind is such a pain to use compared to that.

python's IDEs are awefull. python without ipython is not usable. I never manage to debug, using ipython.

+autocompletion, help for function arguments,...

4) Concise code

To normalize all the columns of a matrix ( which I need all the time), I do: bsxfun(@times,A,1./sqrt(sum(A.^2)))

To remove from a matrix all colums with small sum:

A(:,sum(A)<e)=[]

To do the computation on the GPU:

gpuX = gpuarray(X); 
%%% code normally and everything is done on GPU

To paralize my code:

parfor n=1:100
%%% code normally and everything is multi-threaded

What language can beat that?

And of course, I rarely need to make loops, everything is included in functions, which make the code way easier to read, and no headache with indices. So I can focus, on what I want to program, not how to program it.

5) Plotting tools

Matlab is famous for its plotting tools. They are very helpful.

Python's plotting tools have much less features. But there is one thing super annoying. You can plot figures only once per script??? if I have along script I cannot display stuffs at each step ---> useless.

6) Documentation

Everything is very quick to access, everything is crystal clear, function names are well chosen. With python, I always need to google stuff, look in forums or stackoverflow.... complete time hog.

PS: Finally, what I hate with matlab: its price

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I am getting similar errors recently because recent JDKs (and browsers, and the Linux TLS stack, etc.) refuse to communicate with some servers in my customer's corporate network. The reason of this is that some servers in this network still have SHA-1 certificates.

Please see: https://www.entrust.com/understanding-sha-1-vulnerabilities-ssl-longer-secure/ https://blog.qualys.com/ssllabs/2014/09/09/sha1-deprecation-what-you-need-to-know

If this would be your current case (recent JDK vs deprecated certificate encription) then your best move is to update your network to the proper encription technology.

In case that you should provide a temporal solution for that, please see another answers to have an idea about how to make your JDK trust or distrust certain encription algorithms:

How to force java server to accept only tls 1.2 and reject tls 1.0 and tls 1.1 connections

Anyway I insist that, in case that I have guessed properly your problem, this is not a good solution to the problem and that your network admin should consider removing these deprecated certificates and get a new one.

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

How to install easy_install in Python 2.7.1 on Windows 7

That tool is part of the setuptools (now called Distribute) package. Install Distribute. Of course you'll have to fetch that one manually.

http://pypi.python.org/pypi/distribute#installation-instructions

How to make python Requests work via socks proxy

I installed pysocks and monkey patched create_connection in urllib3, like this:

import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 1080)

def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None, socket_options=None):
    """Connect to *address* and return the socket object.

    Convenience function.  Connect to *address* (a 2-tuple ``(host,
    port)``) and return the socket object.  Passing the optional
    *timeout* parameter will set the timeout on the socket instance
    before attempting to connect.  If no *timeout* is supplied, the
    global default timeout setting returned by :func:`getdefaulttimeout`
    is used.  If *source_address* is set it must be a tuple of (host, port)
    for the socket to bind as a source address before making the connection.
    An host of '' or port 0 tells the OS to use the default.
    """

    host, port = address
    if host.startswith('['):
        host = host.strip('[]')
    err = None
    for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socks.socksocket(af, socktype, proto)

            # If provided, set socket level options before connecting.
            # This is the only addition urllib3 makes to this function.
            urllib3.util.connection._set_socket_options(sock, socket_options)

            if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
                sock.settimeout(timeout)
            if source_address:
                sock.bind(source_address)
            sock.connect(sa)
            return sock

        except socket.error as e:
            err = e
            if sock is not None:
                sock.close()
                sock = None

    if err is not None:
        raise err

    raise socket.error("getaddrinfo returns an empty list")

# monkeypatch
urllib3.util.connection.create_connection = create_connection

I need to get all the cookies from the browser

You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

How do I write a custom init for a UIView subclass in Swift?

Swift 5 Solution

You can try out this implementation for running Swift 5 on XCode 11


class CustomView: UIView {

    var customParam: customType
    
    var container = UIView()
    
    required init(customParamArg: customType) {
        self.customParam = customParamArg
        super.init(frame: .zero)
        // Setting up the view can be done here
        setupView()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    func setupView() {
        // Can do the setup of the view, including adding subviews

        setupConstraints()
    }
    
    func setupConstraints() {
        // setup custom constraints as you wish
    }
    
    
}


Xcode 4: How do you view the console?

There's two options:

  1. Log Navigator (command-7 or view|navigators|log) and select your debug session.

  2. "View | Show Debug Area" to view the NSLog output and interact with the debugger.

Here's a pic with both on. You wouldn't normally have both on, but I can only link one image per post! http://i.stack.imgur.com/4gG4P.png

Maven – Always download sources and javadocs

I had to use KeyStore to Download the Jars. If you have any Certificate related issues you can use this approach:

mvn clean install dependency:sources -Dmaven.test.skip=true -Djavax.net.ssl.trustStore="Path_To_Your_KeyStore"

If you want to know how to create KeyStores, this is a very good link: Problems using Maven and SSL behind proxy

Android Completely transparent Status Bar?

in my case, i dont call at all "onCreate" (its a react native app and this can be fixes also by using the react-native StatusBar component) one can also use this:

override fun onStart() {
        super.onStart()
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
}

Merge two HTML table cells

use colspan for do this

 <td colspan="3">PUR mix up column</td>

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

Hide Text with CSS, Best Practice?

Add .hide-text class to your span that has the text

.hide-text{
display:none;
 }

or make the text transparent

.hide-text{
 color:rgba(0,0,0,0);
 }

use according to your use case.

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

How can I generate a 6 digit unique number?

Among the answers given here before this one, the one by "Yes Barry" is the most appropriate one.

random_int(100000, 999999)

Note that here we use random_int, which was introduced in PHP 7 and uses a cryptographic random generator, something that is important if you want random codes to be hard to guess. random_bytes was also introduced in PHP 7 and likewise uses a cryptographic random generator.

Many other solutions for random value generation, including those involving time(), microtime(), uniqid(), rand(), mt_rand(), str_shuffle(), and array_rand(), are much more predictable and are unsuitable if the random string will serve as a password, a bearer credential, a nonce, a session identifier, a "verification code" or "confirmation code", or another secret value.

The code above generates a string of 6 decimal digits. If you want to use a bigger character set (such as all upper-case letters, all lower-case letters, and the 10 digits), this is a more involved process, but you have to use random_int or random_bytes rather than rand(), mt_rand(), str_shuffle(), etc., if the string will serve as a password, a "confirmation code", or another secret value. See an answer to a related question, and see also: generating a random code in php?

I also list other things to keep in mind when generating unique identifiers, especially random ones.

How do I rotate the Android emulator display?

On Mac: Fn+Left Ctrl+F12

On Linux: Left Ctrl+F12

If you want to rotate just the screen and not the emulator: Ctrl+F10 (I tried it on Linux)

What does it mean by select 1 from table?

Although it is not widely known, a query can have a HAVING clause without a GROUP BY clause.

In such circumstances, the HAVING clause is applied to the entire set. Clearly, the SELECT clause cannot refer to any column, otherwise you would (correct) get the error, "Column is invalid in select because it is not contained in the GROUP BY" etc.

Therefore, a literal value must be used (because SQL doesn't allow a resultset with zero columns -- why?!) and the literal value 1 (INTEGER) is commonly used: if the HAVING clause evaluates TRUE then the resultset will be one row with one column showing the value 1, otherwise you get the empty set.

Example: to find whether a column has more than one distinct value:

SELECT 1
  FROM tableA
HAVING MIN(colA) < MAX(colA);

How is a CSS "display: table-column" supposed to work?

The CSS table model is based on the HTML table model http://www.w3.org/TR/CSS21/tables.html

A table is divided into ROWS, and each row contains one or more cells. Cells are children of ROWS, they are NEVER children of columns.

"display: table-column" does NOT provide a mechanism for making columnar layouts (e.g. newspaper pages with multiple columns, where content can flow from one column to the next).

Rather, "table-column" ONLY sets attributes that apply to corresponding cells within the rows of a table. E.g. "The background color of the first cell in each row is green" can be described.

The table itself is always structured the same way it is in HTML.

In HTML (observe that "td"s are inside "tr"s, NOT inside "col"s):

<table ..>
  <col .. />
  <col .. />
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
  <tr ..>
    <td ..></td>
    <td ..></td>
  </tr>
</table>

Corresponding HTML using CSS table properties (Note that the "column" divs do not contain any contents -- the standard does not allow for contents directly in columns):

_x000D_
_x000D_
.mytable {_x000D_
  display: table;_x000D_
}_x000D_
.myrow {_x000D_
  display: table-row;_x000D_
}_x000D_
.mycell {_x000D_
  display: table-cell;_x000D_
}_x000D_
.column1 {_x000D_
  display: table-column;_x000D_
  background-color: green;_x000D_
}_x000D_
.column2 {_x000D_
  display: table-column;_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 1</div>_x000D_
    <div class="mycell">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow">_x000D_
    <div class="mycell">contents of first cell in row 2</div>_x000D_
    <div class="mycell">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_



OPTIONAL: both "rows" and "columns" can be styled by assigning multiple classes to each row and cell as follows. This approach gives maximum flexibility in specifying various sets of cells, or individual cells, to be styled:

_x000D_
_x000D_
//Useful css declarations, depending on what you want to affect, include:_x000D_
_x000D_
/* all cells (that have "class=mycell") */_x000D_
.mycell {_x000D_
}_x000D_
_x000D_
/* class row1, wherever it is used */_x000D_
.row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 (if you've put "class=mycell" on each cell) */_x000D_
.row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 */_x000D_
.row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows */_x000D_
.cell1 {_x000D_
}_x000D_
_x000D_
/* row1 inside class mytable (so can have different tables with different styles) */_x000D_
.mytable .row1 {_x000D_
}_x000D_
_x000D_
/* all the cells of row1 of a mytable */_x000D_
.mytable .row1 .mycell {_x000D_
}_x000D_
_x000D_
/* cell1 of row1 of a mytable */_x000D_
.mytable .row1 .cell1 {_x000D_
}_x000D_
_x000D_
/* cell1 of all rows of a mytable */_x000D_
.mytable .cell1 {_x000D_
}
_x000D_
<div class="mytable">_x000D_
  <div class="column1"></div>_x000D_
  <div class="column2"></div>_x000D_
  <div class="myrow row1">_x000D_
    <div class="mycell cell1">contents of first cell in row 1</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 1</div>_x000D_
  </div>_x000D_
  <div class="myrow row2">_x000D_
    <div class="mycell cell1">contents of first cell in row 2</div>_x000D_
    <div class="mycell cell2">contents of second cell in row 2</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In today's flexible designs, which use <div> for multiple purposes, it is wise to put some class on each div, to help refer to it. Here, what used to be <tr> in HTML became class myrow, and <td> became class mycell. This convention is what makes the above CSS selectors useful.

PERFORMANCE NOTE: putting class names on each cell, and using the above multi-class selectors, is better performance than using selectors ending with *, such as .row1 * or even .row1 > *. The reason is that selectors are matched last first, so when matching elements are being sought, .row1 * first does *, which matches all elements, and then checks all the ancestors of each element, to find if any ancestor has class row1. This might be slow in a complex document on a slow device. .row1 > * is better, because only the immediate parent is examined. But it is much better still to immediately eliminate most elements, via .row1 .cell1. (.row1 > .cell1 is an even tighter spec, but it is the first step of the search that makes the biggest difference, so it usually isn't worth the clutter, and the extra thought process as to whether it will always be a direct child, of adding the child selector >.)

The key point to take away re performance is that the last item in a selector should be as specific as possible, and should never be *.

how to get request path with express req object

It should be:

req.url

express 3.1.x

How can I do width = 100% - 100px in CSS?

my code, and it works for IE6:

<style>
#container {margin:0 auto; width:100%;}
#header { height:100px; background:#9c6; margin-bottom:5px;}
#mainContent { height:500px; margin-bottom:5px;}
#sidebar { float:left; width:100px; height:500px; background:#cf9;}
#content { margin-left:100px; height:500px; background:#ffa;}

</style>

<div id="container">
  <div id="header">header</div>
  <div id="mainContent">
    <div id="sidebar">left</div>
    <div id="content">right 100% - 100px</div>
  <span style="display:none"></span></div>
</div>

enter image description here

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Can't bind to 'routerLink' since it isn't a known property

You are missing either the inclusion of the route package, or including the router module in your main app module.

Make sure your package.json has this:

"@angular/router": "^3.3.1"

Then in your app.module import the router and configure the routes:

import { RouterModule } from '@angular/router';

imports: [
        RouterModule.forRoot([
            {path: '', component: DashboardComponent},
            {path: 'dashboard', component: DashboardComponent}
        ])
    ],

Update:

Move the AppRoutingModule to be first in the imports:

imports: [
    AppRoutingModule.
    BrowserModule,
    FormsModule,
    HttpModule,
    AlertModule.forRoot(), // What is this?
    LayoutModule,
    UsersModule
  ],

Finding duplicate integers in an array and display how many times they occurred

static void printRepeating(int []arr, int size) { int i;

    Console.Write("The repeating" +  
                   " elements are : "); 

    for (i = 0; i < size; i++) 
    { 
        if (arr[ Math.Abs(arr[i])] >= 0) 
            arr[ Math.Abs(arr[i])] = 
                -arr[ Math.Abs(arr[i])]; 
        else
            Console.Write(Math.Abs(arr[i]) + " "); 
    }          
}  

When to use SELECT ... FOR UPDATE?

Short answers:

Q1: Yes.

Q2: Doesn't matter which you use.

Long answer:

A select ... for update will (as it implies) select certain rows but also lock them as if they have already been updated by the current transaction (or as if the identity update had been performed). This allows you to update them again in the current transaction and then commit, without another transaction being able to modify these rows in any way.

Another way of looking at it, it is as if the following two statements are executed atomically:

select * from my_table where my_condition;

update my_table set my_column = my_column where my_condition;

Since the rows affected by my_condition are locked, no other transaction can modify them in any way, and hence, transaction isolation level makes no difference here.

Note also that transaction isolation level is independent of locking: setting a different isolation level doesn't allow you to get around locking and update rows in a different transaction that are locked by your transaction.

What transaction isolation levels do guarantee (at different levels) is the consistency of data while transactions are in progress.

Changing font size and direction of axes text in ggplot2

Adding to previous solutions, you can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(0.5), angle=90))

Spring: @Component versus @Bean

Difference between Bean and Component:

Difference between Bean and Component

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How Do I Take a Screen Shot of a UIView?

I have created usable extension for UIView to take screenshot in Swift:

extension UIView{

var screenshot: UIImage{

    UIGraphicsBeginImageContext(self.bounds.size);
    let context = UIGraphicsGetCurrentContext();
    self.layer.renderInContext(context)
    let screenShot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return screenShot
}
}

To use it just type:

let screenshot = view.screenshot

C# Collection was modified; enumeration operation may not execute

The error tells you EXACTLY what the problem is (and running in the debugger or reading the stack trace will tell you exactly where the problem is):

C# Collection was modified; enumeration operation may not execute.

Your problem is the loop

foreach (KeyValuePair<int, int> kvp in rankings) {
    //
}

wherein you modify the collection rankings. In particular, the offensive line is

rankings[kvp.Key] = rankings[kvp.Key] + 4;

Before you enter the loop, add the following line:

var listOfRankingsToModify = new List<int>();

Replace the offending line with

listOfRankingsToModify.Add(kvp.Key);

and after you exit the loop

foreach(var key in listOfRankingsToModify) {
    rankings[key] = rankings[key] + 4;
}

That is, record what changes you need to make, and make them without iterating over the collection that you need to modify.

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

I found my problem. The issue was that my integers were actually type numpy.int64.

Get current directory name (without full path) in a Bash script

You can use a combination of pwd and basename. E.g.

#!/bin/bash

CURRENT=`pwd`
BASENAME=`basename "$CURRENT"`

echo "$BASENAME"

exit;

How to load image files with webpack file-loader

Regarding problem #1

Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched

{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: "file-loader?name=/public/icons/[name].[ext]"
}

// For newer versions of Webpack it should be
{
    test: /\.(jpe?g|png|gif|svg)$/i, 
    loader: 'file-loader',
    options: {
      name: '/public/icons/[name].[ext]'
    }
}

and therefore you see the image emitted to

dist/public/icons/imageview_item_normal.png

which is the wanted behavior.

The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:

'file!../../public/icons/imageview_item_normal.png'.

Prefixing with file!, passes the file into the file-loader again, and this time it doesn't have the name configuration.

So your import should really just be:

import img from '../../public/icons/imageview_item_normal.png'

Update

As noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):

import '!!file!../../public/icons/imageview_item_normal.png'.

Regarding problem #2

After importing the png, the img variable only holds the path the file-loader "knows about", which is public/icons/[name].[ext] (aka "file-loader? name=/public/icons/[name].[ext]"). Your output dir "dist" is unknown. You could solve this in two ways:

  1. Run all your code under the "dist" folder
  2. Add publicPath property to your output config, that points to your output directory (in your case ./dist).

Example:

output: {
  path: PATHS.build,
  filename: 'app.bundle.js',
  publicPath: PATHS.build
},

How to declare a variable in MySQL?

  • Declare: SET @a = 1;

  • Usage: INSERT INTO `t` (`c`) VALUES (@a);

How do I debug "Error: spawn ENOENT" on node.js?

I was getting this error when trying to debug a node.js program from within VS Code editor on a Debian Linux system. I noticed the same thing worked OK on Windows. The solutions previously given here weren't much help because I hadn't written any "spawn" commands. The offending code was presumably written by Microsoft and hidden under the hood of the VS Code program.

Next I noticed that node.js is called node on Windows but on Debian (and presumably on Debian-based systems such as Ubuntu) it's called nodejs. So I created an alias - from a root terminal, I ran

ln -s /usr/bin/nodejs /usr/local/bin/node

and this solved the problem. The same or a similar procedure will presumably work in other cases where your node.js is called nodejs but you're running a program which expects it to be called node, or vice-versa.

Error 1022 - Can't write; duplicate key in table

This can also arise in connection with a bug in certain versions of Percona Toolkit's online-schema-change tool. To mutate a large table, pt-osc first creates a duplicate table and copies all the records into it. Under some circumstances, some versions of pt-osc 2.2.x will try to give the constraints on the new table the same names as the constraints on the old table.

A fix was released in 2.3.0.

See https://bugs.launchpad.net/percona-toolkit/+bug/1498128 for more details.

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Cannot stop or restart a docker container

For anyone on a Mac who has Docker Desktop installed. I was able to just click the tray icon and say Restart Docker. Once it restarted was able to delete the containers.

Get the string representation of a DOM node

I have wasted a lot of time figuring out what is wrong when I iterate through DOMElements with the code in the accepted answer. This is what worked for me, otherwise every second element disappears from the document:

_getGpxString: function(node) {
          clone = node.cloneNode(true);
          var tmp = document.createElement("div");
          tmp.appendChild(clone);
          return tmp.innerHTML;
        },

react-router go back a page how do you configure history?

One Line Answer:

window.history.back();

Get current domain

Everybody is using the parse_url function, but sometimes user may pass the argumet in different format.

So as to fix that, I have created the function. Check this out:

function fixDomainName($url='')
{
    $strToLower = strtolower(trim($url));
    $httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
    $httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
    $wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
    $explodeToArray = explode('/', $wwwPregReplace);
    $finalDomainName = trim($explodeToArray[0]);
    return $finalDomainName;
}

Just pass the URL and get the domain.

For example,

echo fixDomainName('https://stackoverflow.com');

will return the result will be

stackoverflow.com

And in some situation:

echo fixDomainName('stackoverflow.com/questions/id/slug');

And it will also return stackoverflow.com.

Python truncate a long string

info = data[:75] + ('..' if len(data) > 75 else '')

.NET NewtonSoft JSON deserialize map to a different property name

Expanding Rentering.com's answer, in scenarios where a whole graph of many types is to be taken care of, and you're looking for a strongly typed solution, this class can help, see usage (fluent) below. It operates as either a black-list or white-list per type. A type cannot be both (Gist - also contains global ignore list).

public class PropertyFilterResolver : DefaultContractResolver
{
  const string _Err = "A type can be either in the include list or the ignore list.";
  Dictionary<Type, IEnumerable<string>> _IgnorePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  Dictionary<Type, IEnumerable<string>> _IncludePropertiesMap = new Dictionary<Type, IEnumerable<string>>();
  public PropertyFilterResolver SetIgnoredProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null) return this;

    if (_IncludePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IgnorePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  public PropertyFilterResolver SetIncludedProperties<T>(params Expression<Func<T, object>>[] propertyAccessors)
  {
    if (propertyAccessors == null)
      return this;

    if (_IgnorePropertiesMap.ContainsKey(typeof(T))) throw new ArgumentException(_Err);

    var properties = propertyAccessors.Select(GetPropertyName);
    _IncludePropertiesMap[typeof(T)] = properties.ToArray();
    return this;
  }

  protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
  {
    var properties = base.CreateProperties(type, memberSerialization);

    var isIgnoreList = _IgnorePropertiesMap.TryGetValue(type, out IEnumerable<string> map);
    if (!isIgnoreList && !_IncludePropertiesMap.TryGetValue(type, out map))
      return properties;

    Func<JsonProperty, bool> predicate = jp => map.Contains(jp.PropertyName) == !isIgnoreList;
    return properties.Where(predicate).ToArray();
  }

  string GetPropertyName<TSource, TProperty>(
  Expression<Func<TSource, TProperty>> propertyLambda)
  {
    if (!(propertyLambda.Body is MemberExpression member))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");

    if (!(member.Member is PropertyInfo propInfo))
      throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");

    var type = typeof(TSource);
    if (!type.GetTypeInfo().IsAssignableFrom(propInfo.DeclaringType.GetTypeInfo()))
      throw new ArgumentException($"Expresion '{propertyLambda}' refers to a property that is not from type '{type}'.");

    return propInfo.Name;
  }
}

Usage:

var resolver = new PropertyFilterResolver()
  .SetIncludedProperties<User>(
    u => u.Id, 
    u => u.UnitId)
  .SetIgnoredProperties<Person>(
    r => r.Responders)
  .SetIncludedProperties<Blog>(
    b => b.Id)
  .Ignore(nameof(IChangeTracking.IsChanged)); //see gist

how to use Spring Boot profiles

mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar

**Source- **https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html

Basically it is need when you multiple application-{environment}.properties is present inside in your project. by default, if you passed -Drun.profiles on command line or activeByDefault true in

 <profile>
    <id>dev</id>
    <properties>
        <activatedProperties>dev</activatedProperties>
    </properties>
    <activation>
        <activeByDefault>true</activeByDefault>
    </activation>
</profile>

Nothing defined like above it will choose by default application.properties otherwise you need to select by appending -Drun.profiles={dev/stage/prod}.

TL;DR

mvn spring-boot:run -Drun.profiles=dev

How do I write a Windows batch script to copy the newest file from a directory?

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

Array as session variable

Yes, you can put arrays in sessions, example:

$_SESSION['name_here'] = $your_array;

Now you can use the $_SESSION['name_here'] on any page you want but make sure that you put the session_start() line before using any session functions, so you code should look something like this:

 session_start();
 $_SESSION['name_here'] = $your_array;

Possible Example:

 session_start();
 $_SESSION['name_here'] = $_POST;

Now you can get field values on any page like this:

 echo $_SESSION['name_here']['field_name'];

As for the second part of your question, the session variables remain there unless you assign different array data:

 $_SESSION['name_here'] = $your_array;

Session life time is set into php.ini file.

More Info Here

HTML Input - already filled in text

All you have to do is use the value attribute of input tags:

<input type="text" value="Your Value" />

Or, in the case of a textarea:

<textarea>Your Value</textarea>

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

How to convert String object to Boolean Object?

boolean b = string.equalsIgnoreCase("true");

Having a UITextField in a UITableViewCell

Here's a drop-in subclass for UITableViewCell which replaces the detailTextLabel with an editable UITextField (or, in case of UITableViewCellStyleDefault, replaces the textLabel). This has the benefit that it allows you to re-use all the familiar UITableViewCellStyles, accessoryViews, etc, just now the detail is editable!

@interface GSBEditableTableViewCell : UITableViewCell <UITextFieldDelegate>
@property UITextField *textField;
@end

@interface GSBEditableTableViewCell ()
@property UILabel *replace;
@end

@implementation GSBEditableTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _replace = (style == UITableViewCellStyleDefault)? self.textLabel : self.detailTextLabel;
        _replace.hidden = YES;

        // Impersonate UILabel with an identical UITextField
        _textField = UITextField.new;
        [self.contentView addSubview:_textField];
        _textField.translatesAutoresizingMaskIntoConstraints = NO;
        [_textField.leftAnchor constraintEqualToAnchor:_replace.leftAnchor].active = YES;
        [_textField.rightAnchor constraintEqualToAnchor:_replace.rightAnchor].active = YES;
        [_textField.topAnchor constraintEqualToAnchor:_replace.topAnchor].active = YES;
        [_textField.bottomAnchor constraintEqualToAnchor:_replace.bottomAnchor].active = YES;
        _textField.font = _replace.font;
        _textField.textColor = _replace.textColor;
        _textField.textAlignment = _replace.textAlignment;

        // Dont want to intercept UITextFieldDelegate, so use UITextFieldTextDidChangeNotification instead
        [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(textDidChange:)
                                               name:UITextFieldTextDidChangeNotification
                                             object:_textField];

        // Also need KVO because UITextFieldTextDidChangeNotification not fired when change programmatically
        [_textField addObserver:self forKeyPath:@"text" options:0 context:nil];
    }
    return self;
}

- (void)textDidChange:(NSNotification*)notification
{
    // Update (hidden) UILabel to ensure correct layout
    if (_textField.text.length) {
        _replace.text = _textField.text;
    } else if (_textField.placeholder.length) {
        _replace.text = _textField.placeholder;
    } else {
        _replace.text = @" "; // otherwise UILabel removed from cell (!?)
    }
    [self setNeedsLayout];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ((object == _textField) && [keyPath isEqualToString:@"text"]) [self textDidChange:nil];
}

- (void)dealloc
{
    [_textField removeObserver:self forKeyPath:@"text"];
}

@end

Simple to use - just create your cell as before, but now use cell.textField instead of cell.detailTextLabel (or cell.textLabel in case of UITableViewCellStyleDefault). eg

GSBEditableTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (!cell) cell = [GSBEditableTableViewCell.alloc initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:@"Cell"];

cell.textLabel.text = @"Name";
cell.textField.text = _editablename;
cell.textField.delegate = self; // to pickup edits
...

Inspired by, and improved upon, FD's answer

How can I update a single row in a ListView?

This question has been asked at the Google I/O 2010, you can watch it here:

The world of ListView, time 52:30

Basically what Romain Guy explains is to call getChildAt(int) on the ListView to get the view and (I think) call getFirstVisiblePosition() to find out the correlation between position and index.

Romain also points to the project called Shelves as an example, I think he might mean the method ShelvesActivity.updateBookCovers(), but I can't find the call of getFirstVisiblePosition().

AWESOME UPDATES COMING:

The RecyclerView will fix this in the near future. As pointed out on http://www.grokkingandroid.com/first-glance-androids-recyclerview/, you will be able to call methods to exactly specify the change, such as:

void notifyItemInserted(int position)
void notifyItemRemoved(int position)
void notifyItemChanged(int position)

Also, everyone will want to use the new views based on RecyclerView because they will be rewarded with nicely-looking animations! The future looks awesome! :-)

When to choose mouseover() and hover() function?

From the official jQuery documentation

  • .mouseover()
    Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element.

  • .hover() Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);


  • .mouseenter()

    Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element.

    mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element.


What this means

Because of this, .mouseover() is not the same as .hover(), for the same reason .mouseover() is not the same as .mouseenter().

$('selector').mouseover(over_function) // may fire multiple times

// enter and exit functions only called once per element per entry and exit
$('selector').hover(enter_function, exit_function) 

Property '...' has no initializer and is not definitely assigned in the constructor

Go to your tsconfig.json file and change "noImplicitReturns": false then add "strictPropertyInitialization": false to your tsconfig.json file under "compilerOptions" property. Here is what my tsconfig.json file looks like

tsconfig.json

{
  ...
  "compilerOptions": {
        ....
        "noImplicitReturns": false,
        ....
        "strictPropertyInitialization": false
  },
  "angularCompilerOptions": {
     ......
  }  
}

Hope this will help !! Good Luck

How to Resize image in Swift?

For Swift 4.0 and iOS 10

    extension UIImage {
        func resizeImage(_ dimension: CGFloat, opaque: Bool, contentMode: UIViewContentMode = .scaleAspectFit) -> UIImage {
            var width: CGFloat
            var height: CGFloat
            var newImage: UIImage

            let size = self.size
            let aspectRatio =  size.width/size.height

            switch contentMode {
                case .scaleAspectFit:
                    if aspectRatio > 1 {                            // Landscape image
                        width = dimension
                        height = dimension / aspectRatio
                    } else {                                        // Portrait image
                        height = dimension
                        width = dimension * aspectRatio
                    }

            default:
                fatalError("UIIMage.resizeToFit(): FATAL: Unimplemented ContentMode")
            }

            if #available(iOS 10.0, *) {
                let renderFormat = UIGraphicsImageRendererFormat.default()
                renderFormat.opaque = opaque
                let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
                newImage = renderer.image {
                    (context) in
                    self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
                }
            } else {
                UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
                    self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
                    newImage = UIGraphicsGetImageFromCurrentImageContext()!
                UIGraphicsEndImageContext()
            }

            return newImage
        }
    }

Maven and adding JARs to system scope

Thanks to Ging3r i got solution:

follow these steps:

  1. don't use in dependency tag. Use following in dependencies tag in pom.xml file::

    <dependency>
    <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
    <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
    <version>1.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
        <artifactId>suitetalk-client-v2019_1</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>com.netsuite.suitetalk.client.common</groupId>
        <artifactId>suitetalk-client-common</artifactId>
        <version>1.0.0</version>
    </dependency>
    
  2. use following code in plugins tag in pom.xml file:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <version>2.5.2</version>
            <executions>
                <execution>
                    <id>suitetalk-proxy</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-axis-proxy-v2019_1-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
                        <artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-v2019_1-2.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
                        <artifactId>suitetalk-client-v2019_1</artifactId>
                        <version>2.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
                <execution>
                    <id>suitetalk-client-common</id>
                    <phase>clean</phase>
                    <configuration>
                        <file>${basedir}/lib/suitetalk-client-common-1.0.0.jar</file>
                        <repositoryLayout>default</repositoryLayout>
                        <groupId>com.netsuite.suitetalk.client.common</groupId>
                        <artifactId>suitetalk-client-common</artifactId>
                        <version>1.0.0</version>
                        <packaging>jar</packaging>
                        <generatePom>true</generatePom>
                    </configuration>
                    <goals>
                        <goal>install-file</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    

I am including 3 jars from lib folder:

including external jar in spring boot project

Finally, use mvn clean and then mvn install or 'mvn clean install' and just run jar file from target folder or the path where install(see mvn install log):

java -jar abc.jar

note: Remember one thing if you are working at jenkins then first use mvn clean and then mvn clean install command work for you because with previous code mvn clean install command store cache for dependency.

Post Build exited with code 1

As a matter of good practice I suggest you replace the post build event with a MS Build File Copy task.

HTML <sup /> tag affecting line height, how to make it consistent?

&sup1, &sup2 etc. might do the trick. it's an HTML trick to superscript

Sum one number to every element in a list (or array) in Python

try this. (I modified the example on the purpose of making it non trivial)

import operator
import numpy as np

n=10
a = list(range(n))
a1 = [1]*len(a)
an = np.array(a)

operator.add is almost more than two times faster

%timeit map(operator.add, a, a1)

than adding with numpy

%timeit an+1

Amazon S3 upload file and get URL

@hussachai and @Jeffrey Kemp answers are pretty good. But they have something in common is the url returned is of virtual-host-style, not in path style. For more info regarding to the s3 url style, can refer to AWS S3 URL Styles. In case of some people want to have path style s3 url generated. Here's the step. Basically everything will be the same as @hussachai and @Jeffrey Kemp answers, only with one line setting change as below:

AmazonS3Client s3Client = (AmazonS3Client) AmazonS3ClientBuilder.standard()
                    .withRegion("us-west-2")
                    .withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
                    .withPathStyleAccessEnabled(true)
                    .build();

// Upload a file as a new object with ContentType and title specified.
PutObjectRequest request = new PutObjectRequest(bucketName, stringObjKeyName, fileToUpload);
s3Client.putObject(request);
URL s3Url = s3Client.getUrl(bucketName, stringObjKeyName);
logger.info("S3 url is " + s3Url.toExternalForm());

This will generate url like: https://s3.us-west-2.amazonaws.com/mybucket/myfilename

How to refresh Gridview after pressed a button in asp.net

I was totally lost on why my Gridview.Databind() would not refresh.

My issue, I discovered, was my gridview was inside a UpdatePanel. To get my GridView to FINALLY refresh was this:

gvServerConfiguration.Databind()
uppServerConfiguration.Update()

uppServerConfiguration is the id associated with my UpdatePanel in my asp.net code.

Hope this helps someone.