Programs & Examples On #Aspnet compiler

What version of Python is on my Mac?

Take a look at the docs regarding Python on Mac.

The version at /System/Library/Frameworks/Python.framework is installed by Apple and is used by the system. It is version 3.3 in your case. You can access and use this Python interpreter, but you shouldn't try to remove it, and it may not be the one that comes up when you type "Python" in a terminal or click on an icon to launch it.

You must have installed another version of Python (2.7) on your own at some point, and now that is the one that is launched by default.

As other answers have pointed out, you can use the command which python on your terminal to find the path to this other installation.

Does MS SQL Server's "between" include the range boundaries?

if you hit this, and don't really want to try and handle adding a day in code, then let the DB do it..

myDate >= '20090101 00:00:00' AND myDate < DATEADD(day,1,'20090101 00:00:00')

If you do include the time portion: make sure it references midnight. Otherwise you can simply omit the time:

myDate >= '20090101' AND myDate < DATEADD(day,1,'20090101')

and not worry about it.

How to return images in flask response?

You use something like

from flask import send_file

@app.route('/get_image')
def get_image():
    if request.args.get('type') == '1':
       filename = 'ok.gif'
    else:
       filename = 'error.gif'
    return send_file(filename, mimetype='image/gif')

to send back ok.gif or error.gif, depending on the type query parameter. See the documentation for the send_file function and the request object for more information.

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

How to get the current date and time of your timezone in Java?

With the java.time classes built into Java 8 and later:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }

How can I get the list of files in a directory using C or C++?

#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;

int main() {
    std::string path = "/path/to/directory";
    for (const auto & entry : fs::directory_iterator(path))
        std::cout << entry.path() << std::endl;
}

How to remove only 0 (Zero) values from column in excel 2010

There is an issue with the Command + F solution. It will replace all 0's if you click replace all. This means if you do not review every zero, zero's contained in important cells will also be removed. For example, if you have phone numbers that have (420) area codes they will all be changed to (40).

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

What are the different NameID format used for?

It is just a hint for the Service Provider on what to expect from the NameID returned by the Identity Provider. It can be:

  1. unspecified
  2. emailAddress – e.g. [email protected]
  3. X509SubjectName – e.g. CN=john,O=Company Ltd.,C=US
  4. WindowsDomainQualifiedName – e.g. CompanyDomain\John
  5. kerberos– e.g. john@realm
  6. entity – this one in used to identify entities that provide SAML-based services and looks like a URI
  7. persistent – this is an opaque service-specific identifier which must include a pseudo-random value and must not be traceable to the actual user, so this is a privacy feature.
  8. transient – opaque identifier which should be treated as temporary.

Incorrect integer value: '' for column 'id' at row 1

To let MySql generate sequence numbers for an AUTO_INCREMENT field you have three options:

  1. specify list a column list and omit your auto_incremented column from it as njk suggested. That would be the best approach. See comments.
  2. explicitly assign NULL
  3. explicitly assign 0

3.6.9. Using AUTO_INCREMENT:

...No value was specified for the AUTO_INCREMENT column, so MySQL assigned sequence numbers automatically. You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

These three statements will produce the same result:

$insertQuery = "INSERT INTO workorders (`priority`, `request_type`) VALUES('$priority', '$requestType', ...)";
$insertQuery = "INSERT INTO workorders VALUES(NULL, '$priority', ...)";
$insertQuery = "INSERT INTO workorders VALUES(0, '$priority', ...";

JQuery get all elements by class name

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

Call PHP function from Twig template

This worked for me (using Slim Twig-View):

$twig->getEnvironment()->addFilter(
   new \Twig_Filter('md5', function($arg){ return md5($arg); })
);

This creates a new filter named md5 which returns the MD5 checksum of the argument.

jQuery checkbox check/uncheck

Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

How to identify numpy types in python?

That actually depends on what you're looking for.

  • If you want to test whether a sequence is actually a ndarray, a isinstance(..., np.ndarray) is probably the easiest. Make sure you don't reload numpy in the background as the module may be different, but otherwise, you should be OK. MaskedArrays, matrix, recarray are all subclasses of ndarray, so you should be set.
  • If you want to test whether a scalar is a numpy scalar, things get a bit more complicated. You could check whether it has a shape and a dtype attribute. You can compare its dtype to the basic dtypes, whose list you can find in np.core.numerictypes.genericTypeRank. Note that the elements of this list are strings, so you'd have to do a tested.dtype is np.dtype(an_element_of_the_list)...

MSVCP140.dll missing

That's probably the C++ runtime library. Since it's a DLL it is not included in your program executable. Your friend can download those libraries from Microsoft.

Best way to get the max value in a Spark dataframe column

Another way of doing it:

df.select(f.max(f.col("A")).alias("MAX")).limit(1).collect()[0].MAX

On my data, I got this benchmarks:

df.select(f.max(f.col("A")).alias("MAX")).limit(1).collect()[0].MAX
CPU times: user 2.31 ms, sys: 3.31 ms, total: 5.62 ms
Wall time: 3.7 s

df.select("A").rdd.max()[0]
CPU times: user 23.2 ms, sys: 13.9 ms, total: 37.1 ms
Wall time: 10.3 s

df.agg({"A": "max"}).collect()[0][0]
CPU times: user 0 ns, sys: 4.77 ms, total: 4.77 ms
Wall time: 3.75 s

All of them give the same answer

Table row and column number in jQuery

Off the top of my head, one way would be to grab all previous elements and count them.

$('td').click(function(){ 
    var colIndex = $(this).prevAll().length;
    var rowIndex = $(this).parent('tr').prevAll().length;
});

java.lang.IllegalArgumentException: contains a path separator

openFileInput() doesn't accept paths, only a file name if you want to access a path, use File file = new File(path) and corresponding FileInputStream

Postgresql column reference "id" is ambiguous

I suppose your p2vg table has also an id field , in that case , postgres cannot find if the id in the SELECT refers to vg or p2vg.

you should use SELECT(vg.id,vg.name) to remove ambiguity

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

Add Whatsapp function to website, like sms, tel

Here is the solution to your problem! You just need to use this format:

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

In the place of "urlencodedtext" you need to keep the content in Url-encode format.

UPDATE-- Use this from now(Nov-2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

Use: https://wa.me/15551234567

Don't use: https://wa.me/+001-(555)1234567

To create your own link with a pre-filled message that will automatically appear in the text field of a chat, use https://wa.me/whatsappphonenumber/?text=urlencodedtext where whatsappphonenumber is a full phone number in international format and URL-encodedtext is the URL-encoded pre-filled message.

Example:https://wa.me/15551234567?text=I'm%20interested%20in%20your%20car%20for%20sale

To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext

Example:https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing

After clicking on the link, you will be shown a list of contacts you can send your message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

if else in a list comprehension

>>> l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
>>> [x+1 if x >= 45 else x+5 for x in l]
[27, 18, 46, 51, 99, 70, 48, 49, 6]

Do-something if <condition>, else do-something else.

How to execute a command prompt command from python

Why do you want to call cmd.exe ? cmd.exe is a command line (shell). If you want to change directory, use os.chdir("C:\\"). Try not to call external commands if Python can provide it. In fact, most operating system commands are provide through the os module (and sys). I suggest you take a look at os module documentation to see the various methods available.

Regarding C++ Include another class

you need to forward declare the name of the class if you don't want a header:

class ClassTwo;

Important: This only works in some cases, see Als's answer for more information..

Python JSON dump / append to .txt with each variable on new line

To avoid confusion, paraphrasing both question and answer. I am assuming that user who posted this question wanted to save dictionary type object in JSON file format but when the user used json.dump, this method dumped all its content in one line. Instead, he wanted to record each dictionary entry on a new line. To achieve this use:

with g as outfile:
  json.dump(hostDict, outfile,indent=2)

Using indent = 2 helped me to dump each dictionary entry on a new line. Thank you @agf. Rewriting this answer to avoid confusion.

How to mark-up phone numbers?

My test results:

callto:

  • Nokia Browser: nothing happens
  • Google Chrome: asks to run skype to call the number
  • Firefox: asks to choose a program to call the number
  • IE: asks to run skype to call the number

tel:

  • Nokia Browser: working
  • Google Chrome: nothing happens
  • Firefox: "Firefox doesnt know how to open this url"
  • IE: could not find url

DELETE ... FROM ... WHERE ... IN

You can achieve this using exists:

DELETE
  FROM table1
 WHERE exists(
           SELECT 1
             FROM table2
            WHERE table2.stn = table1.stn
              and table2.jaar = year(table1.datum)
       )

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

OpenCV - DLL missing, but it's not?

just open the bin folder and copy and paste the .dll files to the folder you are working in..it should fix the problem

Is it possible to modify a registry entry via a .bat/.cmd script?

This is how you can modify registry, without yes or no prompt and don't forget to run as administrator

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\etc\etc   /v Valuename /t REG_SZ /d valuedata  /f 

Below is a real example to set internet explorer as my default browser

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\https\UserChoice   /v ProgId /t REG_SZ /d IE.HTTPS  /f 

/f Force: Force an update without prompting "Value exists, overwrite Y/N"

/d Data : The actual data to store as a "String", integer etc

/v Value : The value name eg ProgId

/t DataType : REG_SZ (default) | REG_DWORD | REG_EXPAND_SZ | REG_MULTI_SZ

Learn more about Read, Set or Delete registry keys and values, save and restore from a .REG file. from here

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

As it is correctly suggested in previous answers, lazy loading means that when you fetch your object from the database, the nested objects are not fetched (and may be fetched later when required).

Now Jackson tries to serialize the nested object (== make JSON out of it), but fails as it finds JavassistLazyInitializer instead of normal object. This is the error you see. Now, how to solve it?

As suggested by CP510 previously, one option is to suppress the error by this line of configuration:

spring.jackson.serialization.fail-on-empty-beans=false

But this is dealing with the symptoms, not the cause. To solve it elegantly, you need to decide whether you need this object in JSON or not?

  1. Should you need the object in JSON, remove the FetchType.LAZY option from the field that causes it (it might also be a field in some nested object, not only in the root entity you are fetching).

  2. If do not need the object in JSON, annotate the getter of this field (or the field itself, if you do not need to accept incoming values either) with @JsonIgnore, for example:

    // this field will not be serialized to/from JSON @JsonIgnore private NestedType secret;

Should you have more complex needs (e.g. different rules for different REST controllers using the same entity), you can use jackson views or filtering or for very simple use case, fetch nested objects separately.

Deserialize json object into dynamic object using Json.net

Yes you can do it using the JsonConvert.DeserializeObject. To do that, just simple do:

dynamic jsonResponse = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonResponse["message"]);

How to solve maven 2.6 resource plugin dependency?

Tried everything. I deleted m2e and installed m2e version 2.7.0. Then deleted the .m2 directory and force updated maven. It worked!

How exactly does the python any() function work?

Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.

list = [2,-3,-4,5,6]

a = any(x>0 for x in lst)

print a:
True


list = [2,3,4,5,6,7]

a = any(x<0 for x in lst)

print a:
False

How to use bluetooth to connect two iPhone?

You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.

For more information, you can also look at the responses to these questions:

How to set data attributes in HTML elements

If you're using jQuery, use .data():

div.data('myval', 20);

You can store arbitrary data with .data(), but you're restricted to just strings when using .attr().

Generate table relationship diagram from existing schema (SQL Server)

Yes you can use SQL Server 2008 itself but you need to install SQL Server Management Studio Express (if not installed ) . Just right Click on Database Diagrams and create new diagram. Select the exisiting tables and if you have specified the references in your tables properly. You will be able to see the complete diagram of selected tables. For further reference see Getting started with SQL Server database diagrams

How do I use the Simple HTTP client in Android?

You can use this code:

int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.setConnectTimeout(TIME_OUT);
                conection.connect();
                // Getting file length
                int lenghtOfFile = conection.getContentLength();
                // Create a Input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/9androidnet.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                connectionTimeout=true;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

Simple 3x3 matrix inverse code (C++)

A rather nice (I think) header file containing macros for most 2x2, 3x3 and 4x4 matrix operations has been available with most OpenGL toolkits. Not as standard but I've seen it at various places.

You can check it out here. At the end of it you will find both inverse of 2x2, 3x3 and 4x4.

vvector.h

Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded

Mine was more of a mistake, what happened was loop click(i guess) basically by clicking on the login the parent was also clicked which ended up causing Maximum call stack size exceeded.

$('.clickhere').click(function(){
   $('.login').click();
});

<li class="clickhere">
  <a href="#" class="login">login</a>
</li>

angular ng-repeat in reverse

If you are using angularjs version 1.4.4 and above,an easy way to sort is using the "$index".

 <ul>
  <li ng-repeat="friend in friends|orderBy:$index:true">{{friend.name}}</li>
</ul>

view demo

Date to milliseconds and back to date in Swift

Unless you absolutely have to convert the date to an integer, consider using a Double instead to represent the time interval. After all, this is the type that timeIntervalSince1970 returns. All of the answers that convert to integers loose sub-millisecond precision, but this solution is much more accurate (although you will still lose some precision due to floating-point imprecision).

public extension Date {
    
    /// The interval, in milliseconds, between the date value and
    /// 00:00:00 UTC on 1 January 1970.
    /// Equivalent to `self.timeIntervalSince1970 * 1000`.
    var millisecondsSince1970: Double {
        return self.timeIntervalSince1970 * 1000
    }

    /**
     Creates a date value initialized relative to 00:00:00 UTC
     on 1 January 1970 by a given number of **milliseconds**.
     
     equivalent to
     ```
     self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
     ```
     - Parameter millisecondsSince1970: A time interval in milliseconds.
     */
    init(millisecondsSince1970: Double) {
        self.init(timeIntervalSince1970: TimeInterval(milliseconds) / 1000)
    }

}

jQuery datepicker, onSelect won't work

datePicker's onSelect equivalent is the dateSelected event.

$(function() {
    $('.date-pick').datePicker( {
        selectWeek: true,
        inline: true,
        startDate: '01/01/2000',
        firstDay: 1,
    }).bind('dateSelected', function(e, selectedDate, $td) {
        alert(selectedDate);
    });
});

This page has a good example showing the dateSelected event and other events being bound.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Moving average or running mean

For a short, fast solution that does the whole thing in one loop, without dependencies, the code below works great.

mylist = [1, 2, 3, 4, 5, 6, 7]
N = 3
cumsum, moving_aves = [0], []

for i, x in enumerate(mylist, 1):
    cumsum.append(cumsum[i-1] + x)
    if i>=N:
        moving_ave = (cumsum[i] - cumsum[i-N])/N
        #can do stuff with moving_ave here
        moving_aves.append(moving_ave)

Calendar date to yyyy-MM-dd format in java

A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

Java 8+

LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"

String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12

Prior to Java 8

You should be making use of the ThreeTen Backport

The following is maintained for historical purposes (as the original answer)

What you can do, is format the date.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"

System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"

These are actually the same date, represented differently.

Tree view of a directory/folder in Windows?

I recommend WinDirStat.

I frequently use WinDirStat to create screen shots for user documentation of open folders and their contents.

It even uses the correct icons for Windows registered file types.

All I would say is missing is an option to display the files without their icons. I can live without it personally, since I am usually pasting the image into a paint program or Visio to edit it, but it would still be a useful feature.

What is the best way to determine a session variable is null or empty in C#?

This method also does not assume that the object in the Session variable is a string

if((Session["MySessionVariable"] ?? "").ToString() != "")
    //More code for the Code God

So basically replaces the null variable with an empty string before converting it to a string since ToString is part of the Object class

JavaFX open new window

If you just want a button to open up a new window, then something like this works:

btnOpenNewWindow.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        Parent root;
        try {
            root = FXMLLoader.load(getClass().getClassLoader().getResource("path/to/other/view.fxml"), resources);
            Stage stage = new Stage();
            stage.setTitle("My New Stage Title");
            stage.setScene(new Scene(root, 450, 450));
            stage.show();
            // Hide this current window (if this is what you want)
            ((Node)(event.getSource())).getScene().getWindow().hide();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How can I trigger a JavaScript event click

Use a testing framework

This might be helpful - http://seleniumhq.org/ - Selenium is a web application automated testing system.

You can create tests using the Firefox plugin Selenium IDE

Manual firing of events

To manually fire events the correct way you will need to use different methods for different browsers - either el.dispatchEvent or el.fireEvent where el will be your Anchor element. I believe both of these will require constructing an Event object to pass in.

The alternative, not entirely correct, quick-and-dirty way would be this:

var el = document.getElementById('anchorelementid');
el.onclick(); // Not entirely correct because your event handler will be called
              // without an Event object parameter.

List of lists into numpy array

I had a list of lists of equal length. Even then Ignacio Vazquez-Abrams's answer didn't work out for me. I got a 1-D numpy array whose elements are lists. If you faced the same problem, you can use the below method

Use numpy.vstack

import numpy as np

np_array = np.empty((0,4), dtype='float')
for i in range(10)
     row_data = ...   # get row_data as list
     np_array = np.vstack((np_array, np.array(row_data)))

Manipulate a url string by adding GET parameters

After searching for many resources/answers on this topic, I decided to code my own. Based on @TaylorOtwell's answer here, this is how I process incoming $_GET request and modify/manipulate each element.

Assuming the url is: http://domain.com/category/page.php?a=b&x=y And I want only one parameter for sorting: either ?desc=column_name or ?asc=column_name. This way, single url parameter is enough to sort and order simultaneously. So the URL will be http://domain.com/category/page.php?a=b&x=y&desc=column_name on first click of the associated table header row.

Then I have table row headings that I want to sort DESC on my first click, and ASC on the second click of the same heading. (Each first click should "ORDER BY column DESC" first) And if there is no sorting, it will sort by "date then id" by default.

You may improve it further, like you may add cleaning/filtering functions to each $_GET component but the below structure lays the foundation.

foreach ($_GET AS $KEY => $VALUE){
    if ($KEY == 'desc'){
        $SORT = $VALUE;
        $ORDER = "ORDER BY $VALUE DESC";
        $URL_ORDER = $URL_ORDER . "&asc=$VALUE";
    } elseif ($KEY == 'asc'){
        $SORT = $VALUE;
        $ORDER = "ORDER BY $VALUE ASC";
        $URL_ORDER = $URL_ORDER . "&desc=$VALUE";
    } else {
        $URL_ORDER .= "&$KEY=$VALUE";
        $URL .= "&$KEY=$VALUE";
    }
}
if (!$ORDER){$ORDER = 'ORDER BY date DESC, id DESC';}
if ($URL_ORDER){$URL_ORDER = $_SERVER[SCRIPT_URL] . '?' . trim($URL_ORDER, '&');}
if ($URL){$URL = $_SERVER[SCRIPT_URL] . '?' . trim($URL, '&');}

(You may use $_SERVER[SCRIPT_URI] for full URL beginning with http://domain.com)

Then I use resulting $ORDER I get above, in the MySQL query:

"SELECT * FROM table WHERE limiter = 'any' $ORDER";

Now the function to look at the URL if there is a previous sorting and add sorting (and ordering) parameter to URL with "?" or "&" according to the sequence:

        function sort_order ($_SORT){
            global $SORT, $URL_ORDER, $URL;
            if ($SORT == $_SORT){
                return $URL_ORDER;
            } else {
                if (strpos($URL, '?') !== false){
                    return "$URL&desc=$_SORT";
                } else {                        
                    return "$URL?desc=$_SORT";
                }
            }
        }

Finally, the table row header to use the function:

        echo "<th><a href='".sort_order('id')."'>ID</a></th>";

Summary: this will read the URL, modify each of the $_GET components and make the final URL with parameters of your choice with the correct form of usage of "?" and "&"

Which font is used in Visual Studio Code Editor and how to change fonts?

In VSCode if "editor.fontFamily": "" is blank, the font size will NOT work. Set a font family to change the size.

"editor.fontFamily": "Verdana", or "editor.fontFamily": "Monaco",

Really, use whatever font family you like.

Then "editor.fontSize": 16, should work.

How to automatically redirect HTTP to HTTPS on Apache servers?

Be advised -- you will lose ALL Facebook Likes when doing this (provided you started collecting your Likes with an http connection!

Instead use JavaScript

if (location.protocol !== 'https:') {       
   location.replace('https:${location.href.substring(location.protocol.length)}'); 
}

and put it last in the header.

Get a resource using getResource()

Instead of explicitly writing the class name you could use

this.getClass().getResource("/unibo/lsb/res/dice.jpg");

How do I automatically scroll to the bottom of a multiline text box?

textBox1.Focus()
textBox1.SelectionStart = textBox1.Text.Length;
textBox1.ScrollToCaret();

didn't work for me (Windows 8.1, whatever the reason).
And since I'm still on .NET 2.0, I can't use ScrollToEnd.

But this works:

public class Utils
{
    [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    private static extern int SendMessage(System.IntPtr hWnd, int wMsg, System.IntPtr wParam, System.IntPtr lParam);

    private const int WM_VSCROLL = 0x115;
    private const int SB_BOTTOM = 7;

    /// <summary>
    /// Scrolls the vertical scroll bar of a multi-line text box to the bottom.
    /// </summary>
    /// <param name="tb">The text box to scroll</param>
    public static void ScrollToBottom(System.Windows.Forms.TextBox tb)
    {
        if(System.Environment.OSVersion.Platform != System.PlatformID.Unix)
             SendMessage(tb.Handle, WM_VSCROLL, new System.IntPtr(SB_BOTTOM), System.IntPtr.Zero);
    }


}

VB.NET:

Public Class Utils
    <System.Runtime.InteropServices.DllImport("user32.dll", CharSet := System.Runtime.InteropServices.CharSet.Auto)> _
    Private Shared Function SendMessage(hWnd As System.IntPtr, wMsg As Integer, wParam As System.IntPtr, lParam As System.IntPtr) As Integer
    End Function

    Private Const WM_VSCROLL As Integer = &H115
    Private Const SB_BOTTOM As Integer = 7

    ''' <summary>
    ''' Scrolls the vertical scroll bar of a multi-line text box to the bottom.
    ''' </summary>
    ''' <param name="tb">The text box to scroll</param>
    Public Shared Sub ScrollToBottom(tb As System.Windows.Forms.TextBox)
        If System.Environment.OSVersion.Platform <> System.PlatformID.Unix Then
            SendMessage(tb.Handle, WM_VSCROLL, New System.IntPtr(SB_BOTTOM), System.IntPtr.Zero)
        End If
    End Sub


End Class

How to disable HTML links

In Razor (.cshtml) you can do:

@{
    var isDisabled = true;
}

<a href="@(isDisabled ? "#" : @Url.Action("Index", "Home"))" @(isDisabled ? "disabled=disabled" : "") class="btn btn-default btn-lg btn-block">Home</a>

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

Object reference not set to an instance of an object.

All versions of .Net:

if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)

.Net 4.0 or later:

if (String.IsNullOrWhitespace(strSearch))

Selecting one row from MySQL using mysql_* API

Ultimately, I want to be able to echo out a signle field like so:

   $row['option_value']

So why don't you? It should work.

log4net vs. Nlog

As I noticed, log4net locks their output files the whole time application is running, so you can't delete them. Otherwise they are similar.

So I prefer NLog.

Error: expected type-specifier before 'ClassName'

For future people struggling with a similar problem, the situation is that the compiler simply cannot find the type you are using (even if your Intelisense can find it).

This can be caused in many ways:

  • You forgot to #include the header that defines it.
  • Your inclusion guards (#ifndef BLAH_H) are defective (your #ifndef BLAH_H doesn't match your #define BALH_H due to a typo or copy+paste mistake).
  • Your inclusion guards are accidentally used twice (two separate files both using #define MYHEADER_H, even if they are in separate directories)
  • You forgot that you are using a template (eg. new Vector() should be new Vector<int>())
  • The compiler is thinking you meant one scope when really you meant another (For example, if you have NamespaceA::NamespaceB, AND a <global scope>::NamespaceB, if you are already within NamespaceA, it'll look in NamespaceA::NamespaceB and not bother checking <global scope>::NamespaceB) unless you explicitly access it.
  • You have a name clash (two entities with the same name, such as a class and an enum member).

To explicitly access something in the global namespace, prefix it with ::, as if the global namespace is a namespace with no name (e.g. ::MyType or ::MyNamespace::MyType).

How to cancel a Task in await?

Or, in order to avoid modifying slowFunc (say you don't have access to the source code for instance):

var source = new CancellationTokenSource(); //original code
source.Token.Register(CancelNotification); //original code
source.CancelAfter(TimeSpan.FromSeconds(1)); //original code
var completionSource = new TaskCompletionSource<object>(); //New code
source.Token.Register(() => completionSource.TrySetCanceled()); //New code
var task = Task<int>.Factory.StartNew(() => slowFunc(1, 2), source.Token); //original code

//original code: await task;  
await Task.WhenAny(task, completionSource.Task); //New code

You can also use nice extension methods from https://github.com/StephenCleary/AsyncEx and have it looks as simple as:

await Task.WhenAny(task, source.Token.AsTask());

Launch Failed. Binary not found. CDT on Eclipse Helios

I had this problem for a long while and I couldn't figure out the answer. I had added all the paths, built everything and pretty much followed what everyone on here had suggested, but no luck.

Finally I read the comments and saw that there were some compilation errors that were aborting the procedure before the binaries and exe file was generated.

Bottom line: Do a code review and make sure that there are no errors in your code because sometimes eclipse will not always catch everything.

If you can run a basic hello world but not your code then obviously something is wrong with your code. I learned the hard way.

High CPU Utilization in java application - why?

In the thread dump you can find the Line Number as below.

for the main thread which is currently running...

"main" #1 prio=5 os_prio=0 tid=0x0000000002120800 nid=0x13f4 runnable [0x0000000001d9f000]
   java.lang.Thread.State: **RUNNABLE**
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:313)
    at com.rana.samples.**HighCPUUtilization.main(HighCPUUtilization.java:17)**

Exiting from python Command Line

This works for me, best way to come out of python prompt.

exit()

How do I use the CONCAT function in SQL Server 2008 R2?

CONCAT is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.

That it is part of SQL Server 2012 can be seen in the document tree:

SQL Server 2012  
Product Documentation  
Books Online for SQL Server 2012  
Database Engine  
  Transact-SQL Reference (Database Engine)  
    Built-in Functions (Transact-SQL)  
      String Functions (Transact-SQL)  

EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT function.

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

Well, the <head> tag has nothing to do with the <header> tag. In the head comes all the metadata and stuff, while the header is just a layout component.
And layout comes into body. So I disagree with you.

Setting the default page for ASP.NET (Visual Studio) server configuration

This One Method For Published Solution To Show SpeciFic Page on startup.

Here Is the Route Example to Redirect to Specific Page...

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            namespaces: new[] { "YourSolutionName.Controllers" }
        );
    }
}

By Default Home Controllers Index method is executed when application is started, Here You Can Define yours.

Note : I am Using Visual Studio 2013 and "YourSolutionName" is to changed to your project Name..

Getting cursor position in Python

Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:

from ctypes import windll, Structure, c_long, byref


class POINT(Structure):
    _fields_ = [("x", c_long), ("y", c_long)]



def queryMousePosition():
    pt = POINT()
    windll.user32.GetCursorPos(byref(pt))
    return { "x": pt.x, "y": pt.y}


pos = queryMousePosition()
print(pos)

I should mention that this code was taken from an example found here So credit goes to Nullege.com for this solution.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET Standard: Think of it as a big standard library. When using this as a dependency you can only make libraries (.DLLs), not executables. A library made with .NET standard as a dependency can be added to a Xamarin.Android, a Xamarin.iOS, a .NET Core Windows/OS X/Linux project.

.NET Core: Think of it as the continuation of the old .NET framework, just it's opensource and some stuff is not yet implemented and others got deprecated. It extends the .NET standard with extra functions, but it only runs on desktops. When adding this as a dependency you can make runnable applications on Windows, Linux and OS X. (Although console only for now, no GUIs). So .NET Core = .NET Standard + desktop specific stuff.

Also UWP uses it and the new ASP.NET Core uses it as a dependency too.

View markdown files offline

You may use Firefox Markdown Viewer plugin that is so easy to install and use.

how do I initialize a float to its max/min value?

You can either use -FLT_MAX (or -DBL_MAX) for the maximum magnitude negative number and FLT_MAX (or DBL_MAX) for positive. This gives you the range of possible float (or double) values.

You probably don't want to use FLT_MIN; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.

FLT_MIN and FLT_MAX correspond to std::numeric_limits<float>::min() and std::numeric_limits<float>::max().

HTTP Get with 204 No Content: Is that normal

Your current combination of a POST with an HTTP 204 response is fine.

Using a POST as a universal replacement for a GET is not supported by the RFC, as each has its own specific purpose and semantics.

The purpose of a GET is to retrieve a resource. Therefore, while allowed, an HTTP 204 wouldn't be the best choice since content IS expected in the response. An HTTP 404 Not Found or an HTTP 410 Gone would be better choices if the server was unable to provide the requested resource.

The RFC also specifically calls out an HTTP 204 as an appropriate response for PUT, POST and DELETE, but omits it for GET.

See the RFC for the semantics of GET.

There are other response codes that could also be returned, indicating no content, that would be more appropriate than an HTTP 204.

For example, for a conditional GET you could receive an HTTP 304 Not Modified response which would contain no body content.

How to get current user who's accessing an ASP.NET application?

The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.

You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace

        using System.Web;
        WindowsIdentity user;
        user  = HttpContext.Current.Request.LogonUserIdentity;

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

What version of Excel?

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

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

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

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

enter image description here

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

JPA entity without id

I guess you can use @CollectionOfElements (for hibernate/jpa 1) / @ElementCollection (jpa 2) to map a collection of "entity properties" to a List in entity.

You can create the EntityProperty type and annotate it with @Embeddable

Checking if a field contains a string

For aggregation framework


Field search

('$options': 'i' for case insensitive search)

db.users.aggregate([
    {
        $match: {
            'email': { '$regex': '@gmail.com', '$options': 'i' }
        }
    }
]);

Full document search

(only works on fields indexed with a text index

db.articles.aggregate([
    {
        $match: { $text: { $search: 'brave new world' } }
    }
])

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

  func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        // action one
        let editAction = UITableViewRowAction(style: .default, title: "Edit", handler: { (action, indexPath) in
            print("Edit tapped")

            self.myArray.add(indexPath.row)
        })
        editAction.backgroundColor = UIColor.blue

        // action two
        let deleteAction = UITableViewRowAction(style: .default, title: "Delete", handler: { (action, indexPath) in
            print("Delete tapped")

            self.myArray.removeObject(at: indexPath.row)
            self.myTableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic)

        })
        deleteAction.backgroundColor = UIColor.red
        // action three
        let shareAction = UITableViewRowAction(style: .default, title: "Share", handler: { (action , indexPath)in
             print("Share Tapped")
        })
        shareAction.backgroundColor = UIColor .green
        return [editAction, deleteAction, shareAction]
    }

Python function to convert seconds into minutes, hours, and days

Do it the other way around subtracting the secs as needed, and don't call it time; there's a package with that name:

def sec_to_time():
    sec = int( input ('Enter the number of seconds:'.strip()) )

    days = sec / 86400
    sec -= 86400*days

    hrs = sec / 3600
    sec -= 3600*hrs

    mins = sec / 60
    sec -= 60*mins
    print days, ':', hrs, ':', mins, ':', sec

Converting Java file:// URL to File(...) path, platform independent, including UNC paths

Java (at least 5 and 6, java 7 Paths solved most) has a problem with UNC and URI. Eclipse team wrapped it up here : http://wiki.eclipse.org/Eclipse/UNC_Paths

From java.io.File javadocs, the UNC prefix is "////", and java.net.URI handles file:////host/path (four slashes).

More details on why this happens and possible problems it causes in other URI and URL methods can be found in the list of bugs at the end of the link given above.

Using these informations, Eclipse team developed org.eclipse.core.runtime.URIUtil class, which source code can probably help out when dealing with UNC paths.

How to convert JTextField to String and String to JTextField?

JTextField allows us to getText() and setText() these are used to get and set the contents of the text field, for example.

text = texfield.getText();

hope this helps

Javascript checkbox onChange

The following solution makes use of jquery. Let's assume you have a checkbox with id of checkboxId.

const checkbox = $("#checkboxId");

checkbox.change(function(event) {
    var checkbox = event.target;
    if (checkbox.checked) {
        //Checkbox has been checked
    } else {
        //Checkbox has been unchecked
    }
});

automatically execute an Excel macro on a cell change

I have a cell which is linked to online stock database and updated frequently. I want to trigger a macro whenever the cell value is updated.

I believe this is similar to cell value change by a program or any external data update but above examples somehow do not work for me. I think the problem is because excel internal events are not triggered, but thats my guess.

I did the following,

Private Sub Worksheet_Change(ByVal Target As Range) 
  If Not Intersect(Target, Target.Worksheets("Symbols").Range("$C$3")) Is Nothing Then
   'Run Macro
End Sub

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

How open PowerShell as administrator from the run window

Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:

runas /user:(ComputerName)\(local admin) powershell.exe

So a basic example would be:

runas /user:MyLaptop\[email protected]  powershell.exe

You can find more information on this subject in Runas.

However, you could also do one more thing :

  • 1: `Windows+R`
  • 2: type: `powershell`
  • 3: type: `Start-Process powershell -verb runAs`

then your system will execute the elevated powershell.

rails bundle clean

If you are using Bundler 1.1 or later you can use bundle clean, just as you imagined you could. This is redundant if you're using bundle install --path (Bundler manages the location you specified with --path, so takes responsibility for removing outdated gems), but if you've used Bundler to install the gems as system gems then bundle clean --force will delete any system gems not required by your Gemfile. Blindingly obvious caveat: don't do this if you have other apps that rely on system gems that aren't in your Gemfile!

Pat Shaughnessy has a good description of bundle clean and other new additions in bundler 1.1.

JavaScript property access: dot notation vs. brackets?

You have to use square bracket notation when -

  1. The property name is number.

    var ob = {
      1: 'One',
      7 : 'Seven'
    }
    ob.7  // SyntaxError
    ob[7] // "Seven"
    
  2. The property name has special character.

    var ob = {
      'This is one': 1,
      'This is seven': 7,
    }  
    ob.'This is one'  // SyntaxError
    ob['This is one'] // 1
    
  3. The property name is assigned to a variable and you want to access the property value by this variable.

    var ob = {
      'One': 1,
      'Seven': 7,
    }
    
    var _Seven = 'Seven';
    ob._Seven  // undefined
    ob[_Seven] // 7
    

EXCEL VBA, inserting blank row and shifting cells

Sub Addrisk()

Dim rActive As Range
Dim Count_Id_Column as long

Set rActive = ActiveCell

Application.ScreenUpdating = False

with thisworkbook.sheets(1) 'change to "sheetname" or sheetindex
    for i = 1 to .range("A1045783").end(xlup).row
        if 'something'  = 'something' then
            .range("A" & i).EntireRow.Copy 'add thisworkbook.sheets(index_of_sheet) if you copy from another sheet
            .range("A" & i).entirerow.insert shift:= xldown 'insert and shift down, can also use xlup
            .range("A" & i + 1).EntireRow.paste 'paste is all, all other defs are less.
            'change I to move on to next row (will get + 1 end of iteration)
            i = i + 1
        end if

            On Error Resume Next
                .SpecialCells(xlCellTypeConstants).ClearContents
            On Error GoTo 0

        End With
    next i
End With

Application.CutCopyMode = False
Application.ScreenUpdating = True 're-enable screen updates

End Sub

How to convert SQL Server's timestamp column to datetime format

Works fine, except this message:

Implicit conversion from data type varchar to timestamp is not allowed. Use the CONVERT function to run this query

So yes, TIMESTAMP (RowVersion) is NOT a DATE :)

To be honest, I fidddled around quite some time myself to find a way to convert it to a date.

Best way is to convert it to INT and compare. That's what this type is meant to be.

If you want a date - just add a Datetime column and live happily ever after :)

cheers mac

Kill some processes by .exe file name

My solution is to use Process.GetProcess() for listing all the processes.

By filtering them to contain the processes I want, I can then run Process.Kill() method to stop them:

var chromeDriverProcesses = Process.GetProcesses().
    Where(pr => pr.ProcessName == "chromedriver"); // without '.exe'
    
foreach (var process in chromeDriverProcesses)
{
     process.Kill();
}

Update:

In case if want to use async approach with some useful recent methods from the C# 8 (Async Enumerables), then check this out:

const string processName = "chromedriver"; // without '.exe'
await Process.GetProcesses()
             .Where(pr => pr.ProcessName == processName)
             .ToAsyncEnumerable()
             .ForEachAsync(p => p.Kill());

Note: using async methods doesn't always mean code will run faster, but it will not waste the CPU time and prevent the foreground thread from hanging while doing the operations. In any case, you need to think about what version you might want.

How to read integer value from the standard input in Java

You can use java.util.Scanner (API):

import java.util.Scanner;

//...

Scanner in = new Scanner(System.in);
int num = in.nextInt();

It can also tokenize input with regular expression, etc. The API has examples and there are many others in this site (e.g. How do I keep a scanner from throwing exceptions when the wrong type is entered?).

Convert a list of characters into a string

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

a = ['a','b','c','d']

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn't a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.

Cannot issue data manipulation statements with executeQuery()

When executing DML statement , you should use executeUpdate/execute rather than executeQuery.

Here is a brief comparison :

executeQueryVSexecuteUpdateVSexecute

How does numpy.newaxis work and when to use it?

newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.

It is not just conversion of row matrix to column matrix.

Consider the example below:

In [1]:x1 = np.arange(1,10).reshape(3,3)
       print(x1)
Out[1]: array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])

Now lets add new dimension to our data,

In [2]:x1_new = x1[:,np.newaxis]
       print(x1_new)
Out[2]:array([[[1, 2, 3]],

              [[4, 5, 6]],

              [[7, 8, 9]]])

You can see that newaxis added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).

How our new dimension enables us to different operations:

In [3]:x2 = np.arange(11,20).reshape(3,3)
       print(x2)
Out[3]:array([[11, 12, 13],
              [14, 15, 16],
              [17, 18, 19]]) 

Adding x1_new and x2, we get:

In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
               [15, 17, 19],
               [18, 20, 22]],

              [[15, 17, 19],
               [18, 20, 22],
               [21, 23, 25]],

              [[18, 20, 22],
               [21, 23, 25],
               [24, 26, 28]]])

Thus, newaxis is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

How to construct a relative path in Java from two absolute paths (or URLs)?

It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.

String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"

Please note that for file path there's java.nio.file.Path#relativize since Java 1.7, as pointed out by @Jirka Meluzin in the other answer.

How does one use glide to download an image into a bitmap?

This is what worked for me: https://github.com/bumptech/glide/wiki/Custom-targets#overriding-default-behavior

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.transition.Transition;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

...

Glide.with(yourFragment)
  .load("yourUrl")
  .asBitmap()
  .into(new BitmapImageViewTarget(yourImageView) {
    @Override
    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> anim) {
        super.onResourceReady(bitmap, anim);
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {  
            @Override
            public void onGenerated(Palette palette) {
                // Here's your generated palette
                Palette.Swatch swatch = palette.getDarkVibrantSwatch();
                int color = palette.getDarkVibrantColor(swatch.getTitleTextColor());
            }
        });
    }
});

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Python + Regex: AttributeError: 'NoneType' object has no attribute 'groups'

You are getting AttributeError because you're calling groups on None, which hasn't any methods.

regex.search returning None means the regex couldn't find anything matching the pattern from supplied string.

when using regex, it is nice to check whether a match has been made:

Result = re.search(SearchStr, htmlString)

if Result:
    print Result.groups()

Spaces cause split in path with PowerShell

There's a hack I've used since the Invoke-Expression works fine for me.

You could set the current location to the path with spaces, invoke the expression, get back to your previous location and continue:

$currLocation = Get-Location
Set-Location = "C:\Windows Services\"
Invoke-Expression ".\MyService.exe"
Set-Location $currLocation

This will only work if the exe doesn't have any spaces in its name.

Hope this helps

iPhone and WireShark

I like to use Pirni (availble for free in Cydia on a jailbroken device), or there's also Pirni Pro now for a few bucks (http://en.wikipedia.org/wiki/Pirni). I've been using the pirni-derv script available for free on Google Code (http://code.google.com/p/pirni-derv/) mixed with Pirni and it's been working very well. I recommend it.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

I had the same error message after upgrading to XCode 5.1. Are you using CocoaPods? If so, this should fix the problem:

  1. Delete the "Pods" project from the workspace in the left pane of Xcode and close Xcode.
  2. Run "pod install" from the command line to recreate the "Pods" project.
  3. Re-open Xcode and make sure "Build Active Architecture Only" is set to "No" in the build settings of both the "Pods" project and your own project.
  4. Clean and build.

How to find out if a Python object is a string?

Python 2

Use isinstance(obj, basestring) for an object-to-test obj.

Docs.

Opening database file from within SQLite command-line shell

The command within the Sqlite shell to open a database is .open

The syntax is,

sqlite> .open dbasename.db

If it is a new database that you would like to create and open, it is

sqlite> .open --new dbasename.db

If the database is existing in a different folder, the path has to be mentioned like this:

sqlite> .open D:/MainFolder/SubFolder/...database.db

In Windows Command shell, you should use '\' to represent a directory, but in SQLite directories are represented by '/'. If you still prefer to use the Windows notation, you should use an escape sequence for every '\'

How to manually trigger validation with jQuery validate?

My approach was as below. Now I just wanted my form to be validated when one specific checkbox was clicked/changed:

$('#myForm input:checkbox[name=yourChkBxName]').click(
 function(e){
  $("#myForm").valid();
}
)

Navigation bar with UIImage for title

If you'd prefer to use autolayout, and want a permanent fixed image in the navigation bar, that doesn't animate in with each screen, this solution works well:

class CustomTitleNavigationController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    let logo = UIImage(named: "MyHeaderImage")

    let imageView = UIImageView(image:logo)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    navigationBar.addSubview(imageView)

    navigationBar.addConstraint (navigationBar.leftAnchor.constraint(equalTo: imageView.leftAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.rightAnchor.constraint(equalTo: imageView.rightAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.bottomAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 0))
}

Batch Script to Run as Administrator

Following is a work-around:

  1. Create a shortcut of the .bat file
  2. Open the properties of the shortcut. Under the shortcut tab, click on advanced.
  3. Tick "Run as administrator"

Running the shortcut will execute your batch script as administrator.

Best way to convert IList or IEnumerable to Array

In case you don't have Linq, I solved it the following way:

    private T[] GetArray<T>(IList<T> iList) where T: new()
    {
        var result = new T[iList.Count];

        iList.CopyTo(result, 0);

        return result;
    }

Hope it helps

Is it possible to use a div as content for Twitter's Popover

Building on jävi's answer, this can be done without IDs or additional button attributes like this:

http://jsfiddle.net/isherwood/E5Ly5/

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My first popover content goes here.</div>

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My second popover content goes here.</div>

<button class="popper" data-toggle="popover">Pop me</button>
<div class="popper-content hide">My third popover content goes here.</div>

$('.popper').popover({
    container: 'body',
    html: true,
    content: function () {
        return $(this).next('.popper-content').html();
    }
});

What are advantages of Artificial Neural Networks over Support Vector Machines?

One obvious advantage of artificial neural networks over support vector machines is that artificial neural networks may have any number of outputs, while support vector machines have only one. The most direct way to create an n-ary classifier with support vector machines is to create n support vector machines and train each of them one by one. On the other hand, an n-ary classifier with neural networks can be trained in one go. Additionally, the neural network will make more sense because it is one whole, whereas the support vector machines are isolated systems. This is especially useful if the outputs are inter-related.

For example, if the goal was to classify hand-written digits, ten support vector machines would do. Each support vector machine would recognize exactly one digit, and fail to recognize all others. Since each handwritten digit cannot be meant to hold more information than just its class, it makes no sense to try to solve this with an artificial neural network.

However, suppose the goal was to model a person's hormone balance (for several hormones) as a function of easily measured physiological factors such as time since last meal, heart rate, etc ... Since these factors are all inter-related, artificial neural network regression makes more sense than support vector machine regression.

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

You can restore the default action (if it is a HREF follow) by doing this:

window.location = $(this).attr('href');

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

My problem is below

Unable to resolve dependency for ':app@debug/compileClasspath': Could not download rxjava.jar (io.reactivex.rxjava2:rxjava:2.2.2)

Solved by checking Enable embedded Maven Repository

enter image description here

How to install pip in CentOS 7?

Below are the steps I followed to install python34 and pip

yum update -y
yum -y install yum-utils
yum -y groupinstall development
yum -y install https://centos7.iuscommunity.org/ius-release.rpm
yum makecache
yum -y install python34u  python34u-pip
python3.6 -v
echo "alias python=/usr/bin/python3.4" >> ~/.bash_profile
source ~/.bash_profile
pip3 install --upgrade pip

# if yum install python34u-pip doesnt work, try 

curl https://bootstrap.pypa.io/get-pip.py | python

What is the role of "Flatten" in Keras?

Here I would like to present another alternative to Flatten function. This may help to understand what is going on internally. The alternative method adds three more code lines. Instead of using

#==========================================Build a Model
model = tf.keras.models.Sequential()

model.add(keras.layers.Flatten(input_shape=(28, 28, 3)))#reshapes to (2352)=28x28x3
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(2,activation=tf.nn.softmax))

model.build()
model.summary()# summary of the model

we can use

    #==========================================Build a Model
    tensor = tf.keras.backend.placeholder(dtype=tf.float32, shape=(None, 28, 28, 3))
    
    model = tf.keras.models.Sequential()
    
    model.add(keras.layers.InputLayer(input_tensor=tensor))
    model.add(keras.layers.Reshape([2352]))
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
    model.add(keras.layers.Dense(128,activation=tf.nn.relu))
    model.add(keras.layers.Dense(2,activation=tf.nn.softmax))
    
    model.build()
    model.summary()# summary of the model

In the second case, we first create a tensor (using a placeholder) and then create an Input layer. After, we reshape the tensor to flat form. So basically,

Create tensor->Create InputLayer->Reshape == Flatten

Flatten is a convenient function, doing all this automatically. Of course both ways has its specific use cases. Keras provides enough flexibility to manipulate the way you want to create a model.

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Dynamic creation of table with DOM

You must create td and text nodes within loop. Your code creates only 2 td, so only 2 are visible. Example:

var table = document.createElement('table');
for (var i = 1; i < 4; i++){
    var tr = document.createElement('tr');   

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    var text1 = document.createTextNode('Text1');
    var text2 = document.createTextNode('Text2');

    td1.appendChild(text1);
    td2.appendChild(text2);
    tr.appendChild(td1);
    tr.appendChild(td2);

    table.appendChild(tr);
}
document.body.appendChild(table);

Does MS Access support "CASE WHEN" clause if connect with ODBC?

Since you are using Access to compose the query, you have to stick to Access's version of SQL.

To choose between several different return values, use the switch() function. So to translate and extend your example a bit:

select switch(
  age > 40, 4,
  age > 25, 3,
  age > 20, 2,
  age > 10, 1,
  true, 0
) from demo

The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.

The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.

How to properly URL encode a string in PHP?

Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.

Use case description

Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto link that lets them do that.

PHP code

// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';

// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);

// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;

// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);

// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';

Note: the above assumes you are outputting to a text/html document. If your output media type is text/json then simply use $retval['url'] = $mailToUri; because output encoding is handled by json_encode().

Test case

  1. Run the code on a PHP test site (is there a canonical one I should mention here?)
  2. Click the link
  3. Send the email
  4. Get the email
  5. Click that link

You should see:

"args": {
  "token": "w%a&!e#\"^2(^@azW"
}, 

And of course this is the JSON representation of $token above.

Is there anyway to exclude artifacts inherited from a parent POM?

You can group your dependencies within a different project with packaging pom as described by Sonatypes Best Practices:

<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>base-dependencies</artifactId>
    <groupId>es.uniovi.innova</groupId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    <dependencies>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
    </dependencies>
</project>

and reference them from your parent-pom (watch the dependency <type>pom</type>):

<project>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>base</artifactId>
    <groupId>es.uniovi.innova</groupId>
    <version>1.0.0</version>
    <packaging>pom</packaging>
    <dependencies>
        <dependency>
            <artifactId>base-dependencies</artifactId>
            <groupId>es.uniovi.innova</groupId>
            <version>1.0.0</version>
            <type>pom</type>
        </dependency>
    </dependencies>
</project>

Your child-project inherits this parent-pom as before. But now, the mail dependency can be excluded in the child-project within the dependencyManagement block:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>test</groupId>
    <artifactId>jruby</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <artifactId>base</artifactId>
        <groupId>es.uniovi.innova</groupId>
        <version>1.0.0</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <artifactId>base-dependencies</artifactId>
                <groupId>es.uniovi.innova</groupId>
                <version>1.0.0</version>
                <exclusions>
                    <exclusion>
                        <groupId>javax.mail</groupId>
                        <artifactId>mail</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

How to get anchor text/href on click using jQuery?

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

How to create global variables accessible in all views using Express / Node.JS?

In your app.js you need add something like this

global.myvar = 100;

Now, in all your files you want use this variable, you can just access it as myvar

Minimal web server using netcat

LOL, a super lame hack, but at least curl and firefox accepts it:

while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l  1500  ; done

You better replace it soon with something proper!

Ah yes, my nc were not exactly the same as yours, it did not like the -p option.

Limit the length of a string with AngularJS

THE EASIEST SOLUTION --> i've found is to let Material Design (1.0.0-rc4) do the work. The md-input-container will do the work for you. It concats the string and adds elipses plus it has the extra advantage of allowing you to click it to get the full text so it's the whole enchilada. You may need to set the width of the md-input-container.

HTML:

<md-input-container>
   <md-select id="concat-title" placeholder="{{mytext}}" ng-model="mytext" aria-label="label">
      <md-option ng-selected="mytext" >{{mytext}}
      </md-option>
   </md-select>
</md-input-container>

CS:

#concat-title .md-select-value .md-select-icon{
   display: none; //if you want to show chevron remove this
}
#concat-title .md-select-value{
   border-bottom: none; //if you want to show underline remove this
}

How to close Browser Tab After Submitting a Form?

You can try this methods

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

Failed to start mongod.service: Unit mongod.service not found

It worked for me on ubuntu 20.04: In my case, mongod.service file was locked so it was giving me the same error. To resolve the issue:- Step 1: Use following command to check if the mongod.service is present there

cd /usr/bin/systemd/system
ls

Step 2: If the file is present there then Run the following command to unlock the file mongod.service

sudo chmod 777 /usr/bin/systemd/system/mongod.service -R

Step 3: Now run the following commands:

sudo systemctl daemon-reload
sudo systemctl start mongod
sudo systemctl enable mongod

Using NSPredicate to filter an NSArray based on NSDictionary keys

I know it's old news but to add my two cents. By default I use the commands LIKE[cd] rather than just [c]. The [d] compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d] strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name where object.name == @"voodoo" will return the object containing the name Vòódòó.

From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.

How to set a default value in react-select

I used the defaultValue parameter, below is the code how I achieved a default value as well as update the default value when an option is selected from the drop-down.

<Select
  name="form-dept-select"
  options={depts}
  defaultValue={{ label: "Select Dept", value: 0 }}
  onChange={e => {
              this.setState({
              department: e.label,
              deptId: e.value
              });
           }}
/>

ORA-28040: No matching authentication protocol exception

This except for adding the following to sqlnet.ora

SQLNET.ALLOWED_LOGON_VERSION_CLIENT = 8
SQLNET.ALLOWED_LOGON_VERSION_SERVER = 8

If you get "ORA-01017: invalid username/password; logon denied" error, then you need to re-create your password.

Need a good hex editor for Linux

Personally, I use Emacs with hexl-mod.

Emacs is able to work with really huge files. You can use search/replace value easily. Finally, you can use 'ediff' to do some diffs.

127 Return code from $?

127 - command not found

example: $caat The error message will

bash:

caat: command not found

now you check using echo $?

Default username password for Tomcat Application Manager

First navigate to below location and open it in a text editor

<TOMCAT_HOME>/conf/tomcat-users.xml

For tomcat 7, Add the following xml code somewhere between <tomcat-users> I find the following solution.

  <role rolename="manager-gui"/>
  <user username="username" password="password" roles="manager-gui"/>

Now restart the tomcat server.

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

Android: long click on a button -> perform actions

Change return false; to return true; in longClickListener

You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.

How Can I Remove “public/index.php” in the URL Generated Laravel?

Option 1: Use .htaccess

If it isn't already there, create an .htaccess file in the Laravel root directory. Create a .htaccess file your Laravel root directory if it does not exists already. (Normally it is under your public_html folder)

Edit the .htaccess file so that it contains the following code:

<IfModule mod_rewrite.c>
   RewriteEngine On 
   RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

Now you should be able to access the website without the "/public/index.php/" part.

Option 2 : Move things in the '/public' directory to the root directory

Make a new folder in your root directory and move all the files and folder except public folder. You can call it anything you want. I'll use "laravel_code".

Next, move everything out of the public directory and into the root folder. It should result in something somewhat similar to this: enter image description here

After that, all we have to do is edit the locations in the laravel_code/bootstrap/paths.php file and the index.php file.

In laravel_code/bootstrap/paths.php find the following line of code:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../public',

And change them to:

'app' => __DIR__.'/../app',
'public' => __DIR__.'/../../',

In index.php, find these lines:

require __DIR__.'/../bootstrap/autoload.php';     
$app = require_once __DIR__.'/../bootstrap/start.php';

And change them to:

require __DIR__.'/laravel_code/bootstrap/autoload.php';     
$app = require_once __DIR__.'/laravel_code/bootstrap/start.php';

Source: How to remove /public/ from URL in Laravel

How to check that a string is parseable to a double?

Google's Guava library provides a nice helper method to do this: Doubles.tryParse(String). You use it like Double.parseDouble but it returns null rather than throwing an exception if the string does not parse to a double.

XSL substring and indexOf

I want to select the text of a string that is located after the occurrence of substring

You could use:

substring-after($string,$match)

If you want a subtring of the above with some length then use:

substring(substring-after($string,$match),1,$length)

But problems begin if there is no ocurrence of the matching substring... So, if you want a substring with specific length located after the occurrence of a substring, or from the whole string if there is no match, you could use:

substring(substring-after($string,substring-before($string,$match)),
          string-length($match) * contains($string,$match) + 1,
          $length) 

Add a CSS border on hover without moving the element

You can make the border transparent. In this way it exists, but is invisible, so it doesn't push anything around:

_x000D_
_x000D_
.jobs .item {
   background: #eee;
   border: 1px solid transparent;
}

.jobs .item:hover {
   background: #e1e1e1;
   border: 1px solid #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

For elements that already have a border, and you don't want them to move, you can use negative margins:

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
   background: #e1e1e1;
    border: 3px solid #d0d0d0;
    margin: -2px;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

Another possible trick for adding width to an existing border is to add a box-shadow with the spread attribute of the desired pixel width.

_x000D_
_x000D_
.jobs .item {
    background: #eee;
    border: 1px solid #d0d0d0;
}

.jobs .item:hover {
    background: #e1e1e1;
    box-shadow: 0 0 0 2px #d0d0d0;
}
_x000D_
<div class="jobs">
  <div class="item">Item</div>
</div>
_x000D_
_x000D_
_x000D_

Table-level backup

A free app named SqlTableZip will get the job done. Basically, you write any query (which, of course can also be [select * from table]) and the app creates a compressed file with all the data, which can be restored later.

Link: http://www.doccolabs.com/products_sqltablezip.html

SQL to add column and comment in table in single command

Query to add column with comment are :

alter table table_name 
add( "NISFLAG"    NUMBER(1,0) )

comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'

commit;

Recommended way to embed PDF in HTML?

  1. Construct a blob of the input PDF bytes
  2. Use an iframe and PDF.js patched with this cross browser workaround

The URI for the iframe should look something like this:

/viewer.html?file=blob:19B579EA-5217-41C6-96E4-5D8DF5A5C70B

Now FF, Chrome, IE 11, and Edge all display the PDF in a viewer in the iframe passed via standard blob URI in the URL.

Convert a list of objects to an array of one of the object's properties

I am fairly sure that Linq can do this.... but MyList does not have a select method on it (which is what I would have used).

Yes, LINQ can do this. It's simply:

MyList.Select(x => x.Name).ToArray();

Most likely the issue is that you either don't have a reference to System.Core, or you are missing an using directive for System.Linq.

Can table columns with a Foreign Key be NULL?

I also stuck on this issue. But I solved simply by defining the foreign key as unsigned integer. Find the below example-

CREATE TABLE parent (
   id int(10) UNSIGNED NOT NULL,
    PRIMARY KEY (id)
) ENGINE=INNODB;

CREATE TABLE child (
    id int(10) UNSIGNED NOT NULL,
    parent_id int(10) UNSIGNED DEFAULT NULL,
    FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE
) ENGINE=INNODB;

How to submit a form using Enter key in react.js?

Change <button type="button" to <button type="submit". Remove the onClick. Instead do <form className="commentForm" onSubmit={this.onFormSubmit}>. This should catch clicking the button and pressing the return key.

onFormSubmit = e => {
  e.preventDefault();
  const { name, email } = this.state;
  // send to server with e.g. `window.fetch`
}

...

<form onSubmit={this.onFormSubmit}>
  ...
  <button type="submit">Submit</button>
</form>

What is the memory consumption of an object in Java?

Mindprod points out that this is not a straightforward question to answer:

A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
For example, the JVM or native compiler might decide to store a boolean[] in 64-bit long chunks like a BitSet. It does not have to tell you, so long as the program gives the same answers.

  • It might allocate some temporary Objects on the stack.
  • It may optimize some variables or method calls totally out of existence replacing them with constants.
  • It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.

Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.

Measurement methods

You can use Instrumentation.getObjectSize() to obtain an estimate of the storage consumed by an object.

To visualize the actual object layout, footprint, and references, you can use the JOL (Java Object Layout) tool.

Object headers and Object references

In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. (From Dmitry Spikhalskiy's answer, Jayen's answer, and JavaWorld.)

Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to -Xmx32G; and 8 bytes above 32Gb (-Xmx32G). (See compressed object references.)

As a result, a 64-bit JVM would typically require 30-50% more heap space. (Should I use a 32- or a 64-bit JVM?, 2012, JDK 1.7)

Boxed types, arrays, and strings

Boxed wrappers have overhead compared to primitive types (from JavaWorld):

  • Integer: The 16-byte result is a little worse than I expected because an int value can fit into just 4 extra bytes. Using an Integer costs me a 300 percent memory overhead compared to when I can store the value as a primitive type

  • Long: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a Long is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, Integer had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.

Other containers are costly too:

  • Multidimensional arrays: it offers another surprise.
    Developers commonly employ constructs like int[dim1][dim2] in numerical and scientific computing.

    In an int[dim1][dim2] array instance, every nested int[dim2] array is an Object in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.

    For example, a int[128][2] instance takes 3,600 bytes. Compared to the 1,040 bytes an int[256] instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of byte[256][1], the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.

  • String: a String's memory growth tracks its internal char array's growth. However, the String class adds another 24 bytes of overhead.

    For a nonempty String of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.

Alignment

Consider this example object:

class X {                      // 8 bytes for reference to the class definition
   int a;                      // 4 bytes
   byte b;                     // 1 byte
   Integer c = new Integer();  // 4 bytes for a reference
}

A naïve sum would suggest that an instance of X would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.

nodeJS - How to create and read session with express

I forgot to tell a bug when i use I use req.session.email = req.param('email'), the server error says cannot sett property email of undefined.

The reason of this error is a wrong order of app.use. You must configure express in this order:

app.use(express.cookieParser());
app.use(express.session({ secret: sessionVal }));
app.use(app.route);

Dynamically add properties to a existing object

If you have a class with an object property, or if your property actually casts to an object, you can reshape the object by reassigning its properties, as in:

  MyClass varClass = new MyClass();
  varClass.propObjectProperty = new { Id = 1, Description = "test" };

  //if you need to treat the class as an object
  var varObjectProperty = ((dynamic)varClass).propObjectProperty;
  ((dynamic)varClass).propObjectProperty = new { Id = varObjectProperty.Id, Description = varObjectProperty.Description, NewDynamicProperty = "new dynamic property description" };

  //if your property is an object, instead
  var varObjectProperty = varClass.propObjectProperty;
  varClass.propObjectProperty = new { Id = ((dynamic)varObjectProperty).Id, Description = ((dynamic)varObjectProperty).Description, NewDynamicProperty = "new dynamic property description" };

With this approach, you basically rewrite the object property adding or removing properties as if you were first creating the object with the

new { ... }

syntax.

In your particular case, you're probably better off creating an actual object to which you assign properties like "dob" and "address" as if it were a person, and at the end of the process, transfer the properties to the actual "Person" object.

Create new XML file and write data to it?

With FluidXML you can generate and store an XML document very easily.

$doc = fluidxml();

$doc->add('Album', true)
        ->add('Track', 'Track Title');

$doc->save('album.xml');

Loading a document from a file is equally simple.

$doc = fluidify('album.xml');

$doc->query('//Track')
        ->attr('id', 123);

https://github.com/servo-php/fluidxml

How to VueJS router-link active style

When you are creating the router, you can specify the linkExactActiveClass as a property to set the class that will be used for the active router link.

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkActiveClass: "active", // active class for non-exact links.
  linkExactActiveClass: "active" // active class for *exact* links.
})

This is documented here.

Setting POST variable without using form

If you want to set $_POST['text'] to another value, why not use:

$_POST['text'] = $var;

on next.php?

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

Setting public class variables

this is the way, but i would suggest to write a getter and setter for that variable.

class Testclass

{
    private $testvar = "default value";

    public function setTestvar($testvar) { 
        $this->testvar = $testvar; 
    }
    public function getTestvar() { 
        return $this->testvar; 
    }

    function dosomething()
    {
        echo $this->getTestvar();
    }
}

$Testclass = new Testclass();

$Testclass->setTestvar("another value");

$Testclass->dosomething();

gitbash command quick reference

from within the git bash shell type:

>cd /bin
>ls -l

You will then see a long listing of all the unix-like commands available. There are lots of goodies in there.

SQL Server: Importing database from .mdf?

Open SQL Management Studio Express and log in to the server to which you want to attach the database. In the 'Object Explorer' window, right-click on the 'Databases' folder and select 'Attach...' The 'Attach Databases' window will open; inside that window click 'Add...' and then navigate to your .MDF file and click 'OK'. Click 'OK' once more to finish attaching the database and you are done. The database should be available for use. best regards :)

How to check for the type of a template parameter?

I think todays, it is better to use, but only with C++17.

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

If you use some type specific operations in if expression body without constexpr, this code will not compile.

Getting Access Denied when calling the PutObject operation with bucket-level permission

I had a similar issue uploading to an S3 bucket protected with KWS encryption. I have a minimal policy that allows the addition of objects under a specific s3 key.

I needed to add the following KMS permissions to my policy to allow the role to put objects in the bucket. (Might be slightly more than are strictly required)

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "kms:ListKeys",
                "kms:GenerateRandom",
                "kms:ListAliases",
                "s3:PutAccountPublicAccessBlock",
                "s3:GetAccountPublicAccessBlock",
                "s3:ListAllMyBuckets",
                "s3:HeadBucket"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "kms:ImportKeyMaterial",
                "kms:ListKeyPolicies",
                "kms:ListRetirableGrants",
                "kms:GetKeyPolicy",
                "kms:GenerateDataKeyWithoutPlaintext",
                "kms:ListResourceTags",
                "kms:ReEncryptFrom",
                "kms:ListGrants",
                "kms:GetParametersForImport",
                "kms:TagResource",
                "kms:Encrypt",
                "kms:GetKeyRotationStatus",
                "kms:GenerateDataKey",
                "kms:ReEncryptTo",
                "kms:DescribeKey"
            ],
            "Resource": "arn:aws:kms:<MY-REGION>:<MY-ACCOUNT>:key/<MY-KEY-GUID>"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
            <The S3 actions>
            ],
            "Resource": [
                "arn:aws:s3:::<MY-BUCKET-NAME>",
                "arn:aws:s3:::<MY-BUCKET-NAME>/<MY-BUCKET-KEY>/*"
            ]
        }
    ]
}

SVG: text inside rect

<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
    <g>
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" style="stop-color:rgb(145,200,103);stop-opacity:1" />
      <stop offset="100%" style="stop-color:rgb(132,168,86);stop-opacity:1" />
    </linearGradient>
  </defs>
  <rect width="220" height="30" class="GradientBorder" fill="url(#grad1)" />
  <text x="60" y="20" font-family="Calibri" font-size="20" fill="white" >My Code , Your Achivement....... </text>
  </g>
</svg> 

Failed to serialize the response in Web API with Json

In my case I have had similar error message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

But when I dig deeper in it, the issue was:

Type 'name.SomeSubRootType' with data contract name 'SomeSubRootType://schemas.datacontract.org/2004/07/WhatEverService' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

The way I solved by adding KnownType.

[KnownType(typeof(SomeSubRootType))]
public partial class SomeRootStructureType

This was solved inspired from this answer.

Reference: https://msdn.microsoft.com/en-us/library/ms730167(v=vs.100).aspx

How to check if a windows form is already open, and close it if it is?

In my app I had a mainmenu form that had buttons to navigate to an assortment of other forms (aka sub-forms). I wanted only one instance of each sub-form to be running at a time. Plus I wanted to ensure if a user attempted to launch a sub-form already in existence, that the sub-form would be forced to show "front&center" if minimized or behind other app windows. Using the currently most upvoted answers, I refactored their answers into this:

private void btnOpenSubForm_Click(object sender, EventArgs e)
    {

        Form fsf = Application.OpenForms["formSubForm"];

        if (fsf != null)
        {
            fsf.WindowState = FormWindowState.Normal;
            fsf.Show();
            fsf.TopMost = true;
        }
        else
        {
            Form formSubForm = new FormSubForm();
            formSubForm.Show();
            formSubForm.TopMost = true;
        }
    }

Returning JSON from PHP to JavaScript?

You can use Simple JSON for PHP. It sends the headers help you to forge the JSON.

It looks like :

<?php
// Include the json class
include('includes/json.php');

// Then create the PHP-Json Object to suits your needs

// Set a variable ; var name = {}
$Json = new json('var', 'name'); 
// Fire a callback ; callback({});
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {}
$Json = new json();

// Build data
$object = new stdClass();
$object->test = 'OK';
$arraytest = array('1','2','3');
$jsonOnly = '{"Hello" : "darling"}';

// Add some content
$Json->add('width', '565px');
$Json->add('You are logged IN');
$Json->add('An_Object', $object);
$Json->add("An_Array",$arraytest);
$Json->add("A_Json",$jsonOnly);

// Finally, send the JSON.

$Json->send();
?>

Index inside map() function

  • suppose you have an array like

_x000D_
_x000D_
   const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    
    arr.map((myArr, index) => {
      console.log(`your index is -> ${index} AND value is ${myArr}`);
    })
_x000D_
_x000D_
_x000D_

> output will be
 index is -> 0 AND value is 1
 index is -> 1 AND value is 2
 index is -> 2 AND value is 3
 index is -> 3 AND value is 4
 index is -> 4 AND value is 5
 index is -> 5 AND value is 6
 index is -> 6 AND value is 7
 index is -> 7 AND value is 8
 index is -> 8 AND value is 9

What are the file limits in Git (number and size)?

I found this trying to store a massive number of files(350k+) in a repo. Yes, store. Laughs.

$ time git add . 
git add . 333.67s user 244.26s system 14% cpu 1:06:48.63 total

The following extracts from the Bitbucket documentation are quite interesting.

When you work with a DVCS repository cloning, pushing, you are working with the entire repository and all of its history. In practice, once your repository gets larger than 500MB, you might start seeing issues.

... 94% of Bitbucket customers have repositories that are under 500MB. Both the Linux Kernel and Android are under 900MB.

The recommended solution on that page is to split your project into smaller chunks.

In Git, how do I figure out what my current revision is?

below will work with any previously pushed revision, not only HEAD

for abbreviated revision hash:

git log -1 --pretty=format:%h

for long revision hash:

git log -1 --pretty=format:%H

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

Simple DateTime sql query

Open up the Access File you are trying to export SQL data to. Delete any Queries that are there. Everytime you run SQL Server Import wizard, even if it fails, it creates a Query in the Access DB that has to be deleted before you can run the SQL export Wizard again.

getting the ng-object selected with ng-change

You can also directly get selected value using following code

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

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

print_r() can print out value but also if second flag parameter is passed and is TRUE - it will return printed result as string and nothing send to standard output. About var_dump. If XDebug debugger is installed so output results will be formatted in much more readable and understandable way.

How to insert blank lines in PDF?

document.add(new Paragraph("")) 

It is ineffective above,must add a blank string, like this:

document.add(new Paragraph(" "));

How to run a function when the page is loaded?

Take a look at the domReady script that allows setting up of multiple functions to execute when the DOM has loaded. It's basically what the Dom ready does in many popular JavaScript libraries, but is lightweight and can be taken and added at the start of your external script file.

Example usage

// add reference to domReady script or place 
// contents of script before here

function codeAddress() {

}

domReady(codeAddress);

Configuring ObjectMapper in Spring

I found the solution now based on https://github.com/FasterXML/jackson-module-hibernate

I extended the object mapper and added the attributes in the inherited constructor.

Then the new object mapper is registered as a bean.

<!-- https://github.com/FasterXML/jackson-module-hibernate -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <array>
            <bean id="jsonConverter"
            class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper">
                    <bean class="de.company.backend.spring.PtxObjectMapper"/>
                </property>
            </bean>
        </array>
    </property>
</bean>   

Replace all 0 values to NA

You can replace 0 with NA only in numeric fields (i.e. excluding things like factors), but it works on a column-by-column basis:

col[col == 0 & is.numeric(col)] <- NA

With a function, you can apply this to your whole data frame:

changetoNA <- function(colnum,df) {
    col <- df[,colnum]
    if (is.numeric(col)) {  #edit: verifying column is numeric
        col[col == -1 & is.numeric(col)] <- NA
    }
    return(col)
}
df <- data.frame(sapply(1:5, changetoNA, df))

Although you could replace the 1:5 with the number of columns in your data frame, or with 1:ncol(df).

Python: download a file from an FTP server

urllib2.urlopen handles ftp links.

SQL Server: Best way to concatenate multiple columns?

If the fields are nullable, then you'll have to handle those nulls. Remember that null is contagious, and concat('foo', null) simply results in NULL as well:

SELECT CONCAT(ISNULL(column1, ''),ISNULL(column2,'')) etc...

Basically test each field for nullness, and replace with an empty string if so.

Python TypeError: not enough arguments for format string

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

These are class stereotypes used in analysis.

  • boundary classes are ones at the boundary of the system - the classes that you or other systems interact with

  • entity classes classes are your typical business entities like "person" and "bank account"

  • control classes implement some business logic or other

Set folder browser dialog start location

fldrDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

"If the SelectedPath property is set before showing the dialog box, the folder with this path will be the selected folder, as long as SelectedPath is set to an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder)."

MSDN - SelectedPath

"The GetFolderPath method returns the locations associated with this enumeration. The locations of these folders can have different values on different operating systems, the user can change some of the locations, and the locations are localized."

Re: Desktop vs DesktopDirectory

Desktop

"The logical Desktop rather than the physical file system location."

DesktopDirectory:

"The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder."

MSDN - Special Folder Enum

MSDN - GetFolderPath

Composer: Command Not Found

This problem arises when you have composer installed locally. To make it globally executable,run the below command in terminal

sudo mv composer.phar /usr/local/bin/composer

For CentOS 7 the command is

sudo mv composer.phar /usr/bin/composer

Create folder in Android

If you are trying to make more than just one folder on the root of the sdcard, ex. Environment.getExternalStorageDirectory() + "/Example/Ex App/"

then instead of folder.mkdir() you would use folder.mkdirs()

I've made this mistake in the past & I took forever to figure it out.

Convert Year/Month/Day to Day of Year in Python

DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.

I found this to work:

import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday

>>>> 77

Or numerically:

import datetime
year,julian = [1936,77]
datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)

>>>> datetime.datetime(1936, 3, 17, 0, 0)

Or with fractional 1-based jdates popular in some domains:

jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
display(jdate_frac)

>>>> 77.5515625

year,julian = [1936,jdate_frac]
display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.

Android Studio - No JVM Installation found

The solution is given in the error itself, Goto My computer(Right click)-->properties-->Advanced system settings-->Environment variables-->Create new variable.

Give the following details to it:

Variable name : JAVA_HOME.

Variable value : (your path to java jdk installation folder).

To find the path for java installation, go to program files in your window installation drive (normally C drive). Find folder named JAVA, in that navigate to JDK folder.

Copy the link address from the top, and paste it in the Variable value .

Now Press Ok and once environment variable gets created restart the android studio.

Hope it helps.

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

Either decorate your root entity with the XmlRoot attribute which will be used at compile time.

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

Or specify the root attribute when de serializing at runtime.

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);

Changing the action of a form with JavaScript/jQuery

I agree with Paolo that we need to see more code. I tested this overly simplified example and it worked. This means that it is able to change the form action on the fly.

<script type="text/javascript">
function submitForm(){
    var form_url = $("#openid_form").attr("action");
    alert("Before - action=" + form_url);   
    //changing the action to google.com
    $("#openid_form").attr("action","http://google.com");
    alert("After - action = "+$("#openid_form").attr("action"));
    //submit the form
    $("#openid_form").submit();
}
</script>


<form id="openid_form" action="test.html">
    First Name:<input type="text" name="fname" /><br/>
    Last Name: <input type="text" name="lname" /><br/>
    <input type="button" onclick="submitForm()" value="Submit Form" />
</form>

EDIT: I tested the updated code you posted and found a syntax error in the declaration of providers_large. There's an extra comma. Firefox ignores the issue, but IE8 throws an error.

var providers_large = {
    google: {
        name: 'Google',
        url: 'https://www.google.com/accounts/o8/id'
    },
    facebook: {
        name: 'Facebook',
        form_url: 'http://wikipediamaze.rpxnow.com/facebook/start?token_url=http://www.wikipediamaze.com/Accounts/Logon'
    },  //<-- Here's the problem. Remove that comma

};

C# List<> Sort by x then y

I had an issue where OrderBy and ThenBy did not give me the desired result (or I just didn't know how to use them correctly).

I went with a list.Sort solution something like this.

    var data = (from o in database.Orders Where o.ClientId.Equals(clientId) select new {
    OrderId = o.id,
    OrderDate = o.orderDate,
    OrderBoolean = (SomeClass.SomeFunction(o.orderBoolean) ? 1 : 0)
    });

    data.Sort((o1, o2) => (o2.OrderBoolean.CompareTo(o1.OrderBoolean) != 0
    o2.OrderBoolean.CompareTo(o1.OrderBoolean) : o1.OrderDate.Value.CompareTo(o2.OrderDate.Value)));

How do I populate a JComboBox with an ArrayList?

I don't like the accepted answer or @fivetwentysix's comment regarding how to solve this. It gets at one method for doing this, but doesn't give the full solution to using toArray. You need to use toArray and give it an argument that's an array of the correct type and size so that you don't end up with an Object array. While an object array will work, I don't think it's best practice in a strongly typed language.

String[] array = arrayList.toArray(new String[arrayList.size()]);
JComboBox comboBox = new JComboBox(array);

Alternatively, you can also maintain strong typing by just using a for loop.

String[] array = new String[arrayList.size()];
for(int i = 0; i < array.length; i++) {
    array[i] = arrayList.get(i);
}
JComboBox comboBox = new JComboBox(array);

Why am I getting 'Assembly '*.dll' must be strong signed in order to be marked as a prerequisite.'?

What helped me was I went onto Package Manager Solution and looked at the installed package which was causing the issue. I saw that several projects were referencing the same package but different versions. I aligned them based on my needs and it worked.

what is reverse() in Django

reverse() | Django documentation


Let's suppose that in your urls.py you have defined this:

url(r'^foo$', some_view, name='url_name'),

In a template you can then refer to this url as:

<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>

<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>

This will be rendered as:

<a href="/foo/">link which calls some_view</a>

Now say you want to do something similar in your views.py - e.g. you are handling some other url (not /foo/) in some other view (not some_view) and you want to redirect the user to /foo/ (often the case on successful form submission).

You could just do:

return HttpResponseRedirect('/foo/')

But what if you want to change the url in future? You'd have to update your urls.py and all references to it in your code. This violates DRY (Don't Repeat Yourself), the whole idea of editing one place only, which is something to strive for.

Instead, you can say:

from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))

This looks through all urls defined in your project for the url defined with the name url_name and returns the actual url /foo/.

This means that you refer to the url only by its name attribute - if you want to change the url itself or the view it refers to you can do this by editing one place only - urls.py.

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Follow these steps- 1.go to config.inc.php file and find - $cfg['Servers'][$i]['auth_type']

2.change the value of $cfg['Servers'][$i]['auth_type'] to 'cookie' or 'http'.

3.find $cfg['Servers'][$i]['AllowNoPassword'] and change it's value to true.

Now whenever you want to login, enter root as your username,skip the password and go ahead pressing the submit button..

Note- if you choose authentication type as cookie then whenever you will close the browser and reopen it ,again you have to login.

XSL xsl:template match="/"

The value of the match attribute of the <xsl:template> instruction must be a match pattern.

Match patterns form a subset of the set of all possible XPath expressions. The first, natural, limitation is that a match pattern must select a set of nodes. There are also other limitations. In particular, reverse axes are not allowed in the location steps (but can be specified within the predicates). Also, no variable or parameter references are allowed in XSLT 1.0, but using these is legal in XSLT 2.x.

/ in XPath denotes the root or document node. In XPath 2.0 (and hence XSLT 2.x) this can also be written as document-node().

A match pattern can contain the // abbreviation.

Examples of match patterns:

<xsl:template match="table">

can be applied on any element named table.

<xsl:template match="x/y">

can be applied on any element named y whose parent is an element named x.

<xsl:template match="*">

can be applied to any element.

<xsl:template match="/*">

can be applied only to the top element of an XML document.

<xsl:template match="@*">

can be applied to any attribute.

<xsl:template match="text()">

can be applied to any text node.

<xsl:template match="comment()">

can be applied to any comment node.

<xsl:template match="processing-instruction()">

can be applied to any processing instruction node.

<xsl:template match="node()">

can be applied to any node: element, text, comment or processing instructon.

How to ignore the certificate check when ssl

Several answers above work. I wanted an approach that I did not have to keep making code changes and did not make my code unsecure. Hence I created a whitelist. Whitelist can be maintained in any datastore. I used config file since it is a very small list.

My code is below.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => {
    return error == System.Net.Security.SslPolicyErrors.None || certificateWhitelist.Contains(cert.GetCertHashString());
};

How to call another components function in angular2

  1. Add injectable decorator to component2(or any component which have the method)
@Injectable({
    providedIn: 'root'
})
  1. Inject into component1 (the component from where component2 method will be called)
constructor(public comp2 : component2) { }
  1. Define method in component1 from where component2 method is called
method1()
{
    this.comp2.method2();
}

component 1 and component 2 code below.

import {Component2} from './Component2';

@Component({
  selector: 'sel-comp1',
  templateUrl: './comp1.html',
  styleUrls: ['./comp1.scss']
})
export class Component1 implements OnInit {
  show = false;
  constructor(public comp2: Component2) { }
method1()
 {
   this.comp2.method2(); 
  }
}


@Component({
  selector: 'sel-comp2',
  templateUrl: './comp2.html',
  styleUrls: ['./comp2.scss']
})
export class Component2 implements OnInit {
  method2()
{
  alert('called comp2 method from comp1');
}

What is the benefit of zerofill in MySQL?

If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.

Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.

Above description is taken from MYSQL official website.

How do I POST XML data with curl

Have you tried url-encoding the data ? cURL can take care of that for you :

curl -H "Content-type: text/xml" --data-urlencode "<XmlContainer xmlns='sads'..." http://myapiurl.com/service.svc/

How does one output bold text in Bash?

In theory like so:

# BOLD
$ echo -e "\033[1mThis is a BOLD line\033[0m"
This is a BOLD line

# Using tput
tput bold 
echo "This" #BOLD
tput sgr0 #Reset text attributes to normal without clear.
echo "This" #NORMAL

# UNDERLINE
$ echo -e "\033[4mThis is a underlined line.\033[0m"
This is a underlined line. 

But in practice it may be interpreted as "high intensity" color instead.

(source: http://unstableme.blogspot.com/2008/01/ansi-escape-sequences-for-writing-text.html)

Make a nav bar stick

add to your .nav css block the

position: fixed

and it will work