Programs & Examples On #Autofield

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

How to define two fields "unique" as couple

There is a simple solution for you called unique_together which does exactly what you want.

For example:

class MyModel(models.Model):
  field1 = models.CharField(max_length=50)
  field2 = models.CharField(max_length=50)

  class Meta:
    unique_together = ('field1', 'field2',)

And in your case:

class Volume(models.Model):
  id = models.AutoField(primary_key=True)
  journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
  volume_number = models.CharField('Volume Number', max_length=100)
  comments = models.TextField('Comments', max_length=4000, blank=True)

  class Meta:
    unique_together = ('journal_id', 'volume_number',)

Default value for field in Django model

You can set the default like this:

b = models.CharField(max_length=7,default="foobar")

and then you can hide the field with your model's Admin class like this:

class SomeModelAdmin(admin.ModelAdmin):
    exclude = ("b")

Java for loop syntax: "for (T obj : objects)"

The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.

Here is an example of this enhanced for loop from Java Tutorials

class EnhancedForDemo {
 public static void main(String[] args){
      int[] numbers = {1,2,3,4,5,6,7,8,9,10};
      for (int item : numbers) {
        System.out.println("Count is: " + item);
      }
 }
}

In this example, the variable item holds the current value from the numbers array.

Output is as follows:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

Hope this helps !

Android ListView with onClick items

In your activity, where you defined your listview

you write

listview.setOnItemClickListener(new OnItemClickListener(){   
    @Override
    public void onItemClick(AdapterView<?>adapter,View v, int position){
        ItemClicked item = adapter.getItemAtPosition(position);

        Intent intent = new Intent(Activity.this,destinationActivity.class);
        //based on item add info to intent
        startActivity(intent);
    }
});

in your adapter's getItem you write

public ItemClicked getItem(int position){
    return items.get(position);
}

Java get last element of a collection

A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.

Object lastElement = null;

for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
  lastElement = collectionItr.next();
}

Read file-contents into a string in C++

maybe not the most efficient, but reads data in one line:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}

How to fix corrupted git repository?

Before trying any of the fixes described on this page, I would advise to make a copy of your repo and work on this copy only. Then at the end if you can fix it, compare it with the original to ensure you did not lose any file in the repair process.

Another alternative which worked for me was to reset the git head and index to its previous state using:

git reset --keep

You can also do the same manually by opening the Git GUI and selecting each "Staged changes" and click on "Unstage the change". When everything is unstaged, you should now be able to compress your database, check your database and commit.

I also tried the following commands but they did not work for me, but they might for you depending on the exact issue you have:

git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all

Finally, to avoid this problem of synchronization damaging your git index (which can happen with DropBox, SpiderOak, or any other cloud disk), you can do the following:

  1. Convert your .git folder into a single "bundle" git file by using: git bundle create my_repo.git --all, then it should work just the same as before, but since everything is in a single file you won't risk the synchronization damaging your git repo anymore.
  2. Disable instantaneous synchronization: SpiderOak allows you to set the scheduling for checking changes to "automatic" (which means that it is as soon as possible, being monitoring file changes thanks to the OS notifications). This is bad because it will start to upload changes as soon as you are doing a change, and then download the change, so it might erase the latest changes you were just doing. A solution to fix this issue is to set the changes monitoring delay to 5 minutes or more. This also fixes issues with instant saving note taking applications (such as Notepad++).

PHP multidimensional array search by value

If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.

If you want just one result:

$key = array_search(40489, array_column($userdb, 'uid'));

For multiple results

$keys = array_keys(array_column($userdb, 'uid'), 40489);

In case you have an associative array as pointed in the comments you could make it with:

$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);

If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!

Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!

How to check if an email address is real or valid using PHP

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html

React-Router External link

Using React with Typescript you get an error as the function must return a react element, not void. So I did it this way using the Route render method (and using React router v4):

redirectToHomePage = (): null => {
    window.location.reload();
    return null;
  };    
<Route exact path={'/'} render={this.redirectToHomePage} />

Where you could instead also use window.location.assign(), window.location.replace() etc

How to get my activity context?

you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()

Should operator<< be implemented as a friend or as a member function?

It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.

I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md

The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).

As a quick fix in this particular situation you could just use the @transient annotation to tell it not to try to serialise the offending value (here, Spark.ctx is a custom class not Spark's one following OP's naming):

@transient
val rddList = Spark.ctx.parallelize(list)

You can also restructure code so that rddList lives somewhere else, but that is also nasty.

The Future is Probably Spores

In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.

http://docs.scala-lang.org/sips/pending/spores.html

A tip on Kryo serialization

When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:

"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."

Strategy for registering classes with kryo

Of course this only gives you type-level control not value-level control.

... more ideas to come.

Retrofit and GET using parameters

Complete working example in Kotlin, I have replaced my API keys with 1111...

        val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
        val params = HashMap<String, String>()
        params["q"] =  "munich,de"
        params["APPID"] = "11111111111111111"

        val call = apiService.getWeather(params)

        call.enqueue(object : Callback<WeatherResponse> {
            override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
                Log.e("Error:::","Error "+t!!.message)
            }

            override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
                if (response != null && response.isSuccessful && response.body() != null) {
                    Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)

                    temperature.setText(""+ response.body()!!.main.temp)

                }
            }

        })

Populating Spring @Value during Unit Test

This seems to work, although still a bit verbose (I'd like something shorter still):

@BeforeClass
public static void beforeClass() {
    System.setProperty("some.property", "<value>");
}

// Optionally:
@AfterClass
public static void afterClass() {
    System.clearProperty("some.property");
}

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

How to change package name in flutter?

Change App Package Name with single command by using following package. It makes the process very easy and fast.

flutter pub run change_app_package_name:main com.new.package.name

https://pub.dev/packages/change_app_package_name

Executing <script> injected by innerHTML after AJAX call

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

Sizing elements to percentage of screen width/height

FractionallySizedBox may also be useful. You can also read the screen width directly out of MediaQuery.of(context).size and create a sized box based on that

MediaQuery.of(context).size.width * 0.65

if you really want to size as a fraction of the screen regardless of what the layout is.

onclick go full screen

var elem = document.getElementById("myvideo");
function openFullscreen() {
  if (elem.requestFullscreen) {
      elem.requestFullscreen();
  } else if (elem.mozRequestFullScreen) { /* Firefox */
      elem.mozRequestFullScreen();
  } else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
      elem.webkitRequestFullscreen();
  } else if (elem.msRequestFullscreen) { /* IE/Edge */
      elem.msRequestFullscreen();
  }
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.

How to display databases in Oracle 11g using SQL*Plus

SELECT NAME FROM v$database; shows the database name in oracle

Convert base64 string to ArrayBuffer

Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.

var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
   var byteArray = new Uint8Array(e.target.response);
   // var shortArray = new Int16Array(e.target.response);
   // var unsignedShortArray = new Int16Array(e.target.response);
   // etc.
}
req.send();

The send request fails if the base 64 string is badly formed.

The mime type (application/octet) is probably unnecessary.

Tested in chrome. Should work in other browsers.

ssh-copy-id no identities found error

Actually issues in one of Ubuntu machine is ssh-keygen command was not run properly. I tried running again and navigated into /home/user1/.ssh and able to see id_rsa and id_rsa.pub keys. then tried command ssh-copy-id and it was working fine.

Dynamically create Bootstrap alerts box through JavaScript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>?

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle: http://jsfiddle.net/WKZ8P/

_x000D_
_x000D_
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
    <span>paragraph</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

Java Compare Two Lists

You can try intersection() and subtract() methods from CollectionUtils.

intersection() method gives you a collection containing common elements and the subtract() method gives you all the uncommon ones.

They should also take care of similar elements

sql query distinct with Row_Number

Try this:

;WITH CTE AS (
               SELECT DISTINCT id FROM table WHERE fid = 64
             )
SELECT id, ROW_NUMBER() OVER (ORDER BY  id) AS RowNum
  FROM cte
 WHERE fid = 64

How can we draw a vertical line in the webpage?

That's no struts related problem but rather plain HMTL/CSS.

I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.

Find location of a removable SD card

Is there an universal way to find the location of an external SD card?

By universal way, if you mean official way; yes there is one.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever.

How to deserialize a list using GSON or another JSON library in Java?

I recomend this one-liner

List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));

Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


Reference:

  1. Method Arrays#asList
  2. Constructor Gson
  3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
  4. Interface List
  5. JLS - Arrays
  6. JLS - Generic Interfaces

How to adjust gutter in Bootstrap 3 grid system?

To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.

To learn more about the grid and the columns / gutter widths, please also read:

In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px. When setting @grid-columns:3; and setting @grid-gutter-width:15px; in variables.less you will get:

15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px

What is a Maven artifact?

Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,

  • a group ID (like com.your.package),
  • an artifact ID (just a name), and
  • a version string.
    The three together uniquely identify the artifact.

Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.

Delete an element in a JSON object

with open('writing_file.json', 'w') as w:
    with open('reading_file.json', 'r') as r:
        for line in r:
            element = json.loads(line.strip())
            if 'hours' in element:
                del element['hours']
            w.write(json.dumps(element))

this is the method i use..

Center-align a HTML table

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work. Cheers

How to integrate SAP Crystal Reports in Visual Studio 2017

Visual Studio 2017 is supported in Crystal Reports SP 21, which is available for download as of 1 Sep 2017.

Why am I getting "Received fatal alert: protocol_version" or "peer not authenticated" from Maven Central?

Update maven version to 3.6.3 and run

mvn -Dhttps.protocols=TLSv1.2 install

it worked on centos 6.9

Javascript can't find element by id?

Script is called before element exists.

You should try one of the following:

  1. wrap code into a function and use a body onload event to call it.
  2. put script at the end of document
  3. use defer attribute into script tag declaration

Get average color of image via Javascript

I would say via the HTML canvas tag.

You can find here a post by @Georg talking about a small code by the Opera dev :

// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
    pix[i  ] = 255 - pix[i  ]; // red
    pix[i+1] = 255 - pix[i+1]; // green
    pix[i+2] = 255 - pix[i+2]; // blue
    // i+3 is alpha (the fourth element)
}

// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);

This invert the image by using the R, G and B value of each pixel. You could easily store the RGB values, then round up the Red, Green and Blue arrays, and finally converting them back into an HEX code.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

For self-hiding you can use getCmdPID.bat and windowMode.bat:

@echo off

echo --- self hiding bat ----
pause
call getCmdPid.bat
set PID=%errorlevel%
call windowMode.bat -pid %PID% -mode hidden

Here's my collection of ways to achieve that - and even more - where it was possible I've tried to return also the PID of the started process (all linked scripts can be downloaded and saved with whatever name you find convenient):

  1. The IEXPRESS solution can be used even on old win 95/98 machines. Iexpress is a really ancient tool that is still packaged with Windows - as arguments accepts only the command and its arguments.

Example usage:

call IEXPhidden.bat "cmd /c myBat.bat"  "argument"
  1. SCHTASKS - Again accepts only two arguments - the command and the arguments.Also checks if it's started with elevated permissions and if possible gets the PID of the process with WEVTUTIL (available from Vista and above so the newer version of windows will receive the PID) command.

Example usage:

call SCHPhidden.bat "cmd /c myBat.bat"  "argument"
  1. 'WScript.Shell' - the script is full wrapper of 'WScript.Shell' and every possible option can be set through the command line options.It's a jscript/batch hybrid and can be called as a bat.

Example usage (for more info print the help with '-h'):

call ShellRunJS.bat "notepad.exe" -style 0 -wait no 
  1. 'Win32_ProcessStartup' - again full wrapper and all options are accessible through the command line arguments.This time it's WSF/batch hybrid with some Jscript and some VBScript pieces of code - but it returns the PID of the started process.If process is not hidden some options like X/Y coordinates can be used (not applicable for every executable - but for example cmd.exe accepts coordinates).

Example usage (for more info print the help with '-h'):

call win32process.bat "notepad" -arguments "/A openFile.txt"  -showWindows 0 -title "notepad"
  1. The .NET solution . Most of the options of ProcessStartInfo options are used (but at the end I was too tired to include everything):

Example usage (for more info print the help with '-h'):

call ProcessStartJS.bat "notepad" -arguments "/A openFile.txt"  -style Hidden -directory "." -title "notepad" -priority Normal

Post-increment and pre-increment within a 'for' loop produce same output

You could read Google answer for it here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement

So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.

EDITED:

There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.

You could check it with such a loop:

for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
    cout << "inside loop body: " << i << endl;
}

What is the difference between const and readonly in C#?

They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.

Example:

public static class Text {
  public const string ConstDescription = "This can be used.";
  public readonly static string ReadonlyDescription = "Cannot be used.";
}

public class Foo 
{
  [Description(Text.ConstDescription)]
  public int BarThatBuilds {
    { get; set; }
  }

  [Description(Text.ReadOnlyDescription)]
  public int BarThatDoesNotBuild {
    { get; set; }
  }
}

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is an abstract class in PHP?

Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes

Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class

Example Code:

abstract class A {
    public function test1() {
        echo 'Hello World';
    }
    abstract protected function f1();
    abstract public function f2();
    protected function test2(){
        echo 'Hello World test';
    }
}

class B extends A {
    public $a = 'India';
    public function f1() {
        echo "F1 Method Call";
    }
    public function f2() {
        echo "F2 Method Call";
    }
}

$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";

Output:

Hello World
India
Hello World test
F1 Method Call
F2 Method Call

How to load external scripts dynamically in Angular?

@rahul-kumar 's solution works good for me, but i wanted to call my javascript function in my typescript

foo.myFunctions() // works in browser console, but foo can't be used in typescript file

I fixed it by declaring it in my typescript :

import { Component } from '@angular/core';
import { ScriptService } from './script.service';
declare var foo;

And now, i can call foo anywhere in my typecript file

How to manually update datatables table with new JSON data

In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).

My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null, for example).

Then I instantiate my table in the on load method

$(function () {
            //.... some code here
            table = $("#detailReportTable").DataTable();
            .... more code here
        });

and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:

function getOrderDetail() {
            table.clear();
            table.destroy();
            ...
            $.ajax({
             //.....api call here
            });
            ....
            table = $("#detailReportTable").DataTable();
   }

I hope someone finds this useful!

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

How to determine if a number is positive or negative?

I think there is a very simple solution:

public boolean isPositive(int|float|double|long i){
    return (((i-i)==0)? true : false);
}

tell me if I'm wrong!

Best practice multi language website

I will suggest you not to really depend of database for translation it could be really a messy task and could be a extreme problem in case of data encoding.

I had face similar issue while ago and written following class to solve my problem

Object: Locale\Locale

<?php

  namespace Locale;

  class Locale{

// Following array stolen from Zend Framework
public $country_to_locale = array(
    'AD' => 'ca_AD',
    'AE' => 'ar_AE',
    'AF' => 'fa_AF',
    'AG' => 'en_AG',
    'AI' => 'en_AI',
    'AL' => 'sq_AL',
    'AM' => 'hy_AM',
    'AN' => 'pap_AN',
    'AO' => 'pt_AO',
    'AQ' => 'und_AQ',
    'AR' => 'es_AR',
    'AS' => 'sm_AS',
    'AT' => 'de_AT',
    'AU' => 'en_AU',
    'AW' => 'nl_AW',
    'AX' => 'sv_AX',
    'AZ' => 'az_Latn_AZ',
    'BA' => 'bs_BA',
    'BB' => 'en_BB',
    'BD' => 'bn_BD',
    'BE' => 'nl_BE',
    'BF' => 'mos_BF',
    'BG' => 'bg_BG',
    'BH' => 'ar_BH',
    'BI' => 'rn_BI',
    'BJ' => 'fr_BJ',
    'BL' => 'fr_BL',
    'BM' => 'en_BM',
    'BN' => 'ms_BN',
    'BO' => 'es_BO',
    'BR' => 'pt_BR',
    'BS' => 'en_BS',
    'BT' => 'dz_BT',
    'BV' => 'und_BV',
    'BW' => 'en_BW',
    'BY' => 'be_BY',
    'BZ' => 'en_BZ',
    'CA' => 'en_CA',
    'CC' => 'ms_CC',
    'CD' => 'sw_CD',
    'CF' => 'fr_CF',
    'CG' => 'fr_CG',
    'CH' => 'de_CH',
    'CI' => 'fr_CI',
    'CK' => 'en_CK',
    'CL' => 'es_CL',
    'CM' => 'fr_CM',
    'CN' => 'zh_Hans_CN',
    'CO' => 'es_CO',
    'CR' => 'es_CR',
    'CU' => 'es_CU',
    'CV' => 'kea_CV',
    'CX' => 'en_CX',
    'CY' => 'el_CY',
    'CZ' => 'cs_CZ',
    'DE' => 'de_DE',
    'DJ' => 'aa_DJ',
    'DK' => 'da_DK',
    'DM' => 'en_DM',
    'DO' => 'es_DO',
    'DZ' => 'ar_DZ',
    'EC' => 'es_EC',
    'EE' => 'et_EE',
    'EG' => 'ar_EG',
    'EH' => 'ar_EH',
    'ER' => 'ti_ER',
    'ES' => 'es_ES',
    'ET' => 'en_ET',
    'FI' => 'fi_FI',
    'FJ' => 'hi_FJ',
    'FK' => 'en_FK',
    'FM' => 'chk_FM',
    'FO' => 'fo_FO',
    'FR' => 'fr_FR',
    'GA' => 'fr_GA',
    'GB' => 'en_GB',
    'GD' => 'en_GD',
    'GE' => 'ka_GE',
    'GF' => 'fr_GF',
    'GG' => 'en_GG',
    'GH' => 'ak_GH',
    'GI' => 'en_GI',
    'GL' => 'iu_GL',
    'GM' => 'en_GM',
    'GN' => 'fr_GN',
    'GP' => 'fr_GP',
    'GQ' => 'fan_GQ',
    'GR' => 'el_GR',
    'GS' => 'und_GS',
    'GT' => 'es_GT',
    'GU' => 'en_GU',
    'GW' => 'pt_GW',
    'GY' => 'en_GY',
    'HK' => 'zh_Hant_HK',
    'HM' => 'und_HM',
    'HN' => 'es_HN',
    'HR' => 'hr_HR',
    'HT' => 'ht_HT',
    'HU' => 'hu_HU',
    'ID' => 'id_ID',
    'IE' => 'en_IE',
    'IL' => 'he_IL',
    'IM' => 'en_IM',
    'IN' => 'hi_IN',
    'IO' => 'und_IO',
    'IQ' => 'ar_IQ',
    'IR' => 'fa_IR',
    'IS' => 'is_IS',
    'IT' => 'it_IT',
    'JE' => 'en_JE',
    'JM' => 'en_JM',
    'JO' => 'ar_JO',
    'JP' => 'ja_JP',
    'KE' => 'en_KE',
    'KG' => 'ky_Cyrl_KG',
    'KH' => 'km_KH',
    'KI' => 'en_KI',
    'KM' => 'ar_KM',
    'KN' => 'en_KN',
    'KP' => 'ko_KP',
    'KR' => 'ko_KR',
    'KW' => 'ar_KW',
    'KY' => 'en_KY',
    'KZ' => 'ru_KZ',
    'LA' => 'lo_LA',
    'LB' => 'ar_LB',
    'LC' => 'en_LC',
    'LI' => 'de_LI',
    'LK' => 'si_LK',
    'LR' => 'en_LR',
    'LS' => 'st_LS',
    'LT' => 'lt_LT',
    'LU' => 'fr_LU',
    'LV' => 'lv_LV',
    'LY' => 'ar_LY',
    'MA' => 'ar_MA',
    'MC' => 'fr_MC',
    'MD' => 'ro_MD',
    'ME' => 'sr_Latn_ME',
    'MF' => 'fr_MF',
    'MG' => 'mg_MG',
    'MH' => 'mh_MH',
    'MK' => 'mk_MK',
    'ML' => 'bm_ML',
    'MM' => 'my_MM',
    'MN' => 'mn_Cyrl_MN',
    'MO' => 'zh_Hant_MO',
    'MP' => 'en_MP',
    'MQ' => 'fr_MQ',
    'MR' => 'ar_MR',
    'MS' => 'en_MS',
    'MT' => 'mt_MT',
    'MU' => 'mfe_MU',
    'MV' => 'dv_MV',
    'MW' => 'ny_MW',
    'MX' => 'es_MX',
    'MY' => 'ms_MY',
    'MZ' => 'pt_MZ',
    'NA' => 'kj_NA',
    'NC' => 'fr_NC',
    'NE' => 'ha_Latn_NE',
    'NF' => 'en_NF',
    'NG' => 'en_NG',
    'NI' => 'es_NI',
    'NL' => 'nl_NL',
    'NO' => 'nb_NO',
    'NP' => 'ne_NP',
    'NR' => 'en_NR',
    'NU' => 'niu_NU',
    'NZ' => 'en_NZ',
    'OM' => 'ar_OM',
    'PA' => 'es_PA',
    'PE' => 'es_PE',
    'PF' => 'fr_PF',
    'PG' => 'tpi_PG',
    'PH' => 'fil_PH',
    'PK' => 'ur_PK',
    'PL' => 'pl_PL',
    'PM' => 'fr_PM',
    'PN' => 'en_PN',
    'PR' => 'es_PR',
    'PS' => 'ar_PS',
    'PT' => 'pt_PT',
    'PW' => 'pau_PW',
    'PY' => 'gn_PY',
    'QA' => 'ar_QA',
    'RE' => 'fr_RE',
    'RO' => 'ro_RO',
    'RS' => 'sr_Cyrl_RS',
    'RU' => 'ru_RU',
    'RW' => 'rw_RW',
    'SA' => 'ar_SA',
    'SB' => 'en_SB',
    'SC' => 'crs_SC',
    'SD' => 'ar_SD',
    'SE' => 'sv_SE',
    'SG' => 'en_SG',
    'SH' => 'en_SH',
    'SI' => 'sl_SI',
    'SJ' => 'nb_SJ',
    'SK' => 'sk_SK',
    'SL' => 'kri_SL',
    'SM' => 'it_SM',
    'SN' => 'fr_SN',
    'SO' => 'sw_SO',
    'SR' => 'srn_SR',
    'ST' => 'pt_ST',
    'SV' => 'es_SV',
    'SY' => 'ar_SY',
    'SZ' => 'en_SZ',
    'TC' => 'en_TC',
    'TD' => 'fr_TD',
    'TF' => 'und_TF',
    'TG' => 'fr_TG',
    'TH' => 'th_TH',
    'TJ' => 'tg_Cyrl_TJ',
    'TK' => 'tkl_TK',
    'TL' => 'pt_TL',
    'TM' => 'tk_TM',
    'TN' => 'ar_TN',
    'TO' => 'to_TO',
    'TR' => 'tr_TR',
    'TT' => 'en_TT',
    'TV' => 'tvl_TV',
    'TW' => 'zh_Hant_TW',
    'TZ' => 'sw_TZ',
    'UA' => 'uk_UA',
    'UG' => 'sw_UG',
    'UM' => 'en_UM',
    'US' => 'en_US',
    'UY' => 'es_UY',
    'UZ' => 'uz_Cyrl_UZ',
    'VA' => 'it_VA',
    'VC' => 'en_VC',
    'VE' => 'es_VE',
    'VG' => 'en_VG',
    'VI' => 'en_VI',
    'VN' => 'vn_VN',
    'VU' => 'bi_VU',
    'WF' => 'wls_WF',
    'WS' => 'sm_WS',
    'YE' => 'ar_YE',
    'YT' => 'swb_YT',
    'ZA' => 'en_ZA',
    'ZM' => 'en_ZM',
    'ZW' => 'sn_ZW'
);

/**
 * Store the transaltion for specific languages
 *
 * @var array
 */
protected $translation = array();

/**
 * Current locale
 *
 * @var string
 */
protected $locale;

/**
 * Default locale
 *
 * @var string
 */
protected $default_locale;

/**
 *
 * @var string
 */
protected $locale_dir;

/**
 * Construct.
 *
 *
 * @param string $locale_dir            
 */
public function __construct($locale_dir)
{
    $this->locale_dir = $locale_dir;
}

/**
 * Set the user define localte
 *
 * @param string $locale            
 */
public function setLocale($locale = null)
{
    $this->locale = $locale;

    return $this;
}

/**
 * Get the user define locale
 *
 * @return string
 */
public function getLocale()
{
    return $this->locale;
}

/**
 * Get the Default locale
 *
 * @return string
 */
public function getDefaultLocale()
{
    return $this->default_locale;
}

/**
 * Set the default locale
 *
 * @param string $locale            
 */
public function setDefaultLocale($locale)
{
    $this->default_locale = $locale;

    return $this;
}

/**
 * Determine if transltion exist or translation key exist
 *
 * @param string $locale            
 * @param string $key            
 * @return boolean
 */
public function hasTranslation($locale, $key = null)
{
    if (null == $key && isset($this->translation[$locale])) {
        return true;
    } elseif (isset($this->translation[$locale][$key])) {
        return true;
    }

    return false;
}

/**
 * Get the transltion for required locale or transtion for key
 *
 * @param string $locale            
 * @param string $key            
 * @return array
 */
public function getTranslation($locale, $key = null)
{
    if (null == $key && $this->hasTranslation($locale)) {
        return $this->translation[$locale];
    } elseif ($this->hasTranslation($locale, $key)) {
        return $this->translation[$locale][$key];
    }

    return array();
}

/**
 * Set the transtion for required locale
 *
 * @param string $locale
 *            Language code
 * @param string $trans
 *            translations array
 */
public function setTranslation($locale, $trans = array())
{
    $this->translation[$locale] = $trans;
}

/**
 * Remove transltions for required locale
 *
 * @param string $locale            
 */
public function removeTranslation($locale = null)
{
    if (null === $locale) {
        unset($this->translation);
    } else {
        unset($this->translation[$locale]);
    }
}

/**
 * Initialize locale
 *
 * @param string $locale            
 */
public function init($locale = null, $default_locale = null)
{
    // check if previously set locale exist or not
    $this->init_locale();
    if ($this->locale != null) {
        return;
    }

    if ($locale == null || (! preg_match('#^[a-z]+_[a-zA-Z_]+$#', $locale) && ! preg_match('#^[a-z]+_[a-zA-Z]+_[a-zA-Z_]+$#', $locale))) {
        $this->detectLocale();
    } else {
        $this->locale = $locale;
    }

    $this->init_locale();
}

/**
 * Attempt to autodetect locale
 *
 * @return void
 */
private function detectLocale()
{
    $locale = false;

    // GeoIP
    if (function_exists('geoip_country_code_by_name') && isset($_SERVER['REMOTE_ADDR'])) {

        $country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);

        if ($country) {

            $locale = isset($this->country_to_locale[$country]) ? $this->country_to_locale[$country] : false;
        }
    }

    // Try detecting locale from browser headers
    if (! $locale) {

        if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {

            $languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

            foreach ($languages as $lang) {

                $lang = str_replace('-', '_', trim($lang));

                if (strpos($lang, '_') === false) {

                    if (isset($this->country_to_locale[strtoupper($lang)])) {

                        $locale = $this->country_to_locale[strtoupper($lang)];
                    }
                } else {

                    $lang = explode('_', $lang);

                    if (count($lang) == 3) {
                        // language_Encoding_COUNTRY
                        $this->locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
                    } else {
                        // language_COUNTRY
                        $this->locale = strtolower($lang[0]) . strtoupper($lang[1]);
                    }

                    return;
                }
            }
        }
    }

    // Resort to default locale specified in config file
    if (! $locale) {
        $this->locale = $this->default_locale;
    }
}

/**
 * Check if config for selected locale exists
 *
 * @return void
 */
private function init_locale()
{
    if (! file_exists(sprintf('%s/%s.php', $this->locale_dir, $this->locale))) {
        $this->locale = $this->default_locale;
    }
}

/**
 * Load a Transtion into array
 *
 * @return void
 */
private function loadTranslation($locale = null, $force = false)
{
    if ($locale == null)
        $locale = $this->locale;

    if (! $this->hasTranslation($locale)) {
        $this->setTranslation($locale, include (sprintf('%s/%s.php', $this->locale_dir, $locale)));
    }
}

/**
 * Translate a key
 *
 * @param
 *            string Key to be translated
 * @param
 *            string optional arguments
 * @return string
 */
public function translate($key)
{
    $this->init();
    $this->loadTranslation($this->locale);

    if (! $this->hasTranslation($this->locale, $key)) {

        if ($this->locale !== $this->default_locale) {

            $this->loadTranslation($this->default_locale);

            if ($this->hasTranslation($this->default_locale, $key)) {

                $translation = $this->getTranslation($this->default_locale, $key);
            } else {
                // return key as it is or log error here
                return $key;
            }
        } else {
            return $key;
        }
    } else {
        $translation = $this->getTranslation($this->locale, $key);
    }
    // Replace arguments
    if (false !== strpos($translation, '{a:')) {
        $replace = array();
        $args = func_get_args();
        for ($i = 1, $max = count($args); $i < $max; $i ++) {
            $replace['{a:' . $i . '}'] = $args[$i];
        }
        // interpolate replacement values into the messsage then return
        return strtr($translation, $replace);
    }

    return $translation;
  }
}

Usage

 <?php
    ## /locale/en.php

    return array(
       'name' => 'Hello {a:1}'
       'name_full' => 'Hello {a:1} {a:2}'
   );

$locale = new Locale(__DIR__ . '/locale');
$locale->setLocale('en');// load en.php from locale dir
//want to work with auto detection comment $locale->setLocale('en');

echo $locale->translate('name', 'Foo');
echo $locale->translate('name', 'Foo', 'Bar');

How it works

{a:1} is replaced by 1st argument passed to method Locale::translate('key_name','arg1') {a:2} is replaced by 2nd argument passed to method Locale::translate('key_name','arg1','arg2')

How detection works

  • By default if geoip is installed then it will return country code by geoip_country_code_by_name and if geoip is not installed the fallback to HTTP_ACCEPT_LANGUAGE header

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

Align nav-items to right side in bootstrap-4

In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;" to the <ul class="navbar-nav"> and then add the ml-auto class to your navbar item.

How do you create an asynchronous HTTP request in JAVA?

If you are in a JEE7 environment, you must have a decent implementation of JAXRS hanging around, which would allow you to easily make asynchronous HTTP request using its client API.

This would looks like this:

public class Main {

    public static Future<Response> getAsyncHttp(final String url) {
        return ClientBuilder.newClient().target(url).request().async().get();
    }

    public static void main(String ...args) throws InterruptedException, ExecutionException {
        Future<Response> response = getAsyncHttp("http://www.nofrag.com");
        while (!response.isDone()) {
            System.out.println("Still waiting...");
            Thread.sleep(10);
        }
        System.out.println(response.get().readEntity(String.class));
    }
}

Of course, this is just using futures. If you are OK with using some more libraries, you could take a look at RxJava, the code would then look like:

public static void main(String... args) {
    final String url = "http://www.nofrag.com";
    rx.Observable.from(ClientBuilder.newClient().target(url).request().async().get(String.class), Schedulers
            .newThread())
            .subscribe(
                    next -> System.out.println(next),
                    error -> System.err.println(error),
                    () -> System.out.println("Stream ended.")
            );
    System.out.println("Async proof");
}

And last but not least, if you want to reuse your async call, you might want to take a look at Hystrix, which - in addition to a bazillion super cool other stuff - would allow you to write something like this:

For example:

public class AsyncGetCommand extends HystrixCommand<String> {

    private final String url;

    public AsyncGetCommand(final String url) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HTTP"))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        .withExecutionIsolationThreadTimeoutInMilliseconds(5000)));
        this.url = url;
    }

    @Override
    protected String run() throws Exception {
        return ClientBuilder.newClient().target(url).request().get(String.class);
    }

 }

Calling this command would look like:

public static void main(String ...args) {
    new AsyncGetCommand("http://www.nofrag.com").observe().subscribe(
            next -> System.out.println(next),
            error -> System.err.println(error),
            () -> System.out.println("Stream ended.")
    );
    System.out.println("Async proof");
}

PS: I know the thread is old, but it felt wrong that no ones mentions the Rx/Hystrix way in the up-voted answers.

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Get week number (in the year) from a date PHP

This get today date then tell the week number for the week

<?php
 $date=date("W");
 echo $date." Week Number";
 ?>

Prevent text selection after double click

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property. For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function (event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

How to change the port of Tomcat from 8080 to 80?

On Ubuntu and Debian systems, there are several steps needed:

  1. In server.xml, change the line <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/> to have port="80".

  2. Install the recommended (not required) authbind package, with a command like:

    sudo apt-get install authbind

  3. Enable authbind in the server.xml file (in either /etc/tomcat6 or /etc/tomcat7) by uncommenting and setting the line like:

    AUTHBIND=yes

All three steps are needed.

How can I make a menubar fixed on the top while scrolling

This should get you started

 <div class="menuBar">
        <img class="logo" src="logo.jpg"/>
        <div class="nav"> 
            <ul>
                <li>Menu1</li>
                <li>Menu 2</li>
                <li>Menu 3</li>
            </ul> 
        </div>
    </div>



body{
    margin-top:50px;}
.menuBar{
    width:100%;
    height:50px;
    display:block;
    position:absolute;
    top:0;
    left:0;
    }
.logo{
    float:left;
    }
.nav{
    float:right;
    margin-right:10px;}
.nav ul li{
    list-style:none;
    float:left;
    }

Parsing a comma-delimited std::string

#include <sstream>
#include <vector>

const char *input = "1,1,1,1,2,1,1,1,0";

int main() {
    std::stringstream ss(input);
    std::vector<int> output;
    int i;
    while (ss >> i) {
        output.push_back(i);
        ss.ignore(1);
    }
}

Bad input (for instance consecutive separators) will mess this up, but you did say simple.

How to hide command output in Bash

You should not use bash in this case to get rid of the output. Yum does have an option -q which suppresses the output.

You'll most certainly also want to use -y

echo "Installing nano..."
yum -y -q install nano

To see all the options for yum, use man yum.

What's the best way to select the minimum value from several columns?

You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.

Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From   YourTable T
       Inner Join (
         Select A.Id, Min(A.Col1) As TheMin
         From   (
                Select Id, Col1
                From   YourTable

                Union All

                Select Id, Col2
                From   YourTable

                Union All

                Select Id, Col3
                From   YourTable
                ) As A
         Group By A.Id
       ) As A
       On T.Id = A.Id

What is the easiest way to ignore a JPA field during persistence?

None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION feature in my Jersey Application:

ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);  

Here is the dependency for the Hibernate5Module:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>2.8.9</version>
</dependency>

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

Haskell: Converting Int to String

The opposite of read is show.

Prelude> show 3
"3"

Prelude> read $ show 3 :: Int
3

How do I specify the columns and rows of a multiline Editor-For in ASP.MVC?

Use TextAreaFor

@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })

or use style for multi-line class.

You could also write EditorTemplate for this.

How to get the python.exe location programmatically?

I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe

which gives this value on my machine:

C:\Python25\Python.exe

You just read the registry key to get the location.

However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.

Convert hex string to int in Python

The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)

Example

a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

Uninstall the old app from the device/emulator. It worked for me

Javascript Array of Functions

up above we saw some with iteration. Let's do the same thing using forEach:

var funcs = [function () {
        console.log(1)
  },
  function () {
        console.log(2)
  }
];

funcs.forEach(function (func) {
  func(); // outputs  1, then 2
});
//for (i = 0; i < funcs.length; i++) funcs[i]();

memory error in python

A memory error means that your program has ran out of memory. This means that your program somehow creates too many objects.

In your example, you have to look for parts of your algorithm that could be consuming a lot of memory. I suspect that your program is given very long strings as inputs. Therefore, s[i:j+1] could be the culprit, since it creates a new list. The first time you use it though, it is not necessary because you don't use the created list. You could try to see if the following helps:

if  j + 1 < a:
    sub_strings.append(s[i:j+1])

To replace the second list creation, you should definitely use a buffer object, as suggested by glglgl.

Also note that since you use if j >= i:, you don't need to start your xrange at 0. You can have:

for i in xrange(0, a):
    for j in xrange(i, a):
        # No need for if j >= i

A more radical alternative would be to try to rework your algorithm so that you don't pre-compute all possible sub-strings. Instead, you could simply compute the substring that are asked.

How often does python flush to a file?

Here is another approach, up to the OP to choose which one he prefers.

When including the code below in the __init__.py file before any other code, messages printed with print and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:

import sys

path = "/Users/#username#"

errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog

(for Mac, change #username# to the name of your user folder. On Windows the path to your user folder will have a different format)

When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.

Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella

What's the best practice for primary keys in tables?

Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.

"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.

I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.

Understanding the difference between Object.create() and new SomeFunction()

Very simply said, new X is Object.create(X.prototype) with additionally running the constructor function. (And giving the constructor the chance to return the actual object that should be the result of the expression instead of this.)

That’s it. :)

The rest of the answers are just confusing, because apparently nobody else reads the definition of new either. ;)

How to hide the title bar for an Activity in XML with existing custom theme

Just use getActionBar().hide(); in your main activity onCreate() method.

Create an ArrayList of unique values

You can easily do this with a Hashmap. You obviously have a key (which is the String data) and some values.

Loop on all your lines and add them to your Map.

Map<String, List<Integer>> map = new HashMap<>();
...
while (s.hasNext()){
  String stringData = ...
  List<Integer> values = ...
  map.put(stringData,values);
}

Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData); before putting in the map.

How can I extract all values from a dictionary in Python?

Normal Dict.values()

will return something like this

dict_values(['value1'])

dict_values(['value2'])

If you want only Values use

  • Use this

list(Dict.values())[0] # Under the List

How do I get the Git commit count?

In our company, we moved from SVN to Git. Lack of revision numbers was a big problem!

Do git svn clone, and then tag the last SVN commit by its SVN revision number:

export hr=`git svn find-rev HEAD`
git tag "$hr" -f HEAD

Then you can get the revision number with help of

git describe --tags --long

This command gives something like:

7603-3-g7f4610d

Means: The last tag is 7603 - it's the SVN revision. 3 - is count of commits from it. We need to add them.

So, the revision number can be counted by this script:

expr $(git describe --tags --long | cut -d '-' -f 1) + $(git describe --tags --long | cut -d '-' -f 2)

Why is there no ForEach extension method on IEnumerable?

You could use the (chainable, but lazily evaluated) Select, first doing your operation, and then returning identity (or something else if you prefer)

IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });

You will need to make sure it is still evaluated, either with Count() (the cheapest operation to enumerate afaik) or another operation you needed anyway.

I would love to see it brought in to the standard library though:

static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
  return src.Select(i => { action(i); return i; } );
}

The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p)) which is effectively equivalent to foreach, but lazy and chainable.

CSS div 100% height

Set the html tag, too. This way no weird position hacks are required.

html, body {height: 100%}

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

Only read selected columns

To read a specific set of columns from a dataset you, there are several other options:

1) With freadfrom the data.table-package:

You can specify the desired columns with the select parameter from fread from the data.table package. You can specify the columns with a vector of column names or column numbers.

For the example dataset:

library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))

Alternatively, you can use the drop parameter to indicate which columns should not be read:

dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))

All result in:

> data
  Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27  -2  -6 -10 -32

UPDATE: When you don't want fread to return a data.table, use the data.table = FALSE-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)

2) With read.csv.sql from the sqldf-package:

Another alternative is the read.csv.sql function from the sqldf package:

library(sqldf)
dat <- read.csv.sql("data.txt",
                    sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
                    sep = "\t")

3) With the read_*-functions from the readr-package:

library(readr)
dat <- read_table("data.txt",
                  col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
                                        Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
                  col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
                                   Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')

From the documentation an explanation for the used characters with col_types:

each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column

What is the difference between max-device-width and max-width for mobile web?

max-device-width is the device rendering width

@media all and (max-device-width: 400px) {
    /* styles for devices with a maximum width of 400px and less
       Changes only on device orientation */
}

@media all and (max-width: 400px) {
    /* styles for target area with a maximum width of 400px and less
       Changes on device orientation , browser resize */
}

The max-width is the width of the target display area means the current size of browser.

Filter Linq EXCEPT on properties

Try a simple where query

var filtered = unfilteredApps.Where(i => !excludedAppIds.Contains(i.Id)); 

The except method uses equality, your lists contain objects of different types, so none of the items they contain will be equal!

How can I remove punctuation from input text in Java?

I don't like to use regex, so here is another simple solution.

public String removePunctuations(String s) {
    String res = "";
    for (Character c : s.toCharArray()) {
        if(Character.isLetterOrDigit(c))
            res += c;
    }
    return res;
}

Note: This will include both Letters and Digits

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull first invokes git fetch, in normal cases fetching a branch from the remote; FETCH_HEAD points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull then invokes git merge, merging FETCH_HEAD into the current branch.

The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.

This is a bit like doing git fetch without arguments (or git remote update), updating all your remote branches, then running git merge origin/<branch>, but using FETCH_HEAD internally instead to refer to whatever single ref was fetched, instead of needing to name things.

Why is <deny users="?" /> included in the following example?

"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."

Article at MSDN

deny = * means deny everyone
deny = ? means deny unauthenticated users

In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.

According to the docs, here is no difference in your 2 rule sets.

Printing an int list in a single line python3

these will both work in Python 2.7 and Python 3.x:

>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3

btw, array is a reserved word in Python.

Where does forever store console.log output?

Based on bryanmac's answer. I'm just saving all logs into one file and then reading it with tail. Simple, but effective way to do this.

forever -o common.log -e common.log index.js && tail -f common.log

how to calculate percentage in python

I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7

marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list

#here we populate the dictionary with the marks for every subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)

print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.

how to find 2d array size in c++

Here is one possible solution of first part

#include<iostream>

using namespace std;
int main()
{
    int marks[][4] = {
                      10, 20, 30, 50,
                      40, 50, 60, 60,
                      10, 20, 10, 70
                     };

int rows =  sizeof(marks)/sizeof(marks[0]);
int cols = sizeof(marks)/(sizeof(int)*rows);


    for(int i=0; i<rows; i++)
    {
        for(int j=0; j<cols; j++)
        {
            cout<<marks[i][j]<<" ";
        }
        cout<<endl;
    }



    return 0;
}

Override valueof() and toString() in Java enum

You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead.

public enum RandomEnum {

    StartHere("Start Here"),
    StopHere("Stop Here");

    private String value;

    RandomEnum(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return this.getValue();
    }

    public static RandomEnum getEnum(String value) {
        for(RandomEnum v : values())
            if(v.getValue().equalsIgnoreCase(value)) return v;
        throw new IllegalArgumentException();
    }
}

Custom fonts and XML layouts (Android)

Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the android:fontFamily attribute to add support for custom fonts in your asset folder, like so:

<TextView 
  android:text="@string/hello_world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:fontFamily="fonts/Roboto-Bold.ttf"/>

The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}

You can also specify your own custom attribute to replace android:fontFamily

It also works in themes, including the AppTheme.

Is there a method to generate a UUID with go language

On Linux, you can read from /proc/sys/kernel/random/uuid:

package main

import "io/ioutil"
import "fmt"

func main() {
    u, _ := ioutil.ReadFile("/proc/sys/kernel/random/uuid")
    fmt.Println(string(u))
}

No external dependencies!

$ go run uuid.go 
3ee995e3-0c96-4e30-ac1e-f7f04fd03e44

Check if value exists in Postgres array

Simpler with the ANY construct:

SELECT value_variable = ANY ('{1,2,3}'::int[])

The right operand of ANY (between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:

Important difference: Array operators (<@, @>, && et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY construct expects an element type as left operand and does not support these indices. Example:

None of this works for NULL elements. To test for NULL:

How can I make setInterval also work when a tab is inactive in Chrome?

Just do this:

var $div = $('div');
var a = 0;

setInterval(function() {
    a++;
    $div.stop(true,true).css("left", a);
}, 1000 / 30);

Inactive browser tabs buffer some of the setInterval or setTimeout functions.

stop(true,true) will stop all buffered events and execute immediatly only the last animation.

The window.setTimeout() method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).

How to find third or n?? maximum salary from salary table?

Try this

SELECT TOP 1 salary FROM (
   SELECT TOP 3 salary 
   FROM employees 
   ORDER BY salary DESC) AS emp 
ORDER BY salary ASC

For 3 you can replace any value...

How do you delete an ActiveRecord object?

There is delete, delete_all, destroy, and destroy_all.

The docs are: older docs and Rails 3.0.0 docs

delete doesn't instantiate the objects, while destroy does. In general, delete is faster than destroy.

Change the Right Margin of a View Programmatically?

Use LayoutParams (as explained already). However be careful which LayoutParams to choose. According to https://stackoverflow.com/a/11971553/3184778 "you need to use the one that relates to the PARENT of the view you're working on, not the actual view"

If for example the TextView is inside a TableRow, then you need to use TableRow.LayoutParams instead of RelativeLayout or LinearLayout

Change Git repository directory location.

I use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:

  1. Close Visual Studio.

  2. Move the code (including git folder, etc)

  3. Click on the solution file from the new location

This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.

Fixed Table Cell Width

table td 
{
  table-layout:fixed;
  width:20px;
  overflow:hidden;
  word-wrap:break-word;
}

how to get 2 digits after decimal point in tsql?

You could cast it to DECIMAL and specify the scale to be 2 digits

decimal and numeric

So, something like

DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))

SQLFiddle DEMO

I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.

Formatting (in my opinion) should happen on the UI/Report/Display level.

Max retries exceeded with URL in requests

Adding my own experience for those who are experiencing this in the future. My specific error was

Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'

It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.

Nginx no-www to www and www to no-www

This solution comes from my personal experience. We used several Amazon S3 buckets and one server for redirecting non-www to www domain names to match S3 "Host" header policy.

I used the following configuration for nginx server:

server {
    listen 80;
    server_name ~^(?!www\.)(?<domain>.+)$;
    return 301 $scheme://www.$domain$request_uri;
}

This matches all domain names pointed to the server starting with whatever but www. and redirects to www.<domain>. In the same manner you can do opposite redirect from www to non-www.

What’s the best RESTful method to return total number of items in an object?

What about a new end point > /api/members/count which just calls Members.Count() and returns the result

"X does not name a type" error in C++

It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1]. GManNickG answer's tells why this happen. But the best way to solve this is to put User class in one header file (User.h) and MyMessageBox class in another header file (MyMessageBox.h). Then in your User.h you include MyMessageBox.h and in MyMessageBox.h you include User.h. Do not forget "include gaurds" [2] so that your code compiles successfully.

Change <select>'s option and trigger events with JavaScript

Unfortunately, you need to manually fire the change event. And using the Event Constructor will be the best solution.

_x000D_
_x000D_
var select = document.querySelector('#sel'),_x000D_
    input = document.querySelector('input[type="button"]');_x000D_
select.addEventListener('change',function(){_x000D_
    alert('changed');_x000D_
});_x000D_
input.addEventListener('click',function(){_x000D_
    select.value = 2;_x000D_
    select.dispatchEvent(new Event('change'));_x000D_
});
_x000D_
<select id="sel" onchange='alert("changed")'>_x000D_
  <option value='1'>One</option>_x000D_
  <option value='2'>Two</option>_x000D_
  <option value='3' selected>Three</option>_x000D_
</select>_x000D_
<input type="button" value="Change option to 2" />
_x000D_
_x000D_
_x000D_

And, of course, the Event constructor is not supported in IE. So you may need to polyfill with this:

function Event( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
}

Not an enclosing class error Android Studio

It should be

Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);

You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.

not an enclosing class error is thrown because of your usage of this keyword. this is a reference to the current object — the object whose method or constructor is being called. With this you can only refer to any member of the current object from within an instance method or a constructor.

Katra_home.this is invalid construct

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

Latex - Change margins of only a few pages

Look up \enlargethispage in some LaTeX reference.

How to calculate percentage when old value is ZERO

When both values are zero, then the change is zero.

If one of the values is zero, it's infinite (ambiguous), but I would set it to 100%.

Here is a C++ code (where v1 is the previous value (old), and v2 is new):

double result = 0;
if (v1 != 0 && v2 != 0) {
  // If values are non-zero, use the standard formula.
  result = (v2 / v1) - 1;
} else if (v1 == 0 || v2 == 0) {
  // Change is zero when both values are zeros, otherwise it's 100%.
  result = v1 == 0 && v2 == 0 ? 0 : 1;
}
result = v2 > v1 ? abs(result) : -abs(result);
// Note: To have format in hundreds, multiply the result by 100.

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

In my case the issue was due to incorrect build order. One project had an xcopy command on post-build events to copy files from bin folder to another folder. But because of incorrect dependencies new files were getting created in bin folder while xcopy is in progress.

In VS right click on the project where you have post-build events. Go to Build Dependencies > Project Dependencies and make sure its correct. Verify the project build order(next tab to dependencies) as well.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.


OpenJDK ? source code
Adoptium/AdoptOpenJDK ? builds

Difference between OpenJDK and AdoptOpenJDK

The first provides source-code, the other provides builds of that source-code.

Several vendors of Java & OpenJDK

Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:

  • Eclipse Foundation (Adoptium/AdoptOpenJDK)
  • Azul Systems
  • Oracle
  • Red Hat / IBM
  • BellSoft
  • SAP
  • Amazon AWS
  • … and more

See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.

Flowchart guiding you in choosing a vendor for a Java 11 implementation

Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.

Here is a list of considerations and motivations to consider in choosing a vendor and implementation.

Motivations in choosing a vendor for Java

Some vendors offer you a choice of JIT technologies.

Diagram showing history of HotSpot & JRockit merging, and OpenJ9 both available in AdoptOpenJDK

To understand more about this Java ecosystem, read Java Is Still Free

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

In such case look at gradle console it will show the issue in detail with exact location which led to this compilation error.

In my case I was using Butterknife in one of my class and I had auto-converted that class to kotlin using android studio's utility

Log in Gradle Console

Executing tasks: [:app:assembleDebug]

Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
:app:buildInfoDebugLoader
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:checkDebugManifest UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:processDebugGoogleServices
Parsing json file: /Users/Downloads/myproject/app/google-services.json
:app:mergeDebugResources UP-TO-DATE
:app:createDebugCompatibleScreenManifests UP-TO-DATE
:app:processDebugManifest
:app:splitsDiscoveryTaskDebug UP-TO-DATE
:app:processDebugResources
:app:kaptGenerateStubsDebugKotlin
Using kotlin incremental compilation
:app:kaptDebugKotlin
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:10: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.imgConfirmationLogo)
e: 

e:     private android.widget.ImageView imgConfirmationLogo;
e:                                      ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:13: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtConfirmationDialogTitle)
e: 

e:     private android.widget.TextView txtConfirmationDialogTitle;
e:                                     ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:16: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtConfirmationDialogMessage)
e: 

e:     private android.widget.TextView txtConfirmationDialogMessage;
e:                                     ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:19: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtViewPositive)
e: 

e:     private android.widget.TextView txtViewPositive;
e:                                     ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:22: error: @BindView fields must not be private or static. (com.pokkt.myproject.ConfirmationDialog.txtViewNegative)
e: 

e:     private android.widget.TextView txtViewNegative;
e:                                     ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ExitDialog.java:10: error: @BindView fields must not be private or static. (com.myproject.util.ExitDialog.txtViewPositive)
e: 

e:     private android.widget.TextView txtViewPositive;
e:                                     ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ExitDialog.java:13: error: @BindView fields must not be private or static. (com.myproject.util.ExitDialog.txtViewNegative)
e: 

e:     private android.widget.TextView txtViewNegative;
e:                                     ^
e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:144)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:167)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:55)
    at org.jetbrains.kotlin.cli.common.CLICompiler.exec(CLICompiler.java:182)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.execCompiler(CompileServiceImpl.kt:397)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execCompiler(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:365)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2$$special$$inlined$withValidClientOrSessionProxy$lambda$1.invoke(CompileServiceImpl.kt:798)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2$$special$$inlined$withValidClientOrSessionProxy$lambda$1.invoke(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:825)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$checkedCompile(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2.invoke(CompileServiceImpl.kt:797)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2.invoke(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive(CompileServiceImpl.kt:1004)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive$default(CompileServiceImpl.kt:865)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:791)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$doCompile(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1.invoke(CompileServiceImpl.kt:364)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1.invoke(CompileServiceImpl.kt:99)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive(CompileServiceImpl.kt:1004)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive$default(CompileServiceImpl.kt:865)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:336)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
    at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
    at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
    at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
    at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:89)
    at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:99)
    at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:76)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.analyze(KotlinToJVMBytecodeCompiler.kt:365)
    at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:105)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:354)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:139)
    ... 40 more


 FAILED
:app:buildInfoGeneratorDebug

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Internal compiler error. See log for more details

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED in 32s

16 actionable tasks: 7 executed, 9 up-to-date

As in my log it clearly shows issues are with declaration of variables with butterknife. So I looked into this issue and was able to solve it.

VBA equivalent to Excel's mod function

You want the mod operator.

The expression a Mod b is equivalent to the following formula:

a - (b * (a \ b))

Edited to add:

There are some special cases you may have to consider, because Excel is using floating point math (and returns a float), which the VBA function returns an integer. Because of this, using mod with floating-point numbers may require extra attention:

  • Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.

  • As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix() function he suggests is explained here (MSDN).

moment.js, how to get day of week number

I think this would work

moment().weekday(); //if today is thursday it will return 4

How to make an element width: 100% minus padding?

For me, using margin:15px;padding:10px 0 15px 23px;width:100%, the result was this:

enter image description here

The solution for me was to use width:auto instead of width:100%. My new code was:

margin:15px;padding:10px 0 15px 23px;width:auto. Then the element aligned properly:

enter image description here

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

You can use elevation property for Android if you don't mind the shadow.

{
  elevation:1
} 

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

How to download/checkout a project from Google Code in Windows?

If you don't want to install anything but do want to download an SVN or GIT repository, then you can use this: http://downloadsvn.codeplex.com/

I have nothing to do with this project, but I just used it now and it saved me a few minutes. Maybe it will help someone.

In Perl, how do I create a hash whose keys come from a given array?

 @hash{@array} = (1) x @array;

It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.

From the docs:

If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

Centering image and text in R Markdown for a PDF report

I had the same question. I have tried all solutions provided above and none of them worked... But I have found a solution that works for me, and hopefully for others too.

<center>

![your image caption](image.png)

</center>

This code will center both the image and the caption. It is essential that you leave lines between <center>, the image code, and </center>, otherwise the image will be centered but the caption will disappear.

If you want your image to have a clickable link, you can embed things like

[![your image caption](image.png)](www.link_to_image.com)

However, the caption will no longer appear.

So if you want a clickable caption you will have to do it in two steps:

<center>

![](image.png)

[your image caption](www.link_to_image.com)

</center>

Same here, make sure there are empty lines in between each command ones. If you want both the image and the caption to be clickable, then combine the middle and the last codes above. I hope this helps a bit.

The opposite of Intersect()

You can use

a.Except(b).Union(b.Except(a));

Or you can use

var difference = new HashSet(a);
difference.SymmetricExceptWith(b);

php & mysql query not echoing in html with tags?

<td class="first"> <?php echo $proxy ?> </td> is inside a literal string that you are echoing. End the string, or concatenate it correctly:

<td class="first">' . $proxy . '</td>

What does "\r" do in the following script?

\r is the ASCII Carriage Return (CR) character.

There are different newline conventions used by different operating systems. The most common ones are:

  • CR+LF (\r\n);
  • LF (\n);
  • CR (\r).

The \n\r (LF+CR) looks unconventional.

edit: My reading of the Telnet RFC suggests that:

  1. CR+LF is the standard newline sequence used by the telnet protocol.
  2. LF+CR is an acceptable substitute:

The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").

How to apply shell command to each line of a command output?

for s in `cmd`; do echo $s; done

If cmd has a large output:

cmd | xargs -L1 echo

How to save data file into .RData?

There are three ways to save objects from your R session:

Saving all objects in your R session:

The save.image() function will save all objects currently in your R session:

save.image(file="1.RData") 

These objects can then be loaded back into a new R session using the load() function:

load(file="1.RData")

Saving some objects in your R session:

If you want to save some, but not all objects, you can use the save() function:

save(city, country, file="1.RData")

Again, these can be reloaded into another R session using the load() function:

load(file="1.RData") 

Saving a single object

If you want to save a single object you can use the saveRDS() function:

saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds") 

You can load these into your R session using the readRDS() function, but you will need to assign the result into a the desired variable:

city <- readRDS("city.rds")
country <- readRDS("country.rds")

But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):

city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Android map v2 zoom to show all the markers

You should use the CameraUpdate class to do (probably) all programmatic map movements.

To do this, first calculate the bounds of all the markers like so:

LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
    builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();

Then obtain a movement description object by using the factory: CameraUpdateFactory:

int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);

Finally move the map:

googleMap.moveCamera(cu);

Or if you want an animation:

googleMap.animateCamera(cu);

That's all :)

Clarification 1

Almost all movement methods require the Map object to have passed the layout process. You can wait for this to happen using the addOnGlobalLayoutListener construct. Details can be found in comments to this answer and remaining answers. You can also find a complete code for setting map extent using addOnGlobalLayoutListener here.

Clarification 2

One comment notes that using this method for only one marker results in map zoom set to a "bizarre" zoom level (which I believe to be maximum zoom level available for given location). I think this is expected because:

  1. The LatLngBounds bounds instance will have northeast property equal to southwest, meaning that the portion of area of the earth covered by this bounds is exactly zero. (This is logical since a single marker has no area.)
  2. By passing bounds to CameraUpdateFactory.newLatLngBounds you essentially request a calculation of such a zoom level that bounds (having zero area) will cover the whole map view.
  3. You can actually perform this calculation on a piece of paper. The theoretical zoom level that is the answer is +∞ (positive infinity). In practice the Map object doesn't support this value so it is clamped to a more reasonable maximum level allowed for given location.

Another way to put it: how can Map object know what zoom level should it choose for a single location? Maybe the optimal value should be 20 (if it represents a specific address). Or maybe 11 (if it represents a town). Or maybe 6 (if it represents a country). API isn't that smart and the decision is up to you.

So, you should simply check if markers has only one location and if so, use one of:

  • CameraUpdate cu = CameraUpdateFactory.newLatLng(marker.getPosition()) - go to marker position, leave current zoom level intact.
  • CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 12F) - go to marker position, set zoom level to arbitrarily chosen value 12.

Merging two CSV files using Python

When I'm working with csv files, I often use the pandas library. It makes things like this very easy. For example:

import pandas as pd

a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)

Some explanation follows. First, we read in the csv files:

>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
   title  stage    jan    feb
0   darn  3.001  0.421  0.532
1     ok  2.829  1.036  0.751
2  three  1.115  1.146  2.921
>>> b
   title    mar    apr    may       jun  Unnamed: 5
0   darn  0.631  1.321  0.951    1.7510         NaN
1     ok  1.001  0.247  2.456    0.3216         NaN
2  three  0.285  1.283  0.924  956.0000         NaN

and we see there's an extra column of data (note that the first line of fileb.csv -- title,mar,apr,may,jun, -- has an extra comma at the end). We can get rid of that easily enough:

>>> b = b.dropna(axis=1)
>>> b
   title    mar    apr    may       jun
0   darn  0.631  1.321  0.951    1.7510
1     ok  1.001  0.247  2.456    0.3216
2  three  0.285  1.283  0.924  956.0000

Now we can merge a and b on the title column:

>>> merged = a.merge(b, on='title')
>>> merged
   title  stage    jan    feb    mar    apr    may       jun
0   darn  3.001  0.421  0.532  0.631  1.321  0.951    1.7510
1     ok  2.829  1.036  0.751  1.001  0.247  2.456    0.3216
2  three  1.115  1.146  2.921  0.285  1.283  0.924  956.0000

and finally write this out:

>>> merged.to_csv("output.csv", index=False)

producing:

title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0

How to display pandas DataFrame of floats using a format string for columns?

Similar to unutbu above, you could also use applymap as follows:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

Vertical align text in block element

You can try the display:inline-block and :after.Like this:

HTML

<ul>
    <li><a href="">I would like this text centered vertically</a></li>
</ul>

CSS

li a {
    width: 300px;
    height: 100px;
    margin: auto 0;
    display: inline-block;
    vertical-align: middle;
    background: red;  
}
li a:after {
  content:"";
  display: inline-block;
  width: 1px solid transparent;
  height: 100%;
  vertical-align: middle;
}

Please view the demo.

How to resolve merge conflicts in Git repository?

git checkout branch1

git fetch origin

git rebase -p origin/mainbranch

If there are merge conflicts, fix them. Then, continue the rebase process by running: git rebase –-continue

after the fixing you can commit and push your local branch to remote branch

git push origin branch1

Access restriction on class due to restriction on required library rt.jar?

  • Go to the Build Path settings in the project properties. Windows -> Preferences -> Java Compiler
  • Remove the JRE System Library
  • Add another JRE with a "perfect match"
  • clean and build your project again. It worked for me.

How to find out if an installed Eclipse is 32 or 64 bit version?

Open eclipse.ini in the installation directory, and observe the line with text:

plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.

If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.

How do I select between the 1st day of the current month and current day in MySQL?

Complete solution for mysql current month and current year, which makes use of indexing properly as well :)

-- Current month
SELECT id, timestampfield 
  FROM table1
 WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY)
   AND timestampfield <=  LAST_DAY(CURRENT_DATE);

-- Current year
SELECT id, timestampfield 
  FROM table1
 WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFYEAR(CURRENT_DATE)-1 DAY)
   AND timestampfield <=  LAST_DAY(CURRENT_DATE);

Create a simple 10 second countdown

This does it in text.

_x000D_
_x000D_
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
    var timeleft = 10;_x000D_
    var downloadTimer = setInterval(function(){_x000D_
    timeleft--;_x000D_
    document.getElementById("countdowntimer").textContent = timeleft;_x000D_
    if(timeleft <= 0)_x000D_
        clearInterval(downloadTimer);_x000D_
    },1000);_x000D_
</script>
_x000D_
_x000D_
_x000D_

How do I use HTML as the view engine in Express?

I recommend using https://www.npmjs.com/package/express-es6-template-engine - extremely lightwave and blazingly fast template engine. The name is a bit misleading as it can work without expressjs too.

The basics required to integrate express-es6-template-engine in your app are pretty simple and quite straight forward to implement:

_x000D_
_x000D_
const express = require('express'),_x000D_
  es6Renderer = require('express-es6-template-engine'),_x000D_
  app = express();_x000D_
  _x000D_
app.engine('html', es6Renderer);_x000D_
app.set('views', 'views');_x000D_
app.set('view engine', 'html');_x000D_
 _x000D_
app.get('/', function(req, res) {_x000D_
  res.render('index', {locals: {title: 'Welcome!'}});_x000D_
});_x000D_
 _x000D_
app.listen(3000);
_x000D_
_x000D_
_x000D_ Here is the content of the index.html file locate inside your 'views' directory:

<!DOCTYPE html>
<html>
<body>
    <h1>${title}</h1>
</body>
</html>

What is perm space?

It holds stuff like class definitions, string pool, etc. I guess you could call it meta-data.

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

How to join two JavaScript Objects, without using JQUERY

Just another solution using underscore.js:

_.extend({}, obj1, obj2);

How to make a DIV not wrap?

The min-width property does not work correctly in Internet Explorer, which is most likely the cause of your problems.

Read info and a brilliant script that fixes many IE CSS problems.

User Get-ADUser to list all properties and export to .csv

@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.

The below examples are based on a domain in the range of 20,000 account objects.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds           : 16
Milliseconds      : 208

measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds           : 3
Milliseconds      : 496

In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).

Note that if I include the where clause per your suggestion to prune to the actually desired results, it's even more expensive.

measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds           : 17
Milliseconds      : 876

Indexed attributes seem to have similar performance (I tried just returning displayName).

Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).

measure-command {$userlist | get-aduser -Properties *}
...
Seconds           : 12
Milliseconds      : 75

I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01

When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

'numpy.ndarray' object is not callable error

The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:

In [16]: import numpy as np

In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()

TypeError: 'numpy.ndarray' object is not callable

If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean or pd.rolling_std to a numpy array earlier in your code.

What I mean is something like this:

In [1]: import numpy as np

In [2]: import pandas as pd

In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan,  nan,  nan])

In [4]: pd.rolling_mean = np.array([1,2,3])

In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...

TypeError: 'numpy.ndarray' object is not callable

So, basically you need to search the rest of your codebase for pd.rolling_mean = ... and/or pd.rolling_std = ... to see where you may have overwritten them.


Also, if you'd like, you can put in reload(pd) just before your snippet, which should make it run by restoring the value of pd to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.

input[type='text'] CSS selector does not apply to default-type text inputs?

try this

 input[type='text']
 {
   background:red !important;
 }

Detecting Enter keypress on VB.NET

Use this code it will work OK. You shall click on TextBox1 and then go to event and select Keyup and double click on it. You wil then get the lines for the SUB.

Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As      
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
    If e.KeyCode = Keys.Enter Then
        MsgBox("Fel lösenord")

    End If
End Sub

PostgreSQL: role is not permitted to log in

CREATE ROLE blog WITH
  LOGIN
  SUPERUSER
  INHERIT
  CREATEDB
  CREATEROLE
  REPLICATION;

COMMENT ON ROLE blog IS 'Test';

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Git's famous "ERROR: Permission to .git denied to user"

I am using Mac and the issue is solved by deleting github record from keychain access app: Here is what i did:

  1. Open "Keychain Access.app" (You can find it in Spotlight orLaunchPad)
  2. Select "All items" in Category
  3. Search "git"
  4. Delete every old & strange items Try to Push again and it just WORKED

Above steps are copied from @spyar for the ease.

How can I dynamically set the position of view in Android?

You can try to use the following methods, if you're using HoneyComb Sdk(API Level 11).

view.setX(float x);

Parameter x is the visual x position of this view.

view.setY(float y);

Parameter y is the visual y position of this view.

I hope it will be helpful to you. :)

Change a Nullable column to NOT NULL with Default Value

If its SQL Server you can do it on the column properties within design view

Try this?:

ALTER TABLE dbo.TableName 
  ADD CONSTRAINT DF_TableName_ColumnName
    DEFAULT '01/01/2000' FOR ColumnName

How to install lxml on Ubuntu

Many answers here are rather old,
thanks to the pointer from @Simplans (https://stackoverflow.com/a/37759871/417747) and the home page...

What worked for me (Ubuntu bionic):

sudo apt-get install python3-lxml  

(+ sudo apt-get install libxml2-dev libxslt1-dev I installed before it, but not sure if that's the requirement still)

Running Node.Js on Android

the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7

It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare

You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.

Using regular expressions to do mass replace in Notepad++ and Vim

In Notepad++ :

<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D


Find what: (.*)(>)(.)
Replace with: \3

Replace All


A
B
C
D

Loop through checkboxes and count each one checked or unchecked

You can loop through all of the checkboxes by writing $(':checkbox').each(...).

If I understand your question correctly, you're looking for the following code:

var str = "";

$(':checkbox').each(function() {
    str += this.checked ? "1," : "0,";
});

str = str.substr(0, str.length - 1);    //Remove the trailing comma

This code will loop through all of the checkboxes and add either 1, or 0, to a string.

How to search a specific value in all tables (PostgreSQL)?

Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.

DO $$
DECLARE
  value int := 0;
  sql text := 'The constructed select statement';
  rec1 record;
  rec2 record;
BEGIN
  DROP TABLE IF EXISTS _x;
  CREATE TEMPORARY TABLE _x (
    schema_name text, 
    table_name text, 
    column_name text,
    found text
  );
  FOR rec1 IN 
        SELECT table_schema, table_name, column_name
        FROM information_schema.columns 
        WHERE table_name <> '_x'
                AND UPPER(column_name) LIKE UPPER('%%')                  
                AND table_schema <> 'pg_catalog'
                AND table_schema <> 'information_schema'
                AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
        LOOP
    sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
    RAISE NOTICE '%', sql;
    BEGIN
        FOR rec2 IN EXECUTE sql LOOP
            RAISE NOTICE '%', sql;
            INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
        END LOOP;
    EXCEPTION WHEN OTHERS THEN
    END;
  END LOOP;
  END; $$;

SELECT * FROM _x;

Create a custom event in Java

The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:

 public class MyClass
 {
        //... class code goes here

        public interface DataLoadFinishedListener {
            public void onDataLoadFinishedListener(int data_type);
        }

        private DataLoadFinishedListener m_lDataLoadFinished;

        public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
            this.m_lDataLoadFinished = dlf;
        }



        private void someOtherMethodOfMyClass()
        {
            m_lDataLoadFinished.onDataLoadFinishedListener(1);
        }    
    }

Usage is as follows:

myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
            @Override
            public void onDataLoadFinishedListener(int data_type) {
                }
            });

Convert string to decimal, keeping fractions

The use of CultureInfo class worked for me, I hope help you.

    string value = "1200.00";
    CultureInfo culture = new CultureInfo("en-US");
    decimal result = Convert.ToDecimal(value, culture);

Count items in a folder with PowerShell

To count the number of a specific filetype in a folder. The example is to count mp3 files on F: drive.

( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count

Tested in 6.2.3, but should work >4.

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

The problem is in the Eclipse Maven support, the related question is here.

Under Eclipse, the java.home variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files doesn't include the JDK so tools.jar is not being found.

To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini (before -vmargs!):

-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll

Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).

Initializing multiple variables to the same value in Java

Works for primitives and immutable classes like String, Wrapper classes Character, Byte.

int i=0,j=2   
String s1,s2  
s1 = s2 = "java rocks"

For mutable classes

Reference r1 = Reference r2 = Reference r3 = new Object();`  

Three references + one object are created. All references point to the same object and your program will misbehave.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Quick and clean solution (linux tested) (After fatidic February 27, 2014)


Uninstall npm

npm rm npm -g

Install npm (new URL is www.npmjs.org instead npmjs.org)

curl https://www.npmjs.org/install.sh | sh

Tip: how to install node.js in linux https://stackoverflow.com/a/22099363/333061

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

Execute an action when an item on the combobox is selected

this is how you do it with ActionLIstener

import java.awt.FlowLayout;
import java.awt.event.*;

import javax.swing.*;

public class MyWind extends JFrame{

    public MyWind() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JTextField field = new JTextField();
        field.setSize(200, 50);
        field.setText("              ");

        JComboBox comboBox = new JComboBox();
        comboBox.setEditable(true);
        comboBox.addItem("item1");
        comboBox.addItem("item2");

        //
        // Create an ActionListener for the JComboBox component.
        //
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                //
                // Get the source of the component, which is our combo
                // box.
                //
                JComboBox comboBox = (JComboBox) event.getSource();

                Object selected = comboBox.getSelectedItem();
                if(selected.toString().equals("item1"))
                field.setText("30");
                else if(selected.toString().equals("item2"))
                    field.setText("40");

            }
        });
        getContentPane().add(comboBox);
        getContentPane().add(field);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MyWind().setVisible(true);
            }
        });
    }
}

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

How to increase heap size for jBoss server

In my case, for jboss 6.3 I had to change JAVA_OPTS in file jboss-eap-6.3\bin\standalone.conf.bat and set following values -Xmx8g -Xms8g -Xmn3080m for jvm to take 8gb space.

How to get the ASCII value of a character

To get the ASCII code of a character, you can use the ord() function.

Here is an example code:

value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)

Output:

Your value here: qwerty
[113, 119, 101, 114, 116, 121]

Changing image on hover with CSS/HTML

What I usually do is that I create a double image with both states, acting like kind of a two-frame film which I then use with as background for the original element so that the element has width / height set in pixels, resulting in showing only one half of the image. Then what the hover state defines is basically "move the film to show the other frame".

For example, imagine that the image has to be a gray Tux, that we need to change to colorful Tux on hover. And the "hosting" element is a span with id "tuxie".

  1. I create 50 x 25 image with two Tuxes, one in color and other gray,
  2. then assign the image as a background for a 25 x 25 span,
  3. and finally set the hover to simply move the background 25px left.

The minimal code:

<style>
    #tuxie {
        width: 25px; height: 25px;
        background: url('images/tuxie.png') no-repeat left top;
    }
    #tuxie:hover { background-position: -25px 0px }
</style>

<div id="tuxie" />

and the image:

Two-frame Tuxie "film"

Advantages are:

  • By putting both frames in one file, it's ensured that they are loaded at once. This avoids the ugly glitch on slower connections when the other frame never loads immediately, so first hover never works properly.

  • It may be easier to manage your images this way since "paired" frames are never confused.

  • With smart use of Javascript or CSS selector, one can extend this and include even more frames in one file.

    In theory you could put even multiple buttons in single file and govern their display by coordinates, although such approach could get quickly out of hand.

Note that this is built with background CSS property, so if you really need to use with <img />s, you must not set the src property since that overlaps the background. (Come to think that clever use of transparency here could lead to interesting results, but probably very dependent on quality of image as well as of the engine.).

android - How to get view from context?

In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);

Now you can access your views via 'view' and cast them to your view type:

myImage = (ImageView) view.findViewById(R.id.my_image);

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Case insensitive string compare in LINQ-to-SQL

Remember that there is a difference between whether the query works and whether it works efficiently! A LINQ statement gets converted to T-SQL when the target of the statement is SQL Server, so you need to think about the T-SQL that would be produced.

Using String.Equals will most likely (I am guessing) bring back all of the rows from SQL Server and then do the comparison in .NET, because it is a .NET expression that cannot be translated into T-SQL.

In other words using an expression will increase your data access and remove your ability to make use of indexes. It will work on small tables and you won't notice the difference. On a large table it could perform very badly.

That's one of the problems that exists with LINQ; people no longer think about how the statements they write will be fulfilled.

In this case there isn't a way to do what you want without using an expression - not even in T-SQL. Therefore you may not be able to do this more efficiently. Even the T-SQL answer given above (using variables with collation) will most likely result in indexes being ignored, but if it is a big table then it is worth running the statement and looking at the execution plan to see if an index was used.

What is the difference between a process and a thread?

Consider process like a unit of ownership or what resources are needed by a task. A Process can have resources like memory space, specific input/output, specific files, and priority etc.

A thread is a dispatchable unit of execution or in simple words the progress through a sequence of instructions

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

Get current working directory in a Qt application

Have you tried QCoreApplication::applicationDirPath()

qDebug() << "App path : " << qApp->applicationDirPath();

Node.js Web Application examples/tutorials

DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).

Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/

And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad

Convert String to double in Java

To convert a string back into a double, try the following

String s = "10.1";
Double d = Double.parseDouble(s);

The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.

How to make custom error pages work in ASP.NET MVC 4

I've done pablo solution and I always had the error (MVC4)

The view 'Error' or its master was not found or no view engine supports the searched location.

To get rid of this, remove the line

 filters.Add(new HandleErrorAttribute());

in FilterConfig.cs

Adding header to all request with Retrofit 2

If you use addInterceptor method for add HttpLoggingInterceptor, it won't be logging the things that added by other interceptors applied later than HttpLoggingInterceptor.

For example: If you have two interceptors "HttpLoggingInterceptor" and "AuthInterceptor", and HttpLoggingInterceptor applied first, then you can't view the http-params or headers which set by AuthInterceptor.

OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(logging)
.addInterceptor(new AuthInterceptor());

I solved it, via using addNetworkInterceptor method.

How do I get HTTP Request body content in Laravel?

Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:

public function foo(Request $request){
    $bodyContent = $request->getContent();
}

MVC ajax post to controller action method

$('#loginBtn').click(function(e) {
    e.preventDefault(); /// it should not have this code or else it wont continue
    //....
});

Is it possible to add dynamically named properties to JavaScript object?

ES6 introduces computed property names, which allows you to do

let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}

The difference between the 'Local System' account and the 'Network Service' account?

Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

First the actual accounts:

  • LocalService account (preferred)

    A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

    • Name: NT AUTHORITY\LocalService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the LocalService user account
    • has minimal privileges on the local computer
    • presents anonymous credentials on the network
    • SID: S-1-5-19
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

     

  • NetworkService account

    Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

    • NT AUTHORITY\NetworkService
    • the account has no password (any password information you provide is ignored)
    • HKCU represents the NetworkService user account
    • has minimal privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers
    • SID: S-1-5-20
    • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
    • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

     

  • LocalSystem account (dangerous, don't use!)

    Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

    • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
    • the account has no password (any password information you provide is ignored)
    • SID: S-1-5-18
    • does not have any profile of its own (HKCU represents the default user)
    • has extensive privileges on the local computer
    • presents the computer's credentials (e.g. MANGO$) to remote servers

     

Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


In Windows Server 2003 you cannot run a scheduled task as

  • NT_AUTHORITY\LocalService (aka the Local Service account), or
  • NT AUTHORITY\NetworkService (aka the Network Service account).

That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

enter image description here

Calling a php function by onclick event

onclick event to call a function

  <strike> <input type="button" value="NEXT"  onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" />    </strike>

it will surely help you

it take a little more time than normal but wait it will work

Excel to CSV with UTF8 encoding

Excel typically saves a csv file as ANSI encoding instead of utf8.

One option to correct the file is to use Notepad or Notepad++:

  1. Open the .csv with Notepad or Notepad++.
  2. Copy the contents to your computer clipboard.
  3. Delete the contents from the file.
  4. Change the encoding of the file to utf8.
  5. Paste the contents back from the clipboard.
  6. Save the file.

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

git checkout foo/bar.txt

did you tried that? (without a HEAD keyword)

I usually revert my changes this way.

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

In MySQL if You don't want to change the collation and want to perform case sensitive search then just use binary keyword like this:

SELECT * FROM table_name WHERE binary username=@search_parameter and binary password=@search_parameter

In CSS what is the difference between "." and "#" when declaring a set of styles?

The # means that it matches the id of an element. The . signifies the class name:

<div id="myRedText">This will be red.</div>
<div class="blueText">this will be blue.</div>


#myRedText {
    color: red;
}
.blueText {
    color: blue;
}

Note that in a HTML document, the id attribute must be unique, so if you have more than one element needing a specific style, you should use a class name.

How to link C++ program with Boost using CMake

In CMake you could use find_package to find libraries you need. There usually is a FindBoost.cmake along with your CMake installation.

As far as I remember, it will be installed to /usr/share/cmake/Modules/ along with other find-scripts for common libraries. You could just check the documentation in that file for more information about how it works.

An example out of my head:

FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )

ADD_EXECUTABLE( anyExecutable myMain.cpp )

TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} )

I hope this code helps.

How can I make content appear beneath a fixed DIV element?

Here's a responsive way of doing it with jQuery.

 $(window).resize(function () {
      $('#YourRelativeDiv').css('margin-top', $('#YourFixedDiv').height());
 });

here-document gives 'unexpected end of file' error

The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:

cat -A myfile.sh

Once you see the output from cat -A the solution will be obvious: remove the offending characters.