Programs & Examples On #Applicationsettingsbase

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Extend the DOM Element, Handle the Error, and Degrade Gracefully

Below I use the prototype function to wrap the native DOM play function, grab its promise, and then degrade to a play button if the browser throws an exception. This extension addresses the shortcoming of the browser and is plug-n-play in any page with knowledge of the target element(s).

// JavaScript
// Wrap the native DOM audio element play function and handle any autoplay errors
Audio.prototype.play = (function(play) {
return function () {
  var audio = this,
      args = arguments,
      promise = play.apply(audio, args);
  if (promise !== undefined) {
    promise.catch(_ => {
      // Autoplay was prevented. This is optional, but add a button to start playing.
      var el = document.createElement("button");
      el.innerHTML = "Play";
      el.addEventListener("click", function(){play.apply(audio, args);});
      this.parentNode.insertBefore(el, this.nextSibling)
    });
  }
};
})(Audio.prototype.play);

// Try automatically playing our audio via script. This would normally trigger and error.
document.getElementById('MyAudioElement').play()

<!-- HTML -->
<audio id="MyAudioElement" autoplay>
  <source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
  <source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
  Your browser does not support the audio element.
</audio>

how to place last div into right top corner of parent div? (css)

 <div class='block1'>
    <p  style="float:left">text</p>
    <div class='block2' style="float:right">block2</div>
    <p  style="float:left; clear:left">text2</p>

 </div>

You can clear:both or clear:left depending on the exact context. Also, you will have to play around with width to get it to work correctly...

Getting today's date in YYYY-MM-DD in Python?

Very late answer, but you can simply use:

import time
today = time.strftime("%Y-%m-%d")
# 2021-02-18

How to make child element higher z-index than parent?

Try using this code, it worked for me:

z-index: unset;

nvarchar(max) still being truncated

I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.

DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.

EXEC (@Query + @Query2)

Entity Framework Provider type could not be loaded?

When I inspected the problem, I have noticed that the following dll were missing in the output folder. The simple solution is copy Entityframework.dll and Entityframework.sqlserver.dll with the app.config to the output folder if the application is on debug mode. At the same time change, the build option parameter "Copy to output folder" of app.config to copy always. This will solve your problem.

PHP array: count or sizeof?

They are identical according to sizeof()

In the absence of any reason to worry about "faster", always optimize for the human. Which makes more sense to the human reader?

Security of REST authentication schemes

Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).

Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:

XML encryption (W3C standard)

XML Security

Gem Command not found

The following command may help you

sudo apt-get install ruby

How to tell if a JavaScript function is defined

Try this:

callback instanceof Function

Stretch child div height to fill parent that has dynamic height

Add the following CSS:

For the parent div:

style="display: flex;"

For child div:

style="align-items: stretch;"

How to read a line from the console in C?

You might need to use a character by character (getc()) loop to ensure you have no buffer overflows and don't truncate the input.

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I have this simple solution I have been using and its works.

In App/Exceptions/Handler.php

Add this at top:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

Then inside the render method

public function render($request, Exception $exception)
{
    .......

       if ($exception instanceof NotFoundHttpException){

        $segment = $request->segments();

        //eg. http://site.dev/member/profile
        //module => member
        // view => member.index
        //where member.index is the root of your angular app could be anything :)
        if(head($segment) != 'api' && $module = $segment[0]){
            return response(view("$module.index"), 404);
        }

        return response()->fail('not_found', $exception->getCode());

    }
    .......

     return parent::render($request, $exception);
}

How to load property file from classpath?

If you use the static method and load the properties file from the classpath folder so you can use the below code :

//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));

How can I get the external SD card path for Android 4.0+?

refer to my code, hope helpful for you:

    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("mount");
    InputStream is = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    String line;
    String mount = new String();
    BufferedReader br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        if (line.contains("secure")) continue;
        if (line.contains("asec")) continue;

        if (line.contains("fat")) {//TF card
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat("*" + columns[1] + "\n");
            }
        } else if (line.contains("fuse")) {//internal storage
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat(columns[1] + "\n");
            }
        }
    }
    txtView.setText(mount);

How to Join to first row

I know this question was answered a while ago, but when dealing with large data sets, nested queries can be costly. Here is a different solution where the nested query will only be ran once, instead of for each row returned.

SELECT 
  Orders.OrderNumber,
  LineItems.Quantity, 
  LineItems.Description
FROM 
  Orders
  INNER JOIN (
    SELECT
      Orders.OrderNumber,
      Max(LineItem.LineItemID) AS LineItemID
    FROM
      Orders INNER JOIN LineItems
      ON Orders.OrderNumber = LineItems.OrderNumber
    GROUP BY Orders.OrderNumber
  ) AS Items ON Orders.OrderNumber = Items.OrderNumber
  INNER JOIN LineItems 
  ON Items.LineItemID = LineItems.LineItemID

Help needed with Median If in Excel

Expanding on Brian Camire's Answer:

Using =MEDIAN(IF($A$1:$A$6="Airline",$B$1:$B$6,"")) with CTRL+SHIFT+ENTER will include blank cells in the calculation. Blank cells will be evaluated as 0 which results in a lower median value. The same is true if using the average funtion. If you don't want to include blank cells in the calculation, use a nested if statement like so:

=MEDIAN(IF($A$1:$A$6="Airline",IF($B$1:$B$6<>"",$B$1:$B$6)))

Don't forget to press CTRL+SHIFT+ENTER to treat the formula as an "array formula".

Access to the requested object is only available from the local network phpmyadmin

Not need to change all config in file /opt/lampp/etc/extra/httpd-xampp.conf. The only thing you need to change is the Require local It's kinda obvious what Require local means so just change to Require all granted Require all granted

Solution

from Require local to Require all granted

What are the differences between C, C# and C++ in terms of real-world applications?

For raw speed, use C. For power, use C++. For .NET compatibility, use C#.

They're all pretty complex as languages go; C through decades of gradual accretion, C++ through years of more rapid enhancement, and C# through the power of Microsoft.

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

How can I make a "color map" plot in matlab?

Note that both pcolor and "surf + view(2)" do not show the last row and the last column of your 2D data.

On the other hand, using imagesc, you have to be careful with the axes. The surf and the imagesc examples in gevang's answer only (almost -- apart from the last row and column) correspond to each other because the 2D sinc function is symmetric.

To illustrate these 2 points, I produced the figure below with the following code:

[x, y] = meshgrid(1:10,1:5);
z      = x.^3 + y.^3;

subplot(3,1,1)
imagesc(flipud(z)), axis equal tight, colorbar
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc')

subplot(3,1,2)
surf(x,y,z,'EdgeColor','None'), view(2), axis equal tight, colorbar
title('surf with view(2)')

subplot(3,1,3)
imagesc(flipud(z)), axis equal tight, colorbar
axis([0.5 9.5 1.5 5.5])
set(gca, 'YTick', 1:5, 'YTickLabel', 5:-1:1);
title('imagesc cropped')

colormap jet

surf vs imagesc

As you can see the 10th row and 5th column are missing in the surf plot. (You can also see this in images in the other answers.)

Note how you can use the "set(gca, 'YTick'..." (and Xtick) command to set the x and y tick labels properly if x and y are not 1:1:N.

Also note that imagesc only makes sense if your z data correspond to xs and ys are (each) equally spaced. If not you can use surf (and possibly duplicate the last column and row and one more "(end,end)" value -- although that's a kind of a dirty approach).

C++ sorting and keeping track of indexes

I wrote generic version of index sort.

template <class RAIter, class Compare>
void argsort(RAIter iterBegin, RAIter iterEnd, Compare comp, 
    std::vector<size_t>& indexes) {

    std::vector< std::pair<size_t,RAIter> > pv ;
    pv.reserve(iterEnd - iterBegin) ;

    RAIter iter ;
    size_t k ;
    for (iter = iterBegin, k = 0 ; iter != iterEnd ; iter++, k++) {
        pv.push_back( std::pair<int,RAIter>(k,iter) ) ;
    }

    std::sort(pv.begin(), pv.end(), 
        [&comp](const std::pair<size_t,RAIter>& a, const std::pair<size_t,RAIter>& b) -> bool 
        { return comp(*a.second, *b.second) ; }) ;

    indexes.resize(pv.size()) ;
    std::transform(pv.begin(), pv.end(), indexes.begin(), 
        [](const std::pair<size_t,RAIter>& a) -> size_t { return a.first ; }) ;
}

Usage is the same as that of std::sort except for an index container to receive sorted indexes. testing:

int a[] = { 3, 1, 0, 4 } ;
std::vector<size_t> indexes ;
argsort(a, a + sizeof(a) / sizeof(a[0]), std::less<int>(), indexes) ;
for (size_t i : indexes) printf("%d\n", int(i)) ;

you should get 2 1 0 3. for the compilers without c++0x support, replace the lamba expression as a class template:

template <class RAIter, class Compare> 
class PairComp {
public:
  Compare comp ;
  PairComp(Compare comp_) : comp(comp_) {}
  bool operator() (const std::pair<size_t,RAIter>& a, 
    const std::pair<size_t,RAIter>& b) const { return comp(*a.second, *b.second) ; }        
} ;

and rewrite std::sort as

std::sort(pv.begin(), pv.end(), PairComp(comp)()) ;

How to create a DataFrame from a text file in Spark

I have given different ways to create DataFrame from text file

val conf = new SparkConf().setAppName(appName).setMaster("local")
val sc = SparkContext(conf)

raw text file

val file = sc.textFile("C:\\vikas\\spark\\Interview\\text.txt")
val fileToDf = file.map(_.split(",")).map{case Array(a,b,c) => 
(a,b.toInt,c)}.toDF("name","age","city")
fileToDf.foreach(println(_))

spark session without schema

import org.apache.spark.sql.SparkSession
val sparkSess = 
SparkSession.builder().appName("SparkSessionZipsExample")
.config(conf).getOrCreate()

val df = sparkSess.read.option("header", 
"false").csv("C:\\vikas\\spark\\Interview\\text.txt")
df.show()

spark session with schema

import org.apache.spark.sql.types._
val schemaString = "name age city"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, 
StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header", 
"false").schema(schema).csv("C:\\vikas\\spark\\Interview\\text.txt")
dfWithSchema.show()

using sql context

import org.apache.spark.sql.SQLContext

val fileRdd = 
sc.textFile("C:\\vikas\\spark\\Interview\\text.txt").map(_.split(",")).map{x 
=> org.apache.spark.sql.Row(x:_*)}
val sqlDf = sqlCtx.createDataFrame(fileRdd,schema)
sqlDf.show()

How to create two columns on a web page?

I agree with @haha on this one, for the most part. But there are several cross-browser related issues with using the "float:right" and could ultimately give you more of a headache than you want. If you know what the widths are going to be for each column use a float:left on both and save yourself the trouble. Another thing you can incorporate into your methodology is build column classes into your CSS.

So try something like this:

CSS

.col-wrapper{width:960px; margin:0 auto;}
.col{margin:0 10px; float:left; display:inline;}
.col-670{width:670px;}
.col-250{width:250px;}

HTML

<div class="col-wrapper">
    <div class="col col-670">[Page Content]</div>
    <div class="col col-250">[Page Sidebar]</div>
</div>

Replace "\\" with "\" in a string in C#

I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from

text2 = text1.Replace(@"\\", @"/");

to

text2 = text1.Replace(@"\", @"/");

and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.

jQuery click event not working after adding class

You should use the following:

$('#gentab').on('click', 'a.tabclick', function(event) {
    event.preventDefault();
    var liId = $(this).closest("li").attr("id");
    alert(liId);  
});

This will attach your event to any anchors within the #gentab element, reducing the scope of having to check the whole document element tree and increasing efficiency.

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

In many case It is java facet problem ,jdk or jre or jsp version is difference than maven project face.

How do I enable EF migrations for multiple contexts to separate databases?

In case you already have a "Configuration" with many migrations and want to keep this as is, you can always create a new "Configuration" class, give it another name, like

class MyNewContextConfiguration : DbMigrationsConfiguration<MyNewDbContext>
{
   ...
}

then just issue the command

Add-Migration -ConfigurationTypeName MyNewContextConfiguration InitialMigrationName

and EF will scaffold the migration without problems. Finally update your database, from now on, EF will complain if you don't tell him which configuration you want to update:

Update-Database -ConfigurationTypeName MyNewContextConfiguration 

Done.

You don't need to deal with Enable-Migrations as it will complain "Configuration" already exists, and renaming your existing Configuration class will bring issues to the migration history.

You can target different databases, or the same one, all configurations will share the __MigrationHistory table nicely.

How to programmatically modify WCF app.config endpoint address setting?

You can do it like this:

  • Keep your settings in a separate xml file and read through it when you create a proxy for your service.

For example , i want to modify my service endpoint address at runtime so i have the following ServiceEndpoint.xml file.

     <?xml version="1.0" encoding="utf-8" ?>
     <Services>
        <Service name="FileTransferService">
           <Endpoints>
              <Endpoint name="ep1" address="http://localhost:8080/FileTransferService.svc" />
           </Endpoints>
        </Service>
     </Services>
  • For reading your xml :

     var doc = new XmlDocument();
     doc.Load(FileTransferConstants.Constants.SERVICE_ENDPOINTS_XMLPATH);
     XmlNodeList endPoints = doc.SelectNodes("/Services/Service/Endpoints");  
     foreach (XmlNode endPoint in endPoints)
     {
        foreach (XmlNode child in endPoint)
        {
            if (child.Attributes["name"].Value.Equals("ep1"))
            {
                var adressAttribute = child.Attributes["address"];
                if (!ReferenceEquals(null, adressAttribute))
                {
                    address = adressAttribute.Value;
                }
           }
       }
    }  
    
  • Then get your web.config file of your client at runtime and assign the service endpoint address as:

        Configuration wConfig = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = @"C:\FileTransferWebsite\web.config" }, ConfigurationUserLevel.None);
        ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);
    
        ClientSection wClientSection = wServiceSection.Client;
        wClientSection.Endpoints[0].Address = new Uri(address);
        wConfig.Save();
    

Chrome sendrequest error: TypeError: Converting circular structure to JSON

I resolve this problem on NodeJS like this:

var util = require('util');

// Our circular object
var obj = {foo: {bar: null}, a:{a:{a:{a:{a:{a:{a:{hi: 'Yo!'}}}}}}}};
obj.foo.bar = obj;

// Generate almost valid JS object definition code (typeof string)
var str = util.inspect(b, {depth: null});

// Fix code to the valid state (in this example it is not required, but my object was huge and complex, and I needed this for my case)
str = str
    .replace(/<Buffer[ \w\.]+>/ig, '"buffer"')
    .replace(/\[Function]/ig, 'function(){}')
    .replace(/\[Circular]/ig, '"Circular"')
    .replace(/\{ \[Function: ([\w]+)]/ig, '{ $1: function $1 () {},')
    .replace(/\[Function: ([\w]+)]/ig, 'function $1(){}')
    .replace(/(\w+): ([\w :]+GMT\+[\w \(\)]+),/ig, '$1: new Date("$2"),')
    .replace(/(\S+): ,/ig, '$1: null,');

// Create function to eval stringifyed code
var foo = new Function('return ' + str + ';');

// And have fun
console.log(JSON.stringify(foo(), null, 4));

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

google chrome extension :: console.log() from background page?

The simplest solution would be to add the following code on the top of the file. And than you can use all full Chrome console api as you would normally.

 console = chrome.extension.getBackgroundPage().console;
// for instance, console.assert(1!=1) will return assertion error
// console.log("msg") ==> prints msg
// etc

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

Looks like someone finally did it, it is a tiny bit ugly - but here it is:

http://forum.xda-developers.com/showthread.php?t=1871281

It involves some kernel recompiling, and a bit of editing, and you loose partial functionality (the MDC?) .. but it's done.

Personally though, now that I see the "true cost", I would probably put together a little adapter on a Teency or something - assuming that Android can talk to serial devices via USB. But that's based on the fact that I have a samsung, and would require a special cable to make a USB connection anyway - no extra pain to have a little device on the end, if I have to carry the damn cable around anyway.

Entity Framework Core add unique constraint code-first

The OP is asking about whether it is possible to add an Attribute to an Entity class for a Unique Key. The short answer is that it IS possible, but not an out-of-the-box feature from the EF Core Team. If you'd like to use an Attribute to add Unique Keys to your Entity Framework Core entity classes, you can do what I've posted here

public class Company
{
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CompanyId { get; set; }

    [Required]
    [UniqueKey(groupId: "1", order: 0)]
    [StringLength(100, MinimumLength = 1)]
    public string CompanyName { get; set; }

    [Required]
    [UniqueKey(groupId: "1", order: 1)]
    [StringLength(100, MinimumLength = 1)]
    public string CompanyLocation { get; set; }
}

How to make an HTML back link?

The easiest way is to use history.go(-1);

Try this:

_x000D_
_x000D_
<a href="#" onclick="history.go(-1)">Go Back</a>
_x000D_
_x000D_
_x000D_

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I was getting this error message due to my EC2 instance's clock being out of sync.

I was able to fix on Ubuntu using this:

sudo ntpdate ntp.ubuntu.com
sudo apt-get install ntp

The character encoding of the plain text document was not declared - mootool script

I got this error using Spring Boot (in Mozilla),

because I was just testing some basic controller -> service -> repository communication by directly returning some entities from the database to the browser (as JSON).

I forgot to put data in the database, so my method wasn't returning anything... and I got this error.

Now that I put some data in my db, it works fine (the error is removed). :D

Finding the median of an unsorted array

The answer is "No, one can't find the median of an arbitrary, unsorted dataset in linear time". The best one can do as a general rule (as far as I know) is Median of Medians (to get a decent start), followed by Quickselect. Ref: [https://en.wikipedia.org/wiki/Median_of_medians][1]

What is the difference between signed and unsigned variables?

This may not be the exact definition but I'll give you an example: If you were to create a random number taking it from the system time, here using the unsigned variable is beneficial as there is large scope for random numbers as signed numbers give both positive and negative numbers. As the system time can't be negative we use unsigned variable(Only positive numbers) and we have more wide range of random numbers.

diff current working copy of a file with another branch's committed copy

The following works for me:

git diff master:foo foo

In the past, it may have been:

git diff foo master:foo

What should my Objective-C singleton look like?

Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. This is taken from another question that I asked:

static Server *instance;

+ (Server *)instance { return instance; }

+ (id)hiddenAlloc
{
    return [super alloc];
}

+ (id)alloc
{
    return [[self instance] retain];
}


+ (void)initialize
{
    static BOOL initialized = NO;
    if(!initialized)
    {
        initialized = YES;
        instance = [[Server hiddenAlloc] init];
    }
}

- (id) init
{
    if (instance)
        return self;
    self = [super init];
    if (self != nil) {
        // whatever
    }
    return self;
}

Why doesn't Java support unsigned ints?

As soon as signed and unsigned ints are mixed in an expression things start to get messy and you probably will lose information. Restricting Java to signed ints only really clears things up. I’m glad I don’t have to worry about the whole signed/unsigned business, though I sometimes do miss the 8th bit in a byte.

How to check if Receiver is registered in Android?

You can use Dagger to create a reference of that receiver.

First provide it:

@Provides
@YourScope
fun providesReceiver(): NotificationReceiver{
    return NotificationReceiver()
}

Then inject it where you need (using constructor or field injection)

and simply pass it to registerReceiver.

Also put it in try/catch block too.

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

How to get autocomplete in jupyter notebook without using tab?

Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)

{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}

Sort table rows In Bootstrap

These examples are minified because StackOverflow has a maximum character limit and links to external code are discouraged since links can break.

There are multiple plugins if you look: Bootstrap Sortable, Bootstrap Table or DataTables.

Bootstrap 3 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap.min.css rel=stylesheet><div class=container><h1>Bootstrap 3 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 4 with DataTables Example: Bootstrap Docs & DataTables Docs

_x000D_
_x000D_
$(document).ready(function() {
  $('#example').DataTable();
});
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/css/dataTables.bootstrap4.min.css rel=stylesheet><div class=container><h1>Bootstrap 4 DataTables</h1><table cellspacing=0 class="table table-bordered table-hover table-inverse table-striped"id=example width=100%><thead><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tfoot><tr><th>Name<th>Position<th>Office<th>Age<th>Start date<th>Salary<tbody><tr><td>Tiger Nixon<td>System Architect<td>Edinburgh<td>61<td>2011/04/25<td>$320,800<tr><td>Garrett Winters<td>Accountant<td>Tokyo<td>63<td>2011/07/25<td>$170,750<tr><td>Ashton Cox<td>Junior Technical Author<td>San Francisco<td>66<td>2009/01/12<td>$86,000<tr><td>Cedric Kelly<td>Senior Javascript Developer<td>Edinburgh<td>22<td>2012/03/29<td>$433,060<tr><td>Airi Satou<td>Accountant<td>Tokyo<td>33<td>2008/11/28<td>$162,700<tr><td>Brielle Williamson<td>Integration Specialist<td>New York<td>61<td>2012/12/02<td>$372,000<tr><td>Herrod Chandler<td>Sales Assistant<td>San Francisco<td>59<td>2012/08/06<td>$137,500<tr><td>Rhona Davidson<td>Integration Specialist<td>Tokyo<td>55<td>2010/10/14<td>$327,900<tr><td>Colleen Hurst<td>Javascript Developer<td>San Francisco<td>39<td>2009/09/15<td>$205,500<tr><td>Sonya Frost<td>Software Engineer<td>Edinburgh<td>23<td>2008/12/13<td>$103,600<tr><td>Jena Gaines<td>Office Manager<td>London<td>30<td>2008/12/19<td>$90,560<tr><td>Quinn Flynn<td>Support Lead<td>Edinburgh<td>22<td>2013/03/03<td>$342,000<tr><td>Charde Marshall<td>Regional Director<td>San Francisco<td>36<td>2008/10/16<td>$470,600<tr><td>Haley Kennedy<td>Senior Marketing Designer<td>London<td>43<td>2012/12/18<td>$313,500<tr><td>Tatyana Fitzpatrick<td>Regional Director<td>London<td>19<td>2010/03/17<td>$385,750<tr><td>Michael Silva<td>Marketing Designer<td>London<td>66<td>2012/11/27<td>$198,500<tr><td>Paul Byrd<td>Chief Financial Officer (CFO)<td>New York<td>64<td>2010/06/09<td>$725,000<tr><td>Gloria Little<td>Systems Administrator<td>New York<td>59<td>2009/04/10<td>$237,500<tr><td>Bradley Greer<td>Software Engineer<td>London<td>41<td>2012/10/13<td>$132,000<tr><td>Dai Rios<td>Personnel Lead<td>Edinburgh<td>35<td>2012/09/26<td>$217,500<tr><td>Jenette Caldwell<td>Development Lead<td>New York<td>30<td>2011/09/03<td>$345,000<tr><td>Yuri Berry<td>Chief Marketing Officer (CMO)<td>New York<td>40<td>2009/06/25<td>$675,000<tr><td>Caesar Vance<td>Pre-Sales Support<td>New York<td>21<td>2011/12/12<td>$106,450<tr><td>Doris Wilder<td>Sales Assistant<td>Sidney<td>23<td>2010/09/20<td>$85,600<tr><td>Angelica Ramos<td>Chief Executive Officer (CEO)<td>London<td>47<td>2009/10/09<td>$1,200,000<tr><td>Gavin Joyce<td>Developer<td>Edinburgh<td>42<td>2010/12/22<td>$92,575<tr><td>Jennifer Chang<td>Regional Director<td>Singapore<td>28<td>2010/11/14<td>$357,650<tr><td>Brenden Wagner<td>Software Engineer<td>San Francisco<td>28<td>2011/06/07<td>$206,850<tr><td>Fiona Green<td>Chief Operating Officer (COO)<td>San Francisco<td>48<td>2010/03/11<td>$850,000<tr><td>Shou Itou<td>Regional Marketing<td>Tokyo<td>20<td>2011/08/14<td>$163,000<tr><td>Michelle House<td>Integration Specialist<td>Sidney<td>37<td>2011/06/02<td>$95,400<tr><td>Suki Burks<td>Developer<td>London<td>53<td>2009/10/22<td>$114,500<tr><td>Prescott Bartlett<td>Technical Author<td>London<td>27<td>2011/05/07<td>$145,000<tr><td>Gavin Cortez<td>Team Leader<td>San Francisco<td>22<td>2008/10/26<td>$235,500<tr><td>Martena Mccray<td>Post-Sales support<td>Edinburgh<td>46<td>2011/03/09<td>$324,050<tr><td>Unity Butler<td>Marketing Designer<td>San Francisco<td>47<td>2009/12/09<td>$85,675<tr><td>Howard Hatfield<td>Office Manager<td>San Francisco<td>51<td>2008/12/16<td>$164,500<tr><td>Hope Fuentes<td>Secretary<td>San Francisco<td>41<td>2010/02/12<td>$109,850<tr><td>Vivian Harrell<td>Financial Controller<td>San Francisco<td>62<td>2009/02/14<td>$452,500<tr><td>Timothy Mooney<td>Office Manager<td>London<td>37<td>2008/12/11<td>$136,200<tr><td>Jackson Bradshaw<td>Director<td>New York<td>65<td>2008/09/26<td>$645,750<tr><td>Olivia Liang<td>Support Engineer<td>Singapore<td>64<td>2011/02/03<td>$234,500<tr><td>Bruno Nash<td>Software Engineer<td>London<td>38<td>2011/05/03<td>$163,500<tr><td>Sakura Yamamoto<td>Support Engineer<td>Tokyo<td>37<td>2009/08/19<td>$139,575<tr><td>Thor Walton<td>Developer<td>New York<td>61<td>2013/08/11<td>$98,540<tr><td>Finn Camacho<td>Support Engineer<td>San Francisco<td>47<td>2009/07/07<td>$87,500<tr><td>Serge Baldwin<td>Data Coordinator<td>Singapore<td>64<td>2012/04/09<td>$138,575<tr><td>Zenaida Frank<td>Software Engineer<td>New York<td>63<td>2010/01/04<td>$125,250<tr><td>Zorita Serrano<td>Software Engineer<td>San Francisco<td>56<td>2012/06/01<td>$115,000<tr><td>Jennifer Acosta<td>Junior Javascript Developer<td>Edinburgh<td>43<td>2013/02/01<td>$75,650<tr><td>Cara Stevens<td>Sales Assistant<td>New York<td>46<td>2011/12/06<td>$145,600<tr><td>Hermione Butler<td>Regional Director<td>London<td>47<td>2011/03/21<td>$356,250<tr><td>Lael Greer<td>Systems Administrator<td>London<td>21<td>2009/02/27<td>$103,500<tr><td>Jonas Alexander<td>Developer<td>San Francisco<td>30<td>2010/07/14<td>$86,500<tr><td>Shad Decker<td>Regional Director<td>Edinburgh<td>51<td>2008/11/13<td>$183,000<tr><td>Michael Bruce<td>Javascript Developer<td>Singapore<td>29<td>2011/06/27<td>$183,000<tr><td>Donna Snider<td>Customer Support<td>New York<td>27<td>2011/01/25<td>$112,000</table></div><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/dataTables.bootstrap4.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Table Example: Bootstrap Docs & Bootstrap Table Docs

_x000D_
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><link href=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.css rel=stylesheet><table data-sort-name=stargazers_count data-sort-order=desc data-toggle=table data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"><thead><tr><th data-field=name data-sortable=true>Name<th data-field=stargazers_count data-sortable=true>Stars<th data-field=forks_count data-sortable=true>Forks<th data-field=description data-sortable=true>Description</thead></table><script src=https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js></script><script src=https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.16.0/bootstrap-table.min.js></script>
_x000D_
_x000D_
_x000D_

Bootstrap 3 with Bootstrap Sortable Example: Bootstrap Docs & Bootstrap Sortable Docs

_x000D_
_x000D_
function randomDate(t,e){return new Date(t.getTime()+Math.random()*(e.getTime()-t.getTime()))}function randomName(){return["Jack","Peter","Frank","Steven"][Math.floor(4*Math.random())]+" "+["White","Jackson","Sinatra","Spielberg"][Math.floor(4*Math.random())]}function newTableRow(){var t=moment(randomDate(new Date(2e3,0,1),new Date)).format("D.M.YYYY"),e=Math.round(Math.random()*Math.random()*100*100)/100,a=Math.round(Math.random()*Math.random()*100*100)/100,r=Math.round(Math.random()*Math.random()*100*100)/100;return"<tr><td>"+randomName()+"</td><td>"+e+"</td><td>"+a+"</td><td>"+r+"</td><td>"+Math.round(100*(e+a+r))/100+"</td><td data-dateformat='D-M-YYYY'>"+t+"</td></tr>"}function customSort(){alert("Custom sort.")}!function(t,e){"use strict";"function"==typeof define&&define.amd?define("tinysort",function(){return e}):t.tinysort=e}(this,function(){"use strict";function t(t,e){for(var a,r=t.length,o=r;o--;)e(t[a=r-o-1],a)}function e(t,e,a){for(var o in e)(a||t[o]===r)&&(t[o]=e[o]);return t}function a(t,e,a){u.push({prepare:t,sort:e,sortBy:a})}var r,o=!1,n=null,s=window,d=s.document,i=parseFloat,l=/(-?\d+\.?\d*)\s*$/g,c=/(\d+\.?\d*)\s*$/g,u=[],f=0,h=0,p=String.fromCharCode(4095),m={selector:n,order:"asc",attr:n,data:n,useVal:o,place:"org",returns:o,cases:o,natural:o,forceStrings:o,ignoreDashes:o,sortFunction:n,useFlex:o,emptyEnd:o};return s.Element&&function(t){t.matchesSelector=t.matchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector||t.webkitMatchesSelector||function(t){for(var e=this,a=(e.parentNode||e.document).querySelectorAll(t),r=-1;a[++r]&&a[r]!=e;);return!!a[r]}}(Element.prototype),e(a,{loop:t}),e(function(a,s){function v(t){var a=!!t.selector,r=a&&":"===t.selector[0],o=e(t||{},m);E.push(e({hasSelector:a,hasAttr:!(o.attr===n||""===o.attr),hasData:o.data!==n,hasFilter:r,sortReturnNumber:"asc"===o.order?1:-1},o))}function b(t,e,a){for(var r=a(t.toString()),o=a(e.toString()),n=0;r[n]&&o[n];n++)if(r[n]!==o[n]){var s=Number(r[n]),d=Number(o[n]);return s==r[n]&&d==o[n]?s-d:r[n]>o[n]?1:-1}return r.length-o.length}function g(t){for(var e,a,r=[],o=0,n=-1,s=0;e=(a=t.charAt(o++)).charCodeAt(0);){var d=46==e||e>=48&&57>=e;d!==s&&(r[++n]="",s=d),r[n]+=a}return r}function w(){return Y.forEach(function(t){F.appendChild(t.elm)}),F}function S(t){var e=t.elm,a=d.createElement("div");return t.ghost=a,e.parentNode.insertBefore(a,e),t}function y(t,e){var a=t.ghost,r=a.parentNode;r.insertBefore(e,a),r.removeChild(a),delete t.ghost}function C(t,e){var a,r=t.elm;return e.selector&&(e.hasFilter?r.matchesSelector(e.selector)||(r=n):r=r.querySelector(e.selector)),e.hasAttr?a=r.getAttribute(e.attr):e.useVal?a=r.value||r.getAttribute("value"):e.hasData?a=r.getAttribute("data-"+e.data):r&&(a=r.textContent),M(a)&&(e.cases||(a=a.toLowerCase()),a=a.replace(/\s+/g," ")),null===a&&(a=p),a}function M(t){return"string"==typeof t}M(a)&&(a=d.querySelectorAll(a)),0===a.length&&console.warn("No elements to sort");var x,N,F=d.createDocumentFragment(),D=[],Y=[],$=[],E=[],k=!0,A=a.length&&a[0].parentNode,T=A.rootNode!==document,R=a.length&&(s===r||!1!==s.useFlex)&&!T&&-1!==getComputedStyle(A,null).display.indexOf("flex");return function(){0===arguments.length?v({}):t(arguments,function(t){v(M(t)?{selector:t}:t)}),f=E.length}.apply(n,Array.prototype.slice.call(arguments,1)),t(a,function(t,e){N?N!==t.parentNode&&(k=!1):N=t.parentNode;var a=E[0],r=a.hasFilter,o=a.selector,n=!o||r&&t.matchesSelector(o)||o&&t.querySelector(o)?Y:$,s={elm:t,pos:e,posn:n.length};D.push(s),n.push(s)}),x=Y.slice(0),Y.sort(function(e,a){var n=0;for(0!==h&&(h=0);0===n&&f>h;){var s=E[h],d=s.ignoreDashes?c:l;if(t(u,function(t){var e=t.prepare;e&&e(s)}),s.sortFunction)n=s.sortFunction(e,a);else if("rand"==s.order)n=Math.random()<.5?1:-1;else{var p=o,m=C(e,s),v=C(a,s),w=""===m||m===r,S=""===v||v===r;if(m===v)n=0;else if(s.emptyEnd&&(w||S))n=w&&S?0:w?1:-1;else{if(!s.forceStrings){var y=M(m)?m&&m.match(d):o,x=M(v)?v&&v.match(d):o;y&&x&&m.substr(0,m.length-y[0].length)==v.substr(0,v.length-x[0].length)&&(p=!o,m=i(y[0]),v=i(x[0]))}n=m===r||v===r?0:s.natural&&(isNaN(m)||isNaN(v))?b(m,v,g):v>m?-1:m>v?1:0}}t(u,function(t){var e=t.sort;e&&(n=e(s,p,m,v,n))}),0==(n*=s.sortReturnNumber)&&h++}return 0===n&&(n=e.pos>a.pos?1:-1),n}),function(){var t=Y.length===D.length;if(k&&t)R?Y.forEach(function(t,e){t.elm.style.order=e}):N?N.appendChild(w()):console.warn("parentNode has been removed");else{var e=E[0].place,a="start"===e,r="end"===e,o="first"===e,n="last"===e;if("org"===e)Y.forEach(S),Y.forEach(function(t,e){y(x[e],t.elm)});else if(a||r){var s=x[a?0:x.length-1],d=s&&s.elm.parentNode,i=d&&(a&&d.firstChild||d.lastChild);i&&(i!==s.elm&&(s={elm:i}),S(s),r&&d.appendChild(s.ghost),y(s,w()))}else(o||n)&&y(S(x[o?0:x.length-1]),w())}}(),Y.map(function(t){return t.elm})},{plugin:a,defaults:m})}()),function(t,e){"function"==typeof define&&define.amd?define(["jquery","tinysort","moment"],e):e(t.jQuery,t.tinysort,t.moment||void 0)}(this,function(t,e,a){var r,o,n,s=t(document);function d(e){var s=void 0!==a;r=e.sign?e.sign:"arrow","default"==e.customSort&&(e.customSort=c),o=e.customSort||o||c,n=e.emptyEnd,t("table.sortable").each(function(){var r=t(this),o=!0===e.applyLast;r.find("span.sign").remove(),r.find("> thead [colspan]").each(function(){for(var e=parseFloat(t(this).attr("colspan")),a=1;a<e;a++)t(this).after('<th class="colspan-compensate">')}),r.find("> thead [rowspan]").each(function(){for(var e=t(this),a=parseFloat(e.attr("rowspan")),r=1;r<a;r++){var o=e.parent("tr"),n=o.next("tr"),s=o.children().index(e);n.children().eq(s).before('<th class="rowspan-compensate">')}}),r.find("> thead tr").each(function(e){t(this).find("th").each(function(a){var r=t(this);r.addClass("nosort").removeClass("up down"),r.attr("data-sortcolumn",a),r.attr("data-sortkey",a+"-"+e)})}),r.find("> thead .rowspan-compensate, .colspan-compensate").remove(),r.find("th").each(function(){var e=t(this);if(void 0!==e.attr("data-dateformat")&&s){var o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var r=t(this);r.attr("data-value",a(r.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss"))})}else if(void 0!==e.attr("data-valueprovider")){o=parseFloat(e.attr("data-sortcolumn"));r.find("td:nth-child("+(o+1)+")").each(function(){var a=t(this);a.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(a.text())[0])})}}),r.find("td").each(function(){var e=t(this);void 0!==e.attr("data-dateformat")&&s?e.attr("data-value",a(e.text(),e.attr("data-dateformat")).format("YYYY/MM/DD/HH/mm/ss")):void 0!==e.attr("data-valueprovider")?e.attr("data-value",new RegExp(e.attr("data-valueprovider")).exec(e.text())[0]):void 0===e.attr("data-value")&&e.attr("data-value",e.text())});var n=l(r),d=n.bsSort;r.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var a=t(this),r=a.closest("table.sortable");a.data("sortTable",r);var s=a.attr("data-sortkey"),i=o?n.lastSort:-1;d[s]=o?d[s]:a.attr("data-defaultsort"),void 0!==d[s]&&o===(s===i)&&(d[s]="asc"===d[s]?"desc":"asc",u(a,r))})})}function i(e){var a=t(e),r=a.data("sortTable")||a.closest("table.sortable");u(a,r)}function l(e){var a=e.data("bootstrap-sortable-context");return void 0===a&&(a={bsSort:[],lastSort:void 0},e.find('> thead th[data-defaultsort!="disabled"]').each(function(e){var r=t(this),o=r.attr("data-sortkey");a.bsSort[o]=r.attr("data-defaultsort"),void 0!==a.bsSort[o]&&(a.lastSort=o)}),e.data("bootstrap-sortable-context",a)),a}function c(t,a){e(t,a)}function u(e,a){a.trigger("before-sort");var s=parseFloat(e.attr("data-sortcolumn")),d=l(a),i=d.bsSort;if(e.attr("colspan")){var c=parseFloat(e.data("mainsort"))||0,f=parseFloat(e.data("sortkey").split("-").pop());if(a.find("> thead tr").length-1>f)return void u(a.find('[data-sortkey="'+(s+c)+"-"+(f+1)+'"]'),a);s+=c}var h=e.attr("data-defaultsign")||r;if(a.find("> thead th").each(function(){t(this).removeClass("up").removeClass("down").addClass("nosort")}),t.browser.mozilla){var p=a.find("> thead div.mozilla");void 0!==p&&(p.find(".sign").remove(),p.parent().html(p.html())),e.wrapInner('<div class="mozilla"></div>'),e.children().eq(0).append('<span class="sign '+h+'"></span>')}else a.find("> thead span.sign").remove(),e.append('<span class="sign '+h+'"></span>');var m=e.attr("data-sortkey"),v="desc"!==e.attr("data-firstsort")?"desc":"asc",b=i[m]||v;d.lastSort!==m&&void 0!==i[m]||(b="asc"===b?"desc":"asc"),i[m]=b,d.lastSort=m,"desc"===i[m]?(e.find("span.sign").addClass("up"),e.addClass("up").removeClass("down nosort")):e.addClass("down").removeClass("up nosort");var g=a.children("tbody").children("tr"),w=[];t(g.filter('[data-disablesort="true"]').get().reverse()).each(function(e,a){var r=t(a);w.push({index:g.index(r),row:r}),r.remove()});var S=g.not('[data-disablesort="true"]');if(0!=S.length){var y="asc"===i[m]&&n;o(S,{emptyEnd:y,selector:"td:nth-child("+(s+1)+")",order:i[m],data:"value"})}t(w.reverse()).each(function(t,e){0===e.index?a.children("tbody").prepend(e.row):a.children("tbody").children("tr").eq(e.index-1).after(e.row)}),a.find("> tbody > tr > td.sorted,> thead th.sorted").removeClass("sorted"),S.find("td:eq("+s+")").addClass("sorted"),e.addClass("sorted"),a.trigger("sorted")}if(t.bootstrapSortable=function(t){null==t?d({}):t.constructor===Boolean?d({applyLast:t}):void 0!==t.sortingHeader?i(t.sortingHeader):d(t)},s.on("click",'table.sortable>thead th[data-defaultsort!="disabled"]',function(t){i(this)}),!t.browser){t.browser={chrome:!1,mozilla:!1,opera:!1,msie:!1,safari:!1};var f=navigator.userAgent;t.each(t.browser,function(e){t.browser[e]=!!new RegExp(e,"i").test(f),t.browser.mozilla&&"mozilla"===e&&(t.browser.mozilla=!!new RegExp("firefox","i").test(f)),t.browser.chrome&&"safari"===e&&(t.browser.safari=!1)})}t(t.bootstrapSortable)}),function(){var t=$("table");t.append(newTableRow()),t.append(newTableRow()),$("button.add-row").on("click",function(){var e=$(this);t.append(newTableRow()),e.data("sort")?$.bootstrapSortable(!0):$.bootstrapSortable(!1)}),$("button.change-sort").on("click",function(){$(this).data("custom")?$.bootstrapSortable(!0,void 0,customSort):$.bootstrapSortable(!0,void 0,"default")}),t.on("sorted",function(){alert("Table was sorted.")}),$("#event").on("change",function(){$(this).is(":checked")?t.on("sorted",function(){alert("Table was sorted.")}):t.off("sorted")}),$("input[name=sign]:radio").change(function(){$.bootstrapSortable(!0,$(this).val())})}();
_x000D_
table.sortable span.sign { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th:after { display: block; position: absolute; top: 50%; right: 5px; font-size: 12px; margin-top: -10px; color: #bfbfc1; } table.sortable th.arrow:after { content: ''; } table.sortable span.arrow, span.reversed, th.arrow.down:after, th.reversedarrow.down:after, th.arrow.up:after, th.reversedarrow.up:after { border-style: solid; border-width: 5px; font-size: 0; border-color: #ccc transparent transparent transparent; line-height: 0; height: 0; width: 0; margin-top: -2px; } table.sortable span.arrow.up, th.arrow.up:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed, th.reversedarrow.down:after { border-color: transparent transparent #ccc transparent; margin-top: -7px; } table.sortable span.reversed.up, th.reversedarrow.up:after { border-color: #ccc transparent transparent transparent; margin-top: -2px; } table.sortable span.az:before, th.az.down:after { content: "a .. z"; } table.sortable span.az.up:before, th.az.up:after { content: "z .. a"; } table.sortable th.az.nosort:after, th.AZ.nosort:after, th._19.nosort:after, th.month.nosort:after { content: ".."; } table.sortable span.AZ:before, th.AZ.down:after { content: "A .. Z"; } table.sortable span.AZ.up:before, th.AZ.up:after { content: "Z .. A"; } table.sortable span._19:before, th._19.down:after { content: "1 .. 9"; } table.sortable span._19.up:before, th._19.up:after { content: "9 .. 1"; } table.sortable span.month:before, th.month.down:after { content: "jan .. dec"; } table.sortable span.month.up:before, th.month.up:after { content: "dec .. jan"; } table.sortable thead th:not([data-defaultsort=disabled]) { cursor: pointer; position: relative; top: 0; left: 0; } table.sortable thead th:hover:not([data-defaultsort=disabled]) { background: #efefef; } table.sortable thead th div.mozilla { position: relative; }
_x000D_
<link href=https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.1/css/all.min.css rel=stylesheet><link href=https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css rel=stylesheet><div class=container><div class=hero-unit><h1>Bootstrap Sortable</h1></div><table class="sortable table table-bordered table-striped"><thead><tr><th style=width:20%;vertical-align:middle data-defaultsign=nospan class=az data-defaultsort=asc rowspan=2><i class="fa fa-fw fa-map-marker"></i>Name<th style=text-align:center colspan=4 data-mainsort=3>Results<th data-defaultsort=disabled><tr><th style=width:20% colspan=2 data-mainsort=1 data-firstsort=desc>Round 1<th style=width:20%>Round 2<th style=width:20%>Total<t
                  

Setting Django up to use MySQL

Follow the given steps in order to setup it up to use MySQL database:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

How to select following sibling/xml tag using xpath

Try the following-sibling axis (following-sibling::td).

Android: Storing username and password?

These are ranked in order of difficulty to break your hidden info.

  1. Store in cleartext

  2. Store encrypted using a symmetric key

  3. Using the Android Keystore

  4. Store encrypted using asymmetric keys

source: Where is the best place to store a password in your Android app

The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.

source: Simple use the Android Keystore to store passwords and other sensitive information

Find an object in array?

For example, if we had an array of numbers:

let numbers = [2, 4, 6, 8, 9, 10]

We could find the first odd number like this:

let firstOdd = numbers.index { $0 % 2 == 1 }

That will send back 4 as an optional integer, because the first odd number (9) is at index four.

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

Compare a date string to datetime in SQL Server?

Technique 2:

DECLARE @p_date DATETIME
SET     @p_date = CONVERT( DATETIME, '14 AUG 2008', 106 )

SELECT  *
FROM    table1
WHERE   DATEDIFF( d, column_datetime, @p_date ) = 0

If the column_datetime field is not indexed, and is unlikely to be (or the index is unlikely to be used) then using DATEDIFF() is shorter.

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

How to remove from a map while iterating it?

I personally prefer this pattern which is slightly clearer and simpler, at the expense of an extra variable:

for (auto it = m.cbegin(), next_it = it; it != m.cend(); it = next_it)
{
  ++next_it;
  if (must_delete)
  {
    m.erase(it);
  }
}

Advantages of this approach:

  • the for loop incrementor makes sense as an incrementor;
  • the erase operation is a simple erase, rather than being mixed in with increment logic;
  • after the first line of the loop body, the meaning of it and next_it remain fixed throughout the iteration, allowing you to easily add additional statements referring to them without headscratching over whether they will work as intended (except of course that you cannot use it after erasing it).

How do you get AngularJS to bind to the title attribute of an A tag?

The search query model lives in the scope defined by the ng-controller="whatever" directive. So if you want to bind the query model to <title>, you have to move the ngController declaration to an HTML element that is a common parent to both the body and title elements:

<html ng-app="phonecatApp" ng-controller="PhoneListCtrl">

Ref: https://docs.angularjs.org/tutorial/step_03

How do I change the ID of a HTML element with JavaScript?

That seems to work for me:

<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>

The expected behaviour is to change the colour of the word "fruit".

Perhaps your document was not fully loaded when you called the routine?

Partly cherry-picking a commit with Git

Use git format-patch to slice out the part of the commit you care about and git am to apply it to another branch

git format-patch <sha> -- path/to/file
git checkout other-branch
git am *.patch

How to get current date in jquery?

In JavaScript you can get the current date and time using the Date object;

var now = new Date();

This will get the local client machine time

Example for jquery LINK

If you are using jQuery DatePicker you can apply it on any textfield like this:

$( "#datepicker" ).datepicker({dateFormat:"yy/mm/dd"}).datepicker("setDate",new Date());

Finding row index containing maximum value using R

See ?which.max

> which.max( matrix[,2] )
[1] 2

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

Script Tag - async & defer

Async is suitable if your script doesn’t contains DOM manipulation and other scripts doesn’t depend upon on this. Eg: bootstrap cdn,jquery

Defer is suitable if your script contains DOM manipulation and other scripts depend upon on this.

Eg: <script src=”createfirst.js”> //let this will create element <script src=”showfirst.js”> //after createfirst create element it will show that.

Thus make it: Eg: <script defer src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will

This will execute scripts in order.

But if i made: Eg: <script async src=”createfirst.js”> //let this will create element <script defer src=”showfirst.js”> //after createfirst create element it will

Then, this code might result unexpected results. Coz: if html parser access createfirst script.It won’t stop DOM creation and starts downloading code from src .Once src got resolved/code got downloaded, it will execute immediately parallel with DOM.

What if showfirst.js execute first than createfirst.js.This might be possible if createfirst takes long time (Assume after DOM parsing finished).Then, showfirst will execute immediately.

How to cast Object to its actual type?

Implement an interface to call your function in your method
interface IMyInterface
{
 void MyinterfaceMethod();
}

IMyInterface MyObj = obj as IMyInterface;
if ( MyObj != null)
{
MyMethod(IMyInterface MyObj );
}

Full-screen responsive background image

Backstretch

Check out this one-liner plugin that scales a background image responsively.

All you need to do is:

1. Include the library:

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>

2. Call the method:

$.backstretch("http://dl.dropbox.com/u/515046/www/garfield-interior.jpg");

I used it for a simple "under construction website" site I had and it worked perfectly.

How to create CSV Excel file C#?

I added ExportToStream so the csv didn't have to save to the hard drive first.

public Stream ExportToStream()
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(Export(true));
    writer.Flush();
    stream.Position = 0;
    return stream;
}

Get URL query string parameters

I will recommended best answer as

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

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

The above example will output:

Hello Hannes!

Python not working in command prompt?

When you add the python directory to the path (Computer > Properties > Advanced System Settings > Advanced > Environmental Variables > System Variables > Path > Edit), remember to add a semicolon, then make sure that you are adding the precise directory where the file "python.exe" is stored (e.g. C:\Python\Python27 if that is where "python.exe" is stored). Then restart the command prompt.

Does Android keep the .apk files? if so where?

As opposed to what's written on the chosen answer, you don't need root and it is possible to get the APKs of the installed apps, which is how I've done it on my app (here). Example:

List<PackageInfo> packages=getPackageManager().getInstalledPackages(0);

Then, for each of the items of the list, you can access packageInfo.applicationInfo.sourceDir, which is the full path of the APK of the installed app.

UITableView - scroll to the top

UITableView is a subclass of UIScrollView, so you can also use:

[mainTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];

Or

[mainTableView setContentOffset:CGPointZero animated:YES];

And in Swift:

mainTableView.setContentOffset(CGPointZero, animated:true)

And in Swift 3 & above:

mainTableView.setContentOffset(.zero, animated: true)

ModalPopupExtender OK Button click event not firing?

I often use a blank label as the TargetControlID. ex. <asp:Label ID="lblghost" runat="server" Text="" />

I've seen two things that cause the click event not fire:
1. you have to remove the OKControlID (as others have mentioned)
2. If you are using field validators you should add CausesValidation="false" on the button.

Both scenarios behaved the same way for me.

How to exit git log or git diff

You're in the less program, which makes the output of git log scrollable.

Type q to exit this screen. Type h to get help.

If you don't want to read the output in a pager and want it to be just printed to the terminal define the environment variable GIT_PAGER to cat or set core.pager to cat (execute git config --global core.pager cat).

How to send json data in the Http request using NSURLRequest

Since my edit to Mike G's answer to modernize the code was rejected 3 to 2 as

This edit was intended to address the author of the post and makes no sense as an edit. It should have been written as a comment or an answer

I'm reposting my edit as a separate answer here. This edit removes the JSONRepresentation dependency with NSJSONSerialization as Rob's comment with 15 upvotes suggests.

    NSArray *objects = [NSArray arrayWithObjects:[[NSUserDefaults standardUserDefaults]valueForKey:@"StoreNickName"],
      [[UIDevice currentDevice] uniqueIdentifier], [dict objectForKey:@"user_question"],     nil];
    NSArray *keys = [NSArray arrayWithObjects:@"nick_name", @"UDID", @"user_question", nil];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:objects forKeys:keys];

    NSDictionary *jsonDict = [NSDictionary dictionaryWithObject:questionDict forKey:@"question"];

    NSLog(@"jsonRequest is %@", jsonRequest);

    NSURL *url = [NSURL URLWithString:@"https://xxxxxxx.com/questions"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];


    NSData *requestData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil]; //TODO handle error

    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData];

    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
     receivedData = [[NSMutableData data] retain];
    }

The receivedData is then handled by:

NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSDictionary *question = [jsonDict objectForKey:@"question"];

Find text string using jQuery?

If you just want the node closest to the text you're searching for, you could use this:

$('*:contains("my text"):last');

This will even work if your HTML looks like this:

<p> blah blah <strong>my <em>text</em></strong></p>

Using the above selector will find the <strong> tag, since that's the last tag which contains that entire string.

Squash the first two commits in Git?

You can use git filter-branch for that. e.g.

git filter-branch --parent-filter \
'if test $GIT_COMMIT != <sha1ofB>; then cat; fi'

This results in AB-C throwing away the commit log of A.

How to move screen without moving cursor in Vim?

I'm surprised no one is using the Scrolloff option which keeps the cursor in the middle of the page. Try it with:

:set so=999

It's the first recommended method on the Vim wiki and works well.

dyld: Library not loaded: @rpath/libswiftCore.dylib

If you're getting an error like this:

The bundle "YourFrameworkTests" couldn't be loaded because it is damaged or missing necessary resources. Try reinstalling the bundle. (dlopen_preflight(/some/path/.../YourFrameworkTests.xctest/YourFrameworkTests): Library not loaded: @rpath/SomeOther.framework/SomeOther Referenced from: /some/path/...)

and use CocoaPods in your framework, then try to edit the Podfile and remove inherit! :search_paths from the Test target, and run pod install again.

For more details, see https://github.com/CocoaPods/CocoaPods/issues/8868.

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

ORA-01438: value larger than specified precision allows for this column

From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):

ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.

http://ora-06512.ora-code.com/:

ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.

How to access the correct `this` inside a callback?

We can not bind this to setTimeout(), as it always execute with global object (Window), if you want to access this context in the callback function then by using bind() to the callback function we can achieve as:

setTimeout(function(){
    this.methodName();
}.bind(this), 2000);

Adding a Method to an Existing Object Instance

Consolidating Jason Pratt's and the community wiki answers, with a look at the results of different methods of binding:

Especially note how adding the binding function as a class method works, but the referencing scope is incorrect.

#!/usr/bin/python -u
import types
import inspect

## dynamically adding methods to a unique instance of a class


# get a list of a class's method type attributes
def listattr(c):
    for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:
        print m[0], m[1]

# externally bind a function as a method of an instance of a class
def ADDMETHOD(c, method, name):
    c.__dict__[name] = types.MethodType(method, c)

class C():
    r = 10 # class attribute variable to test bound scope

    def __init__(self):
        pass

    #internally bind a function as a method of self's class -- note that this one has issues!
    def addmethod(self, method, name):
        self.__dict__[name] = types.MethodType( method, self.__class__ )

    # predfined function to compare with
    def f0(self, x):
        print 'f0\tx = %d\tr = %d' % ( x, self.r)

a = C() # created before modified instnace
b = C() # modified instnace


def f1(self, x): # bind internally
    print 'f1\tx = %d\tr = %d' % ( x, self.r )
def f2( self, x): # add to class instance's .__dict__ as method type
    print 'f2\tx = %d\tr = %d' % ( x, self.r )
def f3( self, x): # assign to class as method type
    print 'f3\tx = %d\tr = %d' % ( x, self.r )
def f4( self, x): # add to class instance's .__dict__ using a general function
    print 'f4\tx = %d\tr = %d' % ( x, self.r )


b.addmethod(f1, 'f1')
b.__dict__['f2'] = types.MethodType( f2, b)
b.f3 = types.MethodType( f3, b)
ADDMETHOD(b, f4, 'f4')


b.f0(0) # OUT: f0   x = 0   r = 10
b.f1(1) # OUT: f1   x = 1   r = 10
b.f2(2) # OUT: f2   x = 2   r = 10
b.f3(3) # OUT: f3   x = 3   r = 10
b.f4(4) # OUT: f4   x = 4   r = 10


k = 2
print 'changing b.r from {0} to {1}'.format(b.r, k)
b.r = k
print 'new b.r = {0}'.format(b.r)

b.f0(0) # OUT: f0   x = 0   r = 2
b.f1(1) # OUT: f1   x = 1   r = 10  !!!!!!!!!
b.f2(2) # OUT: f2   x = 2   r = 2
b.f3(3) # OUT: f3   x = 3   r = 2
b.f4(4) # OUT: f4   x = 4   r = 2

c = C() # created after modifying instance

# let's have a look at each instance's method type attributes
print '\nattributes of a:'
listattr(a)
# OUT:
# attributes of a:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>

print '\nattributes of b:'
listattr(b)
# OUT:
# attributes of b:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>
# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>
# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>
# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>
# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>
# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>

print '\nattributes of c:'
listattr(c)
# OUT:
# attributes of c:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>

Personally, I prefer the external ADDMETHOD function route, as it allows me to dynamically assign new method names within an iterator as well.

def y(self, x):
    pass
d = C()
for i in range(1,5):
    ADDMETHOD(d, y, 'f%d' % i)
print '\nattributes of d:'
listattr(d)
# OUT:
# attributes of d:
# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>
# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>
# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>
# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>
# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How can I add reflection to a C++ application?

This question is a bit old now (don't know why I keep hitting old questions today) but I was thinking about BOOST_FUSION_ADAPT_STRUCT which introduces compile-time reflection.

It is up to you to map this to run-time reflection of course, and it won't be too easy, but it is possible in this direction, while it would not be in the reverse :)

I really think a macro to encapsulate the BOOST_FUSION_ADAPT_STRUCT one could generate the necessary methods to get the runtime behavior.

Disable Pinch Zoom on Mobile Web

I think what you may be after is the CSS property touch-action. You just need a CSS rule like this:

html, body {touch-action: none;}

You will see it has pretty good support (https://caniuse.com/#feat=mdn-css_properties_touch-action_none), including Safari, as well as back to IE10.

Centering a div block without the width

I found a more elegant solution, combining "inline-block" to avoid using float and the hacky clear:both. It still requires nested divs tho, which isnt very semantic but it just works...

div.outer{
    display:inline-block;
    position:relative;
    left:50%;
}

div.inner{
    position:relative;
    left:-50%;
}

Hope it helps!

$(document).ready shorthand

These specific lines are the usual wrapper for jQuery plugins:

"...to make sure that your plugin doesn't collide with other libraries that might use the dollar sign, it's a best practice to pass jQuery to a self executing function (closure) that maps it to the dollar sign so it can't be overwritten by another library in the scope of its execution."

(function( $ ){
  $.fn.myPlugin = function() {
    // Do your awesome plugin stuff here
  };
})( jQuery );

From http://docs.jquery.com/Plugins/Authoring

how to read all files inside particular folder

Try this It is working for me..

The syntax is GetFiles(string path, string searchPattern);

var filePath = Server.MapPath("~/App_Data/");
string[] filePaths = Directory.GetFiles(@filePath, "*.*");

This code will return all the files inside App_Data folder.

The second parameter . indicates the searchPattern with File Extension where the first * is for file name and second is for format of the file or File Extension like (*.png - any file name with .png format.

right click context menu for datagridview

You can use the CellMouseEnter and CellMouseLeave to track the row number that the mouse is currently hovering over.

Then use a ContextMenu object to display you popup menu, customised for the current row.

Here's a quick and dirty example of what I mean...

private void dataGridView1_MouseClick(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        ContextMenu m = new ContextMenu();
        m.MenuItems.Add(new MenuItem("Cut"));
        m.MenuItems.Add(new MenuItem("Copy"));
        m.MenuItems.Add(new MenuItem("Paste"));

        int currentMouseOverRow = dataGridView1.HitTest(e.X,e.Y).RowIndex;

        if (currentMouseOverRow >= 0)
        {
            m.MenuItems.Add(new MenuItem(string.Format("Do something to row {0}", currentMouseOverRow.ToString())));
        }

        m.Show(dataGridView1, new Point(e.X, e.Y));

    }
}

How can I get the named parameters from a URL using Flask?

Use request.args.get(param), for example:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

Here is the referenced link to the code.

How to read existing text files without defining path

If your application is a web service, Directory.CurrentDirectory doesn't work.

Use System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt")) instead.

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

How do I create a unique constraint that also allows nulls?

Create a view that selects only non-NULL columns and create the UNIQUE INDEX on the view:

CREATE VIEW myview
AS
SELECT  *
FROM    mytable
WHERE   mycolumn IS NOT NULL

CREATE UNIQUE INDEX ux_myview_mycolumn ON myview (mycolumn)

Note that you'll need to perform INSERT's and UPDATE's on the view instead of table.

You may do it with an INSTEAD OF trigger:

CREATE TRIGGER trg_mytable_insert ON mytable
INSTEAD OF INSERT
AS
BEGIN
        INSERT
        INTO    myview
        SELECT  *
        FROM    inserted
END

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

How to display scroll bar onto a html table

The accepted answer provided a good starting point, but if you resize the frame, change the column widths, or even change the table data, the headers will get messed up in various ways. Every other example I've seen has similar issues, or imposes some serious restrictions on the table's layout.

I think I've finally got all these problems solved, though. It took a lot of CSS, but the final product is about as reliable and easy to use as a normal table.

Here's an example that has all the required features to replicate the table referenced by the OP: jsFiddle

The colors and borders would have to be changed to make it identical to the reference. Information on how to make those kinds of changes is provided in the CSS comments.

Here's the code:

_x000D_
_x000D_
/*the following html and body rule sets are required only if using a % width or height*/_x000D_
/*html {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}*/_x000D_
body {_x000D_
  box-sizing: border-box;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0 20px 0 20px;_x000D_
  text-align: center;_x000D_
  background: white;_x000D_
}_x000D_
.scrollingtable {_x000D_
  box-sizing: border-box;_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
  width: auto; /*if you want a fixed width, set it here, else set to auto*/_x000D_
  min-width: 0/*100%*/; /*if you want a % width, set it here, else set to 0*/_x000D_
  height: 188px/*100%*/; /*set table height here; can be fixed value or %*/_x000D_
  min-height: 0/*104px*/; /*if using % height, make this large enough to fit scrollbar arrows + caption + thead*/_x000D_
  font-family: Verdana, Tahoma, sans-serif;_x000D_
  font-size: 15px;_x000D_
  line-height: 20px;_x000D_
  padding: 20px 0 20px 0; /*need enough padding to make room for caption*/_x000D_
  text-align: left;_x000D_
}_x000D_
.scrollingtable * {box-sizing: border-box;}_x000D_
.scrollingtable > div {_x000D_
  position: relative;_x000D_
  border-top: 1px solid black;_x000D_
  height: 100%;_x000D_
  padding-top: 20px; /*this determines column header height*/_x000D_
}_x000D_
.scrollingtable > div:before {_x000D_
  top: 0;_x000D_
  background: cornflowerblue; /*header row background color*/_x000D_
}_x000D_
.scrollingtable > div:before,_x000D_
.scrollingtable > div > div:after {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  left: 0;_x000D_
}_x000D_
.scrollingtable > div > div {_x000D_
  min-height: 0/*43px*/; /*if using % height, make this large enough to fit scrollbar arrows*/_x000D_
  max-height: 100%;_x000D_
  overflow: scroll/*auto*/; /*set to auto if using fixed or % width; else scroll*/_x000D_
  overflow-x: hidden;_x000D_
  border: 1px solid black; /*border around table body*/_x000D_
}_x000D_
.scrollingtable > div > div:after {background: white;} /*match page background color*/_x000D_
.scrollingtable > div > div > table {_x000D_
  width: 100%;_x000D_
  border-spacing: 0;_x000D_
  margin-top: -20px; /*inverse of column header height*/_x000D_
  /*margin-right: 17px;*/ /*uncomment if using % width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > caption {_x000D_
  position: absolute;_x000D_
  top: -20px; /*inverse of caption height*/_x000D_
  margin-top: -1px; /*inverse of border-width*/_x000D_
  width: 100%;_x000D_
  font-weight: bold;_x000D_
  text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > * > tr > * {padding: 0;}_x000D_
.scrollingtable > div > div > table > thead {_x000D_
  vertical-align: bottom;_x000D_
  white-space: nowrap;_x000D_
  text-align: center;_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div {_x000D_
  display: inline-block;_x000D_
  padding: 0 6px 0 6px; /*header cell padding*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > :first-child:before {_x000D_
  content: "";_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 20px; /*match column header height*/_x000D_
  border-left: 1px solid black; /*leftmost header border*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div > div:first-child,_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  white-space: pre-wrap;_x000D_
  color: white; /*header row font color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:before,_x000D_
.scrollingtable > div > div > table > thead > tr > * > div[label]:after {content: attr(label);}_x000D_
.scrollingtable > div > div > table > thead > tr > * + :before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  min-height: 20px; /*match column header height*/_x000D_
  padding-top: 1px;_x000D_
  border-left: 1px solid black; /*borders between header cells*/_x000D_
}_x000D_
.scrollingtable .scrollbarhead {float: right;}_x000D_
.scrollingtable .scrollbarhead:before {_x000D_
  position: absolute;_x000D_
  width: 100px;_x000D_
  top: -1px; /*inverse border-width*/_x000D_
  background: white; /*match page background color*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody > tr:after {_x000D_
  content: "";_x000D_
  display: table-cell;_x000D_
  position: relative;_x000D_
  padding: 0;_x000D_
  border-top: 1px solid black;_x000D_
  top: -1px; /*inverse of border width*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody {vertical-align: top;}_x000D_
.scrollingtable > div > div > table > tbody > tr {background: white;}_x000D_
.scrollingtable > div > div > table > tbody > tr > * {_x000D_
  border-bottom: 1px solid black;_x000D_
  padding: 0 6px 0 6px;_x000D_
  height: 20px; /*match column header height*/_x000D_
}_x000D_
.scrollingtable > div > div > table > tbody:last-of-type > tr:last-child > * {border-bottom: none;}_x000D_
.scrollingtable > div > div > table > tbody > tr:nth-child(even) {background: gainsboro;} /*alternate row color*/_x000D_
.scrollingtable > div > div > table > tbody > tr > * + * {border-left: 1px solid black;} /*borders between body cells*/
_x000D_
<div class="scrollingtable">_x000D_
  <div>_x000D_
    <div>_x000D_
      <table>_x000D_
        <caption>Top Caption</caption>_x000D_
        <thead>_x000D_
          <tr>_x000D_
            <th><div label="Column 1"></div></th>_x000D_
            <th><div label="Column 2"></div></th>_x000D_
            <th><div label="Column 3"></div></th>_x000D_
            <th>_x000D_
              <!--more versatile way of doing column label; requires 2 identical copies of label-->_x000D_
              <div><div>Column 4</div><div>Column 4</div></div>_x000D_
            </th>_x000D_
            <th class="scrollbarhead"/> <!--ALWAYS ADD THIS EXTRA CELL AT END OF HEADER ROW-->_x000D_
          </tr>_x000D_
        </thead>_x000D_
        <tbody>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
          <tr><td>Lorem ipsum</td><td>Dolor</td><td>Sit</td><td>Amet consectetur</td></tr>_x000D_
        </tbody>_x000D_
      </table>_x000D_
    </div>_x000D_
    Faux bottom caption_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!--[if lte IE 9]><style>.scrollingtable > div > div > table {margin-right: 17px;}</style><![endif]-->
_x000D_
_x000D_
_x000D_

how to add value to combobox item

If you want to use SelectedValue then your combobox must be databound.

To set up the combobox:

ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"

To get the data:

Function GetMailItems() As List(Of MailItem)

    Dim mailItems = New List(Of MailItem)

    Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
    Command.CommandTimeout = 30
    Reader = Command.ExecuteReader()

    If Reader.HasRows = True Then
        While Reader.Read()
            mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
        End While
    End If

    Return mailItems

End Function

Public Class MailItem

    Public Sub New(ByVal id As Integer, ByVal name As String)
        mID = id
        mName = name
    End Sub

    Private mID As Integer
    Public Property ID() As Integer
        Get
            Return mID
        End Get
        Set(ByVal value As Integer)
            mID = value
        End Set
    End Property

    Private mName As String
    Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property

End Class

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

How to free memory in Java?

System.gc(); 

Runs the garbage collector.

Calling the gc method suggests that the Java Virtual Machine expend effort toward recycling unused objects in order to make the memory they currently occupy available for quick reuse. When control returns from the method call, the Java Virtual Machine has made a best effort to reclaim space from all discarded objects.

Not recommended.

Edit: I wrote the original response in 2009. It's now 2015.

Garbage collectors have gotten steadily better in the ~20 years Java's been around. At this point, if you're manually calling the garbage collector, you may want to consider other approaches:

  • If you're forcing GC on a limited number of machines, it may be worth having a load balancer point away from the current machine, waiting for it to finish serving to connected clients, timeout after some period for hanging connections, and then just hard-restart the JVM. This is a terrible solution, but if you're looking at System.gc(), forced-restarts may be a possible stopgap.
  • Consider using a different garbage collector. For example, the (new in the last six years) G1 collector is a low-pause model; it uses more CPU overall, but does it's best to never force a hard-stop on execution. Since server CPUs now almost all have multiple cores, this is A Really Good Tradeoff to have available.
  • Look at your flags tuning memory use. Especially in newer versions of Java, if you don't have that many long-term running objects, consider bumping up the size of newgen in the heap. newgen (young) is where new objects are allocated. For a webserver, everything created for a request is put here, and if this space is too small, Java will spend extra time upgrading the objects to longer-lived memory, where they're more expensive to kill. (If newgen is slightly too small, you're going to pay for it.) For example, in G1:
    • XX:G1NewSizePercent (defaults to 5; probably doesn't matter.)
    • XX:G1MaxNewSizePercent (defaults to 60; probably raise this.)
  • Consider telling the garbage collector you're not okay with a longer pause. This will cause more-frequent GC runs, to allow the system to keep the rest of it's constraints. In G1:
    • XX:MaxGCPauseMillis (defaults to 200.)

overlay opaque div over youtube iframe

Note that the wmode=transparent fix only works if it's first so

http://www.youtube.com/embed/K3j9taoTd0E?wmode=transparent&rel=0

Not

http://www.youtube.com/embed/K3j9taoTd0E?rel=0&wmode=transparent

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I find that when i choose option of Project->Properties->Linker->System->SubSystem->Console(/subsystem:console), and then make sure include the function : int _tmain(int argc,_TCHAR* argv[]){return 0} all of the compiling ,linking and running will be ok;

javascript: detect scroll end

The accepted answer was fundamentally flawed, it has since been deleted. The correct answer is:

function scrolled(e) {
  if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) {
    scrolledToBottom(e);
  }
}

Tested this in Firefox, Chrome and Opera. It works.

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

Blocks and yields in Ruby

It's quite possible that someone will provide a truly detailed answer here, but I've always found this post from Robert Sosinski to be a great explanation of the subtleties between blocks, procs & lambdas.

I should add that I believe the post I'm linking to is specific to ruby 1.8. Some things have changed in ruby 1.9, such as block variables being local to the block. In 1.8, you'd get something like the following:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Goodbye"

Whereas 1.9 would give you:

>> a = "Hello"
=> "Hello"
>> 1.times { |a| a = "Goodbye" }
=> 1
>> a
=> "Hello"

I don't have 1.9 on this machine so the above might have an error in it.

Read XML Attribute using XmlDocument

You can migrate to XDocument instead of XmlDocument and then use Linq if you prefer that syntax. Something like:

var q = (from myConfig in xDoc.Elements("MyConfiguration")
         select myConfig.Attribute("SuperString").Value)
         .First();

How To Accept a File POST

Toward this same directions, I'm posting a client and server snipets that send Excel Files using WebApi, c# 4:

public static void SetFile(String serviceUrl, byte[] fileArray, String fileName)
{
    try
    {
        using (var client = new HttpClient())
        {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                using (var content = new MultipartFormDataContent())
                {
                    var fileContent = new ByteArrayContent(fileArray);//(System.IO.File.ReadAllBytes(fileName));
                    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = fileName
                    };
                    content.Add(fileContent);
                    var result = client.PostAsync(serviceUrl, content).Result;
                }
        }
    }
    catch (Exception e)
    {
        //Log the exception
    }
}

And the server webapi controller:

public Task<IEnumerable<string>> Post()
{
    if (Request.Content.IsMimeMultipartContent())
    {
        string fullPath = HttpContext.Current.Server.MapPath("~/uploads");
        MyMultipartFormDataStreamProvider streamProvider = new MyMultipartFormDataStreamProvider(fullPath);
        var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
        {
            if (t.IsFaulted || t.IsCanceled)
                    throw new HttpResponseException(HttpStatusCode.InternalServerError);

            var fileInfo = streamProvider.FileData.Select(i =>
            {
                var info = new FileInfo(i.LocalFileName);
                return "File uploaded as " + info.FullName + " (" + info.Length + ")";
            });
            return fileInfo;

        });
        return task;
    }
    else
    {
        throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
    }
}

And the Custom MyMultipartFormDataStreamProvider, needed to customize the Filename:

PS: I took this code from another post http://www.codeguru.com/csharp/.net/uploading-files-asynchronously-using-asp.net-web-api.htm

public class MyMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
{
    public MyMultipartFormDataStreamProvider(string path)
        : base(path)
    {

    }

    public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
    {
        string fileName;
        if (!string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName))
        {
            fileName = headers.ContentDisposition.FileName;
        }
        else
        {
            fileName = Guid.NewGuid().ToString() + ".data";
        }
        return fileName.Replace("\"", string.Empty);
    }
}

Excel VBA function to print an array to the workbook

You can define a Range, the size of your array and use it's value property:

Sub PrintArray(Data, SheetName As String, intStartRow As Integer, intStartCol As Integer)

    Dim oWorksheet As Worksheet
    Dim rngCopyTo As Range
    Set oWorksheet = ActiveWorkbook.Worksheets(SheetName)

    ' size of array
    Dim intEndRow As Integer
    Dim intEndCol As Integer
    intEndRow = UBound(Data, 1)
    intEndCol = UBound(Data, 2)

    Set rngCopyTo = oWorksheet.Range(oWorksheet.Cells(intStartRow, intStartCol), oWorksheet.Cells(intEndRow, intEndCol))
    rngCopyTo.Value = Data

End Sub

Adding new column to existing DataFrame in Python pandas

to insert a new column at a given location (0 <= loc <= amount of columns) in a data frame, just use Dataframe.insert:

DataFrame.insert(loc, column, value)

Therefore, if you want to add the column e at the end of a data frame called df, you can use:

e = [-0.335485, -1.166658, -0.385571]    
DataFrame.insert(loc=len(df.columns), column='e', value=e)

value can be a Series, an integer (in which case all cells get filled with this one value), or an array-like structure

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.insert.html

HTML.HiddenFor value set

For setting value in hidden field do in the following way:

@Html.HiddenFor(model => model.title, 
                new { id= "natureOfVisitField", Value = @Model.title})

It will work

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

What is HTTP "Host" header?

The Host Header tells the webserver which virtual host to use (if set up). You can even have the same virtual host using several aliases (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up one vhost to be the default host. This default vhost is used whenever the host header does not match any of the configured virtual hosts.

That means: You get it right, although saying "multiple hosts" may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different domain names (including subdomains) that are also referred to as hostnames (but not hosts!).


Although not part of the question, a fun fact: This specification led to problems with SSL in early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one ssl-secured domain per IP address / port-combination.

This has been overcome with Server Name Indication; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see which hostname you are trying to connect to.

Although the webserver would know the hostname from Server Name Indication, the Host header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the Host header is still valid (and necessary).

Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one Host header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing METHOD RESOURCE and PROTOCOL VERSION and at least the Host header, like this:

GET /someresource.html HTTP/1.1
Host: www.example.com

In the MDN Documentation on the "Host" header they actually phrase it like this:

A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.

As mentioned by Darrel Miller, the complete specs can be found in RFC7230.

How can I style the border and title bar of a window in WPF?

You need to set

WindowStyle="None", AllowsTransparency="True" and optionally ResizeMode="NoResize"
and then set the Style property of the window to your custom window style, where you design the appearance of the window (title bar, buttons, border) to anything you want and display the window contents in a ContentPresenter.

This seems to be a good article on how you can achieve this, but there are many other articles on the internet.

json_encode is returning NULL?

For me, an issue where json_encode would return null encoding of an entity was because my jsonSerialize implementation fetched entire objects for related entities; I solved the issue by making sure that I fetched the ID of the related/associated entity and called ->toArray() when there were more than one entity associated with the object to be json serialized. Note, I'm speaking about cases where one implements JsonSerializable on entities.

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

Displaying all table names in php from MySQL database

Queries should look like :

SHOW TABLES

SHOW TABLES FROM mydatabase

SHOW TABLES FROM mydatabase LIKE "tab%"

Things from the MySQL documentation in square brackets [] are optional.

check if directory exists and delete in one command unix

Assuming $WORKING_DIR is set to the directory... this one-liner should do it:

if [ -d "$WORKING_DIR" ]; then rm -Rf $WORKING_DIR; fi

(otherwise just replace with your directory)

Read url to string in few lines of java code

The following works with Java 7/8, secure urls, and shows how to add a cookie to your request as well. Note this is mostly a direct copy of this other great answer on this page, but added the cookie example, and clarification in that it works with secure urls as well ;-)

If you need to connect to a server with an invalid certificate or self signed certificate, this will throw security errors unless you import the certificate. If you need this functionality, you could consider the approach detailed in this answer to this related question on StackOverflow.

Example

String result = getUrlAsString("https://www.google.com");
System.out.println(result);

outputs

<!doctype html><html itemscope="" .... etc

Code

import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public static String getUrlAsString(String url)
{
    try
    {
        URL urlObj = new URL(url);
        URLConnection con = urlObj.openConnection();

        con.setDoOutput(true); // we want the response 
        con.setRequestProperty("Cookie", "myCookie=test123");
        con.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        String newLine = System.getProperty("line.separator");
        while ((inputLine = in.readLine()) != null)
        {
            response.append(inputLine + newLine);
        }

        in.close();

        return response.toString();
    }
    catch (Exception e)
    {
        throw new RuntimeException(e);
    }
}

Open another application from your own (intent)

Open application if it is exist, or open Play Store application for install it:

private void open() {
    openApplication(getActivity(), "com.app.package.here");
}

public void openApplication(Context context, String packageN) {
    Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
    if (i != null) {
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
        }
    }
}

Git fetch remote branch

What helped me was

1) To view all available remote branches (e.g. 'remote-branch-name')

git branch -r

2) Create a local branch using remote branch name

git fetch && git checkout 'remote-branch-name'

Can I override and overload static methods in Java?

As any static method is part of class not instance so it is not possible to override static method

Best way to check if MySQL results returned in PHP?

Usually I use the === (triple equals) and __LINE__ , __CLASS__ to locate the error in my code:

$query=mysql_query('SELECT champ FROM table')
or die("SQL Error line  ".__LINE__ ." class ".__CLASS__." : ".mysql_error());

mysql_close();

if(mysql_num_rows($query)===0)
{
    PERFORM ACTION;
}
else
{
    while($r=mysql_fetch_row($query))
    {
          PERFORM ACTION;
    }
}

Python: How to create a unique file name?

This can be done using the unique function in ufp.path module.

import ufp.path
ufp.path.unique('./test.ext')

if current path exists 'test.ext' file. ufp.path.unique function return './test (d1).ext'.

Run cURL commands from Windows console

I was able to use this site to easily download and install curl on my Windows machine. It took all of 30 seconds. I'm using Windows 7 (w/ Admin privelages), so I downloaded curl-7.37.0-win64.msi from http://curl.haxx.se/download.html.

Also, don't forget to restart your console/terminal after you install curl, otherwise you will get the same error messages.

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Can't install Scipy through pip

I face same problem when install Scipy under ubuntu.
I had to use command:

$ sudo apt-get install libatlas-base-dev gfortran
$ sudo pip3 install scipy

You can get more details here Installing SciPy with pip
Sorry don't know how to do it under OS X Yosemite.

Microsoft.ACE.OLEDB.12.0 provider is not registered

I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.

after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.

repaint() in Java

You may need to call frame.repaint() as well to force the frame to actually redraw itself. I've had issues before where I tried to repaint a component and it wasn't updating what was displayed until the parent's repaint() method was called.

Radio buttons not checked in jQuery

$('input:radio[checked=false]');

this will also work

input:radio:not(:checked)

or

:radio:not(:checked)

Javascript date regex DD/MM/YYYY

For people who needs to validate years earlier than year 1900, following should do the trick. Actually this is same as the above answer given by [@OammieR][1] BUT with years including 1800 - 1899.

/^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((18|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((18|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$/

Hope this helps someone who needs to validate years earlier than 1900, such as 01/01/1855, etc.

Thanks @OammieR for the initial idea.

DropDownList in MVC 4 with Razor

This can also be done like

@model IEnumerable<ItemList>

_x000D_
_x000D_
<select id="dropdowntipo">_x000D_
    <option value="0">Select Item</option>_x000D_
    _x000D_
    @{_x000D_
      foreach(var item in Model)_x000D_
      {_x000D_
        <option value= "@item.Value">@item.DisplayText</option>_x000D_
      }_x000D_
    }_x000D_
_x000D_
</select>
_x000D_
_x000D_
_x000D_

how to check and set max_allowed_packet mysql variable

goto cpanel and login as Main Admin or Super Administrator

  1. find SSH/Shell Access ( you will find under the security tab of cpanel )

  2. now give the username and password of Super Administrator as root or whatyougave

    note: do not give any username, cos, it needs permissions
    
  3. once your into console type

    type ' mysql ' and press enter now you find youself in

    mysql> /* and type here like */

    mysql> set global net_buffer_length=1000000;

    Query OK, 0 rows affected (0.00 sec)

    mysql> set global max_allowed_packet=1000000000;

    Query OK, 0 rows affected (0.00 sec)

Now upload and enjoy!!!

How to limit the maximum files chosen when using multiple file input

This should work and protect your form from being submitted if the number of files is greater then max_file_number.

$(function() {

  var // Define maximum number of files.
      max_file_number = 3,
      // Define your form id or class or just tag.
      $form = $('form'), 
      // Define your upload field class or id or tag.
      $file_upload = $('#image_upload', $form), 
      // Define your submit class or id or tag.
      $button = $('.submit', $form); 

  // Disable submit button on page ready.
  $button.prop('disabled', 'disabled');

  $file_upload.on('change', function () {
    var number_of_images = $(this)[0].files.length;
    if (number_of_images > max_file_number) {
      alert(`You can upload maximum ${max_file_number} files.`);
      $(this).val('');
      $button.prop('disabled', 'disabled');
    } else {
      $button.prop('disabled', false);
    }
  });
});

HashMaps and Null values?

You can keep note of below possibilities:

1. Values entered in a map can be null.

However with multiple null keys and values it will only take a null key value pair once.

Map<String, String> codes = new HashMap<String, String>();

codes.put(null, null);
codes.put(null,null);
codes.put("C1", "Acathan");

for(String key:codes.keySet()){
    System.out.println(key);
    System.out.println(codes.get(key));
}

output will be :

null //key  of the 1st entry
null //value of 1st entry
C1
Acathan

2. your code will execute null only once

options.put(null, null);  
Person person = sample.searchPerson(null);   

It depends on the implementation of your searchPerson method if you want multiple values to be null, you can implement accordingly

Map<String, String> codes = new HashMap<String, String>();

    codes.put(null, null);
    codes.put("X1",null);
    codes.put("C1", "Acathan");
    codes.put("S1",null);


    for(String key:codes.keySet()){
        System.out.println(key);
        System.out.println(codes.get(key));
    }

output:

null
null

X1
null
S1
null
C1
Acathan

Escaping special characters in Java Regular Expressions

Is there any method in Java or any open source library for escaping (not quoting) a special character (meta-character), in order to use it as a regular expression?

If you are looking for a way to create constants that you can use in your regex patterns, then just prepending them with "\\" should work but there is no nice Pattern.escape('.') function to help with this.

So if you are trying to match "\\d" (the string \d instead of a decimal character) then you would do:

// this will match on \d as opposed to a decimal character
String matchBackslashD = "\\\\d";
// as opposed to
String matchDecimalDigit = "\\d";

The 4 slashes in the Java string turn into 2 slashes in the regex pattern. 2 backslashes in a regex pattern matches the backslash itself. Prepending any special character with backslash turns it into a normal character instead of a special one.

matchPeriod = "\\.";
matchPlus = "\\+";
matchParens = "\\(\\)";
... 

In your post you use the Pattern.quote(string) method. This method wraps your pattern between "\\Q" and "\\E" so you can match a string even if it happens to have a special regex character in it (+, ., \\d, etc.)

JavaScript math, round to two decimal places

try using discount.toFixed(2);

How do I create a simple Qt console application in C++?

You can call QCoreApplication::exit(0) to exit with code 0

Python: fastest way to create a list of n lists

The probably only way which is marginally faster than

d = [[] for x in xrange(n)]

is

from itertools import repeat
d = [[] for i in repeat(None, n)]

It does not have to create a new int object in every iteration and is about 15 % faster on my machine.

Edit: Using NumPy, you can avoid the Python loop using

d = numpy.empty((n, 0)).tolist()

but this is actually 2.5 times slower than the list comprehension.

c# datatable insert column at position 0

    //Example to define how to do :

    DataTable dt = new DataTable();   

    dt.Columns.Add("ID");
    dt.Columns.Add("FirstName");
    dt.Columns.Add("LastName");
    dt.Columns.Add("Address");
    dt.Columns.Add("City");
           //  The table structure is:
            //ID    FirstName   LastName    Address     City

       //Now we want to add a PhoneNo column after the LastName column. For this we use the                               
             //SetOrdinal function, as iin:
        dt.Columns.Add("PhoneNo").SetOrdinal(3);

            //3 is the position number and positions start from 0.`enter code here`

               //Now the table structure will be:
              // ID      FirstName   LastName    PhoneNo    Address     City

Good Free Alternative To MS Access

VistaDB has an express version which is free to use and is syntax and driver compatible with SQL Server. VistaDB is a single file and only requires their driver .dll to work in your asp.net or winforms project.

Since it is syntax and datasource compatible you can upgrade to SQL Server if needed.

from their site:

VistaDB is a fully managed and typesafe ASP.NET and WinForms applications using C#, VB.NET and other CLR-compliant languages.

VistaDB.net

Uploading images using Node.js, Express, and Mongoose

Again if you don't want to use bodyParser, the following works:

var express = require('express');
var http = require('http');
var app = express();

app.use(express.static('./public'));


app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.multipart({
        uploadDir: './uploads',
        keepExtensions: true
    }));
});


app.use(app.router);

app.get('/upload', function(req, res){
    // Render page with upload form
    res.render('upload');
});

app.post('/upload', function(req, res){
    // Returns json of uploaded file
    res.json(req.files);
});

http.createServer(app).listen(3000, function() {
    console.log('App started');
});

How are parameters sent in an HTTP POST request?

First of all, let's differentiate between GET and POST

Get: It is the default HTTP request that is made to the server and is used to retrieve the data from the server and query string that comes after ? in a URI is used to retrieve a unique resource.

this is the format

GET /someweb.asp?data=value HTTP/1.0

here data=value is the query string value passed.

POST: It is used to send data to the server safely so anything that is needed, this is the format of a POST request

POST /somweb.aspHTTP/1.0
Host: localhost
Content-Type: application/x-www-form-urlencoded //you can put any format here
Content-Length: 11 //it depends
Name= somename

Why POST over GET?

In GET the value being sent to the servers are usually appended to the base URL in the query string,now there are 2 consequences of this

  • The GET requests are saved in browser history with the parameters. So your passwords remain un-encrypted in browser history. This was a real issue for Facebook back in the days.
  • Usually servers have a limit on how long a URI can be. If have too many parameters being sent you might receive 414 Error - URI too long

In case of post request your data from the fields are added to the body instead. Length of request params is calculated, and added to the header for content-length and no important data is directly appended to the URL.

You can use the Google Developer Tools' network section to see basic information about how requests are made to the servers.

and you can always add more values in your Request Headers like Cache-Control , Origin , Accept.

Is it better practice to use String.format over string Concatenation in Java?

Since there is discussion about performance I figured I'd add in a comparison that included StringBuilder. It is in fact faster than the concat and, naturally the String.format option.

To make this a sort of apples to apples comparison I instantiate a new StringBuilder in the loop rather than outside (this is actually faster than doing just one instantiation most likely due to the overhead of re-allocating space for the looping append at the end of one builder).

    String formatString = "Hi %s; Hi to you %s";

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        String s = String.format(formatString, i, +i * 2);
    }

    long end = System.currentTimeMillis();
    log.info("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        String s = "Hi " + i + "; Hi to you " + i * 2;
    }

    end = System.currentTimeMillis();

    log.info("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        StringBuilder bldString = new StringBuilder("Hi ");
        bldString.append(i).append("; Hi to you ").append(i * 2);
    }

    end = System.currentTimeMillis();

    log.info("String Builder = " + ((end - start)) + " millisecond");
  • 2012-01-11 16:30:46,058 INFO [TestMain] - Format = 1416 millisecond
  • 2012-01-11 16:30:46,190 INFO [TestMain] - Concatenation = 134 millisecond
  • 2012-01-11 16:30:46,313 INFO [TestMain] - String Builder = 117 millisecond

Html code as IFRAME source rather than a URL

You can do this with a data URL. This includes the entire document in a single string of HTML. For example, the following HTML:

<html><body>foo</body></html>

can be encoded as this:

data:text/html;charset=utf-8,%3Chtml%3E%3Cbody%3Efoo%3C/body%3E%3C/html%3E

and then set as the src attribute of the iframe. Example.


Edit: The other alternative is to do this with Javascript. This is almost certainly the technique I'd choose. You can't guarantee how long a data URL the browser will accept. The Javascript technique would look something like this:

var iframe = document.getElementById('foo'),
    iframedoc = iframe.contentDocument || iframe.contentWindow.document;

iframedoc.body.innerHTML = 'Hello world';

Example


Edit 2 (December 2017): use the Html5's srcdoc attribute, just like in Saurabh Chandra Patel's answer, who now should be the accepted answer! If you can detect IE/Edge efficiently, a tip is to use srcdoc-polyfill library only for them and the "pure" srcdoc attribute in all non-IE/Edge browsers (check caniuse.com to be sure).

<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>

Finding absolute value of a number without using Math.abs()

If you look inside Math.abs you can probably find the best answer:

Eg, for floats:

    /*
     * Returns the absolute value of a {@code float} value.
     * If the argument is not negative, the argument is returned.
     * If the argument is negative, the negation of the argument is returned.
     * Special cases:
     * <ul><li>If the argument is positive zero or negative zero, the
     * result is positive zero.
     * <li>If the argument is infinite, the result is positive infinity.
     * <li>If the argument is NaN, the result is NaN.</ul>
     * In other words, the result is the same as the value of the expression:
     * <p>{@code Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a))}
     *
     * @param   a   the argument whose absolute value is to be determined
     * @return  the absolute value of the argument.
     */
    public static float abs(float a) {
        return (a <= 0.0F) ? 0.0F - a : a;
    }

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

This link has solution of how to get it working. Removing "pom.xml" from the "Profiles:" line and then click "Run".

How can I determine if a .NET assembly was built for x86 or x64?

Below is a batch file that will run corflags.exe against all dlls and exes in the current working directory and all sub-directories, parse the results and display the target architecture of each.

Depending on the version of corflags.exe that is used, the line items in the output will either include 32BIT, or 32BITREQ (and 32BITPREF). Whichever of these two is included in the output is the critical line item that must be checked to differentiate between Any CPU and x86. If you are using an older version of corflags.exe (pre Windows SDK v8.0A), then only the 32BIT line item will be present in the output, as others have indicated in past answers. Otherwise 32BITREQ and 32BITPREF replace it.

This assumes corflags.exe is in the %PATH%. The simplest way to ensure this is to use a Developer Command Prompt. Alternatively you could copy it from it's default location.

If the batch file below is run against an unmanaged dll or exe, it will incorrectly display it as x86, since the actual output from Corflags.exe will be an error message similar to:

corflags : error CF008 : The specified file does not have a valid managed header

@echo off

echo.
echo Target architecture for all exes and dlls:
echo.

REM For each exe and dll in this directory and all subdirectories...
for %%a in (.exe, .dll) do forfiles /s /m *%%a /c "cmd /c echo @relpath" > testfiles.txt

for /f %%b in (testfiles.txt) do (
    REM Dump corflags results to a text file
    corflags /nologo %%b > corflagsdeets.txt

   REM Parse the corflags results to look for key markers   
   findstr /C:"PE32+">nul .\corflagsdeets.txt && (      
      REM `PE32+` indicates x64
        echo %%~b = x64
    ) || (
      REM pre-v8 Windows SDK listed only "32BIT" line item, 
      REM newer versions list "32BITREQ" and "32BITPREF" line items
        findstr /C:"32BITREQ  : 0">nul /C:"32BIT     : 0" .\corflagsdeets.txt && (
            REM `PE32` and NOT 32bit required indicates Any CPU
            echo %%~b = Any CPU
        ) || (
            REM `PE32` and 32bit required indicates x86
            echo %%~b = x86
        )
    )

    del corflagsdeets.txt
)

del testfiles.txt
echo.

Bootstrap Datepicker - Months and Years Only

I'm using version 2(supports both bootstrap v2 and v3) and for me this works:

$("#datepicker").datepicker( {
    format: "mm/yyyy",
    startView: "year", 
    minView: "year"
});

How to hide underbar in EditText

Set background to null.

android:background="@null"

MySQL - How to select rows where value is in array?

If the array element is not integer you can use something like below :

$skus  = array('LDRES10','LDRES12','LDRES11');   //sample data

if(!empty($skus)){     
    $sql = "SELECT * FROM `products` WHERE `prodCode` IN ('" . implode("','", $skus) . "') "      
}

what does -zxvf mean in tar -zxvf <filename>?

  • z means (un)z_ip.
  • x means ex_tract files from the archive.
  • v means print the filenames v_erbosely.
  • f means the following argument is a f_ilename.

For more details, see tar's man page.

Is it possible to hide/encode/encrypt php source code and let others have the system?

You could just split the frontend and backend. The frontend is hosted on the customers server with an API that makes calls to the backend on your server. This keeps all of the proprietary code proprietary and forces users to sign up / pay for subscriptions.

Sending intent to BroadcastReceiver from adb

As many already noticed, the problem manifests itself only if the extra string contains whitespaces.

The root cause is that OP's host OS/shell (i.e. Windows/cmd.exe) mangles the entered command - the " characters get lost, --es sms_body "test from adb" becomes --es sms_body test from adb. Which results in sms_body string extra getting assigned the value of test and the rest of the string becoming <URI>|<PACKAGE>|<COMPONENT> specifier.

To avoid all that you could use:

adb shell "am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body 'test from adb' -n com.whereismywifeserver/.IntentReceiver"

or just start the interactive adb shell session first and run the am broadcast command from inside of it.

How to set JAVA_HOME path on Ubuntu?

add JAVA_HOME to the file:

/etc/environment

for it to be available to the entire system (you would need to restart Ubuntu though)

Linux command (like cat) to read a specified quantity of characters

I know the answer is in reply to a question asked 6 years ago ...

But I was looking for something similar for a few hours and then found out that: cut -c does exactly that, with an added bonus that you could also specify an offset.

cut -c 1-5 will return Hello and cut -c 7-11 will return world. No need for any other command

How to create a hash or dictionary object in JavaScript

You want to create an Object, not an Array.

Like so,

var Map = {};

Map['key1'] = 'value1';
Map['key2'] = 'value2';

You can check if the key exists in multiple ways:

Map.hasOwnProperty(key);
Map[key] != undefined // For illustration // Edit, remove null check
if (key in Map) ...

How to pass data from 2nd activity to 1st activity when pressed back? - android

this is your first Activity1.

public class Activity1 extends Activity{
private int mRequestCode = 100;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(this, Activity2.class);
    startActivityForResult(intent, mRequestCode);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == mRequestCode && resultCode == RESULT_OK){
        String editTextString = data.getStringExtra("editText");
    }
}
}

From here you are starting your Activity2.class by using startActivityForResult(mRequestCode, Activity2.class);

Now this is your second Activity, name is Activity2

public class Activity2 extends Activity {
private EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //mEditText = (EditText)findViewById(R.id.edit_text);

    Intent intent = new Intent();
    intent.putExtra("editText", mEditText.getText().toString());
    setResult(RESULT_OK, intent);
}

}

Now when you done with your second Activity then you call setResult() method, from onBackPress() or from any button click when your Activity2 will destroy then your Activity1's call back method onActivityResult() will call from there you can get your data from intent..

Hope it will help to you...:)

Which mime type should I use for mp3

The standard way is to use audio/mpeg which is something like this in your PHP header function ...

header('Content-Type: audio/mpeg');

How do you run a command for each line of a file?

You can also use AWK which can give you more flexibility to handle the file

awk '{ print "chmod 755 "$0"" | "/bin/sh"}' file.txt

if your file has a field separator like:

field1,field2,field3

To get only the first field you do

awk -F, '{ print "chmod 755 "$1"" | "/bin/sh"}' file.txt

You can check more details on GNU Documentation https://www.gnu.org/software/gawk/manual/html_node/Very-Simple.html#Very-Simple

How do you completely remove the button border in wpf?

I don't know why others haven't pointed out that this question is duplicated with this one with accepted answer.

I quote here the solution: You need to override the ControlTemplate of the Button:

<Button Content="save" Name="btnSaveEditedText" 
                Background="Transparent" 
                Foreground="White" 
                FontFamily="Tw Cen MT Condensed" 
                FontSize="30" 
                Margin="-280,0,0,10"
                Width="60"
                BorderBrush="Transparent"
                BorderThickness="0">
    <Button.Template>
        <ControlTemplate TargetType="Button">
             <ContentPresenter Content="{TemplateBinding Content}"/>
        </ControlTemplate>
    </Button.Template>  
</Button>

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

var self = this?

I think it actually depends on what are you going to do inside your doSomething function. If you are going to access MyObject properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject) properties.

function doSomething(){
  .........
}

$("#foobar").ready('click', function(){

});

Linking to an external URL in Javadoc?

Hard to find a clear answer from the Oracle site. The following is from javax.ws.rs.core.HttpHeaders.java:

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT = "Accept";

/**
 * See {@link <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.2">HTTP/1.1 documentation</a>}.
 */
public static final String ACCEPT_CHARSET = "Accept-Charset";

How can I add a PHP page to WordPress?

If you don't want to deal with the WordPress API, then Adam's answer is really the best one.

If you were willing to deal with the API I would suggest hooking into the "template-redirect" hook, which would allow you to point a particular URL or page to an arbitrary PHP file while still having access to WordPress.

Install Android App Bundle on device

No, if you are debugging an app without other users use the Build > Build APK(s) menu in Android Studio or execute it in your device/emulator them the debug release apk will install automatically. If you are debugging an app with others use Build > Generate Signed APK... menu. If you want to publish the beta version use the Google Play Store. Your APK(s) will be in app\build\outputs\apk\debug and app\release folders.

How do I access call log for android?

This post is a little bit old, but here is another easy solution for getting data related to Call logs content provider in Android:

Use this lib: https://github.com/EverythingMe/easy-content-providers

Get all calls:

CallsProvider callsProvider = new CallsProvider(context);
List<Call> calls = callsProvider.getCalls().getList();

Each Call has all fields, so you can get any info you need:
callDate, duration, number, type(INCOMING, OUTGOING, MISSED), isRead, ...

It works with List or Cursor and there is a sample app to see how it looks and works.

In fact, there is a support for all Android content providers like: Contacts, SMS, Calendar, ... Full doc with all options: https://github.com/EverythingMe/easy-content-providers/wiki/Android-providers

Hope it also helped :)

Update GCC on OSX

I know it is an old request. But it might still be useful to some. With current versions of MacPorts, you can choose the default gcc version using the port command. To list the available versions of gcc, use:

$ sudo port select --list gcc

Available versions for gcc:
gcc42
llvm-gcc42
mp-gcc46
none (active)

To set gcc to the MacPorts version:

$ sudo port select --set gcc mp-gcc46

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

How can I export the schema of a database in PostgreSQL?

pg_dump -s databasename -t tablename -U user -h host -p port > tablename.sql

this will limit the schema dump to the table "tablename" of "databasename"

Convert string to variable name in JavaScript

It can be done like this

_x000D_
_x000D_
(function(X, Y) {_x000D_
  _x000D_
  // X is the local name of the 'class'_x000D_
  // Doo is default value if param X is empty_x000D_
  var X = (typeof X == 'string') ? X: 'Doo';_x000D_
  var Y = (typeof Y == 'string') ? Y: 'doo';_x000D_
  _x000D_
  // this refers to the local X defined above_x000D_
  this[X] = function(doo) {_x000D_
    // object variable_x000D_
    this.doo = doo || 'doo it';_x000D_
  }_x000D_
  // prototypal inheritance for methods_x000D_
  // defined by another_x000D_
  this[X].prototype[Y] = function() {_x000D_
    return this.doo || 'doo';_x000D_
  };_x000D_
  _x000D_
  // make X global_x000D_
  window[X] = this[X];_x000D_
}('Dooa', 'dooa')); // give the names here_x000D_
_x000D_
// test_x000D_
doo = new Dooa('abc');_x000D_
doo2 = new Dooa('def');_x000D_
console.log(doo.dooa());_x000D_
console.log(doo2.dooa());
_x000D_
_x000D_
_x000D_

Select first and last row from grouped data

using which.min and which.max :

library(dplyr, warn.conflicts = F)
df %>% 
  group_by(id) %>% 
  slice(c(which.min(stopSequence), which.max(stopSequence)))

#> # A tibble: 6 x 3
#> # Groups:   id [3]
#>      id stopId stopSequence
#>   <dbl> <fct>         <dbl>
#> 1     1 a                 1
#> 2     1 c                 3
#> 3     2 b                 1
#> 4     2 c                 4
#> 5     3 b                 1
#> 6     3 a                 3

benchmark

It is also much faster than the current accepted answer because we find the min and max value by group, instead of sorting the whole stopSequence column.

# create a 100k times longer data frame
df2 <- bind_rows(replicate(1e5, df, F)) 
bench::mark(
  mm =df2 %>% 
    group_by(id) %>% 
    slice(c(which.min(stopSequence), which.max(stopSequence))),
  jeremy = df2 %>%
    group_by(id) %>%
    arrange(stopSequence) %>%
    filter(row_number()==1 | row_number()==n()))
#> Warning: Some expressions had a GC in every iteration; so filtering is disabled.
#> # A tibble: 2 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 mm           22.6ms     27ms     34.9     14.2MB     21.3
#> 2 jeremy      254.3ms    273ms      3.66    58.4MB     11.0

Increasing the maximum post size

You can increase that in php.ini

; Maximum allowed size for uploaded files.
upload_max_filesize = 2M

Angular HttpClient "Http failure during parsing"

I was facing the same issue in my Angular application. I was using RocketChat REST API in my application and I was trying to use the rooms.createDiscussion, but as an error as below.

ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"myurl/rocketchat/api/v1/rooms.createDiscussion","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for myrul/rocketchat/api/v1/rooms.createDiscussion","error":{"error":{},"text":"

I have tried couple of things like changing the responseType: 'text' but none of them worked. At the end I was able to find the issue was with my RocketChat installation. As mentioned in the RocketChat change log the API rooms.createDiscussion is been introduced in the version 1.0.0 unfortunately I was using a lower version.

My suggestion is to check the REST API is working fine or not before you spend time to fix the error in your Angular code. I used curl command to check that.

curl -H "X-Auth-Token: token" -H "X-User-Id: userid" -H "Content-Type: application/json" myurl/rocketchat/api/v1/rooms.createDiscussion -d '{ "prid": "GENERAL", "t_name": "Discussion Name"}'

There as well I was getting an invalid HTML as a response.

<!DOCTYPE html>
<html>
<head>
<meta name="referrer" content="origin-when-crossorigin">
<script>/* eslint-disable */

'use strict';
(function() {
        var debounce = function debounce(func, wait, immediate) {

Instead of a valid JSON response as follows.

{
    "discussion": {
        "rid": "cgk88DHLHexwMaFWh",
        "name": "WJNEAM7W45wRYitHo",
        "fname": "Discussion Name",
        "t": "p",
        "msgs": 0,
        "usersCount": 0,
        "u": {
            "_id": "rocketchat.internal.admin.test",
            "username": "rocketchat.internal.admin.test"
        },
        "topic": "general",
        "prid": "GENERAL",
        "ts": "2019-04-03T01:35:32.271Z",
        "ro": false,
        "sysMes": true,
        "default": false,
        "_updatedAt": "2019-04-03T01:35:32.280Z",
        "_id": "cgk88DHLHexwMaFWh"
    },
    "success": true
}

So after updating to the latest RocketChat I was able to use the mentioned REST API.

Fastest way to check if a file exist using standard C++/C++11/C?

I need a fast function that can check if a file is exist or not and PherricOxide's answer is almost what I need except it does not compare the performance of boost::filesystem::exists and open functions. From the benchmark results we can easily see that :

  • Using stat function is the fastest way to check if a file is exist. Note that my results are consistent with that of PherricOxide's answer.

  • The performance of boost::filesystem::exists function is very close to that of stat function and it is also portable. I would recommend this solution if boost libraries is accessible from your code.

Benchmark results obtained with Linux kernel 4.17.0 and gcc-7.3:

2018-05-05 00:35:35
Running ./filesystem
Run on (8 X 2661 MHz CPU s)
CPU Caches:
  L1 Data 32K (x4)
  L1 Instruction 32K (x4)
  L2 Unified 256K (x4)
  L3 Unified 8192K (x1)
--------------------------------------------------
Benchmark           Time           CPU Iterations
--------------------------------------------------
use_stat          815 ns        813 ns     861291
use_open         2007 ns       1919 ns     346273
use_access       1186 ns       1006 ns     683024
use_boost         831 ns        830 ns     831233

Below is my benchmark code:

#include <string.h>                                                                                                                                                                                                                                           
#include <stdlib.h>                                                                                                                                                                                                                                           
#include <sys/types.h>                                                                                                                                                                                                                                        
#include <sys/stat.h>                                                                                                                                                                                                                                         
#include <unistd.h>                                                                                                                                                                                                                                           
#include <dirent.h>                                                                                                                                                                                                                                           
#include <fcntl.h>                                                                                                                                                                                                                                            
#include <unistd.h>                                                                                                                                                                                                                                           

#include "boost/filesystem.hpp"                                                                                                                                                                                                                               

#include <benchmark/benchmark.h>                                                                                                                                                                                                                              

const std::string fname("filesystem.cpp");                                                                                                                                                                                                                    
struct stat buf;                                                                                                                                                                                                                                              

// Use stat function                                                                                                                                                                                                                                          
void use_stat(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(stat(fname.data(), &buf));                                                                                                                                                                                                   
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_stat);                                                                                                                                                                                                                                          

// Use open function                                                                                                                                                                                                                                          
void use_open(benchmark::State &state) {                                                                                                                                                                                                                      
    for (auto _ : state) {                                                                                                                                                                                                                                    
        int fd = open(fname.data(), O_RDONLY);                                                                                                                                                                                                                
        if (fd > -1) close(fd);                                                                                                                                                                                                                               
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_open);                                  
// Use access function                                                                                                                                                                                                                                        
void use_access(benchmark::State &state) {                                                                                                                                                                                                                    
    for (auto _ : state) {                                                                                                                                                                                                                                    
        benchmark::DoNotOptimize(access(fname.data(), R_OK));                                                                                                                                                                                                 
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_access);                                                                                                                                                                                                                                        

// Use boost                                                                                                                                                                                                                                                  
void use_boost(benchmark::State &state) {                                                                                                                                                                                                                     
    for (auto _ : state) {                                                                                                                                                                                                                                    
        boost::filesystem::path p(fname);                                                                                                                                                                                                                     
        benchmark::DoNotOptimize(boost::filesystem::exists(p));                                                                                                                                                                                               
    }                                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                             
BENCHMARK(use_boost);                                                                                                                                                                                                                                         

BENCHMARK_MAIN();   

Getting attribute using XPath

Here is the snippet of getting the attribute value of "lang" with XPath and VTD-XML.

import com.ximpleware.*;
public class getAttrVal {
    public static void main(String s[]) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false)){
            return ;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/bookstore/book/title/@lang");
        System.out.println(" lang's value is ===>"+ap.evalXPathToString());
    }
}

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

The solution is to add your variable to /etc/profile. Then everything works as expected! Of course you MUST do it as a root user with sudo nano /etc/profile. If you edit it with any other way the system will complain with a damaged /etc/profile, even if you change the permissions to root.

changing minDate option in JQuery DatePicker not working

Say we have two date select fields, field1, and field2. field2 date depends on field1

$('#field2').datepicker();
$('#field1').datepicker({
  onSelect: function(dateText, inst) {
    $('#field2').val("");
    $('#field2').datepicker("option", "minDate", new Date(dateText));
  }
});

Is it possible to get element from HashMap by its position?

HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.

php hide ALL errors

The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!

If you want to hide them anyway: error_reporting(0);

Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

Using Case/Switch and GetType to determine the object

You can do this:

if (node is CasusNodeDTO)
{
    ...
}
else if (node is BucketNodeDTO)
{
    ...
}
...

While that would be more elegant, it's possibly not as efficient as some of the other answers here.

jQuery - multiple $(document).ready ...?

All will get executed and On first Called first run basis!!

<div id="target"></div>

<script>
  $(document).ready(function(){
    jQuery('#target').append('target edit 1<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 2<br>');
  });
  $(document).ready(function(){
    jQuery('#target').append('target edit 3<br>');
  });
</script>

Demo As you can see they do not replace each other

Also one thing i would like to mention

in place of this

$(document).ready(function(){});

you can use this shortcut

jQuery(function(){
   //dom ready codes
});

How do you 'redo' changes after 'undo' with Emacs?

Beware of an undo-tree quirk for redo!

Many popular “starter kits” (prelude, purcell, spacemacs) come bundled with undo-tree. Most (all?) even auto-enable it. As mentioned, undo-tree is a handy way to visualize and traverse the undo/redo tree. Prelude even gives it a key-chord (uu), and also C-x u.

The problem is: undo-tree seems to wreck Emacs’ default and well-known binding for redo: C-g C-/.

Instead, you can use these symmetrical keys for undo/redo:

C-/     undo
C-S-/   redo

These are useful since sometimes you want to quickly redo without opening up the visualizer.

node and Error: EMFILE, too many open files

Use the latest fs-extra.

I had that problem on Ubuntu (16 and 18) with plenty of file/socket-descriptors space (count with lsof |wc -l). Used fs-extra version 8.1.0. After the update to 9.0.0 the "Error: EMFILE, too many open files" vanished.

I've experienced diverse problems on diverse OS' with node handling filesystems. Filesystems are obviously not trivial.

Show hide fragment in android

public void showHideFragment(final Fragment fragment){

    FragmentTransaction ft = getFragmentManager().beginTransaction();
    ft.setCustomAnimations(android.R.animator.fade_in,
                    android.R.animator.fade_out);

    if (fragment.isHidden()) {
        ft.show(fragment);
        Log.d("hidden","Show");
    } else {
        ft.hide(fragment);
        Log.d("Shown","Hide");                        
    }

    ft.commit();
}

How can I list all of the files in a directory with Perl?

This will list Everything (including sub directories) from the directory you specify, in order, and with the attributes. I have spent days looking for something to do this, and I took parts from this entire discussion, and a little of my own, and put it together. ENJOY!!

#!/usr/bin/perl --
print qq~Content-type: text/html\n\n~;
print qq~<font face="arial" size="2">~;

use File::Find;

# find( \&wanted_tom, '/home/thomas/public_html'); # if you want just one website, uncomment this, and comment out the next line
find( \&wanted_tom, '/home');
exit;

sub wanted_tom {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat ($_);
$mode = (stat($_))[2];
$mode = substr(sprintf("%03lo", $mode), -3);

if (-d $File::Find::name) {
print "<br><b>--DIR $File::Find::name --ATTR:$mode</b><br>";
 } else {
print "$File::Find::name --ATTR:$mode<br>";
 }
  return;
}

Docker: Container keeps on restarting again on again

The docker logs command will show you the output a container is generating when you don't run it interactively. This is likely to include the error message.

docker logs --tail 50 --follow --timestamps mediawiki_web_1

You can also run a fresh container in the foreground with docker run -ti <your_wiki_image> to see what that does. You may need to map some config from your docker-compose yml to the docker command.

I would guess that attaching to the media wiki process caused a crash which has corrupted something in your data.

How to find length of digits in an integer?

Top answers are saying mathlog10 faster but I got results that suggest len(str(n)) is faster.

arr = []
for i in range(5000000):
    arr.append(random.randint(0,12345678901234567890))
%%timeit

for n in arr:
    len(str(n))
//2.72 s ± 304 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%%timeit

for n in arr:
    int(math.log10(n))+1
//3.13 s ± 545 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Besides, I haven't added logic to the math way to return accurate results and I can only imagine it slows it even more.

I have no idea how the previous answers proved the maths way is faster though.

How can I include css files using node, express, and ejs?

Use this in your server.js file

_x000D_
_x000D_
app.use(express.static('public'));
_x000D_
_x000D_
_x000D_

without the directory ( __dirname ) and then within your project folder create a new file and name it public then put all your static files inside it

How can I see an the output of my C programs using Dev-C++?

I put a getchar() at the end of my programs as a simple "pause-method". Depending on your particular details, investigate getchar, getch, or getc

What is an NP-complete in computer science?

NP stands for Non-deterministic Polynomial time.

This means that the problem can be solved in Polynomial time using a Non-deterministic Turing machine (like a regular Turing machine but also including a non-deterministic "choice" function). Basically, a solution has to be testable in poly time. If that's the case, and a known NP problem can be solved using the given problem with modified input (an NP problem can be reduced to the given problem) then the problem is NP complete.

The main thing to take away from an NP-complete problem is that it cannot be solved in polynomial time in any known way. NP-Hard/NP-Complete is a way of showing that certain classes of problems are not solvable in realistic time.

Edit: As others have noted, there are often approximate solutions for NP-Complete problems. In this case, the approximate solution usually gives an approximation bound using special notation which tells us how close the approximation is.

JQuery Datatables : Cannot read property 'aDataSort' of undefined

In my case I solved the problem by establishing a valid column number when applying the order property inside the script where you configure the data table.

var table = $('#mytable').DataTable({
     .
     .
     .
     order: [[ 1, "desc" ]],

How to check visibility of software keyboard in Android?

Maybe this will help you:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

How to POST the data from a modal form of Bootstrap?

I was facing same issue not able to post form without ajax. but found solution , hope it can help and someones time.

<form name="paymentitrform" id="paymentitrform" class="payment"
                    method="post"
                    action="abc.php">
          <input name="email" value="" placeholder="email" />
          <input type="hidden" name="planamount" id="planamount" value="0">
                                <input type="submit" onclick="form_submit() " value="Continue Payment" class="action"
                                    name="planform">

                </form>

You can submit post form, from bootstrap modal using below javascript/jquery code : call the below function onclick of input submit button

    function form_submit() {
        document.getElementById("paymentitrform").submit();
   }  

System.Data.OracleClient requires Oracle client software version 8.1.7

For me, the issue was some plugin in my Visual Studio started forcing my application into x64 64bit mode, so the Oracle driver wasn't being found as I had Oracle 32bit installed.

So if you are having this issue, try running Visual Studio in safemode (devenv /safemode). I could find that it was looking in SYSWOW64 for the ic.dll file by using the ProcMon app by SysInternals/Microsoft.

Update: For me it was the Telerik JustTrace product that was causing the issue, it was probably hooking in and affecting the runtime version somehow to do tracing.

Update2: It's not just JustTrace causing an issue, JustMock is causing the same processor mode issue. JustMock is easier to fix though: Click JustMock-> Disable Profiler and then my web app's oracle driver runs in the correct CPU mode. This might be fixed by Telerik in the future.

How to load image files with webpack file-loader

Install file loader first:

$ npm install file-loader --save-dev

And add this rule in webpack.config.js

           {
                test: /\.(png|jpg|gif)$/,
                use: [{
                    loader: 'file-loader',
                    options: {}
                }]
            }

MySQL: NOT LIKE

categories_posts and categories_news start with substring 'categories_' then it is enough to check that developer_configurations_cms.cfg_name_unique starts with 'categories' instead of check if it contains the given substring. Translating all that into a query:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE 'categories%'

How can I parse a YAML file in Python

I use ruamel.yaml. Details & debate here.

from ruamel import yaml

with open(filename, 'r') as fp:
    read_data = yaml.load(fp)

Usage of ruamel.yaml is compatible (with some simple solvable problems) with old usages of PyYAML and as it is stated in link I provided, use

from ruamel import yaml

instead of

import yaml

and it will fix most of your problems.

EDIT: PyYAML is not dead as it turns out, it's just maintained in a different place.