Programs & Examples On #Gecko

An open source browser engine developed by Mozilla and used in browsers such as Firefox, Seamonkey and others

What is the correct "-moz-appearance" value to hide dropdown arrow of a <select> element

This is it guys! FIXED!


Wait and see: https://bugzilla.mozilla.org/show_bug.cgi?id=649849

or workaround


For those wondering:

https://bugzilla.mozilla.org/show_bug.cgi?id=649849#c59

First, because the bug has a lot of hostile spam in it, it creates a hostile workplace for anyone who gets assigned to this.

Secondly, the person who has the ability to do this (which includes rewriting ) has been allocated to another project (b2g) for the time being and wont have time until that project get nearer to completion.

Third, even when that person has the time again, there is no guarantee that this will be a priority because, despite webkit having this, it breaks the spec for how is supposed to work (This is what I was told, I do not personally know the spec)

Now see https://wiki.mozilla.org/B2G/Schedule_Roadmap ;)


The page no longer exists and the bug hasn't be fixed but an acceptable workaround came from João Cunha, you guys can thank him for now!

Is there an embeddable Webkit component for Windows / C# development?

There is OpenWebKitSharp, a fork of WebKit.NET 0.5 and very advanced. Details: http://code.google.com/p/open-webkit-sharp/

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Start by figuring out what your current working directory is for your running script.
Add this line at the beginning:

puts Dir.pwd.

This will tell you in which current working directory ruby is running your script. You will most likely see it's not where you assume it is. Then make sure you're specifying pathnames properly for windows. See the docs here how to properly format pathnames for windows:

http://www.ruby-doc.org/core/classes/IO.html

Then either use Dir.chdir to change the working directory to the place where text.txt is, or specify the absolute pathname to the file according to the instructions in the IO docs above. That SHOULD do it...

EDIT

Adding a 3rd solution which might be the most convenient one, if you're putting the text files among your script files:

Dir.chdir(File.dirname(__FILE__))

This will automatically change the current working directory to the same directory as the .rb file that is running the script.

Get yesterday's date in bash on Linux, DST-safe

This should also work, but perhaps it is too much:

date -d @$(( $(date +"%s") - 86400)) +"%Y-%m-%d"

How to copy a java.util.List into another java.util.List

I tried to do something like this, but I still got an IndexOutOfBoundsException.

I got a ConcurrentAccessException

This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either

  • use a collection which is designed for concurrent access.

  • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)

  • find a away to avoid needing to copy the original list.

PHP Array to CSV

This is a simple solution that exports an array to csv string:

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

Modal width (increase)

Simply Use !important after giving width of that class that is override your class.

For Example

.modal .modal-dialog {
  width: 850px !important;
}

Hopefully this will works for you.

Send attachments with PHP Mail()?

Working Concept :

if (isset($_POST['submit'])) {
    $mailto = $_POST["mailTo"];
    $from_mail = $_POST["fromEmail"];
    $replyto = $_POST["fromEmail"];
    $from_name = $_POST["fromName"];
    $message = $_POST["message"];
    $subject = $_POST["subject"];

    $filename = $_FILES["fileAttach"]["name"];
    $content = chunk_split(base64_encode(file_get_contents($_FILES["fileAttach"]["tmp_name"])));

    $uid = md5(uniqid(time()));
    $name = basename($file);
    $header = "From: " . $from_name . " <" . $from_mail . ">\r\n";
    $header .= "Reply-To: " . $replyto . "\r\n";

    $header .= "MIME-Version: 1.0\r\n";
    $header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format.\r\n";
    $header .= "--" . $uid . "\r\n";

// You add html "Content-type: text/html; charset=utf-8\n" or for Text "Content-type:text/plain; charset=iso-8859-1\r\n" by I.khan
    $header .= "Content-type:text/html; charset=utf-8\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";

// User Message you can add HTML if You Selected HTML content
    $header .= "<div style='color: red'>" . $message . "</div>\r\n\r\n";

    $header .= "--" . $uid . "\r\n";
    $header .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"\r\n"; // use different content types here
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n"; // For Attachment
    $header .= $content . "\r\n\r\n";
    $header .= "--" . $uid . "--";
    if (mail($mailto, $subject, "", $header)) {
        echo "<script>alert('Success');</script>"; // or use booleans here
    } else {
        echo "<script>alert('Failed');</script>";
    }
}

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

How can I create a copy of an Oracle table without copying the data?

In other way you can get ddl of table creation from command listed below, and execute the creation.

SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL 
  • TYPE is TABLE,PROCEDURE etc.

With this command you can get majority of ddl from database objects.

DateTime.MinValue and SqlDateTime overflow

I am using this function to tryparse

public static bool TryParseSqlDateTime(string someval, DateTimeFormatInfo dateTimeFormats, out DateTime tryDate)
    {
        bool valid = false;
        tryDate = (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
        System.Data.SqlTypes.SqlDateTime sdt;
        if (DateTime.TryParse(someval, dateTimeFormats, DateTimeStyles.None, out tryDate))
        {
            try
            {
                sdt = new System.Data.SqlTypes.SqlDateTime(tryDate);
                valid = true;
            }
            catch (System.Data.SqlTypes.SqlTypeException ex)
            {

            }
        }

        return valid;
    }

Box shadow for bottom side only

You have to specify negative spread in the box shadow to remove side shadow

-webkit-box-shadow: 0 10px 10px -10px #000000;
   -moz-box-shadow: 0 10px 10px -10px #000000;
        box-shadow: 0 10px 10px -10px #000000;

Check out http://dabblet.com/gist/9532817 and try changing properties and know how it behaves

css transform, jagged edges in chrome

For canvas in Chrome (Version 52)

All listed answers is about images. But my issue is about canvas in chrome (v.52) with transform rotate. They became jagged and all this methods can't help.

Solution that works for me:

  1. Make canvas larger on 1 px for each side => +2 px for width and height;
  2. Draw image with offset + 1px (in position 1,1 instead of 0,0) and fixed size (size of image should be 2px less than size of canvas)
  3. Apply required rotation

So important code blocks:

_x000D_
_x000D_
// Unfixed version
ctx.drawImage(img, 0, 0, 335, 218);
// Fixed version
ctx.drawImage(img, 1, 1, 335, 218);
_x000D_
/* This style should be applied for fixed version */
canvas {
  margin-left: -1px;
  margin-top:-1px;
}        
_x000D_
<!--Unfixed version-->
<canvas width="335" height="218"></canvas>
<!--Fixed version-->
<canvas width="337" height="220"></canvas>
_x000D_
_x000D_
_x000D_

Sample: https://jsfiddle.net/tLbxgusx/1/

Note: there is a lot of nested divs because it is simplified version from my project.


This issue is reproduced also for Firefox for me. There is no such issue on Safari and FF with retina.

And other founded solution is to place canvas into div of same size and apply following css to this div:

overflow: hidden;
box-shadow: 0 0 1px rgba(255,255,255,0);
// Or
//outline:1px solid transparent;

And rotation should be applied to this wrapping div. So listed solution is worked but with small modification.

And modified example for such solution is: https://jsfiddle.net/tLbxgusx/2/

Note: See style of div with class 'third'.

@ViewChild in *ngIf

I had the same problem myself, with Angular 10.

If I tried to use [hidden] or *ngIf, then the @ViewChild variable was always undefined.

<p-calendar #calendar *ngIf="bShowCalendar" >
</p-calendar>

I fixed it by not removing it from the webpage.
I used an [ngClass] to make the control have opacity:0, and move it completely out of the way.

<style>
  .notVisible {
    opacity: 0;
    left: -1000px;
    position: absolute !important;
  }
</style>

<p-calendar #calendar [ngClass]="{'notVisible': bShowCalendar }" >
</p-calendar>

Yeah, I know, it's dumb and ugly, but it fixed the problem.

I also had to make the control static. I don't understand why.. but, again, it refused to work without this change:

export class DatePickerCellRenderer {
    @ViewChild('calendar', {static: true }) calendar: Calendar;

Determining if a number is prime

Someone above had the following.

bool check_prime(int num) {
for (int i = num - 1; i > 1; i--) {
    if ((num % i) == 0)
        return false;
}
return true;
}

This mostly worked. I just tested it in Visual Studio 2017. It would say that anything less than 2 was also prime (so 1, 0, -1, etc.)

Here is a slight modification to correct this.

bool check_prime(int number)
{
    if (number > 1)
    {
        for (int i = number - 1; i > 1; i--)
        {
            if ((number % i) == 0)
                return false;
        }
        return true;
    }
    return false;
}

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("your.package.to.scan");
        return marshaller;
    }

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

How do I convert Word files to PDF programmatically?

Use a foreach loop instead of a for loop - it solved my problem.

int j = 0;
foreach (Microsoft.Office.Interop.Word.Page p in pane.Pages)
{
    var bits = p.EnhMetaFileBits;
    var target = path1 +j.ToString()+  "_image.doc";
    try
    {
        using (var ms = new MemoryStream((byte[])(bits)))
        {
            var image = System.Drawing.Image.FromStream(ms);
            var pngTarget = Path.ChangeExtension(target, "png");
            image.Save(pngTarget, System.Drawing.Imaging.ImageFormat.Png);
        }
    }
    catch (System.Exception ex)
    {
        MessageBox.Show(ex.Message);  
    }
    j++;
}

Here is a modification of a program that worked for me. It uses Word 2007 with the Save As PDF add-in installed. It searches a directory for .doc files, opens them in Word and then saves them as a PDF. Note that you'll need to add a reference to Microsoft.Office.Interop.Word to the solution.

using Microsoft.Office.Interop.Word;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

...

// Create a new Microsoft Word application object
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();

// C# doesn't have optional arguments so we'll need a dummy value
object oMissing = System.Reflection.Missing.Value;

// Get list of Word files in specified directory
DirectoryInfo dirInfo = new DirectoryInfo(@"\\server\folder");
FileInfo[] wordFiles = dirInfo.GetFiles("*.doc");

word.Visible = false;
word.ScreenUpdating = false;

foreach (FileInfo wordFile in wordFiles)
{
    // Cast as Object for word Open method
    Object filename = (Object)wordFile.FullName;

    // Use the dummy value as a placeholder for optional arguments
    Document doc = word.Documents.Open(ref filename, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);
    doc.Activate();

    object outputFileName = wordFile.FullName.Replace(".doc", ".pdf");
    object fileFormat = WdSaveFormat.wdFormatPDF;

    // Save document into PDF Format
    doc.SaveAs(ref outputFileName,
        ref fileFormat, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing,
        ref oMissing, ref oMissing, ref oMissing, ref oMissing);

    // Close the Word document, but leave the Word application open.
    // doc has to be cast to type _Document so that it will find the
    // correct Close method.                
    object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
    ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);
    doc = null;
}

// word has to be cast to type _Application so that it will find
// the correct Quit method.
((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
word = null;

Getting HTML elements by their attribute names

With prototypejs :

 $$('span[property=v.name]');

or

document.body.select('span[property=v.name]');

Both return an array

How to randomize two ArrayLists in the same fashion?

Use Collections.shuffle() twice, with two Random objects initialized with the same seed:

long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));

Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

How do I enable the column selection mode in Eclipse?

You can enable and disable column editing mode via the keyboard shortcut ALT-SHIFT-A.

Once enabled you can then use either the mouse to select a block of text, or the keyboard using SHIFT (like a normal keyboard select, except the selection will now be in a block).

If you've changed your default font for text editing, entering column editing mode will probably change your screen font to the default column editing font (which is probably different to your changed font. To change the font when in column editing mode, go to the menu and select Window -> Preferences, then in the tree on the left hand side, pick General -> Appearance -> Colors and Fonts, and then pick Basic -> Text Editor Block Selection Font on the right hand side tree. You can then select the font to be consistent with your "not in column editing mode" font.

How to check if a Docker image with a specific tag exist locally?

Using test

if test ! -z "$(docker images -q <name:tag>)"; then
  echo "Exist"
fi

or in one line

test ! -z "$(docker images -q <name:tag>)" &&  echo exist

How to use a RELATIVE path with AuthUserFile in htaccess?

For just in case people are looking for solution for this:

<If "req('Host') = 'www.example.com'">
    Authtype Basic
    AuthName "user and password"
    AuthUserFile /var/www/www.example.com/.htpasswd
    Require valid-user
</If>

Which method performs better: .Any() vs .Count() > 0?

Since this is a rather popular topic and answers differ, I had to take a fresh look on the problem.

Testing env: EF 6.1.3, SQL Server, 300k records

Table model:

class TestTable
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Surname { get; set; }
}

Test code:

class Program
{
    static void Main()
    {
        using (var context = new TestContext())
        {
            context.Database.Log = Console.WriteLine;

            context.TestTables.Where(x => x.Surname.Contains("Surname")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Any(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname")).Count(x => x.Id > 1000);
            context.TestTables.Where(x => x.Surname.Contains("Surname") && x.Name.Contains("Name")).Count(x => x.Id > 1000);

            Console.ReadLine();
        }
    }
}

Results:

Any() ~ 3ms

Count() ~ 230ms for first query, ~ 400ms for second

Remarks:

For my case, EF didn't generate SQL like @Ben mentioned in his post.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

just put below code:

    implementation 'com.google.firebase:firebase-core:16.0.6'
    implementation 'com.google.firebase:firebase-database:16.0.6'

and rebuild. it works just for fine for me

Maven: How do I activate a profile from command line?

Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:

<activation> <activeByDefault>false</activeByDefault> </activation>

then your profile will be activated only after explicit declaration as -Pdev1

PHP passing $_GET in linux command prompt

I don't have a php-cgi binary on Ubuntu, so I did this:

% alias php-cgi="php -r '"'parse_str(implode("&", array_slice($argv, 2)), $_GET); include($argv[1]);'"' --"
% php-cgi test1.php foo=123
<html>
You set foo to 123.
</html>

%cat test1.php
<html>You set foo to <?php print $_GET['foo']?>.</html>

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

CSS file not refreshing in browser

Is this a local custom CSS file? Is this your website? Maybe you should clear your cache.

Also the last CSS declaration takes precedence.

Plot two histograms on single chart with matplotlib

Just in case you have pandas (import pandas as pd) or are ok with using it:

test = pd.DataFrame([[random.gauss(3,1) for _ in range(400)], 
                     [random.gauss(4,2) for _ in range(400)]])
plt.hist(test.values.T)
plt.show()

Install a .NET windows service without InstallUtil.exe

Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...

Here's an example:

[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
    public MyServiceInstallerProcess()
    {
        this.Account = ServiceAccount.NetworkService;
    }
}

[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
    public MyServiceInstaller()
    {
        this.Description = "Service Description";
        this.DisplayName = "Service Name";
        this.ServiceName = "ServiceName";
        this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
    }
}

static void Install(bool undo, string[] args)
{
    try
    {
        Console.WriteLine(undo ? "uninstalling" : "installing");
        using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
        {
            IDictionary state = new Hashtable();
            inst.UseNewContext = true;
            try
            {
                if (undo)
                {
                    inst.Uninstall(state);
                }
                else
                {
                    inst.Install(state);
                    inst.Commit(state);
                }
            }
            catch
            {
                try
                {
                    inst.Rollback(state);
                }
                catch { }
                throw;
            }
        }
    }
    catch (Exception ex)
    {
        Console.Error.WriteLine(ex.Message);
    }
}

Passing Arrays to Function in C++

The question has already been answered, but I thought I'd add an answer with more precise terminology and references to the C++ standard.

Two things are going on here, array parameters being adjusted to pointer parameters, and array arguments being converted to pointer arguments. These are two quite different mechanisms, the first is an adjustment to the actual type of the parameter, whereas the other is a standard conversion which introduces a temporary pointer to the first element.

Adjustments to your function declaration:

dcl.fct#5:

After determining the type of each parameter, any parameter of type “array of T” (...) is adjusted to be “pointer to T”.

So int arg[] is adjusted to be int* arg.

Conversion of your function argument:

conv.array#1

An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The temporary materialization conversion is applied. The result is a pointer to the first element of the array.

So in printarray(firstarray, 3);, the lvalue firstarray of type "array of 3 int" is converted to a prvalue (temporary) of type "pointer to int", pointing to the first element.

Checking if a variable is an integer in PHP

I had a similar problem just now!

You can use the filter_input() function with FILTER_VALIDATE_INT and FILTER_NULL_ON_FAILURE to filter only integer values out of the $_GET variable. Works pretty accurately! :)

Check out my question here: How to check whether a variable in $_GET Array is an integer?

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

Bootstrap 3 Align Text To Bottom of Div

The easiest way I have tested just add a <br> as in the following:

<div class="col-sm-6">
    <br><h3><p class="text-center">Some Text</p></h3>
</div>

The only problem is that a extra line break (generated by that <br>) is generated when the screen gets smaller and it stacks. But it is quick and simple.

Determine the number of NA values in a column

In the interests of completeness you can also use the useNA argument in table. For example table(df$col, useNA="always") will count all of non NA cases and the NA ones.

Finding all possible combinations of numbers to reach a given sum

@KeithBeller's answer with slightly changed variable names and some comments.

    public static void Main(string[] args)
    {
        List<int> input = new List<int>() { 3, 9, 8, 4, 5, 7, 10 };
        int targetSum = 15;
        SumUp(input, targetSum);
    }

    public static void SumUp(List<int> input, int targetSum)
    {
        SumUpRecursive(input, targetSum, new List<int>());
    }

    private static void SumUpRecursive(List<int> remaining, int targetSum, List<int> listToSum)
    {
        // Sum up partial
        int sum = 0;
        foreach (int x in listToSum)
            sum += x;

        //Check sum matched
        if (sum == targetSum)
            Console.WriteLine("sum(" + string.Join(",", listToSum.ToArray()) + ")=" + targetSum);

        //Check sum passed
        if (sum >= targetSum)
            return;

        //Iterate each input character
        for (int i = 0; i < remaining.Count; i++)
        {
            //Build list of remaining items to iterate
            List<int> newRemaining = new List<int>();
            for (int j = i + 1; j < remaining.Count; j++)
                newRemaining.Add(remaining[j]);

            //Update partial list
            List<int> newListToSum = new List<int>(listToSum);
            int currentItem = remaining[i];
            newListToSum.Add(currentItem);
            SumUpRecursive(newRemaining, targetSum, newListToSum);
        }
    }'

Attach a file from MemoryStream to a MailMessage in C#

I landed on this question because I needed to attach an Excel file I generate through code and is available as MemoryStream. I could attach it to the mail message but it was sent as 64Bytes file instead of a ~6KB as it was meant. So, the solution that worked for me was this:

MailMessage mailMessage = new MailMessage();
Attachment attachment = new Attachment(myMemorySteam, new ContentType(MediaTypeNames.Application.Octet));

attachment.ContentDisposition.FileName = "myFile.xlsx";
attachment.ContentDisposition.Size = attachment.Length;

mailMessage.Attachments.Add(attachment);

Setting the value of attachment.ContentDisposition.Size let me send messages with the correct size of attachment.

Responsive image map

I come across with same requirement where, I wants to show responsive image map which can resize with any screen size and important thing is, i want to highlight that coordinates.

So i tried many libraries which can resize coordinates according to screen size and event. And i got best solution(jquery.imagemapster.min.js) which works fine with almost all browsers. Also i have integrated it with Summer Plgin which create image map.

_x000D_
_x000D_
 var resizeTime = 100;
 var resizeDelay = 100;    

$('img').mapster({
        areas: [
            {
                key: 'tbl',
                fillColor: 'ff0000',
                staticState: true,
                stroke: true
            }
        ],
        mapKey: 'state'
    });

    // Resize the map to fit within the boundaries provided

    function resize(maxWidth, maxHeight) {
        var image = $('img'),
            imgWidth = image.width(),
            imgHeight = image.height(),
            newWidth = 0,
            newHeight = 0;

        if (imgWidth / maxWidth > imgHeight / maxHeight) {
            newWidth = maxWidth;
        } else {
            newHeight = maxHeight;
        }
        image.mapster('resize', newWidth, newHeight, resizeTime);
    }

    function onWindowResize() {

        var curWidth = $(window).width(),
            curHeight = $(window).height(),
            checking = false;
        if (checking) {
            return;
        }
        checking = true;
        window.setTimeout(function () {
            var newWidth = $(window).width(),
                newHeight = $(window).height();
            if (newWidth === curWidth &&
                newHeight === curHeight) {
                resize(newWidth, newHeight);
            }
            checking = false;
        }, resizeDelay);
    }

    $(window).bind('resize', onWindowResize);
_x000D_
img[usemap] {
        border: none;
        height: auto;
        max-width: 100%;
        width: auto;
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.imagemapster.min.js"></script>

<img src="https://discover.luxury/wp-content/uploads/2016/11/Cities-With-the-Most-Michelin-Star-Restaurants-1024x581.jpg" alt="" usemap="#map" />
<map name="map">
    <area shape="poly" coords="777, 219, 707, 309, 750, 395, 847, 431, 916, 378, 923, 295, 870, 220" href="#" alt="poly" title="Polygon" data-maphilight='' state="tbl"/>
    <area shape="circle" coords="548, 317, 72" href="#" alt="circle" title="Circle" data-maphilight='' state="tbl"/>
    <area shape="rect" coords="182, 283, 398, 385" href="#" alt="rect" title="Rectangle" data-maphilight='' state="tbl"/>
</map>
_x000D_
_x000D_
_x000D_

Hope help it to someone.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

React 16 gets your return as an array so it should be wrapped by one element like div.

Wrong Approach

render(){
    return(
    <input type="text" value="" onChange={this.handleChange} />

     <button className="btn btn-primary" onClick=   {()=>this.addTodo(this.state.value)}>Submit</button>

    );
}

Right Approach (All elements in one div or other element you are using)

render(){
    return(
        <div>
            <input type="text" value="" onChange={this.handleChange} />

            <button className="btn btn-primary" onClick={()=>this.addTodo(this.state.value)}>Submit</button>
        </div>
    );
}

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Rest-assured. Is it possible to extract value from request json?

To serialize the response into a class, define the target class

public class Result {
    public Long user_id;
}

And map response to it:

Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);

You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)

fatal: could not create work tree dir 'kivy'

Assuming that you are using Windows, run the application as Admin.

For that, you have at least two options:

• Open the file location, right click and select "Run as Administrator".

Run Git Bash as Admin

• Using Windows Start menu, search for "Git Bash", and you will find the following:

Git Bash using Windows Start Menu

Then, just press "Run as Administrator".

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

How to get data out of a Node.js http get request

from learnyounode:

var http = require('http')  

http.get(options, function (response) {  
  response.setEncoding('utf8')  
  response.on('data', console.log)  
  response.on('error', console.error)  
})

'options' is the host/path variable

How to reduce the image size without losing quality in PHP

If you are looking to reduce the size using coding itself, you can follow this code in php.

<?php 
function compress($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
        $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
        $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
        $image = imagecreatefrompng($source);

    imagejpeg($image, $destination, $quality);

    return $destination;
}

$source_img = 'source.jpg';
$destination_img = 'destination .jpg';

$d = compress($source_img, $destination_img, 90);
?>

$d = compress($source_img, $destination_img, 90);

This is just a php function that passes the source image ( i.e., $source_img ), destination image ( $destination_img ) and quality for the image that will take to compress ( i.e., 90 ).

$info = getimagesize($source);

The getimagesize() function is used to find the size of any given image file and return the dimensions along with the file type.

Eclipse fonts and background color

On Windows or Mac, you can find this setting under the General ? Editors ? Text Editors menu.

How do I add a reference to the MySQL connector for .NET?

As mysql official documentation:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

Online Documentation:

MySQL Connector/Net Installation Instructions

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

The .sort() function stores the value of new list directly in the list variable; so answer for your third question would be NO. Also if you do this using sorted(list), then you can get it use because it is not stored in the list variable. Also sometimes .sort() method acts as function, or say that it takes arguments in it.

You have to store the value of sorted(list) in a variable explicitly.

Also for short data processing the speed will have no difference; but for long lists; you should directly use .sort() method for fast work; but again you will face irreversible actions.

CSS Flex Box Layout: full-width row and columns

Just use another container to wrap last two divs. Don't forget to use CSS prefixes.

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
   display: flex;_x000D_
   flex-direction: column;_x000D_
   height: 600px;_x000D_
   width: 580px;_x000D_
   background-color: rgb(240, 240, 240);_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
   height: 100px;_x000D_
   background-color: rgb(200, 200, 200);_x000D_
}_x000D_
_x000D_
#anotherContainer{_x000D_
   display: flex;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
   background-color: red;_x000D_
   flex: 4;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
   background-color: blue;_x000D_
   flex: 1;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
   <div id="productShowcaseTitle">1</div>_x000D_
   <div id="anotherContainer">_x000D_
      <div id="productShowcaseDetail">2</div>_x000D_
      <div id="productShowcaseThumbnailContainer">3</div>_x000D_
   </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get current URL from IFRAME

If you're inside an iframe that don't have cross domain src, or src is empty:

Then:

function getOriginUrl() {
    var href = document.location.href;
    var referrer = document.referrer;
    // Check if window.frameElement not null
    if(window.frameElement) {
        href = window.frameElement.ownerDocument.location.href;
        // This one will be origin
        if(window.frameElement.ownerDocument.referrer != "") {
            referrer = window.frameElement.ownerDocument.referrer;
        }
    }
    // Compare if href not equal to referrer
    if(href != referrer) {
        // Take referrer as origin
        return referrer;
    } else {
        // Take href
        return href
    }
}

If you're inside an iframe with cross domain src:

Then:

function getOriginUrl() {
    var href = document.location.href;
    var referrer = document.referrer;
    // Detect if you're inside an iframe
    if(window.parent != window) {
        // Take referrer as origin
        return referrer;
    } else {
        // Take href
        return href;
    }
}

How to vertically center a container in Bootstrap?

Update 2020

Bootstrap 4 includes flexbox, so the method of vertical centering is much easier and doesn't require extra CSS.

Just use the d-flex and align-items-center utility classes..

<div class="jumbotron d-flex align-items-center">
  <div class="container">
    content
  </div>
</div>

http://www.codeply.com/go/ui6ABmMTLv

Important: Vertical centering is relative to height. The parent container of the items you're attempting to center must have a defined height. If you want the height of the page use vh-100 or min-vh-100 on the parent! For example:

<div class="jumbotron d-flex align-items-center min-vh-100">
  <div class="container text-center">
    I am centered vertically
  </div>
</div>

Also see: https://stackoverflow.com/questions/42252443/vertical-align-center-in-bootstrap-4

Is it possible to install another version of Python to Virtualenv?

I'm using virtualenvwrapper and don't want to modify $PATH, here's how:

$ which python3
/usr/local/bin/python3

$ mkvirtualenv --python=/usr/local/bin/python3 env_name

What is the difference between an int and a long in C++?

When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.

GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.

MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.

Why is __dirname not defined in node REPL?

Seems like you could also do this:

__dirname=fs.realpathSync('.');

of course, dont forget fs=require('fs')

(it's not really global in node scripts exactly, its just defined on the module level)

Split string into strings by length?

length = 4
string = "abcdefgh"
str_dict = [ o for o in string ]
parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ]   ) for j in xrange(len(string)/length  )]

Python coding standards/best practices

PEP 8 is good, the only thing that i wish it came down harder on was the Tabs-vs-Spaces holy war.

Basically if you are starting a project in python, you need to choose Tabs or Spaces and then shoot all offenders on sight.

What are all possible pos tags of NLTK?

You can download the list here: ftp://ftp.cis.upenn.edu/pub/treebank/doc/tagguide.ps.gz. It includes confusing parts of speech, capitalization, and other conventions. Also, wikipedia has an interesting section similar to this. Section: Part-of-speech tags used.

How to read a large file line by line?

From the python documentation for fileinput.input():

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty

further, the definition of the function is:

fileinput.FileInput([files[, inplace[, backup[, mode[, openhook]]]]])

reading between the lines, this tells me that files can be a list so you could have something like:

for each_line in fileinput.input([input_file, input_file]):
  do_something(each_line)

See here for more information

How to read all files in a folder from Java?

Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:

import java.io.File;

public class List {
    public static void main(String[] args) {
        for (String f : args) {
            listDir(f);
        }
    }

    private static void listDir(String dir) {
        File f = new File(dir);
        File[] list = f.listFiles();

        if (list == null) {
            return;
        }

        for (File entry : list) {
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                listDir(entry.getAbsolutePath());
            }
        }
    }
}

When I catch an exception, how do I get the type, file, and line number?

Simplest form that worked for me.

import traceback

try:
    print(4/0)
except ZeroDivisionError:
    print(traceback.format_exc())

Output

Traceback (most recent call last):
  File "/path/to/file.py", line 51, in <module>
    print(4/0)
ZeroDivisionError: division by zero

Process finished with exit code 0

How can I git stash a specific file?

To add to svick's answer, the -m option simply adds a message to your stash, and is entirely optional. Thus, the command

git stash push [paths you wish to stash]

is perfectly valid. So for instance, if I want to only stash changes in the src/ directory, I can just run

git stash push src/

What Ruby IDE do you prefer?

I have used Komodo and it's pretty good. I use TextMate now.

Can one do a for each loop in java in reverse order?

AFAIK there isn't a standard "reverse_iterator" sort of thing in the standard library that supports the for-each syntax which is already a syntactic sugar they brought late into the language.

You could do something like for(Item element: myList.clone().reverse()) and pay the associated price.

This also seems fairly consistent with the apparent phenomenon of not giving you convenient ways to do expensive operations - since a list, by definition, could have O(N) random access complexity (you could implement the interface with a single-link), reverse iteration could end up being O(N^2). Of course, if you have an ArrayList, you don't pay that price.

How do I change the number of open files limit in Linux?

1) Add the following line to /etc/security/limits.conf

webuser hard nofile 64000

then login as webuser

su - webuser

2) Edit following two files for webuser

append .bashrc and .bash_profile file by running

echo "ulimit -n 64000" >> .bashrc ; echo "ulimit -n 64000" >> .bash_profile

3) Log out, then log back in and verify that the changes have been made correctly:

$ ulimit -a | grep open
open files                      (-n) 64000

Thats it and them boom, boom boom.

How to get the number of characters in a string

I tried to make to do the normalization a bit faster:

    en, _ = glyphSmart(data)

    func glyphSmart(text string) (int, int) {
        gc := 0
        dummy := 0
        for ind, _ := range text {
            gc++
            dummy = ind
        }
        dummy = 0
        return gc, dummy
    }

"Data too long for column" - why?

Very old question, but I tried everything suggested above and still could not get it resolved.

Turns out that, I had after insert/update trigger for the main table which tracked the changes by inserting the record in history table having similar structure. I increased the size in the main table column but forgot to change the size of history table column and that created the problem.

I did similar changes in the other table and error is gone.

ImportError: No Module Named bs4 (BeautifulSoup)

pip install --user BeautifulSoup4

jquery : focus to div is not working

you can use the below code to bring focus to a div, in this example the page scrolls to the <div id="navigation">

$('html, body').animate({ scrollTop: $('#navigation').offset().top }, 'slow');

Using C# to check if string contains a string in string array

Just use linq method:

stringArray.Contains(stringToCheck)

SELECT * WHERE NOT EXISTS

You can do a LEFT JOIN and assert the joined column is NULL.

Example:

SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL

Undefined symbols for architecture arm64

This worked for me:

ios sdk 9.3

into your build setting of app.xcodeproj valid architecture: armv7 armv7s Build Active architecture : No

Clean and build , worked for me.

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

If you already have "bash", "powershell" and "cmd" CLI's and have correct path settings then switching from one CLI to another can done by the following ways.

Ctrl + ' : Opens the terminal window with default CLI.

bash + enter : Switch from your default/current CLI to bash CLI.

powershell + enter : Switch from your default/current CLI to powershell CLI.

cmd + enter : Switch from your default/current CLI to cmd CLI.

VS Code Version I'm using is 1.45.0

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

python
>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code

#!<path_from_which_python_command>

Phonegap Cordova installation Windows

I too struggled a lot with phonegap steps.

The correct documentation is at the following link. http://docs.phonegap.com/en/edge/guide_cli_index.md.html

There is no more cordova command, It is replaced with phonegap.

Text to speech(TTS)-Android

Try this, its simple : **speakout.xml : **

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#3498db"
android:weightSum="1"
android:orientation="vertical" >
<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight=".1"
android:gravity="center"
android:padding="3dp"
android:text="Speak Out!!!"
android:textColor="#fff"
android:textSize="25sp"
android:textStyle="bold" />
<EditText
android:id="@+id/edtTexttoSpeak"
android:layout_width="match_parent"
android:layout_weight=".5"
android:background="#fff"
android:textColor="#2c3e50"
android:text="Hi there!!!"
android:padding="5dp"
android:gravity="top|left"
android:layout_height="0dp"/>
<Button
android:id="@+id/btnspeakout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".1"
android:background="#e74c3c"
android:textColor="#fff"
android:text="SPEAK OUT"/>
</LinearLayout>

And Your SpeakOut.java :

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SpeakOut extends Activity implements OnInitListener {
private TextToSpeech repeatTTS;
Button btnspeakout;
EditText edtTexttoSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speakout);
    btnspeakout = (Button) findViewById(R.id.btnspeakout);
    edtTexttoSpeak = (EditText) findViewById(R.id.edtTexttoSpeak);
    repeatTTS = new TextToSpeech(this, this);
    btnspeakout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            repeatTTS.speak(edtTexttoSpeak.getText().toString(),
            TextToSpeech.QUEUE_FLUSH, null);
        }
    });
}

@Override
    public void onInit(int arg0) {
        // TODO Auto-generated method stub
    }
}

SOURCE Parallelcodes.com's Post

Convert from DateTime to INT

EDIT: Casting to a float/int no longer works in recent versions of SQL Server. Use the following instead:

select datediff(day, '1899-12-30T00:00:00', my_date_field)
from mytable

Note the string date should be in an unambiguous date format so that it isn't affected by your server's regional settings.


In older versions of SQL Server, you can convert from a DateTime to an Integer by casting to a float, then to an int:

select cast(cast(my_date_field as float) as int)
from mytable

(NB: You can't cast straight to an int, as MSSQL rounds the value up if you're past mid day!)

If there's an offset in your data, you can obviously add or subtract this from the result

You can convert in the other direction, by casting straight back:

select cast(my_integer_date as datetime)
from mytable

Calling a class method raises a TypeError in Python

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

Passing arguments to JavaScript function from code-behind

Some other things I found out:

You can't directly pass in an array like:

this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xx",   
"<script>test("+x+","+y+");</script>");

because that calls the ToString() methods of x and y, which returns "System.Int32[]", and obviously Javascript can't use that. I had to pass in the arrays as strings, like "[1,2,3,4,5]", so I wrote a helper method to do the conversion.

Also, there is a difference between this.Page.ClientScript.RegisterStartupScript() and this.Page.ClientScript.RegisterClientScriptBlock() - the former places the script at the bottom of the page, which I need in order to be able to access the controls (like with document.getElementByID). RegisterClientScriptBlock() is executed before the tags are rendered, so I actually get a Javascript error if I use that method.

http://www.wrox.com/WileyCDA/Section/Manipulating-ASP-NET-Pages-and-Server-Controls-with-JavaScript.id-310803.html covers the difference between the two pretty well.

Here's the complete example I came up with:

// code behind
protected void Button1_Click(object sender, EventArgs e)
{
    int[] x = new int[] { 1, 2, 3, 4, 5 };
    int[] y = new int[] { 1, 2, 3, 4, 5 };

    string xStr = getArrayString(x); // converts {1,2,3,4,5} to [1,2,3,4,5]
    string yStr = getArrayString(y);

    string script = String.Format("test({0},{1})", xStr, yStr);
    this.Page.ClientScript.RegisterStartupScript(this.GetType(),
    "testFunction", script, true);
    //this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
    //"testFunction", script, true); // different result
}
private string getArrayString(int[] array)
{
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.Length; i++)
    {
        sb.Append(array[i] + ",");
    }
    string arrayStr = string.Format("[{0}]", sb.ToString().TrimEnd(','));
    return arrayStr;
}

//aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript">
    function test(x, y)
    {
        var text1 = document.getElementById("text1")
        for(var i = 0; i<x.length; i++)
        {
            text1.innerText += x[i]; // prints 12345
        }
        text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5

    }

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="Button"
         onclick="Button1_Click" />
    </div>
    <div id ="text1"> 
    </div>
    </form>
</body>
</html>

How do I add a auto_increment primary key in SQL Server database?

If the table already contains data and you want to change one of the columns to identity:

First create a new table that has the same columns and specify the primary key-kolumn:

create table TempTable
(
    Id int not null identity(1, 1) primary key
    --, Other columns...
)

Then copy all rows from the original table to the new table using a standard insert-statement.

Then drop the original table.

And finally rename TempTable to whatever you want using sp_rename:

http://msdn.microsoft.com/en-us/library/ms188351.aspx

Get TimeZone offset value from TimeZone without TimeZone name

With java8 now, you can use

Integer offset  = ZonedDateTime.now().getOffset().getTotalSeconds();

to get the current system time offset from UTC. Then you can convert it to any format you want. Found it useful for my case. Example : https://docs.oracle.com/javase/tutorial/datetime/iso/timezones.html

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

How to open my files in data_folder with pandas using relative path?

import pandas as pd
df = pd.read_csv('C:/data_folder/data.csv')

What is VanillaJS?

This is VanillaJS (unmodified):

// VanillaJS v1.0
// Released into the Public Domain
// Your code goes here:

As you can see, it's not really a framework or a library. It's just a running gag for framework-loving bosses or people who think you NEED to use a JS framework. It means you just use whatever your (for you own sake: non-legacy) browser gives you (using Vanilla JS when working with legacy browsers is a bad idea).

How to center a label text in WPF?

You have to use HorizontalContentAlignment="Center" and! Width="Auto".

Catch a thread's exception in the caller thread in Python

In Python 3.8, we can use threading.excepthook to hook the uncaught exceptions in all the child threads! For example,

threading.excepthook = thread_exception_handler

Referer: https://stackoverflow.com/a/60002752/5093308

Java String split removed empty values

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

String[] split = data.split("\\|", -1);

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Exception:

It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array.
It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.

How to create a self-signed certificate with OpenSSL

I can`t comment so I add a separate answer. I tried to create a self-signed certificate for NGINX and it was easy, but when I wanted to add it to Chrome white list I had a problem. And my solution was to create a Root certificate and signed a child certificate by it.

So step by step. Create file config_ssl_ca.cnf Notice, config file has an option basicConstraints=CA:true which means that this certificate is supposed to be root.

This is a good practice, because you create it once and can reuse.

[ req ]
default_bits = 2048

prompt = no
distinguished_name=req_distinguished_name
req_extensions = v3_req

[ req_distinguished_name ]
countryName=UA
stateOrProvinceName=root region
localityName=root city
organizationName=Market(localhost)
organizationalUnitName=roote department
commonName=market.localhost
[email protected]

[ alternate_names ]
DNS.1        = market.localhost
DNS.2        = www.market.localhost
DNS.3        = mail.market.localhost
DNS.4        = ftp.market.localhost
DNS.5        = *.market.localhost

[ v3_req ]
keyUsage=digitalSignature
basicConstraints=CA:true
subjectKeyIdentifier = hash
subjectAltName = @alternate_names

Next config file for your child certificate will be call config_ssl.cnf.

[ req ]
default_bits = 2048

prompt = no
distinguished_name=req_distinguished_name
req_extensions = v3_req

[ req_distinguished_name ]
countryName=UA
stateOrProvinceName=Kyiv region
localityName=Kyiv
organizationName=market place
organizationalUnitName=market place department
commonName=market.localhost
[email protected]

[ alternate_names ]
DNS.1        = market.localhost
DNS.2        = www.market.localhost
DNS.3        = mail.market.localhost
DNS.4        = ftp.market.localhost
DNS.5        = *.market.localhost

[ v3_req ]
keyUsage=digitalSignature
basicConstraints=CA:false
subjectAltName = @alternate_names
subjectKeyIdentifier = hash

The first step - create Root key and certificate

openssl genrsa -out ca.key 2048
openssl req -new -x509 -key ca.key -out ca.crt -days 365 -config config_ssl_ca.cnf

The second step creates child key and file CSR - Certificate Signing Request. Because the idea is to sign the child certificate by root and get a correct certificate

openssl genrsa -out market.key 2048
openssl req -new -sha256 -key market.key -config config_ssl.cnf -out market.csr

Open Linux terminal and do this command

echo 00 > ca.srl
touch index.txt

The ca.srl text file containing the next serial number to use in hex. Mandatory. This file must be present and contain a valid serial number.

Last Step, crate one more config file and call it config_ca.cnf

# we use 'ca' as the default section because we're usign the ca command
[ ca ]
default_ca = my_ca

[ my_ca ]
#  a text file containing the next serial number to use in hex. Mandatory.
#  This file must be present and contain a valid serial number.
serial = ./ca.srl

# the text database file to use. Mandatory. This file must be present though
# initially it will be empty.
database = ./index.txt

# specifies the directory where new certificates will be placed. Mandatory.
new_certs_dir = ./

# the file containing the CA certificate. Mandatory
certificate = ./ca.crt

# the file contaning the CA private key. Mandatory
private_key = ./ca.key

# the message digest algorithm. Remember to not use MD5
default_md = sha256

# for how many days will the signed certificate be valid
default_days = 365

# a section with a set of variables corresponding to DN fields
policy = my_policy

# MOST IMPORTANT PART OF THIS CONFIG
copy_extensions = copy

[ my_policy ]
# if the value is "match" then the field value must match the same field in the
# CA certificate. If the value is "supplied" then it must be present.
# Optional means it may be present. Any fields not mentioned are silently
# deleted.
countryName = match
stateOrProvinceName = supplied
organizationName = supplied
commonName = market.localhost
organizationalUnitName = optional
commonName = supplied

You may ask, why so difficult, why we must create one more config to sign child certificate by root. The answer is simple because child certificate must have a SAN block - Subject Alternative Names. If we sign the child certificate by "openssl x509" utils, the Root certificate will delete the SAN field in child certificate. So we use "openssl ca" instead of "openssl x509" to avoid the deleting of the SAN field. We create a new config file and tell it to copy all extended fields copy_extensions = copy.

openssl ca -config config_ca.cnf -out market.crt -in market.csr

The program asks you 2 questions:

  1. Sign the certificate? Say "Y"
  2. 1 out of 1 certificate requests certified, commit? Say "Y"

In terminal you can see a sentence with the word "Database", it means file index.txt which you create by the command "touch". It will contain all information by all certificates you create by "openssl ca" util. To check the certificate valid use:

openssl rsa -in market.key -check

If you want to see what inside in CRT:

openssl x509 -in market.crt -text -noout

If you want to see what inside in CSR:

openssl req -in market.csr -noout -text 

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I was able to fix this issue by changing $(document).ready() to window.onLoad().

How to remove html special chars?

It looks like what you really want is:

function xmlEntities($string) {
    $translationTable = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);

    foreach ($translationTable as $char => $entity) {
        $from[] = $entity;
        $to[] = '&#'.ord($char).';';
    }
    return str_replace($from, $to, $string);
}

It replaces the named-entities with their number-equivalent.

Restoring MySQL database from physical files

A MySQL MyISAM table is the combination of three files:

  • The FRM file is the table definition.
  • The MYD file is where the actual data is stored.
  • The MYI file is where the indexes created on the table are stored.

You should be able to restore by copying them in your database folder (In linux, the default location is /var/lib/mysql/)

You should do it while the server is not running.

Add characters to a string in Javascript

Simple use text = text + string2

ArrayList or List declaration in Java

List<String> arrayList = new ArrayList<String>();

Is generic where you want to hide implementation details while returning it to client, at later point of time you may change implementation from ArrayList to LinkedList transparently.

This mechanism is useful in cases where you design libraries etc., which may change their implementation details at some point of time with minimal changes on client side.

ArrayList<String> arrayList = new ArrayList<String>();

This mandates you always need to return ArrayList. At some point of time if you would like to change implementation details to LinkedList, there should be changes on client side also to use LinkedList instead of ArrayList.

Convert Difference between 2 times into Milliseconds?

To answer the title-question:

DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;

int millisceonds = (int) diff.TotalMilliseconds;

You can use this to set a Timer:

timer1.interval = millisceonds;
timer1.Enabled = true;

Don't forget to disable the timer when handling the tick.

But if you want an event at 12:03, just substitute DateTime.Now for d1.

But it is not clear what the exact function of textBox1 and textBox2 are.

How do you create vectors with specific intervals in R?

Usually, we want to divide our vector into a number of intervals. In this case, you can use a function where (a) is a vector and (b) is the number of intervals. (Let's suppose you want 4 intervals)

a <- 1:10
b <- 4

FunctionIntervalM <- function(a,b) {
  seq(from=min(a), to = max(a), by = (max(a)-min(a))/b)
}

FunctionIntervalM(a,b)
# 1.00  3.25  5.50  7.75 10.00

Therefore you have 4 intervals:

1.00 - 3.25 
3.25 - 5.50
5.50 - 7.75
7.75 - 10.00

You can also use a cut function

  cut(a, 4)

# (0.991,3.25] (0.991,3.25] (0.991,3.25] (3.25,5.5]   (3.25,5.5]   (5.5,7.75]  
# (5.5,7.75]   (7.75,10]    (7.75,10]    (7.75,10]   
#Levels: (0.991,3.25] (3.25,5.5] (5.5,7.75] (7.75,10]

What is the worst real-world macros/pre-processor abuse you've ever come across?

Related to Raymond's rant is the following horrible (in my opinion, of course) macro:

#define CALL_AND_CHECK(func, arg) \
    int result = func(arg);       \
    if(0 != result)               \
    {                             \
        sys.exit(-1);             \
    }                             \

I was pretty new to the practice of using macros and used this macro, but I expected the function that I passed to it to fail. And I was doing it in a background thread, so it stumped me for days why my entire app was "crashing".

As an aside, if only std::tr1::function was around when this macro was written, I would have a week of my life back!

How can I combine hashes in Perl?

Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

my %new_hash = %hash1; # make a copy; leave %hash1 alone

foreach my $key2 ( keys %hash2 )
    {
    if( exists $new_hash{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $new_hash{$key2} = $hash2{$key2};
        }
    }

If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %hash1.

foreach my $key2 ( keys %hash2 )
    {
    if( exists $hash1{$key2} )
        {
        warn "Key [$key2] is in both hashes!";
        # handle the duplicate (perhaps only warning)
        ...
        next;
        }
    else
        {
        $hash1{$key2} = $hash2{$key2};
        }
    }

If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

@hash1{ keys %hash2 } = values %hash2;

How to generate keyboard events?

    def keyboardevent():
         keyboard.press_and_release('a')
         keyboard.press_and_release('shift + b')
         
    keyboardevent()

Loop over html table and get checked checkboxes (JQuery)

The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('input[type=checkbox]').change(function () {
    $('#test > tbody  tr').each(function () {
        if ($('input[type=checkbox]').is(':checked')) {
            $('#btnexcellSelect').removeAttr('disabled');
        } else {
            $('#btnexcellSelect').attr('disabled', 'disabled');
        }
        if ($(this).is(':checked')){
            console.log( $(this).attr('id'));
         }else{
             console.log($(this).attr('id'));
         }
     });
});

Here is demo in JSFiddle.

Difference between return 1, return 0, return -1 and exit?

return in function return execution back to caller and exit from function terminates the program.

in main function return 0 or exit(0) are same but if you write exit(0) in different function then you program will exit from that position.

returning different values like return 1 or return -1 means that program is returning error .

When exit(0) is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.

Strip out HTML and Special Characters

You can do it in one single line :) specially useful for GET or POST requests

$clear = preg_replace('/[^A-Za-z0-9\-]/', '', urldecode($_GET['id']));

What 'additional configuration' is necessary to reference a .NET 2.0 mixed mode assembly in a .NET 4.0 project?

I was experiencing this same error, and spent forever adding the suggested startup statements to various config files in my solution, attempting to isolate the framework mismatch. Nothing worked. I also added startup information to my XML schemas. That didn't help either. Looking at the actual file that was causing the problem (which would only say it was "moved or deleted") revealed it was actually the License Compiler (LC).

Deleting the offending licenses.licx file seems to have fixed the problem.

Validate SSL certificates with Python

Or simply make your life easier by using the requests library:

import requests
requests.get('https://somesite.com', cert='/path/server.crt', verify=True)

A few more words about its usage.

Why doesn't Mockito mock static methods?

I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.

The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.

That's my guess at it, for what it's worth...

C#: easiest way to populate a ListBox from a List

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

Java HTTP Client Request with defined timeout

HttpConnectionParams.setSoTimeout(params, 10*60*1000);// for 10 mins i have set the timeout

You can as well define your required time out.

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

Allowed characters in filename

On Windows OS create a file and give it a invalid character like \ in the filename. As a result you will get a popup with all the invalid characters in a filename.

enter image description here

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

From the Help:
IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable.
IsEmpty only returns meaningful information for variants.

To check if a cell is empty, you can use cell(x,y) = "".
You might eventually save time by using Range("X:Y").SpecialCells(xlCellTypeBlanks) or xlCellTypeConstants or xlCellTypeFormulas

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

Best ways to teach a beginner to program?

At first I was interested in how different programs worked, so I started by looking at the source code. Then when I began to understand how the program worked, I would change certain parameters to see what would happen. So basically I learned how to read before I learned how to write. Which coincidently is how most people learn English.

So if I was trying to teach someone how to program I would give them a small program to try to read and understand how it works, and have them just just play around with the source code.

Only then would I give them "assignments" to try to accomplish.

Now if they had a particular reason for wanting to learn how to program, it would certainly be a good idea to start with something along the lines of what they want to accomplish. For example if they wanted to be proficient in an application like blender, it would definably be a good idea to start with Alice.

I would absolutely recommend sticking with a language that has garbage collection, like D, Perl, or some interpreted language like javascript. It might be a good idea to stay away from Perl until Perl 6 is closer to completion, because it fixes some of the difficulties of reading and understanding Perl.

Centering elements in jQuery Mobile

Adjust as your requirement

   .ui-btn{
      margin:0.5em 10px;
    }

Redirect using AngularJS

Check your routing method:

if your routing state is like this

 .state('app.register', {
    url: '/register',
    views: {
      'menuContent': {
        templateUrl: 'templates/register.html',
      }
    }
  }) 

then you should use

$location.path("/app/register");

jquery AJAX and json format

Currently you are sending the data as typical POST values, which look like this:

first_name=somename&last_name=somesurname

If you want to send data as json you need to create an object with data and stringify it.

data: JSON.stringify(someobject)

How do I check in JavaScript if a value exists at a certain array index?

if(arrayName.length > index && arrayName[index] !== null) {
    //arrayName[index] has a value
}

How correctly produce JSON by RESTful web service?

@POST
@Path ("Employee")
@Consumes("application/json")
@Produces("application/json")
public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
    return jsonObject;
}       

Optimum way to compare strings in JavaScript?

You can use the comparison operators to compare strings. A strcmp function could be defined like this:

function strcmp(a, b) {
    if (a.toString() < b.toString()) return -1;
    if (a.toString() > b.toString()) return 1;
    return 0;
}

Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:

function strcmp(a, b) {
    a = a.toString(), b = b.toString();
    for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
    if (i === n) return 0;
    return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

How do I vertical center text next to an image in html/css?

That's a fun one. If you know ahead of time the height of the container of the text, you can use line-height equal to that height, and it should center the text vertically.

What IDE to use for Python?

Results

Spreadsheet version

spreadsheet screenshot

Alternatively, in plain text: (also available as a a screenshot)

                         Bracket Matching -.  .- Line Numbering
                          Smart Indent -.  |  |  .- UML Editing / Viewing
         Source Control Integration -.  |  |  |  |  .- Code Folding
                    Error Markup -.  |  |  |  |  |  |  .- Code Templates
  Integrated Python Debugging -.  |  |  |  |  |  |  |  |  .- Unit Testing
    Multi-Language Support -.  |  |  |  |  |  |  |  |  |  |  .- GUI Designer (Qt, Eric, etc)
   Auto Code Completion -.  |  |  |  |  |  |  |  |  |  |  |  |  .- Integrated DB Support
     Commercial/Free -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  .- Refactoring
   Cross Platform -.  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom              |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |  |  |  |  |*many plugins
Editra            |Y |F |Y |Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |
Emacs             |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
Eric Ide          |Y |F |Y |  |Y |Y |  |Y |  |Y |  |Y |  |Y |  |  |  |
Geany             |Y |F |Y*|Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |*very limited
Gedit             |Y |F |Y¹|Y |  |  |  |Y |Y |Y |  |  |Y²|  |  |  |  |¹with plugin; ²sort of
Idle              |Y |F |Y |  |Y |  |  |Y |Y |  |  |  |  |  |  |  |  |
IntelliJ          |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit             |Y |F |  |Y |  |  |  |  |Y |Y |  |Y |  |  |  |  |  |
KDevelop          |Y |F |Y*|Y |  |  |Y |Y |Y |Y |  |Y |  |  |  |  |  |*no type inference
Komodo            |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |Y |  |
NetBeans*         |Y |F |Y |Y |Y |  |Y |Y |Y |Y |Y |Y |Y |Y |  |  |Y |*pre-v7.0
Notepad++         |W |F |Y |Y |  |Y*|Y*|Y*|Y |Y |  |Y |Y*|  |  |  |  |*with plugin
Pfaide            |W |C |Y |Y |  |  |  |Y |Y |Y |  |Y |Y |  |  |  |  |
PIDA              |LW|F |Y |Y |  |  |  |Y |Y |Y |  |Y |  |  |  |  |  |VIM based
PTVS              |W |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |  |  |Y*|  |Y |*WPF bsed
PyCharm           |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse)   |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |  |  |  |
PyScripter        |W |F |Y |  |Y |Y |  |Y |Y |Y |  |Y |Y |Y |  |  |  |
PythonWin         |W |F |Y |  |Y |  |  |Y |Y |  |  |Y |  |  |  |  |  |
SciTE             |Y |F¹|  |Y |  |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |¹Mac version is
ScriptDev         |W |C |Y |Y |Y |Y |  |Y |Y |Y |  |Y |Y |  |  |  |  |    commercial
Spyder            |Y |F |Y |  |Y |Y |  |Y |Y |Y |  |  |  |  |  |  |  |
Sublime Text      |Y |CF|Y |Y |  |Y |Y |Y |Y |Y |  |Y |Y |Y*|  |  |  |extensible w/Python,
TextMate          |M |F |  |Y |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |    *PythonTestRunner
UliPad            |Y |F |Y |Y |Y |  |  |Y |Y |  |  |  |Y |Y |  |  |  |
Vim               |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |
Visual Studio     |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde           |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y |  |Y |Y |Y |  |  |  |*support for C
Zeus              |W |C |  |  |  |  |Y |Y |Y |Y |  |Y |Y |  |  |  |  |
                  +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
   Cross Platform -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |     
     Commercial/Free -'  |  |  |  |  |  |  |  |  |  |  |  |  |  |  '- Refactoring
   Auto Code Completion -'  |  |  |  |  |  |  |  |  |  |  |  |  '- Integrated DB Support
    Multi-Language Support -'  |  |  |  |  |  |  |  |  |  |  '- GUI Designer (Qt, Eric, etc)
  Integrated Python Debugging -'  |  |  |  |  |  |  |  |  '- Unit Testing
                    Error Markup -'  |  |  |  |  |  |  '- Code Templates
         Source Control Integration -'  |  |  |  |  '- Code Folding
                          Smart Indent -'  |  |  '- UML Editing / Viewing
                         Bracket Matching -'  '- Line Numbering

Acronyms used:

 L  - Linux
 W  - Windows
 M  - Mac
 C  - Commercial
 F  - Free
 CF - Commercial with Free limited edition
 ?  - To be confirmed

I don't mention basics like syntax highlighting as I expect these by default.


This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.

PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?

We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Submit edits to the spreadsheet

Python convert csv to xlsx

Adding an answer that exclusively uses the pandas library to read in a .csv file and save as a .xlsx file. This example makes use of pandas.read_csv (Link to docs) and pandas.dataframe.to_excel (Link to docs).

The fully reproducible example uses numpy to generate random numbers only, and this can be removed if you would like to use your own .csv file.

import pandas as pd
import numpy as np

# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)

# Reading in test.csv and saving as test.xlsx

df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Mount remount the /
Eg.

  1. mount -o remount,rw /dev/xyz /
  2. sed -i 's/1 1/0 0/' /etc/fstab
  3. sed -i 's/1 2/0 0/' /etc/fstab
  4. reboot

Facebook login "given URL not allowed by application configuration"

I was getting this problem while using a tunnel because I:

  1. had the tunnel url:port set in the FB app settings
  2. but was accessing the local server by pointing my browser to "http://localhost:3000"

once i started punching the tunnel url:port into the browser, i was good to go.

i'm using Rails and Facebooker, but might help others just the same.

How can I convert string date to NSDate?

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

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

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

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

        //Return Parsed Date
        return dateFromString
    }
}

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

var myDate = myDateString.toDateTime()

Pass Method as Parameter using C#

You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

handling DATETIME values 0000-00-00 00:00:00 in JDBC

If, after adding lines:

<property
name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

hibernate.connection.zeroDateTimeBehavior=convertToNull

<connection-property
name="zeroDateTimeBehavior">convertToNull</connection-property>

continues to be an error:

Illegal DATETIME, DATE, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00 00:00:00' or '0000-00-00').

find lines:

1) resultSet.getTime("time"); // time = 00:00:00
2) resultSet.getTimestamp("timestamp"); // timestamp = 00000000000000
3) resultSet.getDate("date"); // date = 0000-00-00 00:00:00

replace with the following lines, respectively:

1) Time.valueOf(resultSet.getString("time"));
2) Timestamp.valueOf(resultSet.getString("timestamp"));
3) Date.valueOf(resultSet.getString("date"));

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

How to split a delimited string in Ruby and convert it to an array?

"1,2,3,4".split(",") as strings

"1,2,3,4".split(",").map { |s| s.to_i } as integers

Convert string to Python class object?

Using importlib worked the best for me.

import importlib

importlib.import_module('accounting.views') 

This uses string dot notation for the python module that you want to import.

How to append a date in batch files

Bernhard's answer needed some tweaking work for me because the %DATE% environment variable is in a different format (as commented elsewhere). Also, there was a tilde (~) missing.

Instead of:

set backupFilename=%DATE:~6,4%%DATE:~3,2%%DATE:0,2%

I had to use:

set backupFilename=%DATE:~10,4%%DATE:~4,2%%DATE:~7,2%

for the date format:

c:\Scripts>echo %DATE%

Thu 05/14/2009

SQL, How to Concatenate results?

This one automatically excludes the trailing comma, unlike most of the other answers.

DECLARE @csv VARCHAR(1000)

SELECT @csv = COALESCE(@csv + ',', '') + ModuleValue
FROM Table_X
WHERE ModuleID = @ModuleID

(If the ModuleValue column isn't already a string type then you might need to cast it to a VARCHAR.)

PHP mail not working for some reason

This is probably a configuration error. If you insist on using PHP mail function, you will have to edit php.ini.

If you are looking for an easier and more versatile option (in my opinion), you should use PHPMailer.

Why check both isset() and !empty()

isset($vars[1]) AND !empty($vars[1]) is equivalent to !empty($vars[1]).

I prepared simple code to show it empirically.

Last row is undefined variable.

+-----------+---------+---------+----------+---------------------+
| Var value | empty() | isset() | !empty() | isset() && !empty() |
+-----------+---------+---------+----------+---------------------+
| ''        | true    | true    | false    | false               |
| ' '       | false   | true    | true     | true                |
| false     | true    | true    | false    | false               |
| true      | false   | true    | true     | true                |
| array ()  | true    | true    | false    | false               |
| NULL      | true    | false   | false    | false               |
| '0'       | true    | true    | false    | false               |
| 0         | true    | true    | false    | false               |
| 0.0       | true    | true    | false    | false               |
| undefined | true    | false   | false    | false               |
+-----------+---------+---------+----------+---------------------+

And code

$var1 = "";
$var2 = " ";
$var3 = FALSE;
$var4 = TRUE;
$var5 = array();
$var6 = null;
$var7 = "0";
$var8 = 0;
$var9 = 0.0;

function compare($var)
{
    print(var_export($var, true) . "|" .
        var_export(empty($var), true) . "|" .
        var_export(isset($var), true) . "|" .
        var_export(!empty($var), true) . "|" .
        var_export(isset($var) && !empty($var), true) . "\n");
}

for ($i = 1; $i <= 9; $i++) {
    $var = 'var' . $i;
    compare($$var);
}

@print(var_export($var10, true) . "|" .
    var_export(empty($var10), true) . "|" .
    var_export(isset($var10), true) . "|" .
    var_export(!empty($var10), true) . "|" .
    var_export(isset($var10) && !empty($var10), true) . "\n");

Undefined variable must be evaluated outside function, because function itself create temporary variable in the scope itself.

R dplyr: Drop multiple columns

We can try

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

How do I get the Git commit count?

git config --global alias.count 'rev-list --all --count'

If you add this to your config, you can just reference the command;

git count

clearInterval() not working

The setInterval method returns an interval ID that you need to pass to clearInterval in order to clear the interval. You're passing a function, which won't work. Here's an example of a working setInterval/clearInterval

var interval_id = setInterval(myMethod,500);
clearInterval(interval_id);

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How to run a Python script in the background even after I logout SSH?

You could also use GNU screen which just about every Linux/Unix system should have.

If you are on Ubuntu/Debian, its enhanced variant byobu is rather nice too.

How to split a number into individual digits in c#?

You can simply do:

"123456".Select(q => new string(q,1)).ToArray();

to have an enumerable of integers, as per comment request, you can:

"123456".Select(q => int.Parse(new string(q,1))).ToArray();

It is a little weak since it assumes the string actually contains numbers.

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

Checking Date format from a string in C#

You can use below IsValidDate():

 public static bool IsValidDate(string value, string[] dateFormats)
    {
        DateTime tempDate;
        bool validDate = DateTime.TryParseExact(value, dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, ref tempDate);
        if (validDate)
            return true;
        else
            return false;
    }

And you can pass in the value and date formats. For example:

var data = "02-08-2019";
var dateFormats = {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"}

if (IsValidDate(data, dateFormats))
{
    //Do something
}
else
{
    //Do something else
}

Eclipse CDT: no rule to make target all

You need to change your project settings so that Eclipse-CDT manages your Makefiles for you.

  1. Select Project->Properties from the menu bar.
  2. Click C/C++ Build on the left in the dialog that comes up.
  3. Under the Builder Settings tab on the right, select "Generate Makefiles automatically" under the Makefile generation section.
  4. Hit OK and build again.

6 digits regular expression

You could try

^[0-9]{1,6}$

it should work.

momentJS date string add 5 days

moment(moment('2015/04/09 16:00:00').add(7, 'd').format('YYYY/MM/DD HH:mm:mm'))

has to format and then convert to moment again.

Open another page in php

<?php
    header("Location: index.html");
?>

Just make sure nothing is actually written to the page prior to this code, or it won't work.

ServletContext.getRequestDispatcher() vs ServletRequest.getRequestDispatcher()

I would think that your first question is simply a matter of scope. The ServletContext is a much more broad scoped object (the whole servlet context) than a ServletRequest, which is simply a single request. You might look to the Servlet specification itself for more detailed information.

As to how, I am sorry but I will have to leave that for others to answer at this time.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

Caution: This answer was written in 2010 and technology moves fast. For a more recent solution, see @ctrl-alt-dileep's answer below.


Depending on your needs, you may wish to try the jQuery touch plugin; you can try an example here. It works fine to drag on my iPhone, whereas jQuery UI Draggable doesn't.

Alternatively, you can try this plugin, though that might require you to actually write your own draggable function.

As a sidenote: Believe it or not, we're hearing increasing buzz about how touch devices such as the iPad and iPhone is causing problems both for websites using :hover/onmouseover functions and draggable content.

If you're interested in the underlying solution for this, it's to use three new JavaScript events; ontouchstart, ontouchmove and ontouchend. Apple actually has written an article about their use, which you can find here. A simplified example can be found here. These events are used in both of the plugins I linked to.

How do I get a string format of the current date time, in python?

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%B %d, %Y")
'July 23, 2010'

load scripts asynchronously

One reason why your scripts could be loading so slowly is if you were running all of your scripts while loading the page, like this:

callMyFunctions();

instead of:

$(window).load(function() {
      callMyFunctions();
});

This second bit of script waits until the browser has completely loaded all of your Javascript code before it starts executing any of your scripts, making it appear to the user that the page has loaded faster.

If you're looking to enhance the user's experience by decreasing the loading time, I wouldn't go for the "loading screen" option. In my opinion that would be much more annoying than just having the page load more slowly.

Why does JPA have a @Transient annotation?

Because they have different meanings. The @Transient annotation tells the JPA provider to not persist any (non-transient) attribute. The other tells the serialization framework to not serialize an attribute. You might want to have a @Transient property and still serialize it.

How to remove extension from string (only real extension!)

The following code works well for me, and it's pretty short. It just breaks the file up into an array delimited by dots, deletes the last element (which is hypothetically the extension), and reforms the array with the dots again.

$filebroken = explode( '.', $filename);
$extension = array_pop($filebroken);
$fileTypeless = implode('.', $filebroken);

How to convert a timezone aware string to datetime in Python without dateutil?

As of Python 3.7, datetime.datetime.fromisoformat() can handle your format:

>>> import datetime
>>> datetime.datetime.fromisoformat('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))

In older Python versions you can't, not without a whole lot of painstaking manual timezone defining.

Python does not include a timezone database, because it would be outdated too quickly. Instead, Python relies on external libraries, which can have a far faster release cycle, to provide properly configured timezones for you.

As a side-effect, this means that timezone parsing also needs to be an external library. If dateutil is too heavy-weight for you, use iso8601 instead, it'll parse your specific format just fine:

>>> import iso8601
>>> iso8601.parse_date('2012-11-01T04:16:13-04:00')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=<FixedOffset '-04:00'>)

iso8601 is a whopping 4KB small. Compare that tot python-dateutil's 148KB.

As of Python 3.2 Python can handle simple offset-based timezones, and %z will parse -hhmm and +hhmm timezone offsets in a timestamp. That means that for a ISO 8601 timestamp you'd have to remove the : in the timezone:

>>> from datetime import datetime
>>> iso_ts = '2012-11-01T04:16:13-04:00'
>>> datetime.strptime(''.join(iso_ts.rsplit(':', 1)), '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2012, 11, 1, 4, 16, 13, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000)))

The lack of proper ISO 8601 parsing is being tracked in Python issue 15873.

Add to Array jQuery

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]

Play multiple CSS animations at the same time

In case anyone new is coming along and catching this thread, you can specify multiple animations--each with their own properties--with a comma.

Example:

animation: rotate 1s, spin 3s;

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Update: as of the day of this writing, namedTuples are pickable (starting with python 2.7)

The issue here is the child processes aren't able to import the class of the object -in this case, the class P-, in the case of a multi-model project the Class P should be importable anywhere the child process get used

a quick workaround is to make it importable by affecting it to globals()

globals()["P"] = P

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

Getting JSONObject from JSONArray

Here is your json:

{
    "syncresponse": {
       "synckey": "2011-09-30 14:52:00",
        "createdtrs": [

        ],
        "modtrs": [

        ],
        "deletedtrs": [
          {
           "companyid": "UTB17",
           "username": "DA",
           "date": "2011-09-26",
           "reportid": "31341"
      }
       ]
   }
}

and it's parsing:

JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
   JSONObject object3 = jArray3.getJSONObject(i);
   String comp_id = object3.getString("companyid");
   String username = object3.getString("username");
   String date = object3.getString("date");
   String report_id = object3.getString("reportid");
}

map vs. hash_map in C++

I don't know what gives, but, hash_map takes more than 20 seconds to clear() 150K unsigned integer keys and float values. I am just running and reading someone else's code.

This is how it includes hash_map.

#include "StdAfx.h"
#include <hash_map>

I read this here https://bytes.com/topic/c/answers/570079-perfomance-clear-vs-swap

saying that clear() is order of O(N). That to me, is very strange, but, that's the way it is.

Execute external program

import java.io.*;

public class Code {
  public static void main(String[] args) throws Exception {
    ProcessBuilder builder = new ProcessBuilder("ls", "-ltr");
    Process process = builder.start();

    StringBuilder out = new StringBuilder();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line = null;
      while ((line = reader.readLine()) != null) {
        out.append(line);
        out.append("\n");
      }
      System.out.println(out);
    }
  }
}

Try online

Connection to SQL Server Works Sometimes

I had the exact issue, tried several soultion didnt work , lastly restarted the system , it worked fine.

Decimal precision and scale in EF Code First

Entity Framework Ver 6 (Alpha, rc1) has something called Custom Conventions. To set decimal precision:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<decimal>().Configure(config => config.HasPrecision(18, 4));
}

Reference:

Angular - POST uploaded file

Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.

For very basic file upload I created such service function as a workaround (using ???????'s answer):

  uploadFile(file:File):Promise<MyEntity> {
    return new Promise((resolve, reject) => {

        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(<MyEntity>JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.getServiceUrl(), true);

        let formData = new FormData();
        formData.append("file", file, file.name);
        xhr.send(formData);
    });
}

How to get the nvidia driver version from the command line?

modinfo does the trick.

root@nyx:/usr/src# modinfo nvidia|grep version:
version:        331.113

Passing a method parameter using Task.Factory.StartNew

Construct the first parameter as an instance of Action, e.g.

var inputID = 123;
var col = new BlockingDataCollection();
var task = Task.Factory.StartNew(
    () => CheckFiles(inputID, col),
    cancelCheckFile.Token,
    TaskCreationOptions.LongRunning,
    TaskScheduler.Default);

PyTorch: How to get the shape of a Tensor as a list of int

Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]

Laravel is there a way to add values to a request array

I used this code to add something to my request.

$req->query->add(['key'=>'variable']);
$req->request->add(['key'=>'variable']);

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

How to get Maven project version to the bash command line

The Maven Help Plugin is somehow already proposing something for this:

  • help:evaluate evaluates Maven expressions given by the user in an interactive mode.

Here is how you would invoke it on the command line to get the ${project.version}:

mvn org.apache.maven.plugins:maven-help-plugin:2.1.1:evaluate \
    -Dexpression=project.version

What ports does RabbitMQ use?

Port Access

Firewalls and other security tools may prevent RabbitMQ from binding to a port. When that happens, RabbitMQ will fail to start. Make sure the following ports can be opened:

4369: epmd, a peer discovery service used by RabbitMQ nodes and CLI tools

5672, 5671: used by AMQP 0-9-1 and 1.0 clients without and with TLS

25672: used by Erlang distribution for inter-node and CLI tools communication and is allocated from a dynamic range (limited to a single port by default, computed as AMQP port + 20000). See networking guide for details.

15672: HTTP API clients and rabbitmqadmin (only if the management plugin is enabled)

61613, 61614: STOMP clients without and with TLS (only if the STOMP plugin is enabled)

1883, 8883: (MQTT clients without and with TLS, if the MQTT plugin is enabled

15674: STOMP-over-WebSockets clients (only if the Web STOMP plugin is enabled)

15675: MQTT-over-WebSockets clients (only if the Web MQTT plugin is enabled)

Reference doc: https://www.rabbitmq.com/install-windows-manual.html

Convert a string to a datetime

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)

How to define custom exception class in Java, the easiest way?

A typical custom exception I'd define is something like this:

public class CustomException extends Exception {

    public CustomException(String message) {
        super(message);
    }

    public CustomException(String message, Throwable throwable) {
        super(message, throwable);
    }

}

I even create a template using Eclipse so I don't have to write all the stuff over and over again.

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

Regex to validate JSON

Looking at the documentation for JSON, it seems that the regex can simply be three parts if the goal is just to check for fitness:

  1. The string starts and ends with either [] or {}
    • [{\[]{1}...[}\]]{1}
  2. and
    1. The character is an allowed JSON control character (just one)
      • ...[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]...
    2. or The set of characters contained in a ""
      • ...".*?"...

All together: [{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}

If the JSON string contains newline characters, then you should use the singleline switch on your regex flavor so that . matches newline. Please note that this will not fail on all bad JSON, but it will fail if the basic JSON structure is invalid, which is a straight-forward way to do a basic sanity validation before passing it to a parser.

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

How do I set up IntelliJ IDEA for Android applications?

Once I have followed all these steps, I start to receive error messages in all android classes calls like:

Cannot resolve Android Classes

I revolved that including android.jar in the SDKs Platform Settings:

SKDs Classpath

Laravel use same form for create and edit

Simple and clean :)

UserController.php

public function create() {
    $user = new User();

    return View::make('user.edit', compact('user'));
}

public function edit($id) {
    $user = User::find($id);

    return View::make('user.edit', compact('user'));
}

edit.blade.php

{{ Form::model($user, ['url' => ['/user', $user->id]]) }}
   {{ Form::text('name') }}
   <button>save</button>
{{ Form::close() }}

adb command not found

you have to move the adb command to /bin/ folder

in my case:

sudo su
mv /root/Android/Sdk/platform-tools/adb /bin/

Nginx Different Domains on Same IP

Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.

They should be

server {
    listen      80;
    server_name www.domain1.com;
    root /var/www/domain1;
}

server {
    listen       80;
    server_name www.domain2.com;
    root /var/www/domain2;
}

Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

Compare two MySQL databases

For myself, I'd start with dumping both databases and diffing the dumps, but if you want automatically generated merge scripts, you're going to want to get a real tool.

A simple Google search turned up the following tools:

How to validate an email address in PHP

You can use filter_var for this.

<?php
   function validateEmail($email) {
      return filter_var($email, FILTER_VALIDATE_EMAIL);
   }
?>

2 "style" inline css img tags?

You don't need 2 style attributes - just use one:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                     style="height:100px;width:100px;" alt="25"/>

Consider, however, using a CSS class instead:

CSS:

.100pxSquare
{
  width: 100px;
  height: 100px;
}

HTML:

<img src="http://img705.imageshack.us/img705/119/original120x75.png" 
                                          class="100pxSquare" alt="25"/>

MySQL: Quick breakdown of the types of joins

I have 2 tables like this:

> SELECT * FROM table_a;
+------+------+
| id   | name |
+------+------+
|    1 | row1 |
|    2 | row2 |
+------+------+

> SELECT * FROM table_b;
+------+------+------+
| id   | name | aid  |
+------+------+------+
|    3 | row3 |    1 |
|    4 | row4 |    1 |
|    5 | row5 | NULL |
+------+------+------+

INNER JOIN cares about both tables

INNER JOIN cares about both tables, so you only get a row if both tables have one. If there is more than one matching pair, you get multiple rows.

> SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
+------+------+------+------+------+

It makes no difference to INNER JOIN if you reverse the order, because it cares about both tables:

> SELECT * FROM table_b b INNER JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
+------+------+------+------+------+

You get the same rows, but the columns are in a different order because we mentioned the tables in a different order.

LEFT JOIN only cares about the first table

LEFT JOIN cares about the first table you give it, and doesn't care much about the second, so you always get the rows from the first table, even if there is no corresponding row in the second:

> SELECT * FROM table_a a LEFT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
|    2 | row2 | NULL | NULL | NULL |
+------+------+------+------+------+

Above you can see all rows of table_a even though some of them do not match with anything in table b, but not all rows of table_b - only ones that match something in table_a.

If we reverse the order of the tables, LEFT JOIN behaves differently:

> SELECT * FROM table_b b LEFT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
|    5 | row5 | NULL | NULL | NULL |
+------+------+------+------+------+

Now we get all rows of table_b, but only matching rows of table_a.

RIGHT JOIN only cares about the second table

a RIGHT JOIN b gets you exactly the same rows as b LEFT JOIN a. The only difference is the default order of the columns.

> SELECT * FROM table_a a RIGHT JOIN table_b b ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | id   | name | aid  |
+------+------+------+------+------+
|    1 | row1 |    3 | row3 | 1    |
|    1 | row1 |    4 | row4 | 1    |
| NULL | NULL |    5 | row5 | NULL |
+------+------+------+------+------+

This is the same rows as table_b LEFT JOIN table_a, which we saw in the LEFT JOIN section.

Similarly:

> SELECT * FROM table_b b RIGHT JOIN table_a a ON a.id=b.aid;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    4 | row4 | 1    |    1 | row1 |
| NULL | NULL | NULL |    2 | row2 |
+------+------+------+------+------+

Is the same rows as table_a LEFT JOIN table_b.

No join at all gives you copies of everything

If you write your tables with no JOIN clause at all, just separated by commas, you get every row of the first table written next to every row of the second table, in every possible combination:

> SELECT * FROM table_b b, table_a;
+------+------+------+------+------+
| id   | name | aid  | id   | name |
+------+------+------+------+------+
|    3 | row3 | 1    |    1 | row1 |
|    3 | row3 | 1    |    2 | row2 |
|    4 | row4 | 1    |    1 | row1 |
|    4 | row4 | 1    |    2 | row2 |
|    5 | row5 | NULL |    1 | row1 |
|    5 | row5 | NULL |    2 | row2 |
+------+------+------+------+------+

(This is from my blog post Examples of SQL join types)

How do I fix a merge conflict due to removal of a file in a branch?

The conflict message:

CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD

means that res/layout/dialog_item.xml was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).

So you have to decide whether

  • remove file using "git rm res/layout/dialog_item.xml"

or

  • accept version from HEAD (perhaps after editing it) with "git add res/layout/dialog_item.xml"

Then you finalize merge with "git commit".

Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.

Spell Checker for Python

from autocorrect import spell for this you need to install, prefer anaconda and it only works for words, not sentences so that's a limitation u gonna face.

from autocorrect import spell
print(spell('intrerpreter'))
# output: interpreter

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

PDF to image using Java

If GPL is fine you may have an additional look at jPodRenderer (SourceForge)

How to call a function within class?

That doesn't work because distToPoint is inside your class, so you need to prefix it with the classname if you want to refer to it, like this: classname.distToPoint(self, p). You shouldn't do it like that, though. A better way to do it is to refer to the method directly through the class instance (which is the first argument of a class method), like so: self.distToPoint(p).

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

you should configure something like as follows in build.gradle

tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

Logging POST data from $request_body

Try echo_read_request_body.

"echo_read_request_body ... Explicitly reads request body so that the $request_body variable will always have non-empty values (unless the body is so big that it has been saved by Nginx to a local temporary file)."

location /log {
  log_format postdata $request_body;
  access_log /mnt/logs/nginx/my_tracking.access.log postdata;
  echo_read_request_body;
}

How to make an Android Spinner with initial text "Select One"?

This is my way:

List<String> list = new ArrayList<String>();
list.add("string1");
list.add("string2");
list.add("string3");
list.add("[Select one]");
final int listsize = list.size() - 1;
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list) {
 @Override
public int getCount() {
    return(listsize); // Truncate the list
}
};
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(dataAdapter);

mySpinner.setSelection(listsize); // Hidden item to appear in the spinner

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

How merge two objects array in angularjs?

Simple

var a=[{a:4}], b=[{b:5}]

angular.merge(a,b) // [{a:4, b:5}]

Tested on angular 1.4.1

Incrementing in C++ - When to use x++ or ++x?

It's not a question of preference, but of logic.

x++ increments the value of variable x after processing the current statement.

++x increments the value of variable x before processing the current statement.

So just decide on the logic you write.

x += ++i will increment i and add i+1 to x. x += i++ will add i to x, then increment i.

how to fetch array keys with jQuery?

I use something like this function I created...

Object.getKeys = function(obj, add) {
    if(obj === undefined || obj === null) {
        return undefined;
    }
    var keys = [];
    if(add !== undefined) {
        keys = jQuery.merge(keys, add);
    }
    for(key in obj) {
        if(obj.hasOwnProperty(key)) {
                keys.push(key);
        }
    }
    return keys;
};

I think you could set obj to self or something better in the first test. It seems sometimes I'm checking if it's empty too so I did it that way. Also I don't think {} is Object.* or at least there's a problem finding the function getKeys on the Object that way. Maybe you're suppose to put prototype first, but that seems to cause a conflict with GreenSock etc.

How to set 777 permission on a particular folder?

  1. Right click the folder, click on Properties.
  2. Click on the Security tab
  3. Add the name Everyone to the user list.