Programs & Examples On #Ihtmlimgelement

how to pass parameter from @Url.Action to controller function

If you are using Url.Action inside JavaScript then you can

var personId="someId";
$.ajax({
  type: 'POST',
  url: '@Url.Action("CreatePerson", "Person")',
  dataType: 'html',
  data: ({
  //insert your parameters to pass to controller
    id: personId 
  }),
  success: function() {
    alert("Successfully posted!");
  }
});

Display a float with two decimal places in Python

f-string formatting:

This was new in Python 3.6 - the string is placed in quotation marks as usual, prepended with f'... in the same way you would r'... for a raw string. Then you place whatever you want to put within your string, variables, numbers, inside braces f'some string text with a {variable} or {number} within that text' - and Python evaluates as with previous string formatting methods, except that this method is much more readable.

>>> foobar = 3.141592
>>> print(f'My number is {foobar:.2f} - look at the nice rounding!')

My number is 3.14 - look at the nice rounding!

You can see in this example we format with decimal places in similar fashion to previous string formatting methods.

NB foobar can be an number, variable, or even an expression eg f'{3*my_func(3.14):02f}'.

Going forward, with new code I prefer f-strings over common %s or str.format() methods as f-strings can be far more readable, and are often much faster.

Oracle: how to add minutes to a timestamp?

Based on what you're asking for, you want the HH24:MI format for to_char.

How to convert a list into data table

private DataTable CreateDataTable(IList<T> item)
{
    Type type = typeof(T);
    var properties = type.GetProperties();

    DataTable dataTable = new DataTable();
    foreach (PropertyInfo info in properties)
    {
        dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
    }

    foreach (T entity in item)
    {
        object[] values = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            values[i] = properties[i].GetValue(entity);
        }

        dataTable.Rows.Add(values);
    }
    return dataTable;
}

Change UITextField and UITextView Cursor / Caret Color

For people searching the equivalent in SwiftUI for Textfield this is accentColor:

TextField("Label", text: $self.textToBind).accentColor(Color.red)

C Linking Error: undefined reference to 'main'

You're not including the C file that contains main() when compiling, so the linker isn't seeing it.

You need to add it:

$ gcc -o runexp runexp.c scd.o data_proc.o -lm -fopenmp

What is the best way to clone/deep copy a .NET generic Dictionary<string, T>?

Okay, the .NET 2.0 answers:

If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.)

If you do need to clone the values, you can use something like this:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
   (Dictionary<TKey, TValue> original) where TValue : ICloneable
{
    Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                            original.Comparer);
    foreach (KeyValuePair<TKey, TValue> entry in original)
    {
        ret.Add(entry.Key, (TValue) entry.Value.Clone());
    }
    return ret;
}

That relies on TValue.Clone() being a suitably deep clone as well, of course.

How to implement private method in ES6 class with Traceur

Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time. Thus, you have private properties and methods :)

Here is an example (in test.js file)

function tryMe1(a) {
  console.log(a + 2);
}

var tryMe2 = 1234;

class myModule {
  tryMe3(a) {
    console.log(a + 100);
  }

  getTryMe1(a) {
    tryMe1(a);
  }

  getTryMe2() {
    return tryMe2;
  }
}

// Exports just myModule class. Not anything outside of it.
export default myModule; 

In another file

import MyModule from './test';

let bar = new MyModule();

tryMe1(1); // ReferenceError: tryMe1 is not defined
tryMe2; // ReferenceError: tryMe2 is not defined
bar.tryMe1(1); // TypeError: bar.tryMe1 is not a function
bar.tryMe2; // undefined

bar.tryMe3(1); // 101
bar.getTryMe1(1); // 3
bar.getTryMe2(); // 1234

Is multiplication and division using shift operators in C actually faster?

Just tried on my machine compiling this :

int a = ...;
int b = a * 10;

When disassembling it produces output :

MOV EAX,DWORD PTR SS:[ESP+1C] ; Move a into EAX
LEA EAX,DWORD PTR DS:[EAX+EAX*4] ; Multiply by 5 without shift !
SHL EAX, 1 ; Multiply by 2 using shift

This version is faster than your hand-optimized code with pure shifting and addition.

You really never know what the compiler is going to come up with, so it's better to simply write a normal multiplication and let him optimize the way he wants to, except in very precise cases where you know the compiler cannot optimize.

TypeError: module.__init__() takes at most 2 arguments (3 given)

You may also do the following in Python 3.6.1

from Object import Object as Parent

and your class definition to:

class Visitor(Parent):

IllegalMonitorStateException on wait() call

Since you haven't posted code, we're kind of working in the dark. What are the details of the exception?

Are you calling Thread.wait() from within the thread, or outside it?

I ask this because according to the javadoc for IllegalMonitorStateException, it is:

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

To clarify this answer, this call to wait on a thread also throws IllegalMonitorStateException, despite being called from within a synchronized block:


     private static final class Lock { }
     private final Object lock = new Lock();

    @Test
    public void testRun() {
        ThreadWorker worker = new ThreadWorker();
        System.out.println ("Starting worker");
        worker.start();
        System.out.println ("Worker started - telling it to wait");
        try {
            synchronized (lock) {
                worker.wait();
            }
        } catch (InterruptedException e1) {
            String msg = "InterruptedException: [" + e1.getLocalizedMessage() + "]";
            System.out.println (msg);
            e1.printStackTrace();
            System.out.flush();
        }
        System.out.println ("Worker done waiting, we're now waiting for it by joining");
        try {
            worker.join();
        } catch (InterruptedException ex) { }

    }

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

Laravel 5.2 not reading env file

I had the same issue on local environment, I resolved by

  1. php artisan config:clear
  2. php artisan config:cache
  3. and then cancelling php artisan serve command, and restart again.

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

Here is a good article about fluid vs. flex.

Are there dictionaries in php?

No, there are no dictionaries in php. The closest thing you have is an array. However, an array is different than a dictionary in that arrays have both an index and a key. Dictionaries only have keys and no index. What do I mean by that?

$array = array(
    "foo" => "bar",
    "bar" => "foo"
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];

The following line is allowed with the above array but would give an error if it was a dictionary.

print $array[0]

Python has both arrays and dictionaries.

Detect if device is iOS

It's probably worth answering that iPads running iOS 13 will have navigator.platform set to MacIntel, which means you'll need to find another way to detect iPadOS devices.

How to check if a user likes my Facebook Page or URL using Facebook's API

Though this post has been here for quite a while, the solutions are not pure JS. Though Jason noted that requesting permissions is not ideal, I consider it a good thing since the user can reject it explicitly. I still post this code, though (almost) the same thing can also be seen in another post by ifaour. Consider this the JS only version without too much attention to detail.

The basic code is rather simple:

FB.api("me/likes/SOME_ID", function(response) {
    if ( response.data.length === 1 ) { //there should only be a single value inside "data"
        console.log('You like it');
    } else {
        console.log("You don't like it");
    }
});

ALternatively, replace me with the proper UserID of someone else (you might need to alter the permissions below to do this, like friends_likes) As noted, you need more than the basic permission:

FB.login(function(response) {
    //do whatever you need to do after a (un)successfull login         
}, { scope: 'user_likes' });

JAXB Exception: Class not known to this context

This error message happens either because your ProfileDto class is not registered in the JAXB Content, or the class using it does not use @XmlSeeAlso(ProfileDto.class) to make processable by JAXB.

About your comment:

I was under the impression the annotations was only needed when the referenced class was a sub-class.

No, they are also needed when not declared in the JAXB context or, for example, when the only class having a static reference to it has this reference annotated with @XmlTransient. I maintain a tutorial here.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

Windows ignores JAVA_HOME: how to set JDK as default?

I had Java 7 and 8 installed and I want to redirect to java 7 but the java version in my cmd prompt window shows Java 8.
Added Java 7 bin directory path (C:\Program Files\Java\jdk1.7.0_10\bin) to PATH variable at the end, but did not work out and shows Java 8. So I changed the Java 7 path to the starting of the path value and it worked.
Opened a new cmd prompt window and checked my java version and now it shows Java 7

Java to Jackson JSON serialization: Money fields

Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:

SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);

In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).

How do I use variables in Oracle SQL Developer?

I think that the Easiest way in your case is :

DEFINE EmpIDVar = 1234;

SELECT *
FROM Employees
WHERE EmployeeID = &EmpIDVar

For the string values it will be like :

DEFINE EmpIDVar = '1234';

SELECT *
FROM Employees
WHERE EmployeeID = '&EmpIDVar'

Get current date/time in seconds

var seconds = new Date().getTime() / 1000;

....will give you the seconds since midnight, 1 Jan 1970

Reference

C# Ignore certificate errors?

Old, but still helps...

Another great way of achieving the same behavior is through configuration file (web.config)

 <system.net>
    <settings>
      <servicePointManager checkCertificateName="false" checkCertificateRevocationList="false" />
    </settings>
  </system.net>

NOTE: tested on .net full.

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

Adding values to a C# array

C# arrays are fixed length and always indexed. Go with Motti's solution:

int [] terms = new int[400];
for(int runs = 0; runs < 400; runs++)
{
    terms[runs] = value;
}

Note that this array is a dense array, a contiguous block of 400 bytes where you can drop things. If you want a dynamically sized array, use a List<int>.

List<int> terms = new List<int>();
for(int runs = 0; runs < 400; runs ++)
{
    terms.Add(runs);
}

Neither int[] nor List<int> is an associative array -- that would be a Dictionary<> in C#. Both arrays and lists are dense.

How to redirect to action from JavaScript method?

I struggled with this a little because I wanted to use Knockout to bind the button to the click event. Here's my button and the relevant function from inside my view model.

<a class="btn btn-secondary showBusy" data-bind="click: back">Back to Dashboard</a>

var vm = function () {
...
    self.back = function() {
        window.location.href = '@Url.Action("LicenseDashboard", "Application")';
    }
}

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

How do you get the footer to stay at the bottom of a Web page?

Set the CSS for the #footer to:

position: absolute;
bottom: 0;

You will then need to add a padding or margin to the bottom of your #sidebar and #content to match the height of #footer or when they overlap, the #footer will cover them.

Also, if I remember correctly, IE6 has a problem with the bottom: 0 CSS. You might have to use a JS solution for IE6 (if you care about IE6 that is).

What is the difference between a deep copy and a shallow copy?

Breadth vs Depth; think in terms of a tree of references with your object as the root node.

Shallow:

Before Copy Shallow Copying Shallow Done

The variables A and B refer to different areas of memory, when B is assigned to A the two variables refer to the same area of memory. Later modifications to the contents of either are instantly reflected in the contents of other, as they share contents.

Deep:

Before Copy Deep Copying Deep Done

The variables A and B refer to different areas of memory, when B is assigned to A the values in the memory area which A points to are copied into the memory area to which B points. Later modifications to the contents of either remain unique to A or B; the contents are not shared.

Check for special characters (/*-+_@&$#%) in a string?

string s = @"$KUH% I*$)OFNlkfn$";
var withoutSpecial = new string(s.Where(c => Char.IsLetterOrDigit(c) 
                                            || Char.IsWhiteSpace(c)).ToArray());

if (s != withoutSpecial)
{
    Console.WriteLine("String contains special chars");
}

AngularJS $http-post - convert binary to excel file and download

Answer No 5 worked for me ,Suggestion to developer who are facing similar issue.

//////////////////////////////////////////////////////////
//Server side 
//////////////////////////////////////////////////////////
imports ***
public class AgentExcelBuilder extends AbstractExcelView {

protected void buildExcelDocument(Map<String, Object> model,
            HSSFWorkbook workbook, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

        //poi code goes here ....

        response.setHeader("Cache-Control","must-revalidate");
        response.setHeader("Pragma", "public");
        response.setHeader("Content-Transfer-Encoding","binary");
        response.setHeader("Content-disposition", "attachment; filename=test.xls");

        OutputStream output = response.getOutputStream();

        workbook.write(output);
        System.out.println(workbook.getActiveSheetIndex());
        System.out.println(workbook.getNumberOfSheets());
        System.out.println(workbook.getNumberOfNames());
        output.flush();
        output.close(); 
}//method buildExcelDocument ENDS

//service.js at angular JS code
function getAgentInfoExcel(workgroup,callback){
        $http({
            url: CONTEXT_PATH+'/rest/getADInfoExcel',
            method: "POST",
            data: workgroup, //this is your json data string
            headers: {
               'Content-type': 'application/json'
            },
            responseType: 'arraybuffer'
        }).success(function (data, status, headers, config) {
            var blob = new Blob([data], {type: "application/vnd.ms-excel"});
            var objectUrl = URL.createObjectURL(blob);
            window.open(objectUrl);
        }).error(function (data, status, headers, config) {
            console.log('Failed to download Excel')
        });
    }
////////////////////////////////in .html 

<div class="form-group">`enter code here`
                                <a href="javascript:void(0)" class="fa fa-file-excel-o"
                                    ng-click="exportToExcel();"> Agent Export</a>
                            </div>

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

Sometimes it may happen that you run multiple applications on the same java VM. In Case you have tried all the other solutions described above and it didnt work. Try Running your process by running it on a newly created java VM by passing vmargs

-agentlib:jdwp=transport=dt_socket,server=y,address=10049,suspend=n . 

Here address is what the vm takes.

symfony2 twig path with parameter url creation

/**
 * @Route("/category/{id}", name="_category")
 * @Route("/category/{id}/{active}", name="_be_activatecategory")
 * @Template()
 */
public function categoryAction($id, $active = null)
{ .. }

May works.

How do I make Git use the editor of my choice for commits?

To Make Visual Studio Code (vscode) your default git editor

git config --global core.editor "code --wait"

Java - get the current class name?

this answer is late, but i think there is another way to do this in the context of anonymous handler class.

let's say:

class A {
    void foo() {
        obj.addHandler(new Handler() {
            void bar() {
                String className=A.this.getClass().getName();
                // ...
            }
        });
    }
}

it will achieve the same result. additionally, it's actually quite convenience since every class is defined at compile time, so no dynamicity is damaged.

above that, if the class is really nested, i.e. A actually is enclosed by B, the class of B can be easily known as:

B.this.getClass().getName()

Error:(23, 17) Failed to resolve: junit:junit:4.12

Just connect to Internet and start Android Studio and open your project. While Gradle Sync it will download the dependencies from Internet(All JAR Files). This solved it for me. No Editing in Gradle file ,all was done by Android Studio Automatically. Using Android Studio 2.2 :)

Also don't forget to install Java JDK 1.x(7 or 8 all works fine).

Strange out of memory issue while loading an image to a Bitmap object

Such OutofMemoryException cannot be totally resolved by calling the System.gc() and so on .

By referring to the Activity Life Cycle

The Activity States are determined by the OS itself subject to the memory usage for each process and the priority of each process.

You may consider the size and the resolution for each of the bitmap pictures used. I recommend to reduce the size ,resample to lower resolution , refer to the design of galleries (one small picture PNG , and one original picture.)

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

comparing strings in vb

Dim MyString As String = "Hello World"
Dim YourString As String = "Hello World"
Console.WriteLine(String.Equals(MyString, YourString))

returns a bool True. This comparison is case-sensitive.

So in your example,

if String.Equals(string1, string2) and String.Equals(string3, string4) then
  ' do something
else
  ' do something else
end if

Selecting multiple classes with jQuery

This should work:

$('.myClass, .myOtherClass').removeClass('theclass');

You must add the multiple selectors all in the first argument to $(), otherwise you are giving jQuery a context in which to search, which is not what you want.

It's the same as you would do in CSS.

jQuery counting elements by class - what is the best way to implement this?

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

How to use nan and inf in C?

This works for both float and double:

double NAN = 0.0/0.0;
double POS_INF = 1.0 /0.0;
double NEG_INF = -1.0/0.0;

Edit: As someone already said, the old IEEE standard said that such values should raise traps. But the new compilers almost always switch the traps off and return the given values because trapping interferes with error handling.

Remove last character from string. Swift language

The global dropLast() function works on sequences and therefore on Strings:

var expression  = "45+22"
expression = dropLast(expression)  // "45+2"

// in Swift 2.0 (according to cromanelli's comment below)
expression = String(expression.characters.dropLast())

How to get the hours difference between two date objects?

Use the timestamp you get by calling valueOf on the date object:

var diff = date2.valueOf() - date1.valueOf();
var diffInHours = diff/1000/60/60; // Convert milliseconds to hours

Reading binary file and looping over each byte

Reading binary file in Python and looping over each byte

New in Python 3.5 is the pathlib module, which has a convenience method specifically to read in a file as bytes, allowing us to iterate over the bytes. I consider this a decent (if quick and dirty) answer:

import pathlib

for byte in pathlib.Path(path).read_bytes():
    print(byte)

Interesting that this is the only answer to mention pathlib.

In Python 2, you probably would do this (as Vinay Sajip also suggests):

with open(path, 'b') as file:
    for byte in file.read():
        print(byte)

In the case that the file may be too large to iterate over in-memory, you would chunk it, idiomatically, using the iter function with the callable, sentinel signature - the Python 2 version:

with open(path, 'b') as file:
    callable = lambda: file.read(1024)
    sentinel = bytes() # or b''
    for chunk in iter(callable, sentinel): 
        for byte in chunk:
            print(byte)

(Several other answers mention this, but few offer a sensible read size.)

Best practice for large files or buffered/interactive reading

Let's create a function to do this, including idiomatic uses of the standard library for Python 3.5+:

from pathlib import Path
from functools import partial
from io import DEFAULT_BUFFER_SIZE

def file_byte_iterator(path):
    """given a path, return an iterator over the file
    that lazily loads the file
    """
    path = Path(path)
    with path.open('rb') as file:
        reader = partial(file.read1, DEFAULT_BUFFER_SIZE)
        file_iterator = iter(reader, bytes())
        for chunk in file_iterator:
            yield from chunk

Note that we use file.read1. file.read blocks until it gets all the bytes requested of it or EOF. file.read1 allows us to avoid blocking, and it can return more quickly because of this. No other answers mention this as well.

Demonstration of best practice usage:

Let's make a file with a megabyte (actually mebibyte) of pseudorandom data:

import random
import pathlib
path = 'pseudorandom_bytes'
pathobj = pathlib.Path(path)

pathobj.write_bytes(
  bytes(random.randint(0, 255) for _ in range(2**20)))

Now let's iterate over it and materialize it in memory:

>>> l = list(file_byte_iterator(path))
>>> len(l)
1048576

We can inspect any part of the data, for example, the last 100 and first 100 bytes:

>>> l[-100:]
[208, 5, 156, 186, 58, 107, 24, 12, 75, 15, 1, 252, 216, 183, 235, 6, 136, 50, 222, 218, 7, 65, 234, 129, 240, 195, 165, 215, 245, 201, 222, 95, 87, 71, 232, 235, 36, 224, 190, 185, 12, 40, 131, 54, 79, 93, 210, 6, 154, 184, 82, 222, 80, 141, 117, 110, 254, 82, 29, 166, 91, 42, 232, 72, 231, 235, 33, 180, 238, 29, 61, 250, 38, 86, 120, 38, 49, 141, 17, 190, 191, 107, 95, 223, 222, 162, 116, 153, 232, 85, 100, 97, 41, 61, 219, 233, 237, 55, 246, 181]
>>> l[:100]
[28, 172, 79, 126, 36, 99, 103, 191, 146, 225, 24, 48, 113, 187, 48, 185, 31, 142, 216, 187, 27, 146, 215, 61, 111, 218, 171, 4, 160, 250, 110, 51, 128, 106, 3, 10, 116, 123, 128, 31, 73, 152, 58, 49, 184, 223, 17, 176, 166, 195, 6, 35, 206, 206, 39, 231, 89, 249, 21, 112, 168, 4, 88, 169, 215, 132, 255, 168, 129, 127, 60, 252, 244, 160, 80, 155, 246, 147, 234, 227, 157, 137, 101, 84, 115, 103, 77, 44, 84, 134, 140, 77, 224, 176, 242, 254, 171, 115, 193, 29]

Don't iterate by lines for binary files

Don't do the following - this pulls a chunk of arbitrary size until it gets to a newline character - too slow when the chunks are too small, and possibly too large as well:

    with open(path, 'rb') as file:
        for chunk in file: # text newline iteration - not for bytes
            yield from chunk

The above is only good for what are semantically human readable text files (like plain text, code, markup, markdown etc... essentially anything ascii, utf, latin, etc... encoded) that you should open without the 'b' flag.

How do I merge changes to a single file, rather than merging commits?

Assuming B is the current branch:

$ git diff A <file-path> > patch.tmp
$ git apply patch.tmp -R

Note that this only applies changes to the local file. You'll need to commit afterwards.

How to get the sizes of the tables of a MySQL database?

If you are using phpmyadmin then just go to the table structure

e.g.

Space usage
Data    1.5 MiB
Index   0   B
Total   1.5 Mi

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

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

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

How does the getView() method work when creating your own custom adapter?

getView() method in Adapter is for generating item's view of a ListView, Gallery,...

  1. LayoutInflater is used to get the View object which you define in a layout xml (the root object, normally a LinearLayout, FrameLayout, or RelativeLayout)

  2. convertView is for recycling. Let's say you have a listview which can only display 10 items at a time, and currently it is displaying item 1 -> item 10. When you scroll down one item, the item 1 will be out of screen, and item 11 will be displayed. To generate View for item 11, the getView() method will be called, and convertView here is the view of item 1 (which is not neccessary anymore). So instead create a new View object for item 11 (which is costly), why not re-use convertView? => we just check convertView is null or not, if null create new view, else re-use convertView.

  3. parentView is the ListView or Gallery... which contains the item's view which getView() generates.

Note: you don't call this method directly, just need to implement it to tell the parent view how to generate the item's view.

Substring in VBA

Shorter:

   Split(stringval,":")(0)

How to Load an Assembly to AppDomain with all references recursively?

The Key is the AssemblyResolve event raised by the AppDomain.

[STAThread]
static void Main(string[] args)
{
    fileDialog.ShowDialog();
    string fileName = fileDialog.FileName;
    if (string.IsNullOrEmpty(fileName) == false)
    {
        AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        if (Directory.Exists(@"c:\Provisioning\") == false)
            Directory.CreateDirectory(@"c:\Provisioning\");

        assemblyDirectory = Path.GetDirectoryName(fileName);
        Assembly loadedAssembly = Assembly.LoadFile(fileName);

        List<Type> assemblyTypes = loadedAssembly.GetTypes().ToList<Type>();

        foreach (var type in assemblyTypes)
        {
            if (type.IsInterface == false)
            {
                StreamWriter jsonFile = File.CreateText(string.Format(@"c:\Provisioning\{0}.json", type.Name));
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                jsonFile.WriteLine(serializer.Serialize(Activator.CreateInstance(type)));
                jsonFile.Close();
            }
        }
    }
}

static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string[] tokens = args.Name.Split(",".ToCharArray());
    System.Diagnostics.Debug.WriteLine("Resolving : " + args.Name);
    return Assembly.LoadFile(Path.Combine(new string[]{assemblyDirectory,tokens[0]+ ".dll"}));
}

R: Select values from data table in range

Construct some data

df <- data.frame( name=c("John", "Adam"), date=c(3, 5) )

Extract exact matches:

subset(df, date==3)

  name date
1 John    3

Extract matches in range:

subset(df, date>4 & date<6)

  name date
2 Adam    5

The following syntax produces identical results:

df[df$date>4 & df$date<6, ]

  name date
2 Adam    5

How to communicate between iframe and the parent site?

the window.top property should be able to give what you need.

E.g.

alert(top.location.href)

See http://cross-browser.com/talk/inter-frame_comm.html

Cannot run the macro... the macro may not be available in this workbook

In my case the error happened when I placed my macro (public sub) into a ThisWorkbook section of the file expecting it will make it visible for Application.Run function. This was not the case and I got that error you mentioned.

I moved my macro into a separate Module and it resolved the problem.

how to mysqldump remote db from local machine

As I haven't seen it at serverfault yet, and the answer is quite simple:

Change:

ssh -f -L3310:remote.server:3306 [email protected] -N

To:

ssh -f -L3310:localhost:3306 [email protected] -N

And change:

mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name

To:

mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name

(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)

edit: well, to elaborate: if host is set to localhost, a configured (or default) --socket option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.

Is there a way to remove the separator line from a UITableView?

I still had a dark grey line after attempting the other answers. I had to add the following two lines to make everything "invisible" in terms of row lines between cells.

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.separatorColor = [UIColor clearColor];

MVC3 DropDownListFor - a simple example?

     @Html.DropDownListFor(m => m.SelectedValue,Your List,"ID","Values")

Here Value is that object of model where you want to save your Selected Value

TypeError: $(...).on is not a function

In my case this code solved my error :

(function (window, document, $) {
            'use strict';
             var $html = $('html');
             $('input[name="myiCheck"]').on('ifClicked', function (event) {
             alert("You clicked " + this.value);
             });
})(window, document, jQuery);

You don't should put your function inside $(document).ready

Convert string to Python class object?

This could work:

import sys

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

jQuery scroll to ID from different page

On the link put a hash:

<a href="otherpage.html#elementID">Jump</a>

And on other page, you can do:

$('html,body').animate({
  scrollTop: $(window.location.hash).offset().top
});

On other page, you should have element with id set to elementID to scroll to. Of course you can change the name of it.

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

O/P:

20170115072120

With punctuation:

current_date_time="`date "+%Y-%m-%d %H:%M:%S"`";
echo $current_date_time;

O/P:

2017-01-15 07:25:33

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

Stop mouse event propagation

I just checked in an Angular 6 application, the event.stopPropagation() works on an event handler without even passing $event

(click)="doSomething()"  // does not require to pass $event


doSomething(){
   // write any code here

   event.stopPropagation();
}

Creating a copy of a database in PostgreSQL

Here's the whole process of creating a copying over a database using only pgadmin4 GUI (via backup and restore)

Postgres comes with Pgadmin4. If you use macOS you can press CMD+SPACE and type pgadmin4 to run it. This will open up a browser tab in chrome.


Steps for copying

1. Create the backup

Do this by rightclicking the database -> "backup"

enter image description here

2. Give the file a name.

Like test12345. Click backup. This creates a binary file dump, it's not in a .sql format

enter image description here

3. See where it downloaded

There should be a popup at the bottomright of your screen. Click the "more details" page to see where your backup downloaded to

enter image description here

4. Find the location of downloaded file

In this case, it's /users/vincenttang

enter image description here

5. Restore the backup from pgadmin

Assuming you did steps 1 to 4 correctly, you'll have a restore binary file. There might come a time your coworker wants to use your restore file on their local machine. Have said person go to pgadmin and restore

Do this by rightclicking the database -> "restore"

enter image description here

6. Select file finder

Make sure to select the file location manually, DO NOT drag and drop a file onto the uploader fields in pgadmin. Because you will run into error permissions. Instead, find the file you just created:

enter image description here

7. Find said file

You might have to change the filter at bottomright to "All files". Find the file thereafter, from step 4. Now hit the bottomright "Select" button to confirm

enter image description here

8. Restore said file

You'll see this page again, with the location of the file selected. Go ahead and restore it

enter image description here

9. Success

If all is good, the bottom right should popup an indicator showing a successful restore. You can navigate over to your tables to see if the data has been restored propery on each table.

10. If it wasn't successful:

Should step 9 fail, try deleting your old public schema on your database. Go to "Query Tool"

enter image description here

Execute this code block:

DROP SCHEMA public CASCADE; CREATE SCHEMA public;

enter image description here

Now try steps 5 to 9 again, it should work out

EDIT - Some additional notes. Update PGADMIN4 if you are getting an error during upload with something along the lines of "archiver header 1.14 unsupported version" during restore

How to trigger a file download when clicking an HTML button or JavaScript

The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it. conclusion: attribute download in anchor tag only works if your html file is no server.

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

Linux find and grep command together

Now that the question is clearer, you can just do this in one

grep -R --include "*bills*" "put" .

With relevant flags

   -R, -r, --recursive
          Read  all  files  under  each  directory,  recursively;  this is
          equivalent to the -d recurse option.
   --include=GLOB
          Search only files whose base name matches GLOB  (using  wildcard
          matching as described under --exclude).

Bootstrap 3 only for mobile

If you're looking to make the elements be 33.3% only on small devices and lower:

This is backwards from what Bootstrap is designed for, but you can do this:

<div class="row">
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
    <div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>

This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.

JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/

If you're only looking to hide elements for smaller devices:

I think you're looking for the visible-xs and/or visible-sm classes. These will let you make certain elements only visible to small screen devices.

For example, if you want a element to only be visible to small and extra-small devices, do this:

<div class="visible-xs visible-sm">You're using a fairly small device.</div>

To show it only for larger screens, use this:

<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>

See http://getbootstrap.com/css/#responsive-utilities-classes for more information.

How to set timeout on python's socket recv method?

The timeout that you are looking for is the connection socket's timeout not the primary socket's, if you implement the server side. In other words, there is another timeout for the connection socket object, which is the output of socket.accept() method. Therefore:

sock.listen(1)
connection, client_address = sock.accept()
connection.settimeout(5)    # This is the one that affects recv() method.
connection.gettimeout()     # This should result 5
sock.gettimeout()           # This outputs None when not set previously, if I remember correctly.

If you implement the client side, it would be simple.

sock.connect(server_address)
sock.settimeout(3)

Android sqlite how to check if a record exists

SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.

if(cursor.getCount()<=0){
    Log.v("tag","if 1 "+cursor.getCount());
    return false;
}
Log.v("tag","2 else  "+cursor.getCount());

return true;

if you not use cursor.moveToLast();

cursor.getCount() always give same integer (1) or current position of cursor.

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

Gson: How to exclude specific fields from Serialization without annotations

Kotlin's @Transientannotation also does the trick apparently.

data class Json(
    @field:SerializedName("serialized_field_1") val field1: String,
    @field:SerializedName("serialized_field_2") val field2: String,
    @Transient val field3: String
)

Output:

{"serialized_field_1":"VALUE1","serialized_field_2":"VALUE2"}

.htaccess redirect http to https

I had a problem with redirection also. I tried everything that was proposed on Stackoverflow. The one case I found by myself is:

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP:SSL} !=1 [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

IF...THEN...ELSE using XML

Personally, I would prefer

<IF>
  <TIME from="5pm" to="9pm" />
  <THEN>
    <!-- action -->
  </THEN>
  <ELSE>
    <!-- action -->
  </ELSE>
</IF>

In this way you don't need an id attribute to tie together the IF, THEN, ELSE tags

How to Execute SQL Script File in Java?

Flyway library is really good for this:

    Flyway flyway = new Flyway();
    flyway.setDataSource(dbConfig.getUrl(), dbConfig.getUsername(), dbConfig.getPassword());
    flyway.setLocations("classpath:db/scripts");
    flyway.clean();
    flyway.migrate();

This scans the locations for scripts and runs them in order. Scripts can be versioned with V01__name.sql so if just the migrate is called then only those not already run will be run. Uses a table called 'schema_version' to keep track of things. But can do other things too, see the docs: flyway.

The clean call isn't required, but useful to start from a clean DB. Also, be aware of the location (default is "classpath:db/migration"), there is no space after the ':', that one caught me out.

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

MS SQL Date Only Without Time

If you're using SQL Server 2008 it has this built in now, see this in books online

CAST(GETDATE() AS date)

Can you style html form buttons with css?

You can achieve your desired through easily by CSS :-

HTML

<input type="submit" name="submit" value="Submit Application" id="submit" />

CSS

#submit {
    background-color: #ccc;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius:6px;
    color: #fff;
    font-family: 'Oswald';
    font-size: 20px;
    text-decoration: none;
    cursor: pointer;
    border:none;
}



#submit:hover {
    border: none;
    background:red;
    box-shadow: 0px 0px 1px #777;
}

DEMO

How to set Spinner Default by its Value instead of Position?

this is how i did it:

String[] listAges = getResources().getStringArray(R.array.ages);

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter =
                new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, listAges);

        // Drop down layout style - list view with radio button
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner_age.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.spinner_icon), PorterDuff.Mode.SRC_ATOP);
        spinner_age.setAdapter(dataAdapter);
        spinner_age.setSelection(0);
        spinner_age.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String item = parent.getItemAtPosition(position).toString();

                if(position > 0){
                    // get spinner value
                    Toast.makeText(parent.getContext(), "Age..." + item, Toast.LENGTH_SHORT).show();
                }else{
                    // show toast select gender
                    Toast.makeText(parent.getContext(), "none" + item, Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

Git on Windows: How do you set up a mergetool?

i use an app called WinMerge ( http://winmerge.org/ ) info from their manual ( http://manual.winmerge.org/CommandLine.html )

this is the bash script i use from the mergetool directive via .gitconfig

#!/bin/sh
# using winmerge with git
# replaces unix style null files with a newly created empty windows temp file

file1=$1
if [ "$file1" == '/dev/null' ] || [ "$file1" == '\\.\nul' ] || [ ! -e "$file1" ]
    then 
       file1="/tmp/gitnull"
       `echo "">$file1`
fi
file2=$2
if [ "$file2" == '/dev/null' ] || [ "$file2" == '\\.\nul' ] || [ ! -e "$file2" ]
    then 
       file2="/tmp/gitnull"
       `echo "">$file2`
fi
echo diff : $1 -- $2
"C:\Program files (x86)\WinMerge\WinMergeU.exe" -e -ub -dl "Base" -dr "Mine" "$file1" "$file2"

basically the bash accounts for when the result of the diff in an empty file and creates a new temp file in the correct location.

RedirectToAction with parameter

If your parameter happens to be a complex object, this solves the problem. The key is the RouteValueDictionary constructor.

return RedirectToAction("Action", new RouteValueDictionary(Model))

If you happen to have collections, it makes it a bit trickier, but this other answer covers this very nicely.

Decoding a Base64 string in Java

Modify the package you're using:

import org.apache.commons.codec.binary.Base64;

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

'Syntax Error: invalid syntax' for no apparent reason

I encountered a similar problem, with a syntax error that I knew should not be a syntax error. In my case it turned out that a Python 2 interpreter was trying to run Python 3 code, or vice versa; I think that my shell had a PYTHONPATH with a mixture of Python 2 and Python 3.

List of all unique characters in a string?

The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

As far as performance goes, worrying about it at this stage sounds like premature optimization.

sql like operator to get the numbers only

You can try this

ISNUMERIC (Transact-SQL)

ISNUMERIC returns 1 when the input expression evaluates to a valid numeric data type; otherwise it returns 0.

DECLARE @Table TABLE(
        Col VARCHAR(50)
)

INSERT INTO @Table SELECT 'ABC' 
INSERT INTO @Table SELECT 'Italy' 
INSERT INTO @Table SELECT 'Apple' 
INSERT INTO @Table SELECT '234.62' 
INSERT INTO @Table SELECT '2:234:43:22' 
INSERT INTO @Table SELECT 'France' 
INSERT INTO @Table SELECT '6435.23'
INSERT INTO @Table SELECT '2' 
INSERT INTO @Table SELECT 'Lions'

SELECT  *
FROM    @Table
WHERE   ISNUMERIC(Col) = 1

General error: 1364 Field 'user_id' doesn't have a default value

use print_r(Auth);

then see in which format you have user_id / id variable and use it

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

What is an ORM, how does it work, and how should I use one?

An ORM (Object Relational Mapper) is a piece/layer of software that helps map your code Objects to your database.

Some handle more aspects than others...but the purpose is to take some of the weight of the Data Layer off of the developer's shoulders.

Here's a brief clip from Martin Fowler (Data Mapper):

Patterns of Enterprise Application Architecture Data Mappers

Display date/time in user's locale format and time offset

You can use new Date().getTimezoneOffset()/60 for the timezone. There is also a toLocaleString() method for displaying a date using the user's locale.

Here's the whole list: Working with Dates

SQL query: Delete all records from the table except latest N?

Answering this after a long time...Came across the same situation and instead of using the answers mentioned, I came with below -

DELETE FROM table_name order by ID limit 10

This will delete the 1st 10 records and keep the latest records.

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:

from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse

A =  np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)

similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))

#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))

Results:

pairwise dense output:
[[ 1.          0.40824829  0.40824829]
[ 0.40824829  1.          0.33333333]
[ 0.40824829  0.33333333  1.        ]]

pairwise sparse output:
(0, 1)  0.408248290464
(0, 2)  0.408248290464
(0, 0)  1.0
(1, 0)  0.408248290464
(1, 2)  0.333333333333
(1, 1)  1.0
(2, 1)  0.333333333333
(2, 0)  0.408248290464
(2, 2)  1.0

If you want column-wise cosine similarities simply transpose your input matrix beforehand:

A_sparse.transpose()

Does MySQL ignore null values on unique constraints?

Avoid nullable unique constraints. You can always put the column in a new table, make it non-null and unique and then populate that table only when you have a value for it. This ensures that any key dependency on the column can be correctly enforced and avoids any problems that could be caused by nulls.

How do I send a cross-domain POST request via JavaScript?

There is one more way (using html5 feature). You can use proxy iframe hosted on that other domain, you send message using postMessage to that iframe, then that iframe can do POST request (on same domain) and postMessage back with reposnse to the parent window.

parent on sender.com

var win = $('iframe')[0].contentWindow

function get(event) {
    if (event.origin === "http://reciver.com") {
        // event.data is response from POST
    }
}

if (window.addEventListener){
    addEventListener("message", get, false)
} else {
    attachEvent("onmessage", get)
}
win.postMessage(JSON.stringify({url: "URL", data: {}}),"http://reciver.com");

iframe on reciver.com

function listener(event) {
    if (event.origin === "http://sender.com") {
        var data = JSON.parse(event.data);
        $.post(data.url, data.data, function(reponse) {
            window.parent.postMessage(reponse, "*");
        });
    }
}
// don't know if we can use jQuery here
if (window.addEventListener){
    addEventListener("message", listener, false)
} else {
    attachEvent("onmessage", listener)
}

How do I enable C++11 in gcc?

H2CO3 is right, you can use a makefile with the CXXFLAGS set with -std=c++11 A makefile is a simple text file with instructions about how to compile your program. Create a new file named Makefile (with a capital M). To automatically compile your code just type the make command in a terminal. You may have to install make.

Here's a simple one :

CXX=clang++
CXXFLAGS=-g -std=c++11 -Wall -pedantic
BIN=prog

SRC=$(wildcard *.cpp)
OBJ=$(SRC:%.cpp=%.o)

all: $(OBJ)
    $(CXX) -o $(BIN) $^

%.o: %.c
    $(CXX) $@ -c $<

clean:
    rm -f *.o
    rm $(BIN)

It assumes that all the .cpp files are in the same directory as the makefile. But you can easily tweak your makefile to support a src, include and build directories.

Edit : I modified the default c++ compiler, my version of g++ isn't up-to-date. With clang++ this makefile works fine.

Segmentation fault on large array sizes

Also, if you are running in most UNIX & Linux systems you can temporarily increase the stack size by the following command:

ulimit -s unlimited

But be careful, memory is a limited resource and with great power come great responsibilities :)

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

'was not declared in this scope' error

#include <iostream>
using namespace std;
class matrix
{
    int a[10][10],b[10][10],c[10][10],x,y,i,j;
    public :
        void degerler();
        void ters();
};
void matrix::degerler()
{
    cout << "Satirlari giriniz: "; cin >> x;
    cout << "Sütunlari giriniz: "; cin >> y;
    cout << "Ilk matris elamanlarini giriniz:\n\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
            cin >> a[i][j];
        }
    }
    cout << "Ikinci matris elamanlarini giriniz:\n\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
            cin >> b[i][j];
        }
    }
}

void matrix::ters()
{
    cout << "matrisin tersi\n";
    for (i=1; i<=x; i++)
    {
        for (j=1; j<=y; j++)
        {
    if(i==j)
    {
    b[i][j]=1;
    }
    else
    b[i][j]=0;
    }
}
float d,k;
    for (i=1; i<=x; i++)
    {
    d=a[i][j];
        for (j=1; j<=y; j++)
        {
    a[i][j]=a[i][j]/d;
            b[i][j]=b[i][j]/d;
    }
        for (int h=0; h<x; h++)
        {
            if(h!=i)
    {
       k=a[h][j];
               for (j=1; j<=y; j++)
               {
                    a[h][j]=a[h][j]-(a[i][j]*k);
                    b[h][j]=b[h][j]-(b[i][j]*k);
               }
    }
    count << a[i][j] << "";
    }
    count << endl;
}  
}
int main()
{
    int secim;
    char ch;    
    matrix m;
    m.degerler();
    do
     {
    cout << "seçiminizi giriniz\n";
    cout << " 1. matrisin tersi\n";
    cin >> secim;
    switch (secim)
    {
        case 1:
            m.ters();
            break;
    }
    cout << "\nBaska bir sey yap/n?";
    cin >> ch;
    }
    while (ch!= 'n');
    cout << "\n";
    return 0;
}

Is there a way I can retrieve sa password in sql server 2005

Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.

You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/

Calling method using JavaScript prototype

function MyClass() {}

MyClass.prototype.myMethod = function() {
  alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
  MyClass.prototype.myMethod_original.call( this );
  alert( "doing override");
};

myObj = new MyClass();
myObj.myMethod();

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

Best way to integrate Python and JavaScript?

I was playing with Pyjon some time ago and seems manage to write Javascript's eval directly in Python and ran simple programs... Although it is not complete implementation of JS and rather an experiment. Get it here:

http://code.google.com/p/pyjon/

onclick="location.href='link.html'" does not load page in Safari

Give this a go:

<option onclick="parent.location='#5.2'">Bookmark 2</option>

How can I split a text file using PowerShell?

There's also this quick (and somewhat dirty) one-liner:

$linecount=0; $i=0; Get-Content .\BIG_LOG_FILE.txt | %{ Add-Content OUT$i.log "$_"; $linecount++; if ($linecount -eq 3000) {$I++; $linecount=0 } }

You can tweak the number of first lines per batch by changing the hard-coded 3000 value.

How can I build multiple submit buttons django form?

You can also do like this,

 <form method='POST'>
    {{form1.as_p}}
    <button type="submit" name="btnform1">Save Changes</button>
    </form>
    <form method='POST'>
    {{form2.as_p}}
    <button type="submit" name="btnform2">Save Changes</button>
    </form>

CODE

if request.method=='POST' and 'btnform1' in request.POST:
    do something...
if request.method=='POST' and 'btnform2' in request.POST:
    do something...

How to delete parent element using jQuery

Use parents() instead of parent():

$("a").click(function(event) {
  event.preventDefault();
  $(this).parents('.li').remove();
});

Reference list item by index within Django template?

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

How do you kill all current connections to a SQL Server 2005 database?

The reason that the approach that Adam suggested won't work is that during the time that you are looping over the active connections new one can be established, and you'll miss those. You could instead use the following approach which does not have this drawback:

-- set your current connection to use master otherwise you might get an error

use master
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

--do you stuff here 

ALTER DATABASE YourDatabase SET MULTI_USER

what is the use of $this->uri->segment(3) in codeigniter pagination

Let's say you have a url like this http://www.example.com/controller/action/arg1/arg2

If you want to know what are the arguments that are being passed in this url

$param_offset=0;
$params = array_slice($this->uri->rsegment_array(), $param_offset);
var_dump($params);

Output will be:

array (size=2)
  0 => string 'arg1'
  1 => string 'arg2'

How to know function return type and argument types?

Yes it is.

In Python a function doesn't always have to return a variable of the same type (although your code will be more readable if your functions do always return the same type). That means that you can't specify a single return type for the function.

In the same way, the parameters don't always have to be the same type too.

How can I use a custom font in Java?

Here is how I did it!

//create the font

try {
    //create the font to use. Specify the size!
    Font customFont = Font.createFont(Font.TRUETYPE_FONT, new File("Fonts\\custom_font.ttf")).deriveFont(12f);
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    //register the font
    ge.registerFont(customFont);
} catch (IOException e) {
    e.printStackTrace();
} catch(FontFormatException e) {
    e.printStackTrace();
}

//use the font
yourSwingComponent.setFont(customFont);

perform an action on checkbox checked or unchecked event on html form

Have you tried using the JQuery change event?

$("#g01-01").change(function() {
    if(this.checked) {
        //Do stuff
    }
});

Then you can also remove onchange="doalert(this.id)" from your checkbox :)

Edit:

I don't know if you are using JQuery, but if you're not yet using it, you will need to put the following script in your page so you can use it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Comparing two java.util.Dates to see if they are in the same day

Convert dates to Java 8 java.time.LocalDate as seen here.

LocalDate localDate1 = date1.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate2 = date2.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

// compare dates
assertTrue("Not on the same day", localDate1.equals(localDate2));

How do you change the colour of each category within a highcharts column chart?

You can also set the color individually for each point/bar if you change the data array to be configuration objects instead of numbers.

data: [
      {y: 34.4, color: 'red'},     // this point is red
      21.8,                        // default blue
      {y: 20.1, color: '#aaff99'}, // this will be greenish
      20]                          // default blue

Example on jsfiddle

enter image description here

The default for KeyValuePair

You can create a general (and generic) extension method, like this one:

public static class Extensions
{
    public static bool IsDefault<T>(this T value) where T : struct
    {
        bool isDefault = value.Equals(default(T));

        return isDefault;
    }
}

Usage:

// We have to set explicit default value '0' to avoid build error:
// Use of unassigned local variable 'intValue'
int intValue = 0;
long longValue = 12;
KeyValuePair<String, int> kvp1 = new KeyValuePair<String, int>("string", 11);
KeyValuePair<String, int> kvp2 = new KeyValuePair<String, int>();
List<KeyValuePair<String, int>> kvps = new List<KeyValuePair<String, int>> { kvp1, kvp2 };
KeyValuePair<String, int> kvp3 = kvps.FirstOrDefault(kvp => kvp.Value == 11);
KeyValuePair<String, int> kvp4 = kvps.FirstOrDefault(kvp => kvp.Value == 15);

Console.WriteLine(intValue.IsDefault()); // results 'True'
Console.WriteLine(longValue.IsDefault()); // results 'False'
Console.WriteLine(kvp1.IsDefault()); // results 'False'
Console.WriteLine(kvp2.IsDefault()); // results 'True'
Console.WriteLine(kvp3.IsDefault()); // results 'False'
Console.WriteLine(kvp4.IsDefault()); // results 'True'

What are some reasons for jquery .focus() not working?

I had problems triggering focus on an element (a form input) that was transitioning into the page. I found it was fixable by invoking the focus event from inside a setTimeout with no delay on it. As I understand it (from, eg. this answer), this delays the function until the current execution queue finishes, so in this case it delays the focus event until the transition has completed.

setTimeout(function(){
    $('#goal-input').focus();
});

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

Integer to hex string in C++

int num = 30;
std::cout << std::hex << num << endl; // This should give you hexa- decimal of 30

Entity Framework - Code First - Can't Store List<String>

Slightly tweaking @Mathieu Viales's answer, here's a .NET Standard compatible snippet using the new System.Text.Json serializer thus eliminating the dependency on Newtonsoft.Json.

using System.Text.Json;

builder.Entity<YourEntity>().Property(p => p.Strings)
    .HasConversion(
        v => JsonSerializer.Serialize(v, default),
        v => JsonSerializer.Deserialize<List<string>>(v, default));

Note that while the second argument in both Serialize() and Deserialize() is typically optional, you'll get an error:

An expression tree may not contain a call or invocation that uses optional arguments

Explicitly setting that to the default (null) for each clears that up.

Show Youtube video source into HTML5 video tag?

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

_x000D_
_x000D_
<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>
_x000D_
_x000D_
_x000D_

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

equivalent to push() or pop() for arrays?

In Java an array has a fixed size (after initialisation), meaning that you can't add or remove items from an array.

int[] i = new int[10];

The above snippet mean that the array of integers has a length of 10. It's not possible add an eleventh integer, without re-assign the reference to a new array, like the following:

int[] i = new int[11];

In Java the package java.util contains all kinds of data structures that can handle adding and removing items from array-like collections. The classic data structure Stack has methods for push and pop.

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

    constructor(AnimalClass: typeof Animal ) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

How to get Database Name from Connection String using SqlConnectionStringBuilder

See MSDN documentation for InitialCatalog Property:

Gets or sets the name of the database associated with the connection...

This property corresponds to the "Initial Catalog" and "database" keys within the connection string...

How to set iframe size dynamically

If you use jquery, it can be done by using $(window).height();

<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

Is there any way to kill a Thread?

It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:

  • the thread is holding a critical resource that must be closed properly
  • the thread has created several other threads that must be killed as well.

The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.

For example:

import threading

class StoppableThread(threading.Thread):
    """Thread class with a stop() method. The thread itself has to check
    regularly for the stopped() condition."""

    def __init__(self,  *args, **kwargs):
        super(StoppableThread, self).__init__(*args, **kwargs)
        self._stop_event = threading.Event()

    def stop(self):
        self._stop_event.set()

    def stopped(self):
        return self._stop_event.is_set()

In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals.

There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.

The following code allows (with some restrictions) to raise an Exception in a Python thread:

def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
                                                     ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # "if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"
        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
        raise SystemError("PyThreadState_SetAsyncExc failed")

class ThreadWithExc(threading.Thread):
    '''A thread class that supports raising an exception in the thread from
       another thread.
    '''
    def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL: this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        # TODO: in python 2.6, there's a simpler way to do: self.ident

        raise AssertionError("could not determine the thread's id")

    def raiseExc(self, exctype):
        """Raises the given exception type in the context of this thread.

        If the thread is busy in a system call (time.sleep(),
        socket.accept(), ...), the exception is simply ignored.

        If you are sure that your exception should terminate the thread,
        one way to ensure that it works is:

            t = ThreadWithExc( ... )
            ...
            t.raiseExc( SomeException )
            while t.isAlive():
                time.sleep( 0.1 )
                t.raiseExc( SomeException )

        If the exception is to be caught by the thread, you need a way to
        check that your thread has caught it.

        CAREFUL: this function is executed in the context of the
        caller thread, to raise an exception in the context of the
        thread represented by this instance.
        """
        _async_raise( self._get_my_tid(), exctype )

(Based on Killable Threads by Tomer Filiba. The quote about the return value of PyThreadState_SetAsyncExc appears to be from an old version of Python.)

As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.

A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.

Pandas: Subtracting two date columns and the result being an integer

Create a vectorized method

def calc_xb_minus_xa(df):
    time_dict = {
        '<Minute>': 'm',
        '<Hour>': 'h',
        '<Day>': 'D',
        '<Week>': 'W',
        '<Month>': 'M',
        '<Year>': 'Y'
    }

    time_delta = df.at[df.index[0], 'end_time'] - df.at[df.index[0], 'open_time']
    offset_base_name = str(to_offset(time_delta).base)
    time_term = time_dict.get(offset_base_name)

    result = (df.end_time - df.open_time) / np.timedelta64(1, time_term)
    return result

Then in your df do:

df['x'] = calc_xb_minus_xa(df)

This will work for minutes, hours, days, weeks, month and Year. open_time and end_time need to change according your df

How To Auto-Format / Indent XML/HTML in Notepad++

For those who don't know, npp has a lot of support from plugins and other projects. You can download those plugins from SourceForge.

enter image description here

You need XML Tools to format your text in n++

After you have downloaded XML Tools ..

Exit Notepad++

Go To C:\Program File\Notepad++ .... Your N++ installed folder.

  1. Place below files from xml tools which you downloaded in the npp root folder by copy replace

enter image description here

  1. Go To ..\Plugins subfolder and place below downloaded file

enter image description here

Restart and enjoy!!!

Ctrl + Alt + Shft + B to format.

How to get HttpRequestMessage data

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

How can I remove an element from a list, with lodash?

As lyyons pointed out in the comments, more idiomatic and lodashy way to do this would be to use _.remove, like this

_.remove(obj.subTopics, {
    subTopicId: stToDelete
});

Apart from that, you can pass a predicate function whose result will be used to determine if the current element has to be removed or not.

_.remove(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId === stToDelete;
});

Alternatively, you can create a new array by filtering the old one with _.filter and assign it to the same object, like this

obj.subTopics = _.filter(obj.subTopics, function(currentObject) {
    return currentObject.subTopicId !== stToDelete;
});

Or

obj.subTopics = _.filter(obj.subTopics, {subTopicId: stToKeep});

How to set Apache Spark Executor memory

Spark executor memory is required for running your spark tasks based on the instructions given by your driver program. Basically, it requires more resources that depends on your submitted job.

Executor memory includes memory required for executing the tasks plus overhead memory which should not be greater than the size of JVM and yarn maximum container size.

Add the following parameters in spark-defaults.conf

spar.executor.cores=1

spark.executor.memory=2g

If you using any cluster management tools like cloudera manager or amabari please refresh the cluster configuration for reflecting the latest configs to all nodes in the cluster.

Alternatively, we can pass the executor core and memory value as an argument while running spark-submit command along with class and application path.

Example:

spark-submit \

  --class org.apache.spark.examples.SparkPi \

  --master yarn \

  --deploy-mode cluster \  # can be client for client mode

  --executor-memory 2G \

  --num-executors 5 \

  /path/to/examples.jar \

  1000

error 1265. Data truncated for column when trying to load data from txt file

This error means that at least one row in your Pickup_withoutproxy2.txt file has a value in its first column that is larger than an int (your PickupId field).

An Int can only accept values between -2147483648 to 2147483647.

Review your data to see what's going on. You could try to load it into a temp table with a varchar data type if your txt file is extremely large and difficult to see. Easy enough to check for an int once loaded in the database.

Good luck.

Strip Leading and Trailing Spaces From Java String

With Java-11 and above, you can make use of the String.strip API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

The sample cases for these could be:--

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

Java - How do I make a String array with values?

You want to initialize an array. (For more info - Tutorial)

int []ar={11,22,33};

String []stringAr={"One","Two","Three"};

From the JLS

The [] may appear as part of the type at the beginning of the declaration, or as part of the declarator for a particular variable, or both, as in this example:

byte[] rowvector, colvector, matrix[];

This declaration is equivalent to:

byte rowvector[], colvector[], matrix[][];

How do I get bootstrap-datepicker to work with Bootstrap 3?

I also use Stefan Petre’s http://www.eyecon.ro/bootstrap-datepicker and it does not work with Bootstrap 3 without modification. Note that http://eternicode.github.io/bootstrap-datepicker/ is a fork of Stefan Petre's code.

You have to change your markup (the sample markup will not work) to use the new CSS and form grid layout in Bootstrap 3. Also, you have to modify some CSS and JavaScript in the actual bootstrap-datepicker implementation.

Here is my solution:

<div class="form-group row">
  <div class="col-xs-8">
    <label class="control-label">My Label</label>
    <div class="input-group date" id="dp3" data-date="12-02-2012" data-date-format="mm-dd-yyyy">
      <input class="form-control" type="text" readonly="" value="12-02-2012">
      <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
    </div>
  </div>
</div>

CSS changes in datepicker.css on lines 176-177:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 34:

this.component = this.element.is('.date') ? this.element.find('.input-group-addon') : false;

UPDATE

Using the newer code from http://eternicode.github.io/bootstrap-datepicker/ the changes are as follows:

CSS changes in datepicker.css on lines 446-447:

.input-group.date .input-group-addon i,
.input-group.date .input-group-addon i {

Javascript change in datepicker-bootstrap.js on line 46:

 this.component = this.element.is('.date') ? this.element.find('.input-group-addon, .btn') : false;

Finally, the JavaScript to enable the datepicker (with some options):

 $(".input-group.date").datepicker({ autoclose: true, todayHighlight: true });

Tested with Bootstrap 3.0 and JQuery 1.9.1. Note that this fork is better to use than the other as it is more feature rich, has localization support and auto-positions the datepicker based on the control position and window size, avoiding the picker going off the screen which was a problem with the older version.

python: Change the scripts working directory to the script's own directory

Change your crontab command to

* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)

The (...) starts a sub-shell that your crond executes as a single command. The || exit 1 causes your cronjob to fail in case that the directory is unavailable.

Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.

VBA macro that search for file in multiple subfolders

I actually just found this today for something I'm working on. This will return file paths for all files in a folder and its subfolders.

Dim colFiles As New Collection
RecursiveDir colFiles, "C:\Users\Marek\Desktop\Makro\", "*.*", True
Dim vFile As Variant

For Each vFile In colFiles
     'file operation here or store file name/path in a string array for use later in the script
     filepath(n) = vFile
     filename = fso.GetFileName(vFile) 'If you want the filename without full path
     n=n+1
Next vFile


'These two functions are required
Public Function RecursiveDir(colFiles As Collection, strFolder As String, strFileSpec As String, bIncludeSubfolders As Boolean)
Dim strTemp As String
Dim colFolders As New Collection
Dim vFolderName As Variant
strFolder = TrailingSlash(strFolder)
strTemp = Dir(strFolder & strFileSpec)
Do While strTemp <> vbNullString
    colFiles.Add strFolder & strTemp
    strTemp = Dir
Loop
If bIncludeSubfolders Then

    strTemp = Dir(strFolder, vbDirectory)
    Do While strTemp <> vbNullString
        If (strTemp <> ".") And (strTemp <> "..") Then
            If (GetAttr(strFolder & strTemp) And vbDirectory) <> 0 Then
                colFolders.Add strTemp
            End If
        End If
        strTemp = Dir
    Loop
    'Call RecursiveDir for each subfolder in colFolders
    For Each vFolderName In colFolders
        Call RecursiveDir(colFiles, strFolder & vFolderName, strFileSpec, True)
    Next vFolderName
End If
End Function

Public Function TrailingSlash(strFolder As String) As String
If Len(strFolder) > 0 Then
    If Right(strFolder, 1) = "\" Then
        TrailingSlash = strFolder
    Else
        TrailingSlash = strFolder & "\"
    End If
End If
End Function

This is adapted from a post by Ammara Digital Image Solutions.(http://www.ammara.com/access_image_faq/recursive_folder_search.html).

jQuery return ajax result into outside variable

So this is long after the initial question, and technically it isn't a direct answer to how to use Ajax call to populate exterior variable as the question asks. However in research and responses it's been found to be extremely difficult to do this without disabling asynchronous functions within the call, or by descending into what seems like the potential for callback hell. My solution for this has been to use Axios. Using this has dramatically simplified my usages of asynchronous calls getting in the way of getting at data.

For example if I were trying to access session variables in PHP, like the User ID, via a call from JS this might be a problem. Doing something like this..

async function getSession() {
 'use strict';
 const getSession = await axios("http:" + url + "auth/" + "getSession");
 log(getSession.data);//test
 return getSession.data;
}

Which calls a PHP function that looks like this.

public function getSession() {
 $session = new SessionController();
 $session->Session();
 $sessionObj = new \stdClass();
 $sessionObj->user_id = $_SESSION["user_id"];
 echo json_encode($sessionObj);
}

To invoke this using Axios do something like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
});

The result would be, in this case a Json object from PHP.

{"user_id":"1111111-1111-1111-1111-111111111111"}

Which you can either use in a function directly in the response section of the Axios call or set a variable or invoke another function.

Proper syntax for the Axios call would actually look like this.

getSession().then(function (res) {
 log(res);//test
 anyVariable = res;
 anyFunction(res);//set any variable or populate another function waiting for the data
}).catch(function (error) {
 console.log(error);
});

For proper error handling.

I hope this helps anyone having these issues. And yes I am aware this technically is not a direct answer to the question but given the answers supplied already I felt the need to provide this alternative solution which dramatically simplified my code on the client and server sides.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

First of all check the declaration of both the methods.

1) OrElse: Execute logic and pass result as argument.

public T orElse(T other) {    
 return value != null ? value : other;
}

2) OrElseGet: Execute logic if value inside the optional is null

public T orElseGet(Supplier<? extends T> other) {
  return value != null ? value : other.get(); 
}

Some explanation on above declaration: The argument of “Optional.orElse” always gets executed irrespective of the value of the object in optional (null, empty or with value). Always consider the above-mentioned point in mind while using “Optional.orElse”, otherwise use of “Optional.orElse” can be very risky in the following situation.

Risk-1) Logging Issue: If content inside orElse contains any log statement: In this case, you will end up logging it every time.

Optional.of(getModel())
   .map(x -> {
      //some logic
   })
  .orElse(getDefaultAndLogError());

getDefaultAndLogError() {
  log.error("No Data found, Returning default");
  return defaultValue;
}

Risk-2) Performance Issue: If content inside orElse is time-intensive: Time intensive content can be any i/o operations DB call, API call, file reading. If we put such content in orElse(), the system will end up executing a code of no use.

Optional.of(getModel())
   .map(x -> //some logic)
   .orElse(getDefaultFromDb());

getDefaultFromDb() {
   return dataBaseServe.getDefaultValue(); //api call, db call.
}

Risk-3) Illegal State or Bug Issue: If content inside orElse is mutating some object state: We might be using the same object at another place let say inside Optional.map function and it can put us in a critical bug.

List<Model> list = new ArrayList<>();
Optional.of(getModel())
  .map(x -> {
  })
  .orElse(get(list));

get(List < String > list) {
   log.error("No Data found, Returning default");
   list.add(defaultValue);
   return defaultValue;
}

Then, When can we go with orElse()? Prefer using orElse when the default value is some constant object, enum. In all above cases we can go with Optional.orElseGet() (which only executes when Optional contains non empty value)instead of Optional.orElse(). Why?? In orElse, we pass default result value, but in orElseGet we pass Supplier and method of Supplier only executes if the value in Optional is null.

Key takeaways from this:

  1. Do not use “Optional.orElse” if it contains any log statement.
  2. Do not use “Optional.orElse” if it contains time-intensive logic.
  3. Do not use “Optional.orElse” if it is mutating some object state.
  4. Use “Optional.orElse” if we have to return a constant, enum.
  5. Prefer “Optional.orElseGet” in the situations mentioned in 1,2 and 3rd points.

I have explained this in point-2 (“Optional.map/Optional.orElse” != “if/else”) my medium blog. Use Java8 as a programmer not as a coder

Convert JS Object to form data

Here is a short and sweet solution using Object.entries() that will take care of even your nested objects.

// If this is the object you want to convert to FormData...
const item = {
    description: 'First item',
    price: 13,
    photo: File
};

const formData = new FormData();

Object.entries(item).forEach(([key, value]) => {
    formData.append(key, value);
});

// At this point, you can then pass formData to your handler method

Read more about Object.entries() over here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

python pandas dataframe to dictionary

mydict = dict(zip(df.id, df.value))

Get last 3 characters of string

The easiest way would be using Substring

string str = "AM0122200204";
string substr = str.Substring(str.Length - 3);

Using the overload with one int as I put would get the substring of a string, starting from the index int. In your case being str.Length - 3, since you want to get the last three chars.

How to add plus one (+1) to a SQL Server column in a SQL Query

You need both a value and a field to assign it to. The value is TableField + 1, so the assignment is:

SET TableField = TableField + 1

Using ALTER to drop a column if it exists in MySQL

For MySQL, there is none: MySQL Feature Request.

Allowing this is arguably a really bad idea, anyway: IF EXISTS indicates that you're running destructive operations on a database with (to you) unknown structure. There may be situations where this is acceptable for quick-and-dirty local work, but if you're tempted to run such a statement against production data (in a migration etc.), you're playing with fire.

But if you insist, it's not difficult to simply check for existence first in the client, or to catch the error.

MariaDB also supports the following starting with 10.0.2:

DROP [COLUMN] [IF EXISTS] col_name 

i. e.

ALTER TABLE my_table DROP IF EXISTS my_column;

But it's arguably a bad idea to rely on a non-standard feature supported by only one of several forks of MySQL.

Clear data in MySQL table with PHP?

TRUNCATE TABLE table;

is the SQL command. In PHP, you'd use:

mysql_query('TRUNCATE TABLE table;');

Python basics printing 1 to 100

When you use count = count + 3 or count = count + 9 instead of count = count + 1, the value of count will never be 100, and hence it enters an infinite loop.

You could use the following code for your condition to work

while count < 100:

Now the loop will terminate when count >= 100.

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

Java array assignment (multiple values)

int a[] = { 2, 6, 8, 5, 4, 3 }; 
int b[] = { 2, 3, 4, 7 };

if you take float number then you take float and it's your choice

this is very good way to show array elements.

How to make a <div> appear in front of regular text/tables

You can use the stacking index of the div to make it appear on top of anything else. Make it a larger value that other elements and it well be on top of others.

use z-index property. See Specifying the stack level: the 'z-index' property and

Elaborate description of Stacking Contexts

Something like

#divOnTop { z-index: 1000; }

<div id="divOnTop">I am on top</div>

What you have to look out for will be IE6. In IE 6 some elements like <select> will be placed on top of an element with z-index value higher than the <select>. You can have a workaround for this by placing an <iframe> behind the div.

See this Internet Explorer z-index bug?

Pass values of checkBox to controller action in asp.net mvc4

For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this

@Html.CheckBox("checkResp")

to create a checkbox that would play nice with the controller.

Abort a git cherry-pick?

You can do the following

git cherry-pick --abort

From the git cherry-pick docs

--abort  

Cancel the operation and return to the pre-sequence state.

How do I set up Vim autoindentation properly for editing Python files?

Ensure you are editing the correct configuration file for VIM. Especially if you are using windows, where the file could be named _vimrc instead of .vimrc as on other platforms.

In vim type

:help vimrc

and check your path to the _vimrc/.vimrc file with

:echo $HOME

:echo $VIM

Make sure you are only using one file. If you want to split your configuration into smaller chunks you can source other files from inside your _vimrc file.

:help source

How do I scroll to an element using JavaScript?

Similar to @caveman's solution

const element = document.getElementById('theelementsid');

if (element) {
    window.scroll({
        top: element.scrollTop,
        behavior: 'smooth',
    }) 
}

Writing unit tests in Python: How do I start?

nosetests is brilliant solution for unit-testing in python. It supports both unittest based testcases and doctests, and gets you started with it with just simple config file.

Why would an Enum implement an Interface?

Enums don't just have to represent passive sets (e.g. colours). They can represent more complex objects with functionality, and so you're then likely to want to add further functionality to these - e.g. you may have interfaces such as Printable, Reportable etc. and components that support these.

How to cast List<Object> to List<MyClass>

You can create a new List and add the elements to it:

For example:

List<A> a = getListOfA();
List<Object> newList = new ArrayList<>();
newList.addAll(a);

character count using jquery

Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";
   console.log(str.length); 
   console.log($.trim(str).length); 
   console.log(str.replace(/ /g,'').length); 

Output:

20
7
5

Source: How to count number of characters in a string with JQuery

Replacing some characters in a string with another character

echo "$string" | tr xyz _

would replace each occurrence of x, y, or z with _, giving A__BC___DEF__LMN in your example.

echo "$string" | sed -r 's/[xyz]+/_/g'

would replace repeating occurrences of x, y, or z with a single _, giving A_BC_DEF_LMN in your example.

Install Node.js on Ubuntu

Node.js is available as a snap package in all currently supported versions of Ubuntu. Specific to Node.js, developers can choose from one or more of the currently supported releases and get regular automatic updates directly from NodeSource. Node.js versions 6, 8, 9, 10, 11, 13 and 14 are currently available, with the Snap Store being updated within hours or minutes of a Node.js release.

Node.js can be installed with a single command, for example:

sudo snap install node --classic --channel 11/stable

The node snap can be accessed by the command node, for example:

$ node -v
v11.5.0

An up-to-date version of npm will installed as part of the node snap. npm should be run outside of the node repl, in your normal shell. After installing the node snap run the following command to enable npm update checking:

sudo chown -R $USER:$(id -gn $USER) /home/<b>your-username</b>/.config

Replace your-username in the above command with your own username. Then run npm -v to check if the version of npm is up-to-date. As an example I checked that npm was up-to-date, checked the version of an already installed package named yarn with the command npm list yarn and then updated the existing yarn package to the latest version with the command npm update yarn

Users can switch between versions of Node.js at any time without needing to involve additional tools like nvm (Node Version Manager), for example:

sudo snap refresh node --channel=11/stable

Users can test bleeding-edge versions of Node.js that can be installed from the latest edge channel which is currently tracking Node.js version 12 by switching with:

sudo snap switch node --edge

This approach is only recommended for those users who are willing to participate in testing and bug reporting upstream.

Node.js LTS Schedule

Release LTS Status  Codename  LTS Start     Maintenance Start   Maintenance End
 6.x    Active      Boron     2016-10-18    April 2018          April 2019
 7.x    No LTS
 8.x    Active      Carbon    2017-10-31    April 2019          December 2019
 9.x    No LTS
10.x    Active      Dubnium   October 2018  April 2020          April 2021
11.x    No LTS                2019-04-01    2019-06-30
12.x                          2019-10-22    2021-04-01          2022-04-01
13.x    No LTS                2020-04-20    2020-06-01
14.x    Current     Fermium   2020-10-20    2021-10-20          2023-04-30

What does the NS prefix mean?

When NeXT were defining the NextStep API (as opposed to the NEXTSTEP operating system), they used the prefix NX, as in NXConstantString. When they were writing the OpenStep specification with Sun (not to be confused with the OPENSTEP operating system) they used the NS prefix, as in NSObject.

How to position the Button exactly in CSS

It seems some what center of the screen. So I would like to do like this

body { 
     background: url('http://oi44.tinypic.com/33tjudk.jpg') no-repeat center center fixed;    
     background-size:cover; 
     text-align: 0 auto; // Make the play button horizontal center
}

#play_button {
    position:absolute;  // absolutely positioned
    transition: .5s ease;
    top: 50%;  // Makes vertical center
} 

Bootstrap modal: close current, open new

Using click function:

$('.btn-editUser').on('click', function(){
    $('#viewUser').modal('hide'); // hides modal with id viewUser 
    $('#editUser').modal('show'); // display modal with id editUser
});

Heads up:

Make sure that the one you want to show is an independent modal.

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

The one liner to get true postives etc. out of the confusion matrix is to ravel it:

from sklearn.metrics import confusion_matrix

y_true = [1, 1, 0, 0]
y_pred = [1, 0, 1, 0]   

tn, fp, fn, tp = confusion_matrix(y_true, y_pred).ravel()
print(tn, fp, fn, tp)  # 1 1 1 1

How to use a SQL SELECT statement with Access VBA

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

Updating state on props change in React Form

It's quite clearly from their docs:

If you used componentWillReceiveProps for re-computing some data only when a prop changes, use a memoization helper instead.

Use: https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#what-about-memoization

Intellij reformat on file save

I suggest the save actions plugin. It also supports optimize imports and rearrange code.

Works well in combination with the eclipse formatter plugin.

Search and activate the plugin:

enter image description here

Configure it:

enter image description here

Edit: it seems like it the recent version of Intellij the save action plugin is triggered by the automatic Intellij save. This can be quite annoying when it hits while still editing.

This github issue of the plugin gives a hint to some possible solutions:

https://github.com/dubreuia/intellij-plugin-save-actions/issues/63

I actually tried to assign reformat to Ctrl+S and it worked fine - saving is done automatically now.

WordPress asking for my FTP credentials to install plugins

There's a lot of similar responses to this question, but none of them fully touch on the root cause. Sebastian Schmid's comment on the original post touches on it but not fully. Here's my take as of 2018-11-06:

Root Cause

When you try to upload a plugin through the WordPress admin interface, WordPress will make a call over to a function called "get_filesystem_method()" (ref: /wp-admin/includes/file.php:1549). This routine will attempt to write a file to the location in question (in this case the plugin directory). It can of course fail here immediately if file permissions aren't setup right to allow the WordPress user (think the user identity executing the php) to write the file to the location in question.

If the file can be created, this function then detects the file owner of the temporary file, along with the file owner of the function's current file (ref: /wp-admin/includes/file.php:1572) and compares the two. If they match then, in WordPress's words, "WordPress is creating files as the same owner as the WordPress files, this means it's safe to modify & create new files via PHP" and your plugin is uploaded successfully without the FTP Credentials prompt. If they don't match, you get the FTP Credentials prompt.

Fixes

  1. Ensure the plugin directory is writable by the identity running your php process.
  2. Ensure the identity that is running your php process is the file owner for either:

    a) All WordPress application files, or...
    b) At the very least the /wp-admin/includes/file.php file

Final Comments

I'm not overly keen on specifically applying file ownership to the file.php to work around this issue (it feels a tad hacky to say the least!). It seems to me at this point that the WordPress code base is leaning towards having us execute the PHP process under the same user principal as the file owner for the WordPress application files. I would welcome some comments from the community on this.

Change Bootstrap tooltip color

my jQuery fix:

HTML:

   <a href="#" data-toggle="tooltip" data-placement="right" data-original-title="some text">
       <span class="glyphicon glyphicon-question-sign"></span>
   </a>

jQuery:

$('[data-toggle="tooltip"]').hover(function(){
    $('.tooltip-inner').css('min-width', '400px');
    $('.tooltip-inner').css('color', 'red');
});

Call of overloaded function is ambiguous

The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.

As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.

The easiest solution is to just cast the 0 to the right type.
Another option is to ensure the int overload is preferred, for example by making the other one a template:

class huge
{
 private:
  unsigned char data[BYTES];
 public:
  void setval(unsigned int);
  template <class T> void setval(const T *); // not implemented
  template <> void setval(const char*);
};

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

The problem I had was because I had made a database in my LocalDb.
If that's the case then you have to write is as shown below:

    "SELECT * FROM <DatabaseName>.[dbo].[Projects]"

Replace with your database name.
You can probably also drop the "[ ]"

setting y-axis limit in matplotlib

You can instantiate an object from matplotlib.pyplot.axes and call the set_ylim() on it. It would be something like this:

import matplotlib.pyplot as plt
axes = plt.axes()
axes.set_ylim([0, 1])

"Find next" in Vim

The most useful shortcut in Vim, IMHO, is the * key.

Put the cursor on a word and hit the * key and you will jump to the next instance of that word.

The # key does the same, but it jumps to the previous instance of the word.

It is truly a time saver.

No connection string named 'MyEntities' could be found in the application config file

are you using more than one project on your solution?

Because if you are, the web config you must check is the one on the same project as de .edmx file

How to use placeholder as default value in select2 framework

Try this.In html you write the following code.

<select class="select2" multiple="multiple" placeholder="Select State">
    <option value="AK">Alaska</option>
    <option value="HI">Hawaii</option>
</select>

And in your script write the below code.Keep in mind that have the link of select2js.

<script>
         $( ".select2" ).select2( { } );
 </script>

SQL Query to search schema of all tables

  select object_name(c.object_id) as table_name
    , schema_name(t.schema_id) as schema_name
    from sys.columns c
    join sys.tables t on c.object_id = t.object_id
     where c.name=N'CreatedDate';

It gets a little more complicated if you want alsoother table properties, but you'll refer to the object catalog views like sys.tables, sys.columns etc.

What is the difference between MVC and MVVM?

From a practical point of view, MVC (Model-View-Controller) is a pattern. However, MVC when used as ASP.net MVC, when combined with Entity Framework (EF) and the "power tools" is a very powerful, partially automated approach for bringing databases, tables, and columns to a web-page, for either full CRUD operations or R (Retrieve or Read) operations only. At least as I used MVVM, the View Models interacted with models that depended upon business objects, which were in turn "hand-made" and after a lot of effort, one was lucky to get models as good as what EF gives one "out-of-the-box". From a practical programming point of view, MVC seems a good choice because it gives one lots of utility out-of-box, but there is still a potential for bells-and-whistles to be added.

Batch files : How to leave the console window open

In the last line of the batch file that you want to keep open put a

pause >nul

What is the 'open' keyword in Swift?

open is only for another module for example: cocoa pods, or unit test, we can inherit or override

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

How to increase the Java stack size?

Weird! You are saying that you want to generate a recursion of 1<<15 depth???!!!!

I'd suggest DON'T try it. The size of the stack will be 2^15 * sizeof(stack-frame). I don't know what stack-frame size is, but 2^15 is 32.768. Pretty much... Well, if it stops at 1024 (2^10) you'll have to make it 2^5 times bigger, it is, 32 times bigger than with your actual setting.

SimpleXml to string

You can use ->child to get a child element named child.

This element will contain the text of the child element.

But if you try var_dump() on that variable, you will see it is not actually a PHP string.

The easiest way around this is to perform a strval(xml->child); That will convert it to an actual PHP string.

This is useful when debugging when looping your XML and using var_dump() to check the result.

So $s = strval($xml->child);.

ASP.NET MVC: Custom Validation by DataAnnotation

To improve Darin's answer, it can be bit shorter:

public class UniqueFileName : ValidationAttribute
{
    private readonly NewsService _newsService = new NewsService();

    public override bool IsValid(object value)
    {
        if (value == null) { return false; }

        var file = (HttpPostedFile) value;

        return _newsService.IsFileNameUnique(file.FileName);
    }
}

Model:

[UniqueFileName(ErrorMessage = "This file name is not unique.")]

Do note that an error message is required, otherwise the error will be empty.

Get full path of the files in PowerShell

Get-ChildItem -Recurse *.txt | Format-Table FullName

That is what I used. I feel it is more understandable as it doesn't contain any loop syntax.

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

What's the difference between echo, print, and print_r in PHP?

**Echocan accept multiple expressions while print cannot. The Print_r () PHP function is used to return an array in a human readable form. It is simply written as

![Print_r ($your_array)][1]

Error: Cannot invoke an expression whose type lacks a call signature

The function that it returns has a call signature, but you told Typescript to completely ignore that by adding : any in its signature.

How to get the location of the DLL currently executing?

In my case (dealing with my assemblies loaded [as file] into Outlook):

typeof(OneOfMyTypes).Assembly.CodeBase

Note the use of CodeBase (not Location) on the Assembly. Others have pointed out alternative methods of locating the assembly.

How to shift a column in Pandas DataFrame

I suppose imports

import pandas as pd
import numpy as np

First append new row with NaN, NaN,... at the end of DataFrame (df).

s1 = df.iloc[0]    # copy 1st row to a new Series s1
s1[:] = np.NaN     # set all values to NaN
df2 = df.append(s1, ignore_index=True)  # add s1 to the end of df

It will create new DF df2. Maybe there is more elegant way but this works.

Now you can shift it:

df2.x2 = df2.x2.shift(1)  # shift what you want

CSS vertical alignment of inline/inline-block elements

Simply floating both elements left achieves the same result.

div {
background:yellow;
vertical-align:middle;
margin:10px;
}

a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}

span {
background:red;
display:inline-block;
float:left;
}

Using ConfigurationManager to load config from an arbitrary location

For ASP.NET use WebConfigurationManager:

var config = WebConfigurationManager.OpenWebConfiguration("~/Sites/" + requestDomain + "/");
(..)
config.AppSettings.Settings["xxxx"].Value;

How do I run Java .class files?

To run Java class file from the command line, the syntax is:

java -classpath /path/to/jars <packageName>.<MainClassName>

where packageName (usually starts with either com or org) is the folder name where your class file is present.

For example if your main class name is App and Java package name of your app is com.foo.app, then your class file needs to be in com/foo/app folder (separate folder for each dot), so you run your app as:

$ java com.foo.app.App

Note: $ is indicating shell prompt, ignore it when typing

If your class doesn't have any package name defined, simply run as: java App.

If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp/-classpath or using CLASSPATH variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.).


Practical example

Given we've created sample project using Maven as:

$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false 

and we've compiled our project by mvn compile in our my-app/ dir, it'll generate our class file is in target/classes/com/foo/app/App.class.

To run it, we can either specify class path via -cp or going to it directly, check examples below:

$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!

To double check your class and package name, you can use Java class file disassembler tool, e.g.:

$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
  public com.foo.app.App();
  public static void main(java.lang.String[]);
}

Note: javap won't work if the compiled file has been obfuscated.

A simple algorithm for polygon intersection

You have not given us your representation of a polygon. So I am choosing (more like suggesting) one for you :)

Represent each polygon as one big convex polygon, and a list of smaller convex polygons which need to be 'subtracted' from that big convex polygon.

Now given two polygons in that representation, you can compute the intersection as:

Compute intersection of the big convex polygons to form the big polygon of the intersection. Then 'subtract' the intersections of all the smaller ones of both to get a list of subracted polygons.

You get a new polygon following the same representation.

Since convex polygon intersection is easy, this intersection finding should be easy too.

This seems like it should work, but I haven't given it more deeper thought as regards to correctness/time/space complexity.