Programs & Examples On #Bicubic

Bicubic interpolation is an extension of cubic interpolation for interpolating data points on a two dimensional regular grid. The interpolated surface is smoother than corresponding surfaces obtained by bilinear interpolation or nearest-neighbor interpolation. Bicubic interpolation can be accomplished using either Lagrange polynomials, cubic splines, or cubic convolution algorithm.

Playing m3u8 Files with HTML Video Tag

Adding to ben.bourdin answer, you can at least in any HTML based application, check if the browser supports HLS in its video element:

Let´s assume that your video element ID is "myVideo", then through javascript you can use the "canPlayType" function (http://www.w3schools.com/tags/av_met_canplaytype.asp)

var videoElement = document.getElementById("myVideo");
if(videoElement.canPlayType('application/vnd.apple.mpegurl') === "probably" || videoElement.canPlayType('application/vnd.apple.mpegurl') === "maybe"){
    //Actions like playing the .m3u8 content
}
else{
    //Actions like playing another video type
}

The canPlayType function, returns:

"" when there is no support for the specified audio/video type

"maybe" when the browser might support the specified audio/video type

"probably" when it most likely supports the specified audio/video type (you can use just this value in the validation to be more sure that your browser supports the specified type)

Hope this help :)

Best regards!

Resize image with javascript canvas (smoothly)

I don't understand why nobody is suggesting createImageBitmap.

createImageBitmap(
    document.getElementById('image'), 
    { resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap => 
    document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);

works beautifully (assuming you set ids for image and canvas).

A Generic error occurred in GDI+ in Bitmap.Save method

    // Once finished with the bitmap objects, we deallocate them.
    originalBMP.Dispose();

    bannerBMP.Dispose();
    oGraphics.Dispose();

This is a programming style that you'll regret sooner or later. Sooner is knocking on the door, you forgot one. You are not disposing newBitmap. Which keeps a lock on the file until the garbage collector runs. If it doesn't run then the second time you try to save to the same file you'll get the klaboom. GDI+ exceptions are too miserable to give a good diagnostic so serious head-scratching ensues. Beyond the thousands of googlable posts that mention this mistake.

Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.

using (var newBitmap = new Bitmap(thumbBMP)) {
    newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
}

Albeit that it is very unclear why you even create a new bitmap, saving thumbBMP should already be good enough. Anyhoo, give the rest of your disposable objects the same using love.

Image scaling causes poor quality in firefox/internet explorer but not chrome

One way to "normalize" the appearance in the different browsers is using your "server-side" to resize the image. An example using a C# controller:

public ActionResult ResizeImage(string imageUrl, int width)
{
    WebImage wImage = new WebImage(imageUrl);
    wImage = WebImageExtension.Resize(wImage, width);
    return File(wImage.GetBytes(), "image/png");
}

where WebImage is a class in System.Web.Helpers.

WebImageExtension is defined below:

using System.IO;
using System.Web.Helpers;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Collections.Generic;

public static class WebImageExtension
{
    private static readonly IDictionary<string, ImageFormat> TransparencyFormats =
        new Dictionary<string, ImageFormat>(StringComparer.OrdinalIgnoreCase) { { "png", ImageFormat.Png }, { "gif", ImageFormat.Gif } };

    public static WebImage Resize(this WebImage image, int width)
    {
        double aspectRatio = (double)image.Width / image.Height;
        var height = Convert.ToInt32(width / aspectRatio);

        ImageFormat format;

        if (!TransparencyFormats.TryGetValue(image.ImageFormat.ToLower(), out format))
        {
            return image.Resize(width, height);
        }

        using (Image resizedImage = new Bitmap(width, height))
        {
            using (var source = new Bitmap(new MemoryStream(image.GetBytes())))
            {
                using (Graphics g = Graphics.FromImage(resizedImage))
                {
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.DrawImage(source, 0, 0, width, height);
                }
            }

            using (var ms = new MemoryStream())
            {
                resizedImage.Save(ms, format);
                return new WebImage(ms.ToArray());
            }
        }
    }
}

note the option InterpolationMode.HighQualityBicubic. This is the method used by Chrome.

Now you need publish in a web page. Lets going use razor:

<img src="@Url.Action("ResizeImage", "Controller", new { urlImage = "<url_image>", width = 35 })" />

And this worked very fine to me!

Ideally will be better to save the image beforehand in diferent widths, using this resize algorithm, to avoid the controller process in every image load.

(Sorry for my poor english, I'm brazilian...)

Resizing an image in an HTML5 canvas

The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

This function downsample to half at a time until reaching the desired size:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )
           return;

        tmp.src = dst.src;
     }

  }
  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

Credits to this post

c# Image resizing to different size while preserving aspect ratio

Maintain aspect Ration and eliminate letterbox and Pillarbox.

static Image FixedSize(Image imgPhoto, int Width, int Height)
    {
        int sourceWidth = imgPhoto.Width;
        int sourceHeight = imgPhoto.Height;
        int X = 0;
        int Y = 0;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
        }
        else
        {
            nPercent = nPercentW;
        }

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                         imgPhoto.VerticalResolution);

        Graphics grPhoto = Graphics.FromImage(bmPhoto);

        grPhoto.DrawImage(imgPhoto,
                new Rectangle(X, Y, destWidth, destHeight),
                new Rectangle(X, Y, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

        grPhoto.Dispose();
        return bmPhoto;
    }

How do I improve ASP.NET MVC application performance?

I did all the answers above and it just didn't solve my problem.

Finally, I solved my slow site loading problem with setting PrecompileBeforePublish in Publish Profile to true. If you want to use msbuild you can use this argument:

 /p:PrecompileBeforePublish=true

It really help a lot. Now my MVC ASP.NET loads 10 times faster.

IIS Manager in Windows 10

after turning IIS on (by going to Windows Features On/Off) type inetmgr in search bar or run

How do I make a Windows batch script completely silent?

To suppress output, use redirection to NUL.

There are two kinds of output that console commands use:

  • standard output, or stdout,

  • standard error, or stderr.

Of the two, stdout is used more often, both by internal commands, like copy, and by console utilities, or external commands, like find and others, as well as by third-party console programs.

>NUL suppresses the standard output and works fine e.g. for suppressing the 1 file(s) copied. message of the copy command. An alternative syntax is 1>NUL. So,

COPY file1 file2 >NUL

or

COPY file1 file2 1>NUL

or

>NUL COPY file1 file2

or

1>NUL COPY file1 file2

suppresses all of COPY's standard output.

To suppress error messages, which are typically printed to stderr, use 2>NUL instead. So, to suppress a File Not Found message that DEL prints when, well, the specified file is not found, just add 2>NUL either at the beginning or at the end of the command line:

DEL file 2>NUL

or

2>NUL DEL file

Although sometimes it may be a better idea to actually verify whether the file exists before trying to delete it, like you are doing in your own solution. Note, however, that you don't need to delete the files one by one, using a loop. You can use a single command to delete the lot:

IF EXIST "%scriptDirectory%*.noext" DEL "%scriptDirectory%*.noext"

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

'T' and 'Z' are considered here as constants. You need to pass Z without the quotes. Moreover you need to specify the timezone in the input string.

Example : 2013-09-29T18:46:19-0700 And the format as "yyyy-MM-dd'T'HH:mm:ssZ"

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

Some applications like skype uses wamp's default port:80 so you have to find out which application is accessing this port you can easily find it by using TCP View. End the service accessing this port and restart wamp server. Now it will work.

How can I pass arguments to a batch file?

Another useful tip is to use %* to mean "all". For example:

echo off
set arg1=%1
set arg2=%2
shift
shift
fake-command /u %arg1% /p %arg2% %*

When you run:

test-command admin password foo bar

the above batch file will run:

fake-command /u admin /p password admin password foo bar

I may have the syntax slightly wrong, but this is the general idea.

Download a div in a HTML page as pdf using javascript

Yes, it's possible to To capture div as PDFs in JS. You can can check the solution provided by https://grabz.it. They have nice and clean JavaScript API which will allow you to capture the content of a single HTML element such as a div or a span.

So, yo use it you will need and app+key and the free SDK. The usage of it is as following:

Let's say you have a HTML:

<div id="features">
    <h4>Acme Camera</h4>
    <label>Price</label>$399<br />
    <label>Rating</label>4.5 out of 5
</div>
<p>Cras ut velit sed purus porttitor aliquam. Nulla tristique magna ac libero tempor, ac vestibulum felisvulput ate. Nam ut velit eget
risus porttitor tristique at ac diam. Sed nisi risus, rutrum a metus suscipit, euismod tristique nulla. Etiam venenatis rutrum risus at
blandit. In hac habitasse platea dictumst. Suspendisse potenti. Phasellus eget vehicula felis.</p>

To capture what is under the features id you will need to:

//add the sdk
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
//login with your key and secret. 
GrabzIt("KEY", "SECRET").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "format": "pdf"}).Create();
</script>

You need to replace the http://www.example.com/my-page.html with your target url and #feature per your CSS selector.

That's all. Now, when the page is loaded an image screenshot will now be created in the same location as the script tag, which will contain all of the contents of the features div and nothing else.

The are other configuration and customization you can do to the div-screenshot mechanism, please check them out here

Uri not Absolute exception getting while calling Restful Webservice

Maybe the problem only in your IDE encoding settings. Try to set UTF-8 everywhere:

enter image description here

If "0" then leave the cell blank

Use this

=IFERROR((H15+G16-F16)^2/(H15+G16-F16),"")

Is there a library function for Root mean square error (RMSE) in python?

from sklearn import metrics
import bumpy as np
print(no.sqrt(metrics.mean_squared_error(actual,predicted)))

Could not find folder 'tools' inside SDK

This can also happen due to the bad unzipping process of SDK.It Happend to me. Dont use inbuilt windows unzip process. use WINRAR software for unzipping sdk

Explaining Apache ZooKeeper

My approach to understand zookeeper was, to play around with the CLI client. as described in Getting Started Guide and Command line interface

From this I learned that zookeeper's surface looks very similar to a filesystem and clients can create and delete objects and read or write data.

Example CLI commands

create /myfirstnode mydata
ls /
get /myfirstnode
delete /myfirstnode

Try yourself

How to spin up a zookeper environment within minutes on docker for windows, linux or mac:

One time set up:

docker network create dn

Run server in a terminal window:

docker run --network dn --name zook -d zookeeper
docker logs -f zookeeper

Run client in a second terminal window:

docker run -it --rm --network dn zookeeper zkCli.sh -server zook

See also documentation of image on dockerhub

Things possible in IntelliJ that aren't possible in Eclipse?

Probably is not a matter of what can/can't be done, but how.

For instance both have editor surrounded with dock panels for project, classpath, output, structure etc. But in Idea when I start to type all these collapse automatically let me focus on the code it self; In eclipse all these panels keep open leaving my editor area very reduced, about 1/5 of the total viewable area. So I have to grab the mouse and click to minimize in those panels. Doing this all day long is a very frustrating experience in eclipse.

The exact opposite thing happens with the view output window. In Idea running a program brings the output window/panel to see the output of the program even if it was perviously minimized. In eclipse I have to grab my mouse again and look for the output tab and click it to view my program output, because the output window/panel is just another one, like all the rest of the windows, but in Idea it is treated in a special way: "If the user want to run his program, is very likely he wants to see the output of that program!" It seems so natural when I write it, but eclipse fails in this basic user interface concept.

Probably there's a shortcut for this in eclipse ( autohide output window while editing and autoshow it when running the program ) , but as some other tens of features the shortcut must be hunted in forums, online help etc while in Idea is a little bit more "natural".

This can be repeated for almost all the features both have, autocomplete, word wrap, quick documentation view, everything. I think the user experience is far more pleasant in Idea than in eclipse. Then the motto comes true "Develop with pleasure"

Eclipse handles faster larger projects ( +300 jars and +4000 classes ) and I think IntelliJ Idea 8 is working on this.

All this of course is subjective. How can we measure user experience?

Android ListView selected item stay highlighted

From Avinash Kumar Pankaj's example

View v;

then at oncreate method

v = new View(getActivity());

and then onlistitemclick method i wrote

public void onListItemClick(ListView listView, View view, int position,
       long id) {
   v.setBackgroundResource(0);
   view.setBackgroundResource(R.color.green);
   v = view;
}

It worked for me. Thank you.

I replaced

v = new View(getActivity());

to

v = new View(this);

and the code worked well.

It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"

Mauro

How to set scope property with ng-init?

Like CodeHater said you are accessing the variable before it is set.

To fix this move the ng-init directive to the first div.

<body ng-app>
    <div ng-controller="testController" ng-init="testInput='value'">
        <input type="hidden" id="testInput" ng-model="testInput" />
       {{ testInput }}
    </div>
</body>

That should work!

How to enable loglevel debug on Apache2 server

You need to use LogLevel rewrite:trace3 to your httpd.conf in newer version http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

Should __init__() call the parent class's __init__()?

There's no hard and fast rule. The documentation for a class should indicate whether subclasses should call the superclass method. Sometimes you want to completely replace superclass behaviour, and at other times augment it - i.e. call your own code before and/or after a superclass call.

Update: The same basic logic applies to any method call. Constructors sometimes need special consideration (as they often set up state which determines behaviour) and destructors because they parallel constructors (e.g. in the allocation of resources, e.g. database connections). But the same might apply, say, to the render() method of a widget.

Further update: What's the OPP? Do you mean OOP? No - a subclass often needs to know something about the design of the superclass. Not the internal implementation details - but the basic contract that the superclass has with its clients (using classes). This does not violate OOP principles in any way. That's why protected is a valid concept in OOP in general (though not, of course, in Python).

iOS Detection of Screenshot?

Latest SWIFT 3:

func detectScreenShot(action: @escaping () -> ()) {
        let mainQueue = OperationQueue.main
        NotificationCenter.default.addObserver(forName: .UIApplicationUserDidTakeScreenshot, object: nil, queue: mainQueue) { notification in
            // executes after screenshot
            action()
        }
    }

In viewDidLoad, call this function

detectScreenShot { () -> () in
 print("User took a screen shot")
}

However,

NotificationCenter.default.addObserver(self, selector: #selector(test), name: .UIApplicationUserDidTakeScreenshot, object: nil)

    func test() {
    //do stuff here
    }

works totally fine. I don't see any points of mainQueue...

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

If this is an HTML file where you are using file://FileName then using a CDN like src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js" will not work.

You will have to include the .js file in your code.

CSS change button style after click

If your button would be an <a> element, you could use the :visited selector.

You are limited however, you can only change:

  • color
  • background-color
  • border-color (and its sub-properties)
  • outline-color
  • The color parts of the fill and stroke properties

I haven't read this article about revisiting the :visited but maybe some smarter people have found more ways to hack it.

How to remove docker completely from ubuntu 14.04

@miyuru. As suggested by him run all the steps.

Ubuntu version 16.04

Still when I ran docker --version it was returning a version. So to uninstall it completely

Again run the dpkg -l | grep -i docker which will list package still there in system.

For example:

ii  docker-ce-cli      5:19.03.6~3-0~ubuntu-xenial               
amd64        Docker CLI: the open-source application container engine

Now remove them as show below :

sudo apt-get purge -y docker-ce-cli

sudo apt-get autoremove -y --purge docker-ce-cli

sudo apt-get autoclean

Hope this will resolve it, as it did in my case.

Python PDF library

I already have used Reportlab in one project.

How to change the playing speed of videos in HTML5?

javascript:document.getElementsByClassName("video-stream html5-main-video")[0].playbackRate = 0.1;

you can put any number here just don't go to far so you don't overun your computer.

How do I specify "close existing connections" in sql script

According to the ALTER DATABASE SET documentation, there is still a possibility that after setting a database to SINGLE_USER mode you won't be able to access that database:

Before you set the database to SINGLE_USER, verify the AUTO_UPDATE_STATISTICS_ASYNC option is set to OFF. When set to ON, the background thread used to update statistics takes a connection against the database, and you will be unable to access the database in single-user mode.

So, a complete script to drop the database with existing connections may look like this:

DECLARE @dbId int
DECLARE @isStatAsyncOn bit
DECLARE @jobId int
DECLARE @sqlString nvarchar(500)

SELECT @dbId = database_id,
       @isStatAsyncOn = is_auto_update_stats_async_on
FROM sys.databases
WHERE name = 'db_name'

IF @isStatAsyncOn = 1
BEGIN
    ALTER DATABASE [db_name] SET  AUTO_UPDATE_STATISTICS_ASYNC OFF

    -- kill running jobs
    DECLARE jobsCursor CURSOR FOR
    SELECT job_id
    FROM sys.dm_exec_background_job_queue
    WHERE database_id = @dbId

    OPEN jobsCursor

    FETCH NEXT FROM jobsCursor INTO @jobId
    WHILE @@FETCH_STATUS = 0
    BEGIN
        set @sqlString = 'KILL STATS JOB ' + STR(@jobId)
        EXECUTE sp_executesql @sqlString
        FETCH NEXT FROM jobsCursor INTO @jobId
    END

    CLOSE jobsCursor
    DEALLOCATE jobsCursor
END

ALTER DATABASE [db_name] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE

DROP DATABASE [db_name]

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

I hope the above answer works for elastic search <7.0 but in 7.0 we cannot specify doc type and it is no longer supported. And in that case if we specify doc type we get similar error.

I you are making use of Elastic search 7.0 and Nest C# lastest version(6.6). There are some breaking changes with ES 7.0 which is causing this issue. This is because we cannot specify doc type and in the version 6.6 of NEST they are using doctype. So in order to solve that untill NEST 7.0 is released, we need to download their beta package

Please go through this link for fixing it

https://xyzcoder.github.io/elasticsearch/nest/2019/04/12/es-70-and-nest-mapping-error.html

EDIT: NEST 7.0 is now released. NEST 7.0 works with Elastic 7.0. See the release notes here for details.

How to combine two strings together in PHP?

No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :)

$string = "the color is ";
$string .= "red";

echo $string; // gives: the color is red

dispatch_after - GCD in Swift?

Another helper to delay your code that is 100% Swift in usage and optionally allows for choosing a different thread to run your delayed code from:

public func delay(bySeconds seconds: Double, dispatchLevel: DispatchLevel = .main, closure: @escaping () -> Void) {
    let dispatchTime = DispatchTime.now() + seconds
    dispatchLevel.dispatchQueue.asyncAfter(deadline: dispatchTime, execute: closure)
}

public enum DispatchLevel {
    case main, userInteractive, userInitiated, utility, background
    var dispatchQueue: DispatchQueue {
        switch self {
        case .main:                 return DispatchQueue.main
        case .userInteractive:      return DispatchQueue.global(qos: .userInteractive)
        case .userInitiated:        return DispatchQueue.global(qos: .userInitiated)
        case .utility:              return DispatchQueue.global(qos: .utility)
        case .background:           return DispatchQueue.global(qos: .background)
        }
    }
}

Now you simply delay your code on the Main thread like this:

delay(bySeconds: 1.5) { 
    // delayed code
}

If you want to delay your code to a different thread:

delay(bySeconds: 1.5, dispatchLevel: .background) { 
    // delayed code that will run on background thread
}

If you prefer a Framework that also has some more handy features then checkout HandySwift. You can add it to your project via Carthage then use it exactly like in the examples above, e.g.:

import HandySwift    

delay(bySeconds: 1.5) { 
    // delayed code
}

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */

_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }

That works great!

// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass 
{ 
  border: 1px solid brown;
}

https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

This the following line in your php.ini file

mysql.default_socket = "MySQL"

to

mysql.default_socket = /var/run/mysqld/mysqld.sock

What does {0} mean when found in a string in C#?

This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.

The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.

TypeError: not all arguments converted during string formatting python

You're mixing different format functions.

The old-style % formatting uses % codes for formatting:

'It will cost $%d dollars.' % 95

The new-style {} formatting uses {} codes and the .format method

'It will cost ${0} dollars.'.format(95)

Note that with old-style formatting, you have to specify multiple arguments using a tuple:

'%d days and %d nights' % (40, 40)

In your case, since you're using {} format specifiers, use .format:

"'{0}' is longer than '{1}'".format(name1, name2)

Sending mail attachment using Java

To send html file I have used below code in my project.

final String userID = "[email protected]";
final String userPass = "userpass";
final String emailTo = "[email protected]"

Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");

Session session = Session.getDefaultInstance(props,
        new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userID, userPass);
            }
        });
try {

    Message message = new MimeMessage(session);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailTo));
    message.setSubject("Hello, this is a test mail..");

    Multipart multipart = new MimeMultipart();
    String fileName = "fileName";

    addAttachment(multipart, fileName);

    MimeBodyPart messageBodyPart1 = new MimeBodyPart();
    messageBodyPart1.setText("No need to reply.");
    multipart.addBodyPart(messageBodyPart1);

    message.setContent(multipart);

    Transport.send(message);
    System.out.println("Email successfully sent to: " + emailTo);

} catch (MessagingException e) {
    e.printStackTrace();
}



private static void addAttachment(Multipart multipart, String fileName){
    DataSource source = null;
    File f = new File("filepath" +"/"+ fileName);
    if(f.exists() && !f.isDirectory()) {
        source = new FileDataSource("filepath" +"/"+ fileName);
        BodyPart messageBodyPart = new MimeBodyPart();
        try {
            messageBodyPart.setHeader("Content-Type", "text/html");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Regex Match all characters between two strings

For example

(?<=This is)(.*)(?=sentence)

Regexr

I used lookbehind (?<=) and look ahead (?=) so that "This is" and "sentence" is not included in the match, but this is up to your use case, you can also simply write This is(.*)sentence.

The important thing here is that you activate the "dotall" mode of your regex engine, so that the . is matching the newline. But how you do this depends on your regex engine.

The next thing is if you use .* or .*?. The first one is greedy and will match till the last "sentence" in your string, the second one is lazy and will match till the next "sentence" in your string.

Update

Regexr

This is(?s)(.*)sentence

Where the (?s) turns on the dotall modifier, making the . matching the newline characters.

Update 2:

(?<=is \()(.*?)(?=\s*\))

is matching your example "This is (a simple) sentence". See here on Regexr

How to remove the first Item from a list?

With list slicing, see the Python tutorial about lists for more details:

>>> l = [0, 1, 2, 3, 4]
>>> l[1:]
[1, 2, 3, 4]

How can I copy columns from one sheet to another with VBA in Excel?

I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1 or Sheet2. When I rename my Sheet2 to Sheet_2, I get that same problem.

In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.

Sub OneCell()
    Sheets("Sheet1").Select
    Range("A1:A3").Copy
    Sheets("Sheet2").Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

If you don't want to know about what the sheets are called, you can use integer indexes as follows:

Sub OneCell()
    Sheets(1).Select
    Range("A1:A3").Copy
    Sheets(2).Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

iPhone SDK:How do you play video inside a view? Rather than fullscreen

You cannot play a video inside a view. It has to be played fullscreen.

Get filename in batch for loop

The answer by @AKX works on the command line, but not within a batch file. Within a batch file, you need an extra %, like this:

@echo off
for /R TutorialSteps %%F in (*.py) do echo %%~nF

How can I create a carriage return in my C# string

<br /> works for me

So...

String body = String.Format(@"New user: 
 <br /> Name: {0}
 <br /> Email: {1}
 <br /> Phone: {2}", Name, Email, Phone);

Produces...

New user:
Name: Name
Email: Email
Phone: Phone

CSS position absolute full width problem

I don't know if this what you want but try to remove overflow: hidden from #wrap

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

How to delete columns in a CSV file?

import csv
with open("source","rb") as source:
    rdr= csv.reader( source )
    with open("result","wb") as result:
        wtr= csv.writer( result )
        for r in rdr:
            wtr.writerow( (r[0], r[1], r[3], r[4]) )

BTW, the for loop can be removed, but not really simplified.

        in_iter= ( (r[0], r[1], r[3], r[4]) for r in rdr )
        wtr.writerows( in_iter )

Also, you can stick in a hyper-literal way to the requirements to delete a column. I find this to be a bad policy in general because it doesn't apply to removing more than one column. When you try to remove the second, you discover that the positions have all shifted and the resulting row isn't obvious. But for one column only, this works.

            del r[2]
            wtr.writerow( r )

How do I remove a library from the arduino environment?

For others who are looking to remove a built-in library, the route is to get into PackageContents -> Java -> libraries.

BUT : IT MAKES NO SENSE TO ELIMINATE LIBRARIES inside the app, they don't take space, don't have any influence on performance, and if you don't know what you are doing, you can harm the program. I did it because Arduino told me about libraries to update, showing then a board I don't have, and when saying ok it wanted to install a lot of new dependencies - I just felt forced to something I don't want, so I deinstalled that board.

Removing elements with Array.map in JavaScript

Array Filter method

_x000D_
_x000D_
var arr = [1, 2, 3]_x000D_
_x000D_
// ES5 syntax_x000D_
arr = arr.filter(function(item){ return item != 3 })_x000D_
_x000D_
// ES2015 syntax_x000D_
arr = arr.filter(item => item != 3)_x000D_
_x000D_
console.log( arr )
_x000D_
_x000D_
_x000D_

How do I load external fonts into an HTML document?

CSS3 offers a way to do it with the @font-face rule.

http://www.w3.org/TR/css3-webfonts/#the-font-face-rule

http://www.css3.info/preview/web-fonts-with-font-face/

Here is a number of different ways which will work in browsers that don't support the @font-face rule.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Just had this problem (again!) after getting a new Lion box.

Best solution I've found (still not 100% optimal, but working):

you can get it by downloading XCode/Dev Tools from Apple - this is a big download -

... but instead I recommend this github which has what you need (and does not have XCode): https://github.com/kennethreitz/osx-gcc-installer

I downloaded their prebuilt PKG for lion, https://github.com/downloads/kennethreitz/osx-gcc-installer/GCC-10.7-v2.pkg

  • make sure you have downloaded a 64-BIT version of MYSQL Community. (The DMG install is an easy route) http://dev.mysql.com/downloads/mysql/

  • Set paths as follows:

    export PATH=$PATH:/usr/local/mysql-XXXX

    export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

    export ARCHFLAGS='-arch x86_64'

NOTE THAT:

1 in mysql-XXXX above, XXX is the specific version you downloaded. (Probably /usr/local/mysql/ would also work since this is most likely an alias to the same, but I won't pretend to know your setup)

2 I have seen it suggested that ARCHFLAGS be set to '-arch i386 -arch x86_64' but specifying only x86_64 seemed to work better for me. (I can think of some reasons for this but they are not strictly relevant).

  • Install the beast!

    easy_install MySQL-python

  • LAST STEP:

Permanently add the DYLD_LIBRARY_PATH!

You can add it to your bash_profile or similar. This was the missing step for me, without which my system continued to insist on various errors finding _mysql.so and so on.

export DYLD_LIBRARY_PATH = /usr/local/mysql/lib/

@richard-boardman, just noticed your soft link solution, which may in effect be doing the same thing my PATH solution does...folks, whatever works best for you.

Best reference: http://activeintelligence.org/blog/archive/mysql-python-aka-mysqldb-on-osx-lion/

Cannot connect to the Docker daemon on macOS

I had docker up to date, docker said it was running, and the diagnosis was good. I needed to unset some legacy environment variable (thanks https://docs.docker.com/docker-for-mac/troubleshoot/#workarounds-for-common-problems )

unset DOCKER_HOST
unset DOCKER_CERT_PATH
unset DOCKER_TLS_VERIFY

Stop a youtube video with jquery?

Actually you only need javascript and build the embed of the youtube video correctly with swfobject google library

This is an example

<script type="text/javascript" src="swfobject.js"></script>    
<div style="width: 425; height: 356px;">
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>      
  <script type="text/javascript">
    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/y5whWXxGHUA?enablejsapi=1&playerapiid=ytplayer&version=3",
    "ytapiplayer", "425", "356", "8", null, null, params, atts);
  </script>
</div> 

After that you can call this functions:

ytplayer = document.getElementById("myytplayer");
ytplayer.playVideo();
ytplayer.pauseVideo();
ytplayer.stopVideo();

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Try ro use this like libs:

https://www.npmjs.com/package/promise-chain-break

    db.getData()
.then(pb((data) => {
    if (!data.someCheck()) {
        tellSomeone();

        // All other '.then' calls will be skiped
        return pb.BREAK;
    }
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
    console.error(error);
});

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

How to convert QString to std::string?

 QString data;
   data.toStdString().c_str();

could even throw exception on VS2017 compiler in xstring

 ~basic_string() _NOEXCEPT
        {   // destroy the string
        _Tidy_deallocate();
        }

the right way ( secure - no exception) is how is explained above from Artyom

 QString qs;

    // Either this if you use UTF-8 anywhere
    std::string utf8_text = qs.toUtf8().constData();

    // or this if you're on Windows :-)
    std::string current_locale_text = qs.toLocal8Bit().constData();

How can I do a BEFORE UPDATED trigger with sql server?

Full example:

CREATE TRIGGER [dbo].[trig_020_Original_010_010_Gamechanger]
   ON  [dbo].[T_Original]
   AFTER UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @Old_Gamechanger int;
    DECLARE @New_Gamechanger int;

    -- Insert statements for trigger here
    SELECT @Old_Gamechanger = Gamechanger from DELETED;
    SELECT @New_Gamechanger = Gamechanger from INSERTED;

    IF @Old_Gamechanger != @New_Gamechanger

        BEGIN

            INSERT INTO [dbo].T_History(ChangeDate, Reason, Callcenter_ID, Old_Gamechanger, New_Gamechanger)
            SELECT GETDATE(), 'Time for a change', Callcenter_ID, @Old_Gamechanger, @New_Gamechanger
                FROM deleted
            ;

        END

END

How do I upload a file with metadata using a REST web service?

Just because you're not wrapping the entire request body in JSON, doesn't meant it's not RESTful to use multipart/form-data to post both the JSON and the file(s) in a single request:

curl -F "metadata=<metadata.json" -F "[email protected]" http://example.com/add-file

on the server side:

class AddFileResource(Resource):
    def render_POST(self, request):
        metadata = json.loads(request.args['metadata'][0])
        file_body = request.args['file'][0]
        ...

to upload multiple files, it's possible to either use separate "form fields" for each:

curl -F "metadata=<metadata.json" -F "[email protected]" -F "[email protected]" http://example.com/add-file

...in which case the server code will have request.args['file1'][0] and request.args['file2'][0]

or reuse the same one for many:

curl -F "metadata=<metadata.json" -F "[email protected]" -F "[email protected]" http://example.com/add-file

...in which case request.args['files'] will simply be a list of length 2.

or pass multiple files through a single field:

curl -F "metadata=<metadata.json" -F "[email protected],some-other-file.tar.gz" http://example.com/add-file

...in which case request.args['files'] will be a string containing all the files, which you'll have to parse yourself — not sure how to do it, but I'm sure it's not difficult, or better just use the previous approaches.

The difference between @ and < is that @ causes the file to get attached as a file upload, whereas < attaches the contents of the file as a text field.

P.S. Just because I'm using curl as a way to generate the POST requests doesn't mean the exact same HTTP requests couldn't be sent from a programming language such as Python or using any sufficiently capable tool.

How to replace a character from a String in SQL?

Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ? is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.

What does the DUMP function show is actually stored in the database?

SELECT column_name,
       dump(column_name,1016)
  FROM your_table
 WHERE <<predicate that returns just the sample data you posted>>

What application are you using to view the data? What is the client's NLS_LANG set to?

What is the database and national character set? Is the data stored in a VARCHAR2 column? Or NVARCHAR2?

SELECT parameter, value
  FROM v$nls_parameters
 WHERE parameter LIKE '%CHARACTERSET';

If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE would need to be something like

UPDATE table_name
   SET column1 = REPLACE(column1, chr(25), q'[']'),
       column2 = REPLACE(column2, chr(25), q'[']'),
       ...
       columnN = REPLACE(columnN, chr(25), q'[']')
 WHERE INSTR(column1,chr(25)) > 0
    OR INSTR(column2,chr(25)) > 0 
    ...
    OR INSTR(columnN,chr(25)) > 0

How do you overcome the svn 'out of date' error?

I just got this while I was trying to commit from a trunk directory. Doing svn update from the trunk directory did not solve the error; however, doing svn update from the parent directory (where the .svn directory belongs) did solve the error.

My guess about what happened (a use case among other, there may be multiple reasons for this “svn: E160024: resource out of date; try updating”): along to trunk, there was a branches directory. I pulled a branches/branch-1 into master from GitHub. Doing svn update from the parent directory (that is, the root of my working copy) instead of trunk seems to have done something in branches in addition to trunk. When I tried to commit again, there was no error.

However, as I said above, this is one case among probably many others.

Side note: unlike what someone suggested, I don't believe it's a good idea to play manually in the .svn directory.

g++ undefined reference to typeinfo

One possible reason is because you are declaring a virtual function without defining it.

When you declare it without defining it in the same compilation unit, you're indicating that it's defined somewhere else - this means the linker phase will try to find it in one of the other compilation units (or libraries).

An example of defining the virtual function is:

virtual void fn() { /* insert code here */ }

In this case, you are attaching a definition to the declaration, which means the linker doesn't need to resolve it later.

The line

virtual void fn();

declares fn() without defining it and will cause the error message you asked about.

It's very similar to the code:

extern int i;
int *pi = &i;

which states that the integer i is declared in another compilation unit which must be resolved at link time (otherwise pi can't be set to it's address).

Setting a log file name to include current date in Log4j

Even if u use DailyRollingFileAppender like @gedevan suggested, u will still get logname.log.2008-10-10 (After a day, because the previous day log will get archived and the date will be concatenated to it's filename). So if u want .log at the end, u'll have to do it like this on the DatePattern:

log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm'.log'

How to export and import a .sql file from command line with options?

mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;

mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql

How to change button text or link text in JavaScript?

Change .text to .textContent to get/set the text content.

Or since you're dealing with a single text node, use .firstChild.data in the same manner.

Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById.

function toggleText(button_id) 
{
   var el = document.getElementById(button_id);
   if (el.firstChild.data == "Lock") 
   {
       el.firstChild.data = "Unlock";
   }
   else 
   {
     el.firstChild.data = "Lock";
   }
}

Or even more compact like this:

function toggleText(button_id)  {
   var text = document.getElementById(button_id).firstChild;
   text.data = text.data == "Lock" ? "Unlock" : "Lock";
}

git with IntelliJ IDEA: Could not read from remote repository

  1. Go to Settings->Git->Select Native in SSH executable dropdown. (If it is not selected)
  2. Copy HTTPS link from your Github repository.
  3. Go to VCS->Git->Remotes..
  4. Edit the origin and Paste HTTPS link in the URL field.
  5. Press Ctrl+Shift+k and push the project to repository. It works.

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

What is the best project structure for a Python application?

In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses.

As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around.

With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

How to read a specific line using the specific line number from a file in Java?

They are all wrong I just wrote this in about 10 seconds. With this I managed to just call the object.getQuestion("linenumber") in the main method to return whatever line I want.

public class Questions {

File file = new File("Question2Files/triviagame1.txt");

public Questions() {

}

public String getQuestion(int numLine) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line = "";
    for(int i = 0; i < numLine; i++) {
        line = br.readLine();
    }
    return line; }}

Flask raises TemplateNotFound error even though template file exists

If you run your code from an installed package, make sure template files are present in directory <python root>/lib/site-packages/your-package/templates.


Some details:

In my case I was trying to run examples of project flask_simple_ui and jinja would always say

jinja2.exceptions.TemplateNotFound: form.html

The trick was that sample program would import installed package flask_simple_ui. And ninja being used from inside that package is using as root directory for lookup the package path, in my case ...python/lib/site-packages/flask_simple_ui, instead of os.getcwd() as one would expect.

To my bad luck, setup.py has a bug and doesn't copy any html files, including the missing form.html. Once I fixed setup.py, the problem with TemplateNotFound vanished.

I hope it helps someone.

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

How to increment an iterator by 2?

http://www.cplusplus.com/reference/std/iterator/advance/

std::advance(it,n);

where n is 2 in your case.

The beauty of this function is, that If "it" is an random access iterator, the fast

it += n

operation is used (i.e. vector<,,>::iterator). Otherwise its rendered to

for(int i = 0; i < n; i++)
    ++it;

(i.e. list<..>::iterator)

Setting selected values for ng-options bound select elements

You can use the ID field as the equality identifier. You can't use the adhoc object for this case because AngularJS checks references equality when comparing objects.

<select 
    ng-model="Choice.SelectedOption.ID" 
    ng-options="choice.ID as choice.Name for choice in Choice.Options">
</select>

How to import an existing directory into Eclipse?

For Spring Tool Suite I do:

File -> Open projects from File System

How can you use php in a javascript function

I think you're confusing server code with client code.

JavaScript runs on the client after it has received data from the server (like a webpage).

PHP runs on the server before it sends the data.

So there are two ways with interacting with JavaScript with php.

Like above, you can generate javascript with php in the same fashion you generate HTML with php.

Or you can use an AJAX request from javascript to interact with the server. The server can respond with data and the javascript can receive that and do something with it.

I'd recommend going back to the basics and studying how HTTP works in the server-client relationship. Then study the concept of server side languages and client side languages.

Then take a tutorial with ajax, and you will start getting the concept.

Good luck, google is your friend.

How to get Maven project version to the bash command line

mvn help:evaluate -Dexpression=project.version | sed -e 1h -e '2,3{H;g}' -e '/\[INFO\] BUILD SUCCESS/ q' -e '1,2d' -e '{N;D}' | sed -e '1q'

I'm just adding small sed filter improvement I have recently implemented to extract project.version from maven output.

Escape double quotes for JSON in Python

>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>> 

When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...

>>> s = """my string with "double quotes" blablabla"""
'my string with "double quotes" blablabla'
>>> print s.replace('"', '\\"')
my string with \"double quotes\" blablabla
>>> 

Given a class, see if instance has method (Ruby)

If you're checking to see if an object can respond to a series of methods, you could do something like:

methods = [:valid?, :chase, :test]

def has_methods?(something, methods)
  methods & something.methods == methods
end

the methods & something.methods will join the two arrays on their common/matching elements. something.methods includes all of the methods you're checking for, it'll equal methods. For example:

[1,2] & [1,2,3,4,5]
==> [1,2]

so

[1,2] & [1,2,3,4,5] == [1,2]
==> true

In this situation, you'd want to use symbols, because when you call .methods, it returns an array of symbols and if you used ["my", "methods"], it'd return false.

How to execute an .SQL script file using c#

I couldn't find any exact and valid way to do this. So after a whole day, I came with this mixed code achieved from different sources and trying to get the job done.

But it is still generating an exception ExecuteNonQuery: CommandText property has not been Initialized even though it successfully runs the script file - in my case, it successfully creates the database and inserts data on the first startup.

public partial class Form1 : MetroForm
{
    SqlConnection cn;
    SqlCommand cm;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        if (!CheckDatabaseExist())
        {
            GenerateDatabase();
        }
    }

    private bool CheckDatabaseExist()
    {
        SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=SalmanTradersDB;Integrated Security=true");
        try
        {
            con.Open();
            return true;
        }
        catch
        {
            return false;
        }
    }

    private void GenerateDatabase()
    {

        try
        {
            cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True");
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("drop databse {0}", "SalmanTradersDB"));
            cm = new SqlCommand(sb.ToString() , cn);
            cn.Open();
            cm.ExecuteNonQuery();
            cn.Close();
        }
        catch
        {

        }
        try
        {
            //Application.StartupPath is the location where the application is Installed
            //Here File Path Can Be Provided Via OpenFileDialog
            if (File.Exists(Application.StartupPath + "\\script.sql"))
            {
                string script = null;
                script = File.ReadAllText(Application.StartupPath + "\\script.sql");
                string[] ScriptSplitter = script.Split(new string[] { "GO" }, StringSplitOptions.None);
                using (cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True"))
                {
                    cn.Open();
                    foreach (string str in ScriptSplitter)
                    {
                        using (cm = cn.CreateCommand())
                        {
                            cm.CommandText = str;
                            cm.ExecuteNonQuery();
                        }
                    }
                }
            }
        }
        catch
        {

        }

    }

}

Table 'mysql.user' doesn't exist:ERROR

 show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| datapass_schema    |
| mysql              |
| test               |
+--------------------+
4 rows in set (0.05 sec)

mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables
    -> ;
+---------------------------+
| Tables_in_mysql           |
+---------------------------+
| columns_priv              |
| db                        |
| event                     |
| func                      |
| general_log               |
| help_category             |
| help_keyword              |
| help_relation             |
| help_topic                |
| host                      |
| ndb_binlog_index          |
| plugin                    |
| proc                      |
| procs_priv                |
| servers                   |
| slow_log                  |
| tables_priv               |
| time_zone                 |
| time_zone_leap_second     |
| time_zone_name            |
| time_zone_transition      |
| time_zone_transition_type |
| user                      |
+---------------------------+
23 rows in set (0.00 sec)

mysql> create user m identified by 'm';
Query OK, 0 rows affected (0.02 sec)

check for the database mysql and table user as shown above if that dosent work, your mysql installation is not proper.

use the below command as mention in other post to install tables again

mysql_install_db

How to determine whether a given Linux is 32 bit or 64 bit?

Try uname -m. Which is short of uname --machine and it outputs:

x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Otherwise, not for the Linux kernel, but for the CPU, you type:

cat /proc/cpuinfo

or:

grep flags /proc/cpuinfo

Under "flags" parameter, you will see various values: see "What do the flags in /proc/cpuinfo mean?" Among them, one is named lm: Long Mode (x86-64: amd64, also known as Intel 64, i.e. 64-bit capable)

lm ==> 64-bit processor

Or using lshw (as mentioned below by Rolf of Saxony), without sudo (just for grepping the cpu width):

lshw -class cpu|grep "^       width"|uniq|awk '{print $2}'

Note: you can have a 64-bit CPU with a 32-bit kernel installed.
(as ysdx mentions in his/her own answer, "Nowadays, a system can be multiarch so it does not make sense anyway. You might want to find the default target of the compiler")

Merge unequal dataframes and replace missing rows with 0

Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:

require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Your RecyclerView in Kotlin

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

Converting HTML element to string in JavaScript / JQuery

You can do this:

_x000D_
_x000D_
var $html = $('<iframe width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>');    _x000D_
var str = $html.prop('outerHTML');_x000D_
console.log(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

FIDDLE DEMO

How can I open a Shell inside a Vim Window?

If you haven't found out yet, you can use the amazing screen plugin.

Conque is also exceptional but I find screen much more practical (it wont "litter" your buffer for example and you can just send the commands that you really want after editing them in your buffer)

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

In my case solution is really silly, and strange.

Below code was pre-populated by _Layout.cshtml file. (NOT written by me)

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>

But, when I verified in Scripts folder, jquery-1.10.2.min.js was not even available. Hence, replaced code like below where jquery-1.9.1.min.js is an existing file:

<script src="~/Scripts/jquery-1.9.1.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>

How to restore SQL Server 2014 backup in SQL Server 2008

No I guess you cannot restore the databases from higher version to lower version , you can make data flow b/w them i,e you can scriptout. http://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

How to strip HTML tags with jQuery?

If you want to keep the innerHTML of the element and only strip the outermost tag, you can do this:

$(".contentToStrip").each(function(){
  $(this).replaceWith($(this).html());
});

ERROR 1049 (42000): Unknown database

blog_development doesn't exist

You can see this in sql by the 0 rows affected message

create it in mysql with

mysql> create database blog_development

However as you are using rails you should get used to using

$ rake db:create

to do the same task. It will use your database.yml file settings, which should include something like:

development:
  adapter: mysql2
  database: blog_development
  pool: 5

Also become familiar with:

$ rake db:migrate  # Run the database migration
$ rake db:seed     # Run thew seeds file create statements
$ rake db:drop     # Drop the database

Split string based on a regular expression

When you use re.split and the split pattern contains capturing groups, the groups are retained in the output. If you don't want this, use a non-capturing group instead.

Change location of log4j.properties

Yes, define log4j.configuration property

java -Dlog4j.configuration=file:/path/to/log4j.properties myApp

Note, that property value must be a URL.

For more read section 'Default Initialization Procedure' in Log4j manual.

UIButton title text color

In Swift:

Changing the label text color is quite different than changing it for a UIButton. To change the text color for a UIButton use this method:

self.headingButton.setTitleColor(UIColor(red: 107.0/255.0, green: 199.0/255.0, blue: 217.0/255.0), forState: UIControlState.Normal)

Vertically align text to top within a UILabel

For Swift 3...

@IBDesignable class TopAlignedLabel: UILabel {
    override func drawText(in rect: CGRect) {
        if let stringText = text {
            let stringTextAsNSString = stringText as NSString
            let labelStringSize = stringTextAsNSString.boundingRect(with: CGSize(width: self.frame.width,height: CGFloat.greatestFiniteMagnitude),
                                                                            options: NSStringDrawingOptions.usesLineFragmentOrigin,
                                                                            attributes: [NSFontAttributeName: font],
                                                                            context: nil).size
            super.drawText(in: CGRect(x:0,y: 0,width: self.frame.width, height:ceil(labelStringSize.height)))
        } else {
            super.drawText(in: rect)
        }
    }
    override func prepareForInterfaceBuilder() {
        super.prepareForInterfaceBuilder()
        layer.borderWidth = 1
        layer.borderColor = UIColor.black.cgColor
    }
}

How do I decode a URL parameter using C#?

Try:

var myUrl = "my.aspx?val=%2Fxyz2F";
var decodeUrl = System.Uri.UnescapeDataString(myUrl);

How to properly create an SVN tag from trunk?

svn copy http://URL/svn/trukSource http://URL/svn/tagDestination -m "Test tag code" 
  $error[0].Exception | Select-object Data

All you have to do change URL path. This command will create new dir "tagDestination". The second line will be let know you the full error details if any occur. Create svn env variable if not created. Can check (Cmd:- set, Powershell:- Get-ChildItem Env:) Default path is "C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe"

How to get a string after a specific substring?

The easiest way is probably just to split on your target word

my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1] 

split takes the word(or character) to split on and optionally a limit to the number of splits.

In this example split on "world" and limit it to only one split.

java SSL and cert keystore

you can also mention the path at runtime using -D properties as below

-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks

In my apache spark application, I used to provide the path of certs and keystore using --conf option and extraJavaoptions in spark-submit as below

--conf 'spark.driver.extraJavaOptions= 
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks' 

#pragma pack effect

I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.

What does %~d0 mean in a Windows batch file?

The magic variables %n contains the arguments used to invoke the file: %0 is the path to the bat-file itself, %1 is the first argument after, %2 is the second and so on.

Since the arguments are often file paths, there is some additional syntax to extract parts of the path. ~d is drive, ~p is the path (without drive), ~n is the file name. They can be combined so ~dp is drive+path.

%~dp0 is therefore pretty useful in a bat: it is the folder in which the executing bat file resides.

You can also get other kinds of meta info about the file: ~t is the timestamp, ~z is the size.

Look here for a reference for all command line commands. The tilde-magic codes are described under for.

How to check if an app is installed from a web-page on an iPhone?

To further the accepted answer, you sometimes need to add extra code to handle people returning the browser after launching the app- that setTimeout function will run whenever they do. So, I do something like this:

var now = new Date().valueOf();
setTimeout(function () {
    if (new Date().valueOf() - now > 100) return;
    window.location = "https://itunes.apple.com/appdir";
}, 25);
window.location = "appname://";

That way, if there has been a freeze in code execution (i.e., app switching), it won't run.

PHP convert string to hex and hex to string

PHP :

string to hex:

implode(unpack("H*", $string));

hex to string:

pack("H*", $hex);

How to link to specific line number on github

Click the line number, and then copy and paste the link from the address bar. To select a range, click the number, and then shift click the later number.

Alternatively, the links are a relatively simple format, just append #L<number> to the end for that specific line number, using the link to the file. Here's a link to the third line of the git repository's README:

https://github.com/git/git/blob/master/README#L3

Screenshot with highlighted line and the modified address line

Mail multipart/alternative vs multipart/mixed

Building on Iain's example, I had a similar need to compose these emails with separate plaintext, HTML and multiple attachments, but using PHP. Since we are using Amazon SES to send emails with attachments, the API currently requires you to build the email from scratch using the sendRawEmail(...) function.

After much investigation (and greater than normal frustration), the problem was solved and the PHP source code posted so that it may help others experiencing a similar problem. Hope this help someone out - the troop of monkeys I forced to work on this problem are now exhausted.

PHP Source Code for sending emails with attachments using Amazon SES.

<?php

require_once('AWSSDKforPHP/aws.phar');

use Aws\Ses\SesClient;

/**
 * SESUtils is a tool to make it easier to work with Amazon Simple Email Service
 * Features:
 * A client to prepare emails for use with sending attachments or not
 * 
 * There is no warranty - use this code at your own risk.  
 * @author sbossen with assistance from Michael Deal
 * http://righthandedmonkey.com
 *
 * Update: Error checking and new params input array provided by Michael Deal
 * Update2: Corrected for allowing to send multiple attachments and plain text/html body
 *   Ref: Http://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed/
 */
class SESUtils {

    const version = "1.0";
    const AWS_KEY = "YOUR-KEY";
    const AWS_SEC = "YOUR-SECRET";
    const AWS_REGION = "us-east-1";
    const MAX_ATTACHMENT_NAME_LEN = 60;

    /**
     * Usage:
        $params = array(
          "to" => "[email protected]",
          "subject" => "Some subject",
          "message" => "<strong>Some email body</strong>",
          "from" => "sender@verifiedbyaws",
          //OPTIONAL
          "replyTo" => "[email protected]",
          //OPTIONAL
          "files" => array(
            1 => array(
               "name" => "filename1", 
              "filepath" => "/path/to/file1.txt", 
              "mime" => "application/octet-stream"
            ),
            2 => array(
               "name" => "filename2", 
              "filepath" => "/path/to/file2.txt", 
              "mime" => "application/octet-stream"
            ),
          )
        );

      $res = SESUtils::sendMail($params);

     * NOTE: When sending a single file, omit the key (ie. the '1 =>') 
     * or use 0 => array(...) - otherwise the file will come out garbled
     * ie. use:
     *    "files" => array(
     *        0 => array( "name" => "filename", "filepath" => "path/to/file.txt",
     *        "mime" => "application/octet-stream")
     * 
     * For the 'to' parameter, you can send multiple recipiants with an array
     *    "to" => array("[email protected]", "[email protected]")
     * use $res->success to check if it was successful
     * use $res->message_id to check later with Amazon for further processing
     * use $res->result_text to look for error text if the task was not successful
     * 
     * @param array $params - array of parameters for the email
     * @return \ResultHelper
     */
    public static function sendMail($params) {

        $to = self::getParam($params, 'to', true);
        $subject = self::getParam($params, 'subject', true);
        $body = self::getParam($params, 'message', true);
        $from = self::getParam($params, 'from', true);
        $replyTo = self::getParam($params, 'replyTo');
        $files = self::getParam($params, 'files');

        $res = new ResultHelper();

        // get the client ready
        $client = SesClient::factory(array(
                    'key' => self::AWS_KEY,
                    'secret' => self::AWS_SEC,
                    'region' => self::AWS_REGION
        ));

        // build the message
        if (is_array($to)) {
            $to_str = rtrim(implode(',', $to), ',');
        } else {
            $to_str = $to;
        }

        $msg = "To: $to_str\n";
        $msg .= "From: $from\n";

        if ($replyTo) {
            $msg .= "Reply-To: $replyTo\n";
        }

        // in case you have funny characters in the subject
        $subject = mb_encode_mimeheader($subject, 'UTF-8');
        $msg .= "Subject: $subject\n";
        $msg .= "MIME-Version: 1.0\n";
        $msg .= "Content-Type: multipart/mixed;\n";
        $boundary = uniqid("_Part_".time(), true); //random unique string
        $boundary2 = uniqid("_Part2_".time(), true); //random unique string
        $msg .= " boundary=\"$boundary\"\n";
        $msg .= "\n";

        // now the actual body
        $msg .= "--$boundary\n";

        //since we are sending text and html emails with multiple attachments
        //we must use a combination of mixed and alternative boundaries
        //hence the use of boundary and boundary2
        $msg .= "Content-Type: multipart/alternative;\n";
        $msg .= " boundary=\"$boundary2\"\n";
        $msg .= "\n";
        $msg .= "--$boundary2\n";

        // first, the plain text
        $msg .= "Content-Type: text/plain; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= strip_tags($body); //remove any HTML tags
        $msg .= "\n";

        // now, the html text
        $msg .= "--$boundary2\n";
        $msg .= "Content-Type: text/html; charset=utf-8\n";
        $msg .= "Content-Transfer-Encoding: 7bit\n";
        $msg .= "\n";
        $msg .= $body; 
        $msg .= "\n";
        $msg .= "--$boundary2--\n";

        // add attachments
        if (is_array($files)) {
            $count = count($files);
            foreach ($files as $file) {
                $msg .= "\n";
                $msg .= "--$boundary\n";
                $msg .= "Content-Transfer-Encoding: base64\n";
                $clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
                $msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
                $msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
                $msg .= "\n";
                $msg .= base64_encode(file_get_contents($file['filepath']));
                $msg .= "\n--$boundary";
            }
            // close email
            $msg .= "--\n";
        }

        // now send the email out
        try {
            $ses_result = $client->sendRawEmail(
                    array(
                'RawMessage' => array(
                    'Data' => base64_encode($msg)
                )
                    ), array(
                'Source' => $from,
                'Destinations' => $to_str
                    )
            );
            if ($ses_result) {
                $res->message_id = $ses_result->get('MessageId');
            } else {
                $res->success = false;
                $res->result_text = "Amazon SES did not return a MessageId";
            }
        } catch (Exception $e) {
            $res->success = false;
            $res->result_text = $e->getMessage().
                    " - To: $to_str, Sender: $from, Subject: $subject";
        }
        return $res;
    }

    private static function getParam($params, $param, $required = false) {
        $value = isset($params[$param]) ? $params[$param] : null;
        if ($required && empty($value)) {
            throw new Exception('"'.$param.'" parameter is required.');
        } else {
            return $value;
        }
    }

    /**
    Clean filename function - to get a file friendly 
    **/
    public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
        if( !empty($replace) ) {
            $str = str_replace((array)$replace, ' ', $str);
        }

        $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
        $clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
        $clean = preg_replace("/[\/| -]+/", '-', $clean);

        if ($limit > 0) {
            //don't truncate file extension
            $arr = explode(".", $clean);
            $size = count($arr);
            $base = "";
            $ext = "";
            if ($size > 0) {
                for ($i = 0; $i < $size; $i++) {
                    if ($i < $size - 1) { //if it's not the last item, add to $bn
                        $base .= $arr[$i];
                        //if next one isn't last, add a dot
                        if ($i < $size - 2)
                            $base .= ".";
                    } else {
                        if ($i > 0)
                            $ext = ".";
                        $ext .= $arr[$i];
                    }
                }
            }
            $bn_size = mb_strlen($base);
            $ex_size = mb_strlen($ext);
            $bn_new = mb_substr($base, 0, $limit - $ex_size);
            // doing again in case extension is long
            $clean = mb_substr($bn_new.$ext, 0, $limit); 
        }
        return $clean;
    }

}

class ResultHelper {

    public $success = true;
    public $result_text = "";
    public $message_id = "";

}

?>

How do I determine whether an array contains a particular value in Java?

With Java 8 you can create a stream and check if any entries in the stream matches "s":

String[] values = {"AB","BC","CD","AE"};
boolean sInArray = Arrays.stream(values).anyMatch("s"::equals);

Or as a generic method:

public static <T> boolean arrayContains(T[] array, T value) {
    return Arrays.stream(array).anyMatch(value::equals);
}

How to remove the focus from a TextBox in WinForms?

You can also set the forms activecontrol property to null like

ActiveControl = null;

How to create a sub array from another array in Java?

JDK >= 1.8

I agree with all the answers above. There is also a nice way with Java 8 Streams:

int[] subArr = IntStream.range(startInclusive, endExclusive)
                        .map(i -> src[i])
                        .toArray();

The benefit about this is, it can be useful for many different types of "src" array and helps to improve writing pipeline operations on the stream.

Not particular about this question, but for example, if the source array was double[] and we wanted to take average() of the sub-array:

double avg = IntStream.range(startInclusive, endExclusive)
                    .mapToDouble(index -> src[index])
                    .average()
                    .getAsDouble();

enum - getting value of enum on string conversion

You are printing the enum object. Use the .value attribute if you wanted just to print that:

print(D.x.value)

See the Programmatic access to enumeration members and their attributes section:

If you have an enum member and need its name or value:

>>>
>>> member = Color.red
>>> member.name
'red'
>>> member.value
1

You could add a __str__ method to your enum, if all you wanted was to provide a custom string representation:

class D(Enum):
    def __str__(self):
        return str(self.value)

    x = 1
    y = 2

Demo:

>>> from enum import Enum
>>> class D(Enum):
...     def __str__(self):
...         return str(self.value)
...     x = 1
...     y = 2
... 
>>> D.x
<D.x: 1>
>>> print(D.x)
1

Django Forms: if not valid, show form with error message

@AamirAdnan's answer missing field.label; the other way to show the errors in few lines.

{% if form.errors %}
    <!-- Error messaging -->
    <div id="errors">
        <div class="inner">
            <p>There were some errors in the information you entered. Please correct the following:</p>
            <ul>
                {% for field in form %}
                    {% if field.errors %}<li>{{ field.label }}: {{ field.errors|striptags }}</li>{% endif %}
                {% endfor %}
            </ul>
        </div>
    </div>
    <!-- /Error messaging -->
{% endif %}

jQuery send HTML data through POST

As far as you're concerned once you've "pulled out" the contents with something like .html() it's just a string. You can test that with

<html> 
  <head>
    <title>runthis</title>
    <script type="text/javascript" language="javascript" src="jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready( function() {
            var x = $("#foo").html();
            alert( typeof(x) );
        });
    </script>
    </head>
    <body>
        <div id="foo"><table><tr><td>x</td></tr></table><span>xyz</span></div>
    </body>
</html>

The alert text is string. As long as you don't pass it to a parser there's no magic about it, it's a string like any other string.
There's nothing that hinders you from using .post() to send this string back to the server.

edit: Don't pass a string as the parameter data to .post() but an object, like

var data = {
  id: currid,
  html: div_html
};
$.post("http://...", data, ...);

jquery will handle the encoding of the parameters.
If you (for whatever reason) want to keep your string you have to encode the values with something like escape().

var data = 'id='+ escape(currid) +'&html='+ escape(div_html);

What should be in my .gitignore for an Android Studio project?

As of Android Studio 0.8.4 .gitignore file is generated automatically when starting new project. By default it contains:

.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
build/
/captures

I agree with this statement, however I modify this file to change /build to build/ (This will include /build and /app/build) So I don't end up with all the files in app/build in my repository.

Note also that if you import a project from Eclipse, the .gitignore won't be copied, or "automagically" created for you.

How can I enter latitude and longitude in Google Maps?

for higher precision. this format:

45 11.735N,004 34.281E

and this

45 23.623, 5 38.77

Round double in two decimal places in C#?

Math.Round(inputValue, 2, MidpointRounding.AwayFromZero)

Passing parameter to controller from route in laravel

You don't need anything special for adding paramaters. Just like you had it.

Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));


class Groups_Controller extends Base_Controller {

    public $restful = true;    

    public function get_show($groupID) {
        return 'I am group id ' . $groupID;
    }  


}

How to replace multiple substrings of a string?

This is just a more concise recap of F.J and MiniQuark great answers. All you need to achieve multiple simultaneous string replacements is the following function:

def multiple_replace(string, rep_dict):
    pattern = re.compile("|".join([re.escape(k) for k in sorted(rep_dict,key=len,reverse=True)]), flags=re.DOTALL)
    return pattern.sub(lambda x: rep_dict[x.group(0)], string)

Usage:

>>>multiple_replace("Do you like cafe? No, I prefer tea.", {'cafe':'tea', 'tea':'cafe', 'like':'prefer'})
'Do you prefer tea? No, I prefer cafe.'

If you wish, you can make your own dedicated replacement functions starting from this simpler one.

NameError: global name 'unicode' is not defined - in Python 3

One can replace unicode with u''.__class__ to handle the missing unicode class in Python 3. For both Python 2 and 3, you can use the construct

isinstance(unicode_or_str, u''.__class__)

or

type(unicode_or_str) == type(u'')

Depending on your further processing, consider the different outcome:

Python 3

>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True

Python 2

>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False

500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid

In my case I had .Net core SDK 3.1.403 was installed. So I installed the corresponding .Net Core Windows Server Hosting which is .NET core 3.1.9 - Windows Server Hosting.

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

List(of String) or Array or ArrayList

look to the List AddRange method here

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

How to reload current page in ReactJS?

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;

Java: How to get input from System.console()

It will depend on your environment. If you're running a Swing UI via javaw for example, then there isn't a console to display. If you're running within an IDE, it will very much depend on the specific IDE's handling of console IO.

From the command line, it should be fine though. Sample:

import java.io.Console;

public class Test {

    public static void main(String[] args) throws Exception {
        Console console = System.console();
        if (console == null) {
            System.out.println("Unable to fetch console");
            return;
        }
        String line = console.readLine();
        console.printf("I saw this line: %s", line);
    }
}

Run this just with java:

> javac Test.java
> java Test
Foo  <---- entered by the user
I saw this line: Foo    <---- program output

Another option is to use System.in, which you may want to wrap in a BufferedReader to read lines, or use Scanner (again wrapping System.in).

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

How to see the changes in a Git commit?

Another possibility:

git log -p COMMIT -1

Find Facebook user (url to profile page) by known email address

Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com

You can use Person Api there and get the info.

This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********

Also there is xml or json choice.

Python 3 turn range to a list

You really shouldn't need to use the numbers 1-1000 in a list. But if for some reason you really do need these numbers, then you could do:

[i for i in range(1, 1001)]

List Comprehension in a nutshell:

The above list comprehension translates to:

nums = []
for i in range(1, 1001):
    nums.append(i)

This is just the list comprehension syntax, though from 2.x. I know that this will work in python 3, but am not sure if there is an upgraded syntax as well

Range starts inclusive of the first parameter; but ends Up To, Not Including the second Parameter (when supplied 2 parameters; if the first parameter is left off, it'll start at '0')

range(start, end+1)
[start, start+1, .., end]

When to use pthread_exit() and when to use pthread_join() in Linux?

Hmm.

POSIX pthread_exit description from http://pubs.opengroup.org/onlinepubs/009604599/functions/pthread_exit.html:

After a thread has terminated, the result of access to local (auto) variables of the thread is 
undefined. Thus, references to local variables of the exiting thread should not be used for 
the pthread_exit() value_ptr parameter value.

Which seems contrary to the idea that local main() thread variables will remain accessible.

Are "while(true)" loops so bad?

I would say that generally the reason it's not considered a good idea is that you are not using the construct to it's full potential. Also, I tend to think that a lot of programming instructors don't like it when their students come in with "baggage". By that I mean I think they like to be the primary influence on their students programming style. So perhaps that's just a pet peeve of the instructor's.

Add new item in existing array in c#.net

All proposed answers do the same as what they say they'd like to avoid, creating a new array and adding a new entry in it only with lost more overhead. LINQ is not magic, list of T is an array with a buffer space with some extra space as to avoid resizing the inner array when items are added.

All the abstractions have to solve the same issue, create an array with no empty slots that hold all values and return them.

If you need the flexibility an can create a large enough list that you can use to pass then do that. else use an array and share that thread-safe object. Also, the new Span helps to share data without having to copy the lists around.

To answer the question:

Array.Resize(ref myArray, myArray.Length + 1);
data[myArray.Length - 1] = Value;

how to count length of the JSON array element

Before going to answer read this Documentation once. Then you clearly understand the answer.

Try this It may work for you.

Object.keys(data.shareInfo[i]).length

Ruby replace string with captured regex pattern

def get_code(str)
  str.sub(/^(Z_.*): .*/, '\1')
end
get_code('Z_foo: bar!') # => "Z_foo"

DNS caching in linux

You have here available an example of DNS Caching in Debian using dnsmasq.

Configuration summary:

/etc/default/dnsmasq

# Ensure you add this line
DNSMASQ_OPTS="-r /etc/resolv.dnsmasq"

/etc/resolv.dnsmasq

# Your preferred servers
nameserver 1.1.1.1
nameserver 8.8.8.8
nameserver 2001:4860:4860::8888

/etc/resolv.conf

nameserver 127.0.0.1

Then just restart dnsmasq.

Benchmark test using DNS 1.1.1.1:

for i in {1..100}; do time dig slashdot.org @1.1.1.1; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Benchmark test using you local cached DNS:

for i in {1..100}; do time dig slashdot.org; done 2>&1 | grep ^real | sed -e s/.*m// | awk '{sum += $1} END {print sum / NR}'

Conditional Binding: if let error – Initializer for conditional binding must have Optional type

for my specific problem I had to replace

if let count = 1
    {
        // do something ...
    }

With

let count = 1
if(count > 0)
    {
        // do something ...
    }

How to keep a Python script output window open?

In python 2 you can do it with: raw_input()

>>print("Hello World!")    
>>raw_input('Waiting a key...')

In python 3 you can do it with: input()

>>print("Hello world!")    
>>input('Waiting a key...')

Also, you can do it with the time.sleep(time)

>>import time
>>print("The program will close in 5 seconds")
>>time.sleep(5)

Create folder with batch but only if it doesn't already exist

i created this for my script I use in my work for eyebeam.

:CREATES A CHECK VARIABLE

set lookup=0

:CHECKS IF THE FOLDER ALREADY EXIST"

IF EXIST "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\" (set lookup=1)

:IF CHECK is still 0 which means does not exist. It creates the folder

IF %lookup%==0 START "" mkdir "%UserProfile%\AppData\Local\CounterPath\RegNow Enhanced\default_user\"

Windows batch: echo without new line

The simple SET /P method has limitations that vary slightly between Windows versions.

  • Leading quotes may be stripped

  • Leading white space may be stripped

  • Leading = causes a syntax error.

See http://www.dostips.com/forum/viewtopic.php?f=3&t=4209 for more information.

jeb posted a clever solution that solves most of the problems at Output text without linefeed, even with leading space or = I've refined the method so that it can safely print absolutely any valid batch string without the new line, on any version of Windows from XP onward. Note that the :writeInitialize method contains a string literal that may not post well to the site. A remark is included that describes what the character sequence should be.

The :write and :writeVar methods are optimized such that only strings containing troublesome leading characters are written using my modified version of jeb's COPY method. Non-troublesome strings are written using the simpler and faster SET /P method.

@echo off
setlocal disableDelayedExpansion
call :writeInitialize
call :write "=hello"
call :write " world!%$write.sub%OK!"
echo(
setlocal enableDelayedExpansion
set lf=^


set "str= hello!lf!world^!!!$write.sub!hello!lf!world"
echo(
echo str=!str!
echo(
call :write "str="
call :writeVar str
echo(
exit /b

:write  Str
::
:: Write the literal string Str to stdout without a terminating
:: carriage return or line feed. Enclosing quotes are stripped.
::
:: This routine works by calling :writeVar
::
setlocal disableDelayedExpansion
set "str=%~1"
call :writeVar str
exit /b


:writeVar  StrVar
::
:: Writes the value of variable StrVar to stdout without a terminating
:: carriage return or line feed.
::
:: The routine relies on variables defined by :writeInitialize. If the
:: variables are not yet defined, then it calls :writeInitialize to
:: temporarily define them. Performance can be improved by explicitly
:: calling :writeInitialize once before the first call to :writeVar
::
if not defined %~1 exit /b
setlocal enableDelayedExpansion
if not defined $write.sub call :writeInitialize
set $write.special=1
if "!%~1:~0,1!" equ "^!" set "$write.special="
for /f delims^=^ eol^= %%A in ("!%~1:~0,1!") do (
  if "%%A" neq "=" if "!$write.problemChars:%%A=!" equ "!$write.problemChars!" set "$write.special="
)
if not defined $write.special (
  <nul set /p "=!%~1!"
  exit /b
)
>"%$write.temp%_1.txt" (echo !str!!$write.sub!)
copy "%$write.temp%_1.txt" /a "%$write.temp%_2.txt" /b >nul
type "%$write.temp%_2.txt"
del "%$write.temp%_1.txt" "%$write.temp%_2.txt"
set "str2=!str:*%$write.sub%=%$write.sub%!"
if "!str2!" neq "!str!" <nul set /p "=!str2!"
exit /b


:writeInitialize
::
:: Defines 3 variables needed by the :write and :writeVar routines
::
::   $write.temp - specifies a base path for temporary files
::
::   $write.sub  - contains the SUB character, also known as <CTRL-Z> or 0x1A
::
::   $write.problemChars - list of characters that cause problems for SET /P
::      <carriageReturn> <formFeed> <space> <tab> <0xFF> <equal> <quote>
::      Note that <lineFeed> and <equal> also causes problems, but are handled elsewhere
::
set "$write.temp=%temp%\writeTemp%random%"
copy nul "%$write.temp%.txt" /a >nul
for /f "usebackq" %%A in ("%$write.temp%.txt") do set "$write.sub=%%A"
del "%$write.temp%.txt"
for /f %%A in ('copy /z "%~f0" nul') do for /f %%B in ('cls') do (
  set "$write.problemChars=%%A%%B    ""
  REM the characters after %%B above should be <space> <tab> <0xFF>
)
exit /b

Convert a Map<String, String> to a POJO

Yes, its definitely possible to avoid the intermediate conversion to JSON. Using a deep-copy tool like Dozer you can convert the map directly to a POJO. Here is a simplistic example:

Example POJO:

public class MyPojo implements Serializable {
    private static final long serialVersionUID = 1L;

    private String id;
    private String name;
    private Integer age;
    private Double savings;

    public MyPojo() {
        super();
    }

    // Getters/setters

    @Override
    public String toString() {
        return String.format(
                "MyPojo[id = %s, name = %s, age = %s, savings = %s]", getId(),
                getName(), getAge(), getSavings());
    }
}

Sample conversion code:

public class CopyTest {
    @Test
    public void testCopyMapToPOJO() throws Exception {
        final Map<String, String> map = new HashMap<String, String>(4);
        map.put("id", "5");
        map.put("name", "Bob");
        map.put("age", "23");
        map.put("savings", "2500.39");
        map.put("extra", "foo");

        final DozerBeanMapper mapper = new DozerBeanMapper();
        final MyPojo pojo = mapper.map(map, MyPojo.class);
        System.out.println(pojo);
    }
}

Output:

MyPojo[id = 5, name = Bob, age = 23, savings = 2500.39]

Note: If you change your source map to a Map<String, Object> then you can copy over arbitrarily deep nested properties (with Map<String, String> you only get one level).

Creating a zero-filled pandas data frame

Assuming having a template DataFrame, which one would like to copy with zero values filled here...

If you have no NaNs in your data set, multiplying by zero can be significantly faster:

In [19]: columns = ["col{}".format(i) for i in xrange(3000)]                                                                                       

In [20]: indices = xrange(2000)

In [21]: orig_df = pd.DataFrame(42.0, index=indices, columns=columns)

In [22]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
100 loops, best of 3: 12.6 ms per loop

In [23]: %timeit d = orig_df * 0.0
100 loops, best of 3: 7.17 ms per loop

Improvement depends on DataFrame size, but never found it slower.

And just for the heck of it:

In [24]: %timeit d = orig_df * 0.0 + 1.0
100 loops, best of 3: 13.6 ms per loop

In [25]: %timeit d = pd.eval('orig_df * 0.0 + 1.0')
100 loops, best of 3: 8.36 ms per loop

But:

In [24]: %timeit d = orig_df.copy()
10 loops, best of 3: 24 ms per loop

EDIT!!!

Assuming you have a frame using float64, this will be the fastest by a huge margin! It is also able to generate any value by replacing 0.0 to the desired fill number.

In [23]: %timeit d = pd.eval('orig_df > 1.7976931348623157e+308 + 0.0')
100 loops, best of 3: 3.68 ms per loop

Depending on taste, one can externally define nan, and do a general solution, irrespective of the particular float type:

In [39]: nan = np.nan
In [40]: %timeit d = pd.eval('orig_df > nan + 0.0')
100 loops, best of 3: 4.39 ms per loop

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

biggest integer that can be stored in a double

9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)

Program

#include <math.h>
#include <stdio.h>

int main(void) {
  double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
  while (dbl + 1 != dbl) dbl++;
  printf("%.0f\n", dbl - 1);
  printf("%.0f\n", dbl);
  printf("%.0f\n", dbl + 1);
  return 0;
}

Result

9007199254740991
9007199254740992
9007199254740992

How do I call a JavaScript function on page load?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>Test</title>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript">_x000D_
        function codeAddress() {_x000D_
            alert('ok');_x000D_
        }_x000D_
        window.onload = codeAddress;_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
    _x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Chrome / Safari not filling 100% height of flex parent

I had a similar bug, but while using a fixed number for height and not a percentage. It was also a flex container within the body (which has no specified height). It appeared that on Safari, my flex container had a height of 9px for some reason, but in all other browsers it displayed the correct 100px height specified in the stylesheet.

I managed to get it to work by adding both the height and min-height properties to the CSS class.

The following worked for me on both Safari 13.0.4 and Chrome 79.0.3945.130:

.flex-container {
  display: flex;
  flex-direction: column;
  min-height: 100px;
  height: 100px;
}

Hope this helps!

How to remove all white spaces from a given text file

Easiest way for me ->

        echo "Hello my name is Donald" | sed  s/\ //g

How can I change the width and height of slides on Slick Carousel?

I made this plugin. There is some css interference taking place.

It's your border on the slider itself. Either use

box-sizing: border-box 

to absorb the border width, or put the border on the content inside the slide.

How do I close an Android alertdialog

The AlertDialog.Builder itself does not contain a dismiss() or cancel() method.

It is a convenience class to help you create a Dialog, which DOES have access to those methods.

Here is an example:

AlertDialog.Builder builder = new AlertDialog.Builder(this); 

AlertDialog alert = builder.create();

alert.show();

You can then call the alert.cancel() method on the alert (not the builder).

set serveroutput on in oracle procedure

Actually, you need to call SET SERVEROUTPUT ON; before the BEGIN call.

Everyone suggested this but offers no advice where to actually place the line:

SET SERVEROUTPUT ON;

BEGIN
    FOR rec in (SELECT * FROM EMPLOYEES) LOOP
        DBMS_OUTPUT.PUT_LINE(rec.EmployeeName);
    ENDLOOP;
END;

Otherwise, you won't see any output.

Get query string parameters url values with jQuery / Javascript (querystring)

After years of ugly string parsing, there's a better way: URLSearchParams Let's have a look at how we can use this new API to get values from the location!

//Assuming URL has "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

UPDATE : IE is not supported

use this function from an answer below instead of URLSearchParams

$.urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log($.urlParam('action')); //edit

window.close and self.close do not close the window in Chrome

The below code worked for me -

window.open('location', '_self', '');
window.close();

Tested on Chrome 43.0.2357.81

Maximum number of threads in a .NET app?

You can test it by using this snipped code:

private static void Main(string[] args)
{
   int threadCount = 0;
   try
   {
      for (int i = 0; i < int.MaxValue; i ++)
      {
         new Thread(() => Thread.Sleep(Timeout.Infinite)).Start();
         threadCount ++;
      }
   }
   catch
   {
      Console.WriteLine(threadCount);
      Console.ReadKey(true);
   }
}

Beware of 32-bit and 64-bit mode of application.

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

How to pass parameters in GET requests with jQuery

Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].

You should have processData set to true.

processData: true, // You should comment this out if is false or set to true

Best way to do multi-row insert in Oracle?

Cursors may also be used, although it is inefficient. The following stackoverflow post discusses the usage of cursors :

INSERT and UPDATE a record using cursors in oracle

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

Go to Window ? Preferences ? Java ? Installed JREs.

And see if there is an entry pointing to your JDK path, and if not, click on Edit button and put the path you configured your JAVA_HOME environment.

How to select last two characters of a string

Shortest:

str.slice(-2)

Example:

_x000D_
_x000D_
const str = "test";
const last2 = str.slice(-2);

console.log(last2);
_x000D_
_x000D_
_x000D_

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

You will need to set the permissions every time you plug the converter in. I use PuTTY to connect. In order to do so, I have created a little Bash script to sort out the permissions and launch PuTTY:

#!/bin/bash
sudo chmod 666 /dev/ttyUSB0

putty

P.S. I would never recommend that permissions are set to 777.

How do you make a div follow as you scroll?

You can use the fixed CSS position property to accomplish this. There is a basic tutorial on this here.

EDIT: However, this approach is NOT supported in IE versions < IE7, and only in IE7 if it is in standards mode. This is discussed in a little more detail here.

There is also a hack, explained here, that shows how to accomplish fixed positioning in IE6 without affecting absolute positioning. What version of IE are you targeting your website for?

How to access data/data folder in Android device?

If you are using Android Studio 3.0 or later version then follow these steps.

  1. Click View > Tool Windows > Device File Explorer.
  2. Expand /data/data/[package-name] nodes.

You can only expand packages which runs in debug mode on non-rooted device.

Steps followed in Android Studio 3.0

When should iteritems() be used instead of items()?

dict.iteritems was removed because dict.items now does the thing dict.iteritems did in python 2.x and even improved it a bit by making it an itemview.

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

On Windows when you are using PowerShell you have to enclose all parameters with quotes.

So if you want to create a maven webapp archetype you would do as follows:

Prerequisites:

  1. Make sure you have maven installed and have it in your PATH environment variable.

Howto:

  1. Open windows powershell
  2. mkdir MyWebApp
  3. cd MyWebApp
  4. mvn archetype:generate "-DgroupId=com.javan.dev" "-DartifactId=MyWebApp" "-DarchetypeArtifactId=maven-archetype-webapp" "-DinteractiveMode=false"

enter image description here

Note: This is tested only on windows 10 powershell

PHP convert XML to JSON

Sorry for answering an old post, but this article outlines an approach that is relatively short, concise and easy to maintain. I tested it myself and works pretty well.

http://lostechies.com/seanbiefeld/2011/10/21/simple-xml-to-json-with-php/

<?php   
class XmlToJson {
    public function Parse ($url) {
        $fileContents= file_get_contents($url);
        $fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
        $fileContents = trim(str_replace('"', "'", $fileContents));
        $simpleXml = simplexml_load_string($fileContents);
        $json = json_encode($simpleXml);

        return $json;
    }
}
?>

How to upload a file in Django?

Not sure if there any disadvantages to this approach but even more minimal, in views.py:

entry = form.save()

# save uploaded file
if request.FILES['myfile']:
    entry.myfile.save(request.FILES['myfile']._name, request.FILES['myfile'], True)

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Radio button checked event handling

The HTML code:

<input type="radio" name="theName" value="1" id="option-1">
<input type="radio" name="theName" value="2">
<input type="radio" name="theName" value="3">

The Javascript code:

$(document).ready(function(){
    $('input[name="theName"]').change(function(){
        if($('#option-1').prop('checked')){
            alert('Option 1 is checked!');
        }else{
            alert('Option 1 is unchecked!');
        }
    });
});

In multiple radio with name "theName", detect when option 1 is checked or unchecked. Works in all situations: on click control, use the keyboard, use joystick, automatic change the values from other dinamicaly function, etc.

Converting SVG to PNG using C#

There is a much easier way using the library http://svg.codeplex.com/ (Newer version @GIT, @NuGet). Here is my code

var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
    var svgDocument = SvgDocument.Open(stream);
    var bitmap = svgDocument.Draw();
    bitmap.Save(path, ImageFormat.Png);
}

MySQL - Selecting data from multiple tables all with same structure but different data

I think you're looking for the UNION clause, a la

(SELECT * from us_music where `genre` = 'punk')
UNION
(SELECT * from de_music where `genre` = 'punk')

Using Google maps API v3 how do I get LatLng with a given address?

There is a pretty good example on https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

To shorten it up a little:

geocoder = new google.maps.Geocoder();

function codeAddress() {

    //In this case it gets the address from an element on the page, but obviously you  could just pass it to the method instead
    var address = document.getElementById( 'address' ).value;

    geocoder.geocode( { 'address' : address }, function( results, status ) {
        if( status == google.maps.GeocoderStatus.OK ) {

            //In this case it creates a marker, but you can get the lat and lng from the location.LatLng
            map.setCenter( results[0].geometry.location );
            var marker = new google.maps.Marker( {
                map     : map,
                position: results[0].geometry.location
            } );
        } else {
            alert( 'Geocode was not successful for the following reason: ' + status );
        }
    } );
}

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

When a 'blur' event occurs, how can I find out which element focus went *to*?

I do not like using timeout when coding javascript so I would do it the opposite way of Michiel Borkent. (Did not try the code behind but you should get the idea).

<input id="myInput" onblur="blured = this.id;"></input>
<span onfocus = "sortOfCallback(this.id)" id="mySpan">Hello World</span>

In the head something like that

<head>
    <script type="text/javascript">
        function sortOfCallback(id){
            bluredElement = document.getElementById(blured);
            // Do whatever you want on the blured element with the id of the focus element


        }

    </script>
</head>

Connection string with relative path to the database file

After several strange errors with relative paths in connectionstring I felt the need to post this here.

When using "|DataDirectory|" or "~" you are not allowed to step up and out using "../" !

Example is using several projects accessing the same localdb file placed in one of the projects.

" ~/../other" and " |DataDirectory|/../other" will fail

Even if it is clearly written at MSDN here the errors it gave where a bit unclear so hard to find and could not find it here at SO.

WPF - add static items to a combo box

You can also add items in code:

cboWhatever.Items.Add("SomeItem");

Also, to add something where you control display/value, (almost categorically needed in my experience) you can do so. I found a good stackoverflow reference here:

Key Value Pair Combobox in WPF

Sum-up code would be something like this:

ComboBox cboSomething = new ComboBox();
cboSomething.DisplayMemberPath = "Key";
cboSomething.SelectedValuePath = "Value";
cboSomething.Items.Add(new KeyValuePair<string, string>("Something", "WhyNot"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Deus", "Why"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Flirptidee", "Stuff"));
cboSomething.Items.Add(new KeyValuePair<string, string>("Fernum", "Blictor"));

How can I set up an editor to work with Git on Windows?

Update September 2015 (6 years later)

The last release of git-for-Windows (2.5.3) now includes:

By configuring git config core.editor notepad, users can now use notepad.exe as their default editor.
Configuring git config format.commitMessageColumns 72 will be picked up by the notepad wrapper and line-wrap the commit message after the user edits it.

See commit 69b301b by Johannes Schindelin (dscho).

And Git 2.16 (Q1 2018) will show a message to tell the user that it is waiting for the user to finish editing when spawning an editor, in case the editor opens to a hidden window or somewhere obscure and the user gets lost.

See commit abfb04d (07 Dec 2017), and commit a64f213 (29 Nov 2017) by Lars Schneider (larsxschneider).
Helped-by: Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 0c69a13, 19 Dec 2017)

launch_editor(): indicate that Git waits for user input

When a graphical GIT_EDITOR is spawned by a Git command that opens and waits for user input (e.g. "git rebase -i"), then the editor window might be obscured by other windows.
The user might be left staring at the original Git terminal window without even realizing that s/he needs to interact with another window before Git can proceed. To this user Git appears hanging.

Print a message that Git is waiting for editor input in the original terminal and get rid of it when the editor returns, if the terminal supports erasing the last line


Original answer

I just tested it with git version 1.6.2.msysgit.0.186.gf7512 and Notepad++5.3.1

I prefer to not have to set an EDITOR variable, so I tried:

git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\""
# or
git config --global core.editor "\"c:\Program Files\Notepad++\notepad++.exe\" %*"

That always gives:

C:\prog\git>git config --global --edit
"c:\Program Files\Notepad++\notepad++.exe" %*: c:\Program Files\Notepad++\notepad++.exe: command not found
error: There was a problem with the editor '"c:\Program Files\Notepad++\notepad++.exe" %*'.

If I define a npp.bat including:

"c:\Program Files\Notepad++\notepad++.exe" %*

and I type:

C:\prog\git>git config --global core.editor C:\prog\git\npp.bat

It just works from the DOS session, but not from the git shell.
(not that with the core.editor configuration mechanism, a script with "start /WAIT..." in it would not work, but only open a new DOS window)


Bennett's answer mentions the possibility to avoid adding a script, but to reference directly the program itself between simple quotes. Note the direction of the slashes! Use / NOT \ to separate folders in the path name!

git config --global core.editor \
"'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Or if you are in a 64 bit system:

git config --global core.editor \
"'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

But I prefer using a script (see below): that way I can play with different paths or different options without having to register again a git config.


The actual solution (with a script) was to realize that:
what you refer to in the config file is actually a shell (/bin/sh) script, not a DOS script.

So what does work is:

C:\prog\git>git config --global core.editor C:/prog/git/npp.bat

with C:/prog/git/npp.bat:

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"

or

#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$*"

With that setting, I can do 'git config --global --edit' from DOS or Git Shell, or I can do 'git rebase -i ...' from DOS or Git Shell.
Bot commands will trigger a new instance of notepad++ (hence the -multiInst' option), and wait for that instance to be closed before going on.

Note that I use only '/', not \'. And I installed msysgit using option 2. (Add the git\bin directory to the PATH environment variable, but without overriding some built-in windows tools)

The fact that the notepad++ wrapper is called .bat is not important.
It would be better to name it 'npp.sh' and to put it in the [git]\cmd directory though (or in any directory referenced by your PATH environment variable).


See also:


lightfire228 adds in the comments:

For anyone having an issue where N++ just opens a blank file, and git doesn't take your commit message, see "Aborting commit due to empty message": change your .bat or .sh file to say:

"<path-to-n++" .git/COMMIT_EDITMSG -<arguments>. 

That will tell notepad++ to open the temp commit file, rather than a blank new one.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

Or try adding this...

$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)

By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

How to set a string's color

setColor(). Assuming you use Graphics g in an AWT context.

Please refer to the documentation for additional information.

How can I conditionally require form inputs with AngularJS?

In AngularJS (version 1.x), there is a build-in directive ngRequired

<input type='email'
       name='email'
       ng-model='user.email' 
       placeholder='[email protected]'
       ng-required='!user.phone' />

<input type='text'
       ng-model='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       ng-required='!user.email' /> 

In Angular2 or above

<input type='email'
       name='email'
       [(ngModel)]='user.email' 
       placeholder='[email protected]'
       [required]='!user.phone' />

<input type='text'
       [(ngModel)]='user.phone'             
       placeholder='(xxx) xxx-xxxx'
       [required]='!user.email' /> 

wp-admin shows blank page, how to fix it?

i have wasted a lot of time to solve it , But the only solution i find is to rename your word press plugins folder and active theme , and your wp-admin will be visible , so then you can change and check for suspected plugin or theme.

How can I create an array/list of dictionaries in python?

weightMatrix = [{'A':0,'C':0,'G':0,'T':0} for k in range(motifWidth)]

Use Font Awesome Icons in CSS

I am bit late to the part. Just like to suggest another way.

  button.calendar::before {
    content: '\f073';
    font-family: 'Font Awesome 5 Free';
    left: -4px;
    bottom: 4px;
    position: relative;
  }

position,left and bottom is used to align icon.

Sometimes adding font-weight 600 or above also helps.

What is the difference between #include <filename> and #include "filename"?

An #include with angle brackets will search an "implementation-dependent list of places" (which is a very complicated way of saying "system headers") for the file to be included.

An #include with quotes will just search for a file (and, "in an implementation-dependent manner", bleh). Which means, in normal English, it will try to apply the path/filename that you toss at it and will not prepend a system path or tamper with it otherwise.

Also, if #include "" fails, it is re-read as #include <> by the standard.

The gcc documentation has a (compiler specific) description which although being specific to gcc and not the standard, is a lot easier to understand than the attorney-style talk of the ISO standards.

How does Facebook Sharer select Images and other metadata when sharing my URL?

Old way, no longer works:

<link rel="image_src" href="http://yoururl/yourimage"/>

Reported new way, also does not work:

<meta property="og:image" content="http://yoururl/yourimage"/>

It randomly worked off and on during the first day I implemented it, hasn't worked at all since.

The Facebook linter page, a utility that inspects your page, reports that everything is correct and does display the thumbnail I selected... just that the share.php page itself doesn't seem to be functioning. Has to be a bug over at Facebook, one they apparently don't care to fix as every bug report regarding this issue I've seen in their system all say resolved or fixed.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

In my case this worked (Mac, Excel 2011, both Cyrillic and Latin characters with Czech diacritics):

  • Charset UTF-16LE (simply UTF-16 was not enough)
  • BOM "\xFF\xFE"
  • \t (tab) as separator
  • Don't forget to encode also separator and CRLFs :-)
  • Use iconv instead of mb_convert_encoding

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

It might be that you are forgetting to specify the settings which was the case with me.

Try:

mvn clean install -s settings_file.xml

How to return a list of keys from a Hash Map?

Using map.keySet(), you can get a set of keys. Then convert this set into List by:

List<String> l = new ArrayList<String>(map.keySet());

And then use l.get(int) method to access keys.

PS:- source- Most concise way to convert a Set<String> to a List<String>

Setting focus to iframe contents

Try listening for events in the parent document and passing the event to a handler in the iframe document.

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

Update query PHP MySQL

you must write single quotes then double quotes then dot before name of field and after like that

mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

How to access a dictionary key value present inside a list?

If you know which dict in the list has the key you're looking for, then you already have the solution (as presented by Matt and Ignacio). However, if you don't know which dict has this key, then you could do this:

def getValueOf(k, L):
    for d in L:
        if k in d:
            return d[k]

How do I clear inner HTML

The problem appears to be that the global symbol clear is already in use and your function doesn't succeed in overriding it. If you change that name to something else (I used blah), it works just fine:

Live: Version using clear which fails | Version using blah which works

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 onmouseover="go('The dog is in its shed')" onmouseout="blah()">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
    function go(what) {
        document.getElementById("goy").innerHTML = what;
    }
    function blah() {
        document.getElementById("goy").innerHTML = "";
    }
    </script>
</body>
</html>

This is a great illustration of the fundamental principal: Avoid global variables wherever possible. The global namespace in browsers is incredibly crowded, and when conflicts occur, you get weird bugs like this.

A corollary to that is to not use old-style onxyz=... attributes to hook up event handlers, because they require globals. Instead, at least use code to hook things up: Live Copy

<html>
<head>
    <title>lala</title>
</head>
<body>
    <h1 id="the-header">lalala</h1>
    <div id="goy"></div>
    <script type="text/javascript">
      // Scoping function makes the declarations within
      // it *not* globals
      (function(){
        var header = document.getElementById("the-header");
        header.onmouseover = function() {
          go('The dog is in its shed');
        };
        header.onmouseout = clear;

        function go(what) {
          document.getElementById("goy").innerHTML = what;
        }
        function clear() {
          document.getElementById("goy").innerHTML = "";
        }
      })();
    </script>
</body>
</html>

...and even better, use DOM2's addEventListener (or attachEvent on IE8 and earlier) so you can have multiple handlers for an event on an element.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

Moment.js - tomorrow, today and yesterday

You can use this:


const today     = moment();

const tomorrow  = moment().add(1, 'days');

const yesterday = moment().subtract(1, 'days');

Get all table names of a particular database by SQL query?

Simply get all improtanat information with this below SQL in Mysql

    SELECT t.TABLE_NAME , t.ENGINE , t.TABLE_ROWS ,t.AVG_ROW_LENGTH, 
t.INDEX_LENGTH FROM 
INFORMATION_SCHEMA.TABLES as t where t.TABLE_SCHEMA = 'YOURTABLENAMEHERE' 
order by t.TABLE_NAME ASC limit 10000;

What to use now Google News API is deprecated?

Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431

Also, it sounds like they are building a replacement... but it's going to cost you.

I'd say, go to a different service. I think bing has a news API.

You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

What is the difference between docker-compose ports vs expose

Ports This section is used to define the mapping between the host server and Docker container.

ports:
   - 10005:80

It means the application running inside the container is exposed at port 80. But external system/entity cannot access it, so it need to be mapped to host server port.

Note: you have to open the host port 10005 and modify firewall rules to allow external entities to access the application.

They can use

http://{host IP}:10005

something like this

EXPOSE This is exclusively used to define the port on which application is running inside the docker container.

You can define it in dockerfile as well. Generally, it is good and widely used practice to define EXPOSE inside dockerfile because very rarely anyone run them on other port than default 80 port

Static class initializer in PHP

If you don't like public static initializer, reflection can be a workaround.

<?php

class LanguageUtility
{
    public static function initializeClass($class)
    {
        try
        {
            // Get a static method named 'initialize'. If not found,
            // ReflectionMethod() will throw a ReflectionException.
            $ref = new \ReflectionMethod($class, 'initialize');

            // The 'initialize' method is probably 'private'.
            // Make it accessible before calling 'invoke'.
            // Note that 'setAccessible' is not available
            // before PHP version 5.3.2.
            $ref->setAccessible(true);

            // Execute the 'initialize' method.
            $ref->invoke(null);
        }   
        catch (Exception $e)
        {
        }
    }
}

class MyClass
{
    private static function initialize()
    {
    }
}

LanguageUtility::initializeClass('MyClass');

?>

Linq where clause compare only date value without time value

There is also EntityFunctions.TruncateTime or DbFunctions.TruncateTime in EF 6.0

Make 2 functions run at the same time

Try this

from threading import Thread

def fun1():
    print("Working1")
def fun2():
    print("Working2")

t1 = Thread(target=fun1)
t2 = Thread(target=fun2)

t1.start()
t2.start()

TypeError: 'str' object cannot be interpreted as an integer

A simplest fix would be:

x = input("Give starting number: ")
y = input("Give ending number: ")

x = int(x)  # parse string into an integer
y = int(y)  # parse string into an integer

for i in range(x,y):
    print(i)

input returns you a string (raw_input in Python 2). int tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try/except statements.

JavaScript equivalent to printf/String.Format

It's funny because Stack Overflow actually has their own formatting function for the String prototype called formatUnicorn. Try it! Go into the console and type something like:

"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});

Firebug

You get this output:

Hello, Gabriel, are you feeling OK?

You can use objects, arrays, and strings as arguments! I got its code and reworked it to produce a new version of String.prototype.format:

String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
    "use strict";
    var str = this.toString();
    if (arguments.length) {
        var t = typeof arguments[0];
        var key;
        var args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];

        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }

    return str;
};

Note the clever Array.prototype.slice.call(arguments) call -- that means if you throw in arguments that are strings or numbers, not a single JSON-style object, you get C#'s String.Format behavior almost exactly.

"a{0}bcd{1}ef".formatUnicorn("FOO", "BAR"); // yields "aFOObcdBARef"

That's because Array's slice will force whatever's in arguments into an Array, whether it was originally or not, and the key will be the index (0, 1, 2...) of each array element coerced into a string (eg, "0", so "\\{0\\}" for your first regexp pattern).

Neat.

Regex to remove letters, symbols except numbers

Use /[^0-9.,]+/ if you want floats.

Gradle to execute Java class (without modifying build.gradle)

There is no direct equivalent to mvn exec:java in gradle, you need to either apply the application plugin or have a JavaExec task.

application plugin

Activate the plugin:

plugins {
    id 'application'
    ...
}

Configure it as follows:

application {
    mainClassName = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
}

On the command line, write

$ gradle -PmainClass=Boo run

JavaExec task

Define a task, let's say execute:

task execute(type:JavaExec) {
   main = project.hasProperty("mainClass") ? getProperty("mainClass") : "NULL"
   classpath = sourceSets.main.runtimeClasspath
}

To run, write gradle -PmainClass=Boo execute. You get

$ gradle -PmainClass=Boo execute
:compileJava
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes
:execute
I am BOO!

mainClass is a property passed in dynamically at command line. classpath is set to pickup the latest classes.


If you do not pass in the mainClass property, both of the approaches fail as expected.

$ gradle execute

FAILURE: Build failed with an exception.

* Where:
Build file 'xxxx/build.gradle' line: 4

* What went wrong:
A problem occurred evaluating root project 'Foo'.
> Could not find property 'mainClass' on task ':execute'.