Programs & Examples On #Uidatepicker

The UIDatePicker is a class in the UIKit framework of iOS which represents an graphical object that uses multiple rotating wheels to allow users to select dates and times.

jQuery Date Picker - disable past dates

just replace your code:

old code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd'

});

new code:

$("#dateSelect").datepicker({
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showButtonPanel: true,
    dateFormat: 'yy-mm-dd',
    minDate: 0
});

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

Jquery date picker z-index issue

In fact you can effectively add in your css .ui-datepicker{ z-index: 9999 !important;} but you can modify jquery-ui.css or jquery-ui.min.css and add at the end of the ui-datepicker class z-index: 9999 !important;. both things work for me (You only need one ;-))

Jquery UI Datepicker not displaying

I had the same problem using JQuery-UI 1.8.21, and JQuery-UI 1.8.22.

Problem was because I had two DatePicker script, one embedded with jquery-ui-1.8.22.custom.min.js and another one in jquery.ui.datepicker.js (an old version before I upgrade to 1.8.21).

Deleting the duplicate jquery.ui.datepicker.js, resolve problem for both 1.8.21 and 1.8.22.

What is the best way to return different types of ResponseEntity in Spring MVC or Spring-Boot

Using custom exception class you can return different HTTP status code and dto object.

@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
    if(userDto.getId() != null) {
        throw new UserNotFoundException("A new user cannot already have an ID");
    }
    return ResponseEntity.ok(userService.saveUser(userDto));
}

Exception class

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {

    public UserNotFoundException(String message) {

        super(message);
    }
}

What is the maximum value for an int32?

Well, it has 32 bits and hence can store 2^32 different values. Half of those are negative.

The solution is 2,147,483,647

And the lowest is -2,147,483,648.

(Notice that there is one more negative value.)

jquery count li elements inside ul -> length?

alert( "Size: " + $("li").size() ); 

or

alert( "Size: " + $("li").length );

You can find some examples of the .size() method here.

Facebook how to check if user has liked page and show content?

There is an article here that describes your problem

http://www.hyperarts.com/blog/facebook-fan-pages-content-for-fans-only-static-fbml/

    <fb:visible-to-connection>
       Fans will see this content.
       <fb:else>
           Non-fans will see this content.
       </fb:else>
    </fb:visible-to-connection>

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

how to bind datatable to datagridview in c#

foreach (DictionaryEntry entry in Hashtable)
{
    datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}

How can I enable CORS on Django REST Framework

pip install django-cors-headers

and then add it to your installed apps:

INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)

You will also need to add a middleware class to listen in on responses:

MIDDLEWARE_CLASSES = (
    ...
    'corsheaders.middleware.CorsMiddleware',  
    'django.middleware.common.CommonMiddleware',  
    ...
)

CORS_ORIGIN_ALLOW_ALL = True # If this is used then `CORS_ORIGIN_WHITELIST` will not have any effect
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
    'http://localhost:3030',
] # If this is used, then not need to use `CORS_ORIGIN_ALLOW_ALL = True`
CORS_ORIGIN_REGEX_WHITELIST = [
    'http://localhost:3030',
]

more details: https://github.com/ottoyiu/django-cors-headers/#configuration

read the official documentation can resolve almost all problem

bootstrap jquery show.bs.modal event won't fire

I had the same issue with bootstrap4. The solution was to add it inside the jQuery document ready() function:

$(document).ready(function() {
    $('#myModal').on('show.bs.modal', function () {
       alert('hi')
    })
}

Error: package or namespace load failed for ggplot2 and for data.table

This solved the issue:

remove.packages(c("ggplot2", "data.table"))
install.packages('Rcpp', dependencies = TRUE)
install.packages('ggplot2', dependencies = TRUE)
install.packages('data.table', dependencies = TRUE)

What is 'Currying'?

In an algebra of functions, dealing with functions that take multiple arguments (or equivalent one argument that's an N-tuple) is somewhat inelegant -- but, as Moses Schönfinkel (and, independently, Haskell Curry) proved, it's not needed: all you need are functions that take one argument.

So how do you deal with something you'd naturally express as, say, f(x,y)? Well, you take that as equivalent to f(x)(y) -- f(x), call it g, is a function, and you apply that function to y. In other words, you only have functions that take one argument -- but some of those functions return other functions (which ALSO take one argument;-).

As usual, wikipedia has a nice summary entry about this, with many useful pointers (probably including ones regarding your favorite languages;-) as well as slightly more rigorous mathematical treatment.

List of macOS text editors and code editors

Eclipse and Netbeans have text editors among a whole lot of other stuff. I don't think you would want to wait 10 seconds for your text editor to become ready :/...If you are going to spend some serious time coding then spend some time and learn to use vim (emacs too but, I recommend vim)

#1227 - Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In my case there was no DEFINER or root@localhost mentioned in my SQL file. Actually I was trying to import and run SQL file into SQLYog from Database->Import->Execute SQL Script menu. That was giving error.

Then I copied all the script from SQL file and ran in SQLYog query editor. That worked perfectly fine.

What is the Java equivalent of PHP var_dump?

It is not quite as baked-in in Java, so you don't get this for free. It is done with convention rather than language constructs. In all data transfer classes (and maybe even in all classes you write...), you should implement a sensible toString method. So here you need to override toString() in your Person class and return the desired state.

There are utilities available that help with writing a good toString method, or most IDEs have an automatic toString() writing shortcut.

Accessing @attribute from SimpleXML

You can get the attributes of an XML element by calling the attributes() function on an XML node. You can then var_dump the return value of the function.

More info at php.net http://php.net/simplexmlelement.attributes

Example code from that page:

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

How to handle ListView click in Android

This solution is really minimalistic and doesn't mess up your code.

In your list_item.xml (NOT listView!) assign the attribute android:onClick like this:

<RelativeLayout android:onClick="onClickDoSomething">

and then in your activity call this method:

public void onClickDoSomething(View view) {
   // the view is the line you have clicked on
}

HTML anchor tag with Javascript onclick event

From what I understand you do not want to redirect when the link is clicked. You can do :

<a href='javascript:;' onclick='show_more_menu();'>More ></a>

Setting background-image using jQuery CSS property

You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

Twitter Bootstrap modal on mobile devices

Admittedly, I haven't tried any of the solutions listed above but I was (eventually) jumping for joy when I tried jschr's Bootstrap-modal project in Bootstrap 3 (linked to in the top answer). The js was giving me trouble so I abandoned it (maybe mine was a unique issue or it works fine for Bootstrap 2) but the CSS files on their own seem to do the trick in Android's native 2.3.4 browser.

In my case, I've resorted so far to using (sub-optimal) user-agent detection before using the overrides to allow expected behaviour in modern phones.

For example, if you wanted all Android phones ver 3.x and below only to use the full set of hacks you could add a class "oldPhoneModalNeeded" to the body after user agent detection using javascript and then modify jschr's Bootstrap-modal CSS properties to always have .oldPhoneModalNeeded as an ancestor.

PHP JSON String, escape Double Quotes for JS output

This is a solutions that takes care of single and double quotes:

<?php
$php_data = array("title"=>"Example string's with \"special\" characters");

$escaped_data = json_encode( $php_data, JSON_HEX_QUOT|JSON_HEX_APOS );
$escaped_data = str_replace("\u0022", "\\\"", $escaped_data );
$escaped_data = str_replace("\u0027", "\\'",  $escaped_data );
?>
<script>
// no need to use JSON.parse()...
var js_data = <?= $escaped_data ?>;
alert(js_data.title); // should alert `Example string's with "special" characters`
</script>

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

Here's generally how to select multiple columns from a subquery:

SELECT
     A.SalesOrderID,
     A.OrderDate,
     SQ.Max_Foo,
     SQ.Max_Foo2
FROM
     A
LEFT OUTER JOIN
     (
     SELECT
          B.SalesOrderID,
          MAX(B.Foo) AS Max_Foo,
          MAX(B.Foo2) AS Max_Foo2
     FROM
          B
     GROUP BY
          B.SalesOrderID
     ) AS SQ ON SQ.SalesOrderID = A.SalesOrderID

If what you're ultimately trying to do is get the values from the row with the highest value for Foo (rather than the max of Foo and the max of Foo2 - which is NOT the same thing) then the following will usually work better than a subquery:

SELECT
     A.SalesOrderID,
     A.OrderDate,
     B1.Foo,
     B1.Foo2
FROM
     A
LEFT OUTER JOIN B AS B1 ON
     B1.SalesOrderID = A.SalesOrderID
LEFT OUTER JOIN B AS B2 ON
     B2.SalesOrderID = A.SalesOrderID AND
     B2.Foo > B1.Foo
WHERE
     B2.SalesOrderID IS NULL

You're basically saying, give me the row from B where I can't find any other row from B with the same SalesOrderID and a greater Foo.

how to create inline style with :before and :after

You can't. With inline styles you are targeting the element directly. You can't use other selectors there.

What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

CSS, Images, JS not loading in IIS

If you tried all the above solutions and still have problems, consider using the method ResolveClientUrl() of ASP.NET .

A script for Example :

Instead of using

<script src="~/dist/js/app.min.js" ></script>

Use the method

<script src="<%= ResolveClientUrl("~/dist/js/app.min.js") %>" ></script>

This was my solution that worked for a friend I was helping!

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

Calculate compass bearing / heading to location in Android

@Damian - The idea is very good and I agree with answer, but when I used your code I had wrong values, so I wrote this on my own (somebody told the same in your comments). Counting heading with the declination is good, I think, but later I used something like that:

heading = (bearing - heading) * -1;

instead of Damian's code:

heading = myBearing - (myBearing + heading); 

and changing -180 to 180 for 0 to 360:

      private float normalizeDegree(float value){
          if(value >= 0.0f && value <= 180.0f){
              return value;
          }else{
              return 180 + (180 + value);
          }

and then when you want to rotate your arrow you can use code like this:

      private void rotateArrow(float angle){

            Matrix matrix = new Matrix();
            arrowView.setScaleType(ScaleType.MATRIX);
            matrix.postRotate(angle, 100f, 100f);
            arrowView.setImageMatrix(matrix);
      }

where arrowView is ImageView with arrow picture and 100f parameters in postRotate is pivX and pivY).

I hope I will help somebody.

Meaning of "487 Request Terminated"

It's the response code a SIP User Agent Server (UAS) will send to the client after the client sends a CANCEL request for the original unanswered INVITE request (yet to receive a final response).

Here is a nice CANCEL SIP Call Flow illustration.

Maven with Eclipse Juno

All the info you need, is provided in the release announcement for m2e 1.1:

m2e 1.1 has been released as part of Eclipse Juno simultaneous release today.

[...]

m2e 1.1 is already included in "Eclipse IDE for Java Developers" package available from http://eclipse.org/downloads/ or it can be installed from Eclipse Juno release repository [2]. Eclipse 3.7/Indigo users can install the new version from m2e release repository [3]

[...]

[2] http://download.eclipse.org/releases/juno

[3] http://download.eclipse.org/technology/m2e/releases

How to apply font anti-alias effects in CSS?

Short answer: You can't.

CSS does not have techniques which affect the rendering of fonts in the browser; only the system can do that.

Obviously, text sharpness can easily be achieved with pixel-dense screens, but if you're using a normal PC that's gonna be hard to achieve.

There are some newer fonts that are smooth but at the sacrifice of it appearing somewhat blurry (look at most of Adobe's fonts, for example). You can also find some smooth-but-blurry-by-design fonts at Google Fonts, however.

There are some new CSS3 techniques for font rendering and text effects though the consistency, performance, and reliability of these techniques vary so largely to the point where you generally shouldn't rely on them too much.

Printing without newline (print 'a',) prints a space, how to remove?

There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20 works).

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print. Note that string concatenation using += is now linear in the size of the string you're concatenating so this will be fast.

>>> for i in xrange(20):
...     s += 'a'
... 
>>> print s
aaaaaaaaaaaaaaaaaaaa

Or you can do it more directly using sys.stdout.write(), which print is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 as.

>>> import sys
>>> for i in xrange(20):
...     sys.stdout.write('a')
... 
aaaaaaaaaaaaaaaaaaaa>>> 

Python 3 changes the print statement into a print() function, which allows you to set an end parameter. You can use it in >=2.6 by importing from __future__. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.

>>> from __future__ import print_function
>>> for i in xrange(20):
...     print('a', end='')
... 
aaaaaaaaaaaaaaaaaaaa>>> 

How can I check that two objects have the same set of property names?

If you are using underscoreJs then you can simply use _.isEqual function and it compares all keys and values at each and every level of hierarchy like below example.

var object = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};

var object1 = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};

console.log(_.isEqual(object, object1));//return true

If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.

Android: How to enable/disable option menu item on button click?

Anyway, the documentation covers all the things.

Changing menu items at runtime

Once the activity is created, the onCreateOptionsMenu() method is called only once, as described above. The system keeps and re-uses the Menu you define in this method until your activity is destroyed. If you want to change the Options Menu any time after it's first created, you must override the onPrepareOptionsMenu() method. This passes you the Menu object as it currently exists. This is useful if you'd like to remove, add, disable, or enable menu items depending on the current state of your application.

E.g.

@Override
public boolean onPrepareOptionsMenu (Menu menu) {
    if (isFinalized) {
        menu.getItem(1).setEnabled(false);
        // You can also use something like:
        // menu.findItem(R.id.example_foobar).setEnabled(false);
    }
    return true;
}

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu() to request that the system call onPrepareOptionsMenu().

How to retrieve SQL result column value using column name in Python?

selecting values from particular column:

import pymysql
db = pymysql.connect("localhost","root","root","school")
cursor=db.cursor()
sql="""select Total from student"""
l=[]
try:
    #query execution
    cursor.execute(sql)
    #fetch all rows 
    rs = cursor.fetchall()
    #iterate through rows
    for i in rs:
        #converting set to list
        k=list(i)
        #taking the first element from the list and append it to the list
        l.append(k[0])
    db.commit()
except:
    db.rollback()
db.close()
print(l)

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

How to do an array of hashmaps?

You can't have an array of a generic type. Use List instead.

How to change the window title of a MATLAB plotting figure?

If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:

  1. Go to "Edit" in the figure window

  2. Go to "Figure Properties"

  3. At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".

That's all.

Good luck.

SQL SERVER: Get total days between two dates

See DateDiff:

DECLARE @startdate date = '2011/1/1'
DECLARE @enddate date = '2011/3/1'
SELECT DATEDIFF(day, @startdate, @enddate)

Set height 100% on absolute div

Few answers have given a solution with height and width 100% but I recommend you to not use percentage in css, use top/bottom and left/right positionning.

This is a better approach that allow you to control margin.

Here is the code :

body {
    position: relative;
    height: 3000px;
}
body div {

    top:0px;
    bottom: 0px;
    right: 0px;
    left:0px;
    background-color: yellow;
    position: absolute;
}

Changing variable names with Python for loops

It looks like you want to use a list instead:

group=[]
for i in range(3):
     group[i]=self.getGroup(selected, header+i)

Null vs. False vs. 0 in PHP

Somebody can explain to me why 'NULL' is not just a string in a comparison instance?

$x = 0;
var_dump($x == 'NULL');  # TRUE   !!!WTF!!!

Apache Spark: map vs mapPartitions?

Map:

Map transformation.

The map works on a single Row at a time.

Map returns after each input Row.

The map doesn’t hold the output result in Memory.

Map no way to figure out then to end the service.

// map example

val dfList = (1 to 100) toList

val df = dfList.toDF()

val dfInt = df.map(x => x.getInt(0)+2)

display(dfInt)

MapPartition:

MapPartition transformation.

MapPartition works on a partition at a time.

MapPartition returns after processing all the rows in the partition.

MapPartition output is retained in memory, as it can return after processing all the rows in a particular partition.

MapPartition service can be shut down before returning.

// MapPartition example

Val dfList = (1 to 100) toList

Val df = dfList.toDF()

Val df1 = df.repartition(4).rdd.mapPartition((int) => Iterator(itr.length))

Df1.collec()

//display(df1.collect())

For more details, please refer to the Spark map vs mapPartitions transformation article.

Hope this is helpful!

How to convert NSNumber to NSString

You can do it with:

NSNumber *myNumber = @15;
NSString *myNumberInString = [myNumber stringValue];

Get a random item from a JavaScript array

jQuery is JavaScript! It's just a JavaScript framework. So to find a random item, just use plain old JavaScript, for example,

var randomItem = items[Math.floor(Math.random()*items.length)]

Using Bootstrap Tooltip with AngularJS

easiest way , add $("[data-toggle=tooltip]").tooltip(); to the concerned controller.

Error CS1705: "which has a higher version than referenced assembly"

My problem was that I had 2 projects referencing 2 different copies of the same dll which had different versions. I fixed it by removing them both and making sure they were referencing the same dll file.

How can I remove a style added with .css() function?

either of these jQuery functions should work:

$("#element").removeAttr("style");
$("#element").removeAttr("background-color") 

In C can a long printf statement be broken up into multiple lines?

The C compiler can glue adjacent string literals into one, like

printf("foo: %s "
       "bar: %d", foo, bar);

The preprocessor can use a backslash as a last character of the line, not counting CR (or CR/LF, if you are from Windowsland):

printf("foo %s \
bar: %d", foo, bar);

Convert a date format in epoch

  String dateTime="15-3-2019 09:50 AM" //time should be two digit like 08,09,10 
   DateTimeFormatter dtf  = DateTimeFormatter.ofPattern("dd-MM-yyyy hh:mm a");
        LocalDateTime zdt  = LocalDateTime.parse(dateTime,dtf);
        LocalDateTime now = LocalDateTime.now();
        ZoneId zone = ZoneId.of("Asia/Kolkata");
        ZoneOffset zoneOffSet = zone.getRules().getOffset(now);
        long a= zdt.toInstant(zoneOffSet).toEpochMilli();
        Log.d("time","---"+a);

you can get zone id form this a link!

What is the python "with" statement designed for?

Another example for out-of-the-box support, and one that might be a bit baffling at first when you are used to the way built-in open() behaves, are connection objects of popular database modules such as:

The connection objects are context managers and as such can be used out-of-the-box in a with-statement, however when using the above note that:

When the with-block is finished, either with an exception or without, the connection is not closed. In case the with-block finishes with an exception, the transaction is rolled back, otherwise the transaction is commited.

This means that the programmer has to take care to close the connection themselves, but allows to acquire a connection, and use it in multiple with-statements, as shown in the psycopg2 docs:

conn = psycopg2.connect(DSN)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL1)

with conn:
    with conn.cursor() as curs:
        curs.execute(SQL2)

conn.close()

In the example above, you'll note that the cursor objects of psycopg2 also are context managers. From the relevant documentation on the behavior:

When a cursor exits the with-block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.

WPF Button with Image

<Button x:Name="myBtn_DetailsTab_Save" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="835,544,0,0" VerticalAlignment="Top"  Width="143" Height="53" BorderBrush="#FF0F6287" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" Click="myBtn_DetailsTab_Save_Click">
    <StackPanel HorizontalAlignment="Stretch" Background="#FF1FB3F5" Cursor="Hand" >
        <Image HorizontalAlignment="Left"  Source="image/bg/Save.png" Height="36" Width="124" />
        <TextBlock HorizontalAlignment="Center" Width="84" Height="22" VerticalAlignment="Top" Margin="0,-31,-58,0" Text="??? ?????" />
    </StackPanel>
</Button>

How to hide only the Close (x) button?

Well, you can hide it, by removing the entire system menu:

private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.Style &= ~WS_SYSMENU;
        return cp;
    }
}

Of course, doing so removes the minimize and maximize buttons.

If you keep the system menu but remove the close item then the close button remains but is disabled.

The final alternative is to paint the non-client area yourself. That's pretty hard to get right.

What to do with "Unexpected indent" in python?

Turn on visible whitespace in whatever editor you are using and turn on replace tabs with spaces.

While you can use tabs with Python mixing tabs and space usually leads to the error you are experiencing. Replacing tabs with 4 spaces is the recommended approach for writing Python code.

Generate table relationship diagram from existing schema (SQL Server)

Why don't you just use the database diagram functionality built into SQL Server?

Does JavaScript guarantee object property order?

At the time of writing, most browsers did return properties in the same order as they were inserted, but it was explicitly not guaranteed behaviour so shouldn't have been relied upon.

The ECMAScript specification used to say:

The mechanics and order of enumerating the properties ... is not specified.

However in ES2015 and later non-integer keys will be returned in insertion order.

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I do not think one can push the user credentials from the browser to the database (and does it makes sense ? I think not)

But if you want to use the credentials of the user running Tomcat to connect to SQL Server then you can use Microsoft's JDBC Driver. Just build your JDBC URL like this:

jdbc:sqlserver://localhost;integratedSecurity=true;

And copy the appropriate DLL to Tomcat's bin directory (sqljdbc_auth.dll provided with the driver)

MSDN > Connecting to SQL Server with the JDBC Driver > Building the Connection URL

Oracle date "Between" Query

You need to convert those to actual dates instead of strings, try this:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('2010-01-15','YYYY-MM-DD') AND TO_DATE('2010-01-17', 'YYYY-MM-DD');

Edited to deal with format as specified:

SELECT *
FROM <TABLENAME>
WHERE start_date BETWEEN TO_DATE('15-JAN-10','DD-MON-YY') AND TO_DATE('17-JAN-10','DD-MON-YY');

How to add two edit text fields in an alert dialog

Check this code in alert box have edit textview when click OK it displays on screen using toast.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    final EditText input = new EditText(this);
    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            String value = input.getText().toString().trim();
            Toast.makeText(getApplicationContext(), value, 
                Toast.LENGTH_SHORT).show();
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            dialog.cancel();
        }
    });
    alert.show();               
}

start/play embedded (iframe) youtube-video on click of an image

You can do this simply like this

$('#image_id').click(function() {
  $("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1'); 
});

where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.

Enabling HTTPS on express.js

Including Points:

  1. SSL setup
    1. In config/local.js
    2. In config/env/production.js

HTTP and WS handling

  1. The app must run on HTTP in development so we can easily debug our app.
  2. The app must run on HTTPS in production for security concern.
  3. App production HTTP request should always redirect to https.

SSL configuration

In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env folder and each file contains settings for particular env.

Sails first looks in config/env folder and then look forward to config/ *.js

Now lets setup ssl in config/local.js.

var local = {
   port: process.env.PORT || 1337,
   environment: process.env.NODE_ENV || 'development'
};

if (process.env.NODE_ENV == 'production') {
    local.ssl = {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
    };
    local.port = 443; // This port should be different than your default port
}

module.exports = local;

Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)

Or in production.js

module.exports = {
    port: 443,
    ssl: {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: [
            require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
        ],
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
    }
};

http/https & ws/wss redirection

Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.

There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.

So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.

In config/bootstrap.js (Create http server and redirect all request to https)

module.exports.bootstrap = function(cb) {
    var express = require("express"),
        app = express();

    app.get('*', function(req, res) {  
        if (req.isSocket) 
            return res.redirect('wss://' + req.headers.host + req.url)  

        return res.redirect('https://' + req.headers.host + req.url)  
    }).listen(80);
    cb();
};

Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com

How to get data from observable in angular2

You need to subscribe to the observable and pass a callback that processes emitted values

this.myService.getConfig().subscribe(val => console.log(val));

Spring cron expression for every day 1:01:am

Try with:

@Scheduled(cron = "0 1 1 * * ?")

Below you can find the example patterns from the spring forum:

* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight

Cron expression is represented by six fields:

second, minute, hour, day of month, month, day(s) of week

(*) means match any

*/X means "every X"

? ("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.

PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support

Printing string variable in Java

You could also use BufferedReader:

import java.io.*;

public class TestApplication {
   public static void main (String[] args) {
      System.out.print("Enter a password: ");
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      String password = null;
      try {
         password = br.readLine();
      } catch (IOException e) {
         System.out.println("IO error trying to read your password!");
         System.exit(1);
      }
      System.out.println("Successfully read your password.");
   }
}

Python to print out status bar and percentage

based on the above answers and other similar questions about CLI progress bar, I think I got a general common answer to all of them. Check it at https://stackoverflow.com/a/15860757/2254146

Here is a copy of the function, but modified to fit your style:

import time, sys

# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
    barLength = 20 # Modify this to change the length of the progress bar
    status = ""
    if isinstance(progress, int):
        progress = float(progress)
    if not isinstance(progress, float):
        progress = 0
        status = "error: progress var must be float\r\n"
    if progress < 0:
        progress = 0
        status = "Halt...\r\n"
    if progress >= 1:
        progress = 1
        status = "Done...\r\n"
    block = int(round(barLength*progress))
    text = "\rPercent: [{0}] {1}% {2}".format( "="*block + " "*(barLength-block), progress*100, status)
    sys.stdout.write(text)
    sys.stdout.flush()

Looks like

Percent: [====================] 99.0%

How to change Format of a Cell to Text using VBA

One point: you have to set NumberFormat property BEFORE loading the value into the cell. I had a nine digit number that still displayed as 9.14E+08 when the NumberFormat was set after the cell was loaded. Setting the property before loading the value made the number appear as I wanted, as straight text.

OR:

Could you try an autofit first:

Excel_Obj.Columns("A:V").EntireColumn.AutoFit

Where is my .vimrc file?

These methods work, if you already have a .vimrc file:

:scriptnames list all the .vim files that Vim loaded for you, including your .vimrc file.

:e $MYVIMRC open & edit the current .vimrc that you are using, then use Ctrl + G to view the path in status bar.

PHP upload image

Here is a basic example of how an image file with certain restrictions (listed below) can be uploaded to the server.

  • Existence of the image.
  • Image extension validation
  • Checks for image size.

    <?php
       $newfilename = "newfilename";
    
       if(isset($_FILES['image'])){
          $errors= array();
          $file_name = $_FILES['image']['name'];
          $file_size =$_FILES['image']['size'];
          $file_tmp =$_FILES['image']['tmp_name'];
          $file_type=$_FILES['image']['type'];
          $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
    
          $expensions= array("jpeg","jpg","png");
          if(file_exists($file_name)) {
            echo "Sorry, file already exists.";
            }
          if(in_array($file_ext,$expensions)=== false){
             $errors[]="extension not allowed, please choose a JPEG or PNG file.";
          }
    
          if($file_size > 2097152){
             $errors[]='File size must be excately 2 MB';
          }
    
          if(empty($errors)==true){
            move_uploaded_file($file_tmp,"images/".$newfilename.".".$file_ext);
            echo "Success";
            echo "<script>window.close();</script>";
    
          }
    
          else{
             print_r($errors);
          }
       }
    ?>
    <html>
       <body>
    
          <form action="" method="POST" enctype="multipart/form-data">
             <input type="file" name="image" />
             <input type="submit"/>
          </form>
    
       </body>
    </html>
    

    Credit to this page.

How to determine the current language of a wordpress page when using polylang?

To show current language, you can use:

 <?php echo $lang=get_bloginfo("language"); ?>

Plain and simple

IntelliJ cannot find any declarations

IDEA may ignore some of your maven dependency files. The "External Libraries" node in your project structure might be empty or incomplete.

Go to:

  1. IntelliJ --> Preferences
  2. Search for Maven [on the left tab] -> Ignored Files
  3. See if there is any path on the right side that is checked(ignored) and uncheck that.enter image description here

How do I get the SharedPreferences from a PreferenceActivity in Android?

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);

Getting selected value of a combobox

I had a similar error, My Class is

public class ServerInfo
{
    public string Text { get; set; }
    public string Value { get; set; }
    public string PortNo { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

But what I did, I casted my class to the SelectedItem property of the ComboBox. So, i'll have all of the class properties of the selected item.

// Code above
ServerInfo emailServer = (ServerInfo)cbServerName.SelectedItem;

mailClient.ServerName = emailServer.Value;
mailClient.ServerPort = emailServer.PortNo;

I hope this helps someone! Cheers!

Cannot connect to Database server (mysql workbench)

For those who ignored that the initial error message displaying is the following one:

The name org.freedesktop.secrets was not provided by any .service files

Make sure to install gnome-keyring using the following

sudo apt install gnome-keyring

Regex to split a CSV

I personally tried many RegEx expressions without having found the perfect one that match all cases.

I think that regular expressions is hard to configure properly to match all cases properly. Although few persons will not like the namespace (and I was part of them), I propose something that is part of the .Net framework and give me proper results all the times in all cases (mainly managing every double quotes cases very well):

Microsoft.VisualBasic.FileIO.TextFieldParser

Found it here: StackOverflow

Example of usage:

TextReader textReader = new StringReader(simBaseCaseScenario.GetSimStudy().Study.FilesToDeleteWhenComplete);
Microsoft.VisualBasic.FileIO.TextFieldParser textFieldParser = new TextFieldParser(textReader);
textFieldParser.SetDelimiters(new string[] { ";" });
string[] fields = textFieldParser.ReadFields();
foreach (string path in fields)
{
    ...

Hope it could help.

How can I get the current directory name in Javascript?

This one-liner works:

var currentDirectory = window.location.pathname.split('/').slice(0, -1).join('/')

Replacing H1 text with a logo image: best method for SEO and accessibility?

One point no one has touched on is the fact that the h1 attribute should be specific to every page and using the site logo will effectively replicate the H1 on every page of the site.

I like to use a z index hidden h1 for each page as the best SEO h1 is often not the best for sales or aesthetic value.

How to consume a webApi from asp.net Web API to store result in database?

public class EmployeeApiController : ApiController
{
    private readonly IEmployee _employeeRepositary;

    public EmployeeApiController()
    {
        _employeeRepositary = new EmployeeRepositary();
    }

    public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
    {
        var returnStatus = await _employeeRepositary.Create(Employee);
        return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
    }
} 

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{    
    var responseStatusViewModel = new ResponseStatusViewModel();
    var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
                var command = new SqlCommand("usp_CreateEmployee", connection);
                command.CommandType = CommandType.StoredProcedure;
                var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
                pEmployeeName.Value = Employee.EmployeeName;
                command.Parameters.Add(pEmployeeName);


                try
                {
                    await connection.OpenAsync();
                    await command.ExecuteNonQueryAsync();

                    command.Dispose();
                    connection.Dispose();

                }
                catch (Exception ex)
                {

                    throw ex;
                }
                return responseStatusViewModel;
            }

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
    public static string EmployeeConnectionString;
    private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
    public static void InitializeConfig()
    {
        EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
    }

    private static string GetConnectionStringValue(string connectionStringName)
    {
        return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
    }
}

clearing select using jquery

Here is a small jQuery plugin that (among other things) can empty an dropdown list.

Just write:

$('your-select-element').selectUtils('setEmpty');

Change key pair for ec2 instance

You don't need to rotate root device and change the SSH Public Key in authorized_keys. For that can utilize userdata to add you ssh keys to any instance. For that first you need to create a new KeyPair using AWS console or through ssh-keygen.

ssh-keygen -f YOURKEY.pem -y

This will generate public key for your new SSH KeyPair, copy this public key and use it in below script.

Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0

--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"

#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
/bin/echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC6xigPPA/BAjDPJFflqNuJt5QY5IBeBwkVoow/uBJ8Rorke/GT4KMHJ3Ap2HjsvjYrkQaKANFDfqrizCmb5PfAovUjojvU1M8jYcjkwPG6hIcAXrD5yXdNcZkE7hGK4qf2BRY57E3s25Ay3zKjvdMaTplbJ4yfM0UAccmhKw/SmH0osFhkvQp/wVDzo0PyLErnuLQ5UoMAIYI6TUpOjmTOX9OI/k/zUHOKjHNJ1cFBdpnLTLdsUbvIJbmJ6oxjSrOSTuc5mk7M8HHOJQ9JITGb5LvJgJ9Bcd8gayTXo58BukbkwAX7WsqCmac4OXMNoMOpZ1Cj6BVOOjhluOgYZbLr" >> /home/hardeep/.ssh/authorized_keys
--//

After the restart the machine will be having the specified SSH publch key. Remove the userdata after first restart. Read more about userdata on startup.

Best ways to teach a beginner to program?

Copy some simple code line by line and get them to read and interpret it as they go along. They will soon work it out. I started programming on an Acorn Electron with snippets of code from Acorn magazines. I had no idea about programming when I was 6, I used to copy the text, but gradually I learnt what the different words meant.

Checkout Jenkins Pipeline Git SCM with credentials?

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]
            ])

How to read a file line-by-line into a list?

Use this:

import pandas as pd
data = pd.read_csv(filename) # You can also add parameters such as header, sep, etc.
array = data.values

data is a dataframe type, and uses values to get ndarray. You can also get a list by using array.tolist().

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Install Genymotion 2.10 or above, now there is a dedicated button to install Google Play Services name "Open GApps". Link for more info

3 Steps process for Genymotion 2.9 or below:-

4.4 Kitkat
5.0 Lollipop
5.1 Lollipop
6.0 Marshmallow
7.0 Nougat
7.1 Nougat (webview patch)
8.0 Oreo
8.1 Oreo
9.0 Pie

  1. Download from above link
  2. Just drag & drop downloaded zip file to genymotion and restart
  3. Add google account and download "Google Play Music" and Run.


How can I escape double quotes in XML attributes values?

The String conversion page on the Coder's Toolbox site is handy for encoding more than a small amount of HTML or XML code for inclusion as a value in an XML element.

Writing to an Excel spreadsheet

import xlwt

def output(filename, sheet, list1, list2, x, y, z):
    book = xlwt.Workbook()
    sh = book.add_sheet(sheet)

    variables = [x, y, z]
    x_desc = 'Display'
    y_desc = 'Dominance'
    z_desc = 'Test'
    desc = [x_desc, y_desc, z_desc]

    col1_name = 'Stimulus Time'
    col2_name = 'Reaction Time'

    #You may need to group the variables together
    #for n, (v_desc, v) in enumerate(zip(desc, variables)):
    for n, v_desc, v in enumerate(zip(desc, variables)):
        sh.write(n, 0, v_desc)
        sh.write(n, 1, v)

    n+=1

    sh.write(n, 0, col1_name)
    sh.write(n, 1, col2_name)

    for m, e1 in enumerate(list1, n+1):
        sh.write(m, 0, e1)

    for m, e2 in enumerate(list2, n+1):
        sh.write(m, 1, e2)

    book.save(filename)

for more explanation: https://github.com/python-excel

How to assign string to bytes array

Safe and simple:

[]byte("Here is a string....")

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

Rounding a variable to two decimal places C#

Console.WriteLine(decimal.Round(pay,2));

angular ng-repeat in reverse

The orderBy filter performs a stable sorting as of Angular 1.4.5. (See the GitHub pull request https://github.com/angular/angular.js/pull/12408.)

So it is sufficient to use a constant predicate and reverse set to true:

<div ng-repeat="friend in friends | orderBy:0:true">{{friend.name}}</div>

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

How to type a new line character in SQL Server Management Studio

You're talking about right-clicking on a table and selecting "Edit Top 50 Rows", right?

I tried [Ctl][Enter] and [Alt][Enter], but neither of those works.

Even when I insert data with CR/LF (using a standard INSERT statement), it shows up here in a single line with a rectangle representing the control codes.

Cast int to varchar

Yes

SELECT id || '' FROM some_table;
or SELECT id::text FROM some_table;

is postgresql, but mySql doesn't allow that!

short cut in mySql:

SELECT concat(id, '') FROM some_table;

jQuery return ajax result into outside variable

Using 'async': false to prevent asynchronous code is a bad practice,

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. https://xhr.spec.whatwg.org/

On the surface setting async to false fixes a lot of issues because, as the other answers show, you get your data into a variable. However, while waiting for the post data to return (which in some cases could take a few seconds because of database calls, slow connections, etc.) the rest of your Javascript functionality (like triggered events, Javascript handled buttons, JQuery transitions (like accordion, or autocomplete (JQuery UI)) will not be able to occur while the response is pending (which is really bad if the response never comes back as your site is now essentially frozen).

Try this instead,

var return_first;
function callback(response) {
  return_first = response;
  //use return_first variable here
}

$.ajax({
  'type': "POST",
  'global': false,
  'dataType': 'html',
  'url': "ajax.php?first",
  'data': { 'request': "", 'target': arrange_url, 'method': method_target },
  'success': function(data){
       callback(data);
  },
});

Return multiple values from a function in swift

Return a tuple:

func getTime() -> (Int, Int, Int) {
    ...
    return ( hour, minute, second)
}

Then it's invoked as:

let (hour, minute, second) = getTime()

or:

let time = getTime()
println("hour: \(time.0)")

How to push a docker image to a private repository

First go to your Docker Hub account and make the repo. Here is a screenshot of my Docker Hub account: enter image description here

From the pic, you can see my repo is “chuangg”

Now go into the repo and make it private by clicking on your image’s name. So for me, I clicked on “chuangg/gene_commited_image”, then I went to Settings -> Make Private. Then I followed the on screen instructions enter image description here

HOW TO UPLOAD YOUR DOCKER IMAGE ONTO DOCKER HUB

Method #1= Pushing your image through the command line (cli)

1) docker commit <container ID> <repo name>/<Name you want to give the image>

Yes, I think it has to be the container ID. It probably cannot be the image ID.

For example= docker commit 99e078826312 chuangg/gene_commited_image

2) docker run -it chaung/gene_commited_image

3) docker login --username=<user username> --password=<user password>

For example= docker login --username=chuangg [email protected]

Yes, you have to login first. Logout using “docker logout”

4) docker push chuangg/gene_commited_image

Method #2= Pushing your image using pom.xml and command line.

Note, I used a Maven Profile called “build-docker”. If you don’t want to use a profile, just remove the <profiles>, <profile>, and <id>build-docker</id> elements.

Inside the parent pom.xml:

<profiles>
        <profile>
            <id>build-docker</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>io.fabric8</groupId>
                        <artifactId>docker-maven-plugin</artifactId>
                        <version>0.18.1</version>
                        <configuration>
                            <images>
                                <image>
                                    <name>chuangg/gene_project</name>
                                    <alias>${docker.container.name}</alias>
                                    <!-- Configure build settings -->
                                    <build>
                                        <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                        <assembly>
                                            <inline>
                                                <fileSets>
                                                    <fileSet>
                                                        <directory>${project.basedir}\target</directory>
                                                        <outputDirectory>.</outputDirectory>
                                                        <includes>
                                                            <include>*.jar</include>
                                                        </includes>
                                                    </fileSet>
                                                </fileSets>
                                            </inline>
                                        </assembly>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                        <executions>
                            <execution>
                                <id>docker:build</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

Docker Terminal Command to deploy the Docker Image (from the directory where your pom.xml is located)= mvn clean deploy -Pbuild-docker docker:push

Note, the difference between Method #2 and #3 is that Method #3 has an extra <execution> for the deployment.

Method #3= Using Maven to automatically deploy to Docker Hub

Add this stuff to your parent pom.xml:

    <distributionManagement>
        <repository>
            <id>gene</id>
            <name>chuangg</name>
            <uniqueVersion>false</uniqueVersion>
            <layout>legacy</layout>
            <url>https://index.docker.io/v1/</url>
        </repository>
    </distributionManagement>


    <profiles>
        <profile>
            <id>build-docker</id>
            <build>
                <plugins>

                    <plugin>
                        <groupId>io.fabric8</groupId>
                        <artifactId>docker-maven-plugin</artifactId>
                        <version>0.18.1</version>
                        <configuration>
                            <images>
                                <image>
                                    <name>chuangg/gene_project1</name>
                                    <alias>${docker.container.name}</alias>
                                    <!-- Configure build settings -->
                                    <build>
                                        <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                        <assembly>
                                            <inline>
                                                <fileSets>
                                                    <fileSet>
                                                        <directory>${project.basedir}\target</directory>
                                                        <outputDirectory>.</outputDirectory>
                                                        <includes>
                                                            <include>*.jar</include>
                                                        </includes>
                                                    </fileSet>
                                                </fileSets>
                                            </inline>
                                        </assembly>
                                    </build>
                                </image>
                            </images>
                        </configuration>
                        <executions>
                            <execution>
                                <id>docker:build</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>build</goal>
                                </goals>
                            </execution>
                            <execution>
                                <id>docker:push</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>push</goal>
                                </goals>
                            </execution>

                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>
</project>

Go to C:\Users\Gene.docker\ directory and add this to your config.json file: enter image description here

Now in your Docker Quickstart Terminal type= mvn clean install -Pbuild-docker

For those of you not using Maven Profiles, just type mvn clean install

Here is the screenshot of the success message: enter image description here

Here is my full pom.xml and a screenshot of my directory structure:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.gene.app</groupId>
<artifactId>VendingMachineDockerMavenPlugin</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>
<url>www.gene.com</url>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.gene.sample.Customer_View</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>

                    <source>1.7</source>
                    <target>1.7</target>

                </configuration>
            </plugin>
        </plugins>
    </pluginManagement>
</build>


<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>

</dependencies>

<distributionManagement>
    <repository>
        <id>gene</id>
        <name>chuangg</name>
        <uniqueVersion>false</uniqueVersion>
        <layout>legacy</layout>
        <url>https://index.docker.io/v1/</url>
    </repository>
</distributionManagement>


<profiles>
    <profile>
        <id>build-docker</id>
        <properties>
            <java.docker.version>1.8.0</java.docker.version>
        </properties>
        <build>
            <plugins>

                <plugin>
                    <groupId>io.fabric8</groupId>
                    <artifactId>docker-maven-plugin</artifactId>
                    <version>0.18.1</version>
                    <configuration>
                        <images>
                            <image>
                                <name>chuangg/gene_project1</name>
                                <alias>${docker.container.name}</alias>
                                <!-- Configure build settings -->
                                <build>
                                    <dockerFileDir>${project.basedir}\src\docker\vending_machine_emulator</dockerFileDir>
                                    <assembly>
                                        <inline>
                                            <fileSets>
                                                <fileSet>
                                                    <directory>${project.basedir}\target</directory>
                                                    <outputDirectory>.</outputDirectory>
                                                    <includes>
                                                        <include>*.jar</include>
                                                    </includes>
                                                </fileSet>
                                            </fileSets>
                                        </inline>
                                    </assembly>
                                </build>
                            </image>
                        </images>
                    </configuration>
                    <executions>
                        <execution>
                            <id>docker:build</id>
                            <phase>package</phase>
                            <goals>
                                <goal>build</goal>
                            </goals>
                        </execution>
                        <execution>
                            <id>docker:push</id>
                            <phase>install</phase>
                            <goals>
                                <goal>push</goal>
                            </goals>
                        </execution>

                    </executions>
                </plugin>
            </plugins>
        </build>
    </profile>
</profiles>

Here is my Eclipse Directory: enter image description here

Here is my Dockerfile:

FROM java:8

MAINTAINER Gene Chuang
RUN echo Running Dockerfile in src/docker/vending_machine_emulator/Dockerfile directory

ADD maven/VendingMachineDockerMavenPlugin-1.0-SNAPSHOT.jar /bullshitDirectory/gene-app-1.0-SNAPSHOT.jar 

CMD ["java", "-classpath", "/bullshitDirectory/gene-app-1.0-SNAPSHOT.jar", "com/gene/sample/Customer_View" ] 

Common Error #1: enter image description here

Solution for Error #1= Do not sync the <execution> with maven deploy phase because then maven tries to deploy the image 2x and puts a timestamp on the jar. That’s why I used <phase>install</phase>.

What is the meaning of polyfills in HTML5?

First off let's clarify what a polyfil is not: A polyfill is not part of the HTML5 Standard. Nor is a polyfill limited to Javascript, even though you often see polyfills being referred to in those contexts.

The term polyfill itself refers to some code that "allows you to have some specific functionality that you expect in current or “modern” browsers to also work in other browsers that do not have the support for that functionality built in. "

Source and example of polyfill here:

http://www.programmerinterview.com/index.php/html5/html5-polyfill/

How to create a batch file to run cmd as administrator

Here's a more simple version of essentially the same file.

@echo off
break off
title C:\Windows\system32\cmd.exe
cls

:cmd
set /p cmd=C:\Enter Command:

%cmd%
echo.
goto cmd

How to remove last n characters from a string in Bash?

To remove four characters from the end of the string use ${var%????}.

To remove everything after the final . use ${var%.*}.

git: fatal: Could not read from remote repository

Make sure ssh-agent is running by executing the following command on your terminal:

eval $(ssh-agent -s)

Source: Github documentation

Create a asmx web service in C# using visual studio 2013

Check your namespaces. I had and issue with that. I found that out by adding another web service to the project to dup it like you did yours and noticed the namespace was different. I had renamed it at the beginning of the project and it looks like its persisted.

How do I sort arrays using vbscript?

Some old school array sorting. Of course this only sorts single dimension arrays.

'C:\DropBox\Automation\Libraries\Array.vbs

Option Explicit

Public Function Array_AdvancedBubbleSort(ByRef rarr_ArrayToSort(), ByVal rstr_SortOrder)
'   ==================================================================================
'   Date            : 12/09/1999
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Creates a sorted Array from a one dimensional array
'                       in Ascending (default) or Descending order based on the rstr_SortOrder.
'   Variables       :
'                   rarr_ArrayToSort()     The array to sort and return.
'                   rstr_SortOrder   The order to sort in, default ascending or D for descending.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_AdvancedBubbleSort"
    Dim bln_Sorted
    Dim lng_Loop_01
    Dim str_SortOrder
    Dim str_Temp

    bln_Sorted = False
    str_SortOrder = Left(UCase(rstr_SortOrder), 1) 'We only need to know if the sort order is A(SENC) or D(ESEND)...and for that matter we really only need to know if it's D because we are defaulting to Ascending.
    Do While (bln_Sorted = False)
       bln_Sorted = True
        str_Temp = ""
        If (str_SortOrder = "D") Then
            'Sort in descending order.
            For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)
                If (rarr_ArrayToSort(lng_Loop_01) < rarr_ArrayToSort(lng_Loop_01 + 1)) Then
                    bln_Sorted = False
                    str_Temp = rarr_ArrayToSort(lng_Loop_01)
                    rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)
                    rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp
                End If
                If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) > rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then
                    bln_Sorted = False
                    str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))
                    rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)
                    rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp
                End If
            Next
        Else
            'Default to Ascending.
            For lng_Loop_01 = LBound(rarr_ArrayToSort) To (UBound(rarr_ArrayToSort) - 1)
                If (rarr_ArrayToSort(lng_Loop_01) > rarr_ArrayToSort(lng_Loop_01 + 1)) Then
                    bln_Sorted = False
                    str_Temp = rarr_ArrayToSort(lng_Loop_01)
                    rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Loop_01 + 1)
                    rarr_ArrayToSort(lng_Loop_01 + 1) = str_Temp
                End If
                If (rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) < rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)) Then
                    bln_Sorted = False
                    str_Temp = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1))
                    rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - (lng_Loop_01 - 1)) = rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01)
                    rarr_ArrayToSort((UBound(rarr_ArrayToSort) - 1) - lng_Loop_01) = str_Temp
                End If
            Next
        End If
    Loop
End Function

Public Function Array_BubbleSort(ByRef rarr_ArrayToSort())
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_BubbleSort"
    Dim lng_Loop_01
    Dim lng_Loop_02
    Dim var_Temp

    For lng_Loop_01 = (UBound(rarr_ArrayToSort) - 1) To 0 Step -1
        For lng_Loop_02 = 0 To lng_Loop_01
            If rarr_ArrayToSort(lng_Loop_02) > rarr_ArrayToSort(lng_Loop_02 + 1) Then
                var_Temp = rarr_ArrayToSort(lng_Loop_02 + 1)
                rarr_ArrayToSort(lng_Loop_02 + 1) = rarr_ArrayToSort(lng_Loop_02)
                rarr_ArrayToSort(lng_Loop_02) = var_Temp
            End If
        Next
    Next
End Function

Public Function Array_GetDimensions(ByVal rarr_Array)
    Const const_FUNCTION_NAME = "Array_GetDimensions"
    Dim int_Dimensions
    Dim int_Result
    Dim str_Dimensions

    int_Result = 0
    If IsArray(rarr_Array) Then
        On Error Resume Next
        Do
            int_Dimensions = -2
            int_Dimensions = UBound(rarr_Array, int_Result + 1)
            If int_Dimensions > -2 Then
                int_Result = int_Result + 1
                If int_Result = 1 Then
                    str_Dimensions = str_Dimensions & int_Dimensions
                Else
                    str_Dimensions = str_Dimensions & ":" & int_Dimensions
                End If
            End If
        Loop Until int_Dimensions = -2
        On Error GoTo 0
    End If
    Array_GetDimensions = int_Result ' & ";" & str_Dimensions
End Function

Public Function Array_GetUniqueCombinations(ByVal rarr_Fields, ByRef robj_Combinations)
    Const const_FUNCTION_NAME = "Array_GetUniqueCombinations"
    Dim int_Element
    Dim str_Combination

    On Error Resume Next

    Array_GetUniqueCombinations = CBool(False)
    For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)
        str_Combination = rarr_Fields(int_Element)
        Call robj_Combinations.Add(robj_Combinations.Count & ":" & str_Combination, 0)
'        Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)
    Next 'int_Element
    For int_Element = LBound(rarr_Fields) To UBound(rarr_Fields)
        Call Array_GetUniqueCombinationsSub(rarr_Fields, robj_Combinations, int_Element)
    Next 'int_Element
    Array_GetUniqueCombinations = CBool(True)
End Function 'Array_GetUniqueCombinations

Public Function Array_GetUniqueCombinationsSub(ByVal rarr_Fields, ByRef robj_Combinations, ByRef rint_LBound)
    Const const_FUNCTION_NAME = "Array_GetUniqueCombinationsSub"
    Dim int_Element
    Dim str_Combination

    On Error Resume Next

    Array_GetUniqueCombinationsSub = CBool(False)
    str_Combination = rarr_Fields(rint_LBound)
    For int_Element = (rint_LBound + 1) To UBound(rarr_Fields)
        str_Combination = str_Combination & "," & rarr_Fields(int_Element)
        Call robj_Combinations.Add(robj_Combinations.Count & ":" & str_Combination, str_Combination)
    Next 'int_Element
    Array_GetUniqueCombinationsSub = CBool(True)
End Function 'Array_GetUniqueCombinationsSub

Public Function Array_HeapSort(ByRef rarr_ArrayToSort())
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_HeapSort"
    Dim lng_Loop_01
    Dim var_Temp
    Dim arr_Size

    arr_Size = UBound(rarr_ArrayToSort) + 1
    For lng_Loop_01 = ((arr_Size / 2) - 1) To 0 Step -1
        Call Array_SiftDown(rarr_ArrayToSort, lng_Loop_01, arr_Size)
    Next
    For lng_Loop_01 = (arr_Size - 1) To 1 Step -1
        var_Temp = rarr_ArrayToSort(0)
        rarr_ArrayToSort(0) = rarr_ArrayToSort(lng_Loop_01)
        rarr_ArrayToSort(lng_Loop_01) = var_Temp
        Call Array_SiftDown(rarr_ArrayToSort, 0, (lng_Loop_01 - 1))
    Next
End Function

Public Function Array_InsertionSort(ByRef rarr_ArrayToSort())
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_InsertionSort"
    Dim lng_ElementCount
    Dim lng_Loop_01
    Dim lng_Loop_02
    Dim lng_Index

    lng_ElementCount = UBound(rarr_ArrayToSort) + 1
    For lng_Loop_01 = 1 To (lng_ElementCount - 1)
        lng_Index = rarr_ArrayToSort(lng_Loop_01)
        lng_Loop_02 = lng_Loop_01
        Do While lng_Loop_02 > 0
            If rarr_ArrayToSort(lng_Loop_02 - 1) > lng_Index Then
                rarr_ArrayToSort(lng_Loop_02) = rarr_ArrayToSort(lng_Loop_02 - 1)
                lng_Loop_02 = (lng_Loop_02 - 1)
            End If
        Loop
        rarr_ArrayToSort(lng_Loop_02) = lng_Index
    Next
End Function

Private Function Array_Merge(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_Left, ByVal rlng_MiddleIndex, ByVal rlng_Right)
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Merges an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_Merge"
    Dim lng_Loop_01
    Dim lng_LeftEnd
    Dim lng_ElementCount
    Dim lng_TempPos

    lng_LeftEnd = (rlng_MiddleIndex - 1)
    lng_TempPos = rlng_Left
    lng_ElementCount = (rlng_Right - rlng_Left + 1)
    Do While (rlng_Left <= lng_LeftEnd) _
    And (rlng_MiddleIndex <= rlng_Right)
        If rarr_ArrayToSort(rlng_Left) <= rarr_ArrayToSort(rlng_MiddleIndex) Then
            rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)
            lng_TempPos = (lng_TempPos + 1)
            rlng_Left = (rlng_Left + 1)
        Else
            rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)
            lng_TempPos = (lng_TempPos + 1)
            rlng_MiddleIndex = (rlng_MiddleIndex + 1)
        End If
    Loop
    Do While rlng_Left <= lng_LeftEnd
        rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_Left)
        rlng_Left = (rlng_Left + 1)
        lng_TempPos = (lng_TempPos + 1)
    Loop
    Do While rlng_MiddleIndex <= rlng_Right
        rarr_ArrayTemp(lng_TempPos) = rarr_ArrayToSort(rlng_MiddleIndex)
        rlng_MiddleIndex = (rlng_MiddleIndex + 1)
        lng_TempPos = (lng_TempPos + 1)
    Loop
    For lng_Loop_01 = 0 To (lng_ElementCount - 1)
        rarr_ArrayToSort(rlng_Right) = rarr_ArrayTemp(rlng_Right)
        rlng_Right = (rlng_Right - 1)
    Next
End Function

Public Function Array_MergeSort(ByRef rarr_ArrayToSort(), ByRef rarr_ArrayTemp(), ByVal rlng_FirstIndex, ByVal rlng_LastIndex)
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   Note            :The rarr_ArrayTemp array that is passed in has to be dimensionalized to the same size
'                           as the rarr_ArrayToSort array that is passed in prior to calling the function.
'                           Also the rlng_FirstIndex variable should be the value of the LBound(rarr_ArrayToSort)
'                           and the rlng_LastIndex variable should be the value of the UBound(rarr_ArrayToSort)
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_MergeSort"
    Dim lng_MiddleIndex

    If rlng_LastIndex > rlng_FirstIndex Then
        ' Recursively sort the two halves of the list.
        lng_MiddleIndex = ((rlng_FirstIndex + rlng_LastIndex) / 2)
        Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex)
        Call Array_MergeSort(rarr_ArrayToSort, rarr_ArrayTemp, lng_MiddleIndex + 1, rlng_LastIndex)
        '  Merge the results.
        Call Array_Merge(rarr_ArrayToSort, rarr_ArrayTemp, rlng_FirstIndex, lng_MiddleIndex + 1, rlng_LastIndex)
    End If
End Function

Public Function Array_Push(ByRef rarr_Array, ByVal rstr_Value, ByVal rstr_Delimiter)
    Const const_FUNCTION_NAME = "Array_Push"
    Dim int_Loop
    Dim str_Array_01
    Dim str_Array_02

    'If there is no delimiter passed in then set the default delimiter equal to a comma.
    If rstr_Delimiter = "" Then
        rstr_Delimiter = ","
    End If

    'Check to see if the rarr_Array is actually an Array.
    If IsArray(rarr_Array) = True Then
        'Verify that the rarr_Array variable is only a one dimensional array.
        If Array_GetDimensions(rarr_Array) <> 1 Then
            Array_Push = "ERR, the rarr_Array variable passed in was not a one dimensional array."
            Exit Function
        End If
        If IsArray(rstr_Value) = True Then
            'Verify that the rstr_Value variable is is only a one dimensional array.
            If Array_GetDimensions(rstr_Value) <> 1 Then
                Array_Push = "ERR, the rstr_Value variable passed in was not a one dimensional array."
                Exit Function
            End If
            str_Array_01 = Split(rarr_Array, rstr_Delimiter)
            str_Array_02 = Split(rstr_Value, rstr_Delimiter)
            rarr_Array = Join(str_Array_01 & rstr_Delimiter & str_Array_02)
        Else
            On Error Resume Next
            ReDim Preserve rarr_Array(UBound(rarr_Array) + 1)
            If Err.Number <> 0 Then ' "Subscript out of range"  An array that was passed in must have been Erased to re-create it with new elements (possibly when passing an array to be populated into a recursive function)
                ReDim rarr_Array(0)
                Err.Clear
            End If
            If IsObject(rstr_Value) = True Then
                Set rarr_Array(UBound(rarr_Array)) = rstr_Value
            Else
                rarr_Array(UBound(rarr_Array)) = rstr_Value
            End If
        End If
    Else
        'Check to see if the rstr_Value is an Array.
        If IsArray(rstr_Value) = True Then
            'Verify that the rstr_Value variable is is only a one dimensional array.
            If Array_GetDimensions(rstr_Value) <> 1 Then
                Array_Push = "ERR, the rstr_Value variable passed in was not a one dimensional array."
                Exit Function
            End If
            rarr_Array = rstr_Value
        Else
            rarr_Array = Split(rstr_Value, rstr_Delimiter)
        End If
    End If
    Array_Push = UBound(rarr_Array)
End Function

Public Function Array_QuickSort(ByRef rarr_ArrayToSort(), ByVal rlng_Low, ByVal rlng_High)
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   Note            :The rlng_Low variable should be the value of the LBound(rarr_ArrayToSort)
'                           and the rlng_High variable should be the value of the UBound(rarr_ArrayToSort)
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_QuickSort"
    Dim var_Pivot
    Dim lng_Swap
    Dim lng_Low
    Dim lng_High

    lng_Low = rlng_Low
    lng_High = rlng_High
    var_Pivot = rarr_ArrayToSort((rlng_Low + rlng_High) / 2)
    Do While lng_Low <= lng_High
        Do While (rarr_ArrayToSort(lng_Low) < var_Pivot _
        And lng_Low < rlng_High)
            lng_Low = lng_Low + 1
        Loop
        Do While (var_Pivot < rarr_ArrayToSort(lng_High) _
        And lng_High > rlng_Low)
            lng_High = (lng_High - 1)
        Loop
        If lng_Low <= lng_High Then
            lng_Swap = rarr_ArrayToSort(lng_Low)
            rarr_ArrayToSort(lng_Low) = rarr_ArrayToSort(lng_High)
            rarr_ArrayToSort(lng_High) = lng_Swap
            lng_Low = (lng_Low + 1)
            lng_High = (lng_High - 1)
        End If
    Loop
    If rlng_Low < lng_High Then
        Call Array_QuickSort(rarr_ArrayToSort, rlng_Low, lng_High)
    End If
    If lng_Low < rlng_High Then
        Call Array_QuickSort(rarr_ArrayToSort, lng_Low, rlng_High)
    End If
End Function

Public Function Array_SelectionSort(ByRef rarr_ArrayToSort())
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_SelectionSort"
    Dim lng_ElementCount
    Dim lng_Loop_01
    Dim lng_Loop_02
    Dim lng_Min
    Dim var_Temp

    lng_ElementCount = UBound(rarr_ArrayToSort) + 1
    For lng_Loop_01 = 0 To (lng_ElementCount - 2)
        lng_Min = lng_Loop_01
        For lng_Loop_02 = (lng_Loop_01 + 1) To lng_ElementCount - 1
            If rarr_ArrayToSort(lng_Loop_02) < rarr_ArrayToSort(lng_Min) Then
            lng_Min = lng_Loop_02
            End If
        Next
        var_Temp = rarr_ArrayToSort(lng_Loop_01)
        rarr_ArrayToSort(lng_Loop_01) = rarr_ArrayToSort(lng_Min)
        rarr_ArrayToSort(lng_Min) = var_Temp
    Next
End Function

Public Function Array_ShellSort(ByRef rarr_ArrayToSort())
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sorts an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_ShellSort"
    Dim lng_Loop_01
    Dim var_Temp
    Dim lng_Hold
    Dim lng_HValue

    lng_HValue = LBound(rarr_ArrayToSort)
    Do
        lng_HValue = (3 * lng_HValue + 1)
    Loop Until lng_HValue > UBound(rarr_ArrayToSort)
    Do
        lng_HValue = (lng_HValue / 3)
        For lng_Loop_01 = (lng_HValue + LBound(rarr_ArrayToSort)) To UBound(rarr_ArrayToSort)
            var_Temp = rarr_ArrayToSort(lng_Loop_01)
            lng_Hold = lng_Loop_01
            Do While rarr_ArrayToSort(lng_Hold - lng_HValue) > var_Temp
                rarr_ArrayToSort(lng_Hold) = rarr_ArrayToSort(lng_Hold - lng_HValue)
                lng_Hold = (lng_Hold - lng_HValue)
                If lng_Hold < lng_HValue Then
                    Exit Do
                End If
            Loop
            rarr_ArrayToSort(lng_Hold) = var_Temp
        Next
    Loop Until lng_HValue = LBound(rarr_ArrayToSort)
End Function

Private Function Array_SiftDown(ByRef rarr_ArrayToSort(), ByVal rlng_Root, ByVal rlng_Bottom)
'   ==================================================================================
'   Date            : 03/18/2008
'   Author          : Christopher J. Scharer (CJS)
'   Description     : Sifts the elements down in an array.
'   ==================================================================================
    Const const_FUNCTION_NAME = "Array_SiftDown"
    Dim bln_Done
    Dim max_Child
    Dim var_Temp

    bln_Done = False
    Do While ((rlng_Root * 2) <= rlng_Bottom) _
    And bln_Done = False
        If rlng_Root * 2 = rlng_Bottom Then
            max_Child = (rlng_Root * 2)
        ElseIf rarr_ArrayToSort(rlng_Root * 2) > rarr_ArrayToSort(rlng_Root * 2 + 1) Then
            max_Child = (rlng_Root * 2)
        Else
            max_Child = (rlng_Root * 2 + 1)
        End If
        If rarr_ArrayToSort(rlng_Root) < rarr_ArrayToSort(max_Child) Then
            var_Temp = rarr_ArrayToSort(rlng_Root)
            rarr_ArrayToSort(rlng_Root) = rarr_ArrayToSort(max_Child)
            rarr_ArrayToSort(max_Child) = var_Temp
            rlng_Root = max_Child
        Else
            bln_Done = True
        End If
    Loop
End Function

Angular 2 select option (dropdown) - how to get the value on change so it can be used in a function?

Template/HTML File (component.ts)

<select>
 <option *ngFor="let v of values" [value]="v" (ngModelChange)="onChange($event)">  
    {{v.name}}
  </option>
</select>

Typescript File (component.ts)

values = [
  { id: 3432, name: "Recent" },
  { id: 3442, name: "Most Popular" },
  { id: 3352, name: "Rating" }
];

onChange(cityEvent){
    console.log(cityEvent); // It will display the select city data
}

(ngModelChange) is the @Output of the ngModel directive. It fires when the model changes. You cannot use this event without the ngModel directive

What is the difference between % and %% in a cmd file?

In DOS you couldn't use environment variables on the command line, only in batch files, where they used the % sign as a delimiter. If you wanted a literal % sign in a batch file, e.g. in an echo statement, you needed to double it.

This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your % signs in a .cmd file.

Remove new lines from string and replace with one empty space

Whats about:

$string = trim( str_replace( PHP_EOL, ' ', $string ) );

This should be a pretty robust solution because \n doesn't work correctly in all systems if i'm not wrong ...

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

CSS div 100% height

I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:

myDiv {
    min-height: 100%;
    overflow-y: hidden;
    position: relative;
}

That should do the job!

WampServer orange icon

After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.

Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)

link: http://bugs.mysql.com/bug.php?id=72533

Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.

Regards SB

Reading string by char till end of line C/C++

If you are using C function fgetc then you should check a next character whether it is equal to the new line character or to EOF. For example

unsigned int count = 0;
while ( 1 )
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
      if ( c == EOF ) break;
   }
   else
   {
      ++count;
   }
}    

or maybe it would be better to rewrite the code using do-while loop. For example

unsigned int count = 0;
do
{
   int c = fgetc( FileStream );

   if ( c == EOF || c == '\n' )
   {
      printF( "The length of the line is %u\n", count );
      count = 0;
   }
   else
   {
      ++count;
   }
} while ( c != EOF );

Of course you need to insert your own processing of read xgaracters. It is only an example how you could use function fgetc to read lines of a file.

But if the program is written in C++ then it would be much better if you would use std::ifstream and std::string classes and function std::getline to read a whole line.

Getting multiple values with scanf()

Yes.

int minx, miny, maxx,maxy;
do {
   printf("enter four integers: ");
} while (scanf("%d %d %d %d", &minx, &miny, &maxx, &maxy)!=4);

The loop is just to demonstrate that scanf returns the number of fields succesfully read (or EOF).

Euclidean distance of two vectors

Use the dist() function, but you need to form a matrix from the two inputs for the first argument to dist():

dist(rbind(x1, x2))

For the input in the OP's question we get:

> dist(rbind(x1, x2))
        x1
x2 7.94821

a single value that is the Euclidean distance between x1 and x2.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

unique object identifier in javascript

I've used code like this, which will cause Objects to stringify with unique strings:

Object.prototype.__defineGetter__('__id__', function () {
    var gid = 0;
    return function(){
        var id = gid++;
        this.__proto__ = {
             __proto__: this.__proto__,
             get __id__(){ return id }
        };
        return id;
    }
}.call() );

Object.prototype.toString = function () {
    return '[Object ' + this.__id__ + ']';
};

the __proto__ bits are to keep the __id__ getter from showing up in the object. this has been only tested in firefox.

Error to run Android Studio

On my Linux Mint 17.3 install, I found these instructions incredibly helpful.

The problem seems to boil down to the system's default Java being OpenJDK and Android Studio preferring Oracle's JDK. I actually did not perform the OpenJDK removal steps given in the tutorial, but only downloaded the Oracle JDK and set it as my system's default. Android Studio worked right away.

In case the linked page ever goes away, the steps I took were

Download Oracle JDK. Mine was version 1.7.0_79.

tar -zxvf jdk-7u79-linux-x64.tar.gz
sudo mkdir -p /opt/java
sudo mv jdk1.7.0_79 /opt/java
sudo update-alternatives --install "/usr/bin/java" "java" "/opt/java/jdk1.7.0_79/bin/java" 1
sudo update-alternatives --set java /opt/java/jdk1.7.0_25/bin/java

and

java -version

confirms the system is using Oracle's JDK, giving output like

java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

How to float 3 divs side by side using CSS?

Float all three divs to the left. Like here:

.first-div {
  width:370px;
  height:150px;
  float:left;
  background-color:pink;
}

.second-div {
  width:370px;
  height:150px;
  float:left;
  background-color:blue;
}

.third-div {
  width:370px;
  height:150px;
  float:left;
  background-color:purple;
}

Two submit buttons in one form

There’s a new HTML5 approach to this, the formaction attribute:

<button type="submit" formaction="/action_one">First action</button>
<button type="submit" formaction="/action_two">Second action</button>

Apparently this does not work in IE9 and earlier, but for other browsers you should be fine (see: w3schools.com HTML <button> formaction Attribute).

Personally, I generally use Javascript to submit forms remotely (for faster perceived feedback) with this approach as backup. Between the two, the only people not covered are IE<9 with Javascript disabled.

Of course, this may be inappropriate if you’re basically taking the same action server-side regardless of which button was pushed, but often if there are two user-side actions available then they will map to two server-side actions as well.

Edit: As noted by Pascal_dher in the comments, this attribute is also available on the <input> tag as well.

Counting inversions in an array

Implementation of counting inversions in an array with merge sort in Swift:

Note that the number of swaps is incremented by

nSwaps += mid + 1 - iL 

(which is the relative length of the left side of the array minus the index of the current element in the left side)

... because that is the number of elements which the element in the right side of the array had to skip over (# of inversions) to become sorted.

func merge(arr: inout [Int], arr2: inout [Int], low: Int, mid: Int, high: Int) -> Int {
    var nSwaps = 0;

    var i = low;
    var iL = low;
    var iR = mid + 1;

    while iL <= mid && iR <= high {
        if arr2[iL] <= arr2[iR] {
            arr[i] = arr2[iL]
            iL += 1
            i += 1
        } else {
            arr[i] = arr2[iR]
            nSwaps += mid + 1 - iL
            iR += 1
            i += 1
        }
    }

    while iL <= mid {
        arr[i] = arr2[iL]
        iL += 1
        i += 1
    }

    while iR <= high {
        arr[i] = arr2[iR]
        iR += 1
        i += 1
    }

    return nSwaps
}

func mergeSort(arr: inout [Int]) -> Int {
    var arr2 = arr
    let nSwaps = mergeSort(arr: &arr, arr2: &arr2, low: 0, high: arr.count-1)
    return nSwaps
}

func mergeSort(arr: inout [Int], arr2: inout [Int], low: Int, high: Int) -> Int {

    if low >= high {
        return 0
    }

    let mid = low + ((high - low) / 2)

    var nSwaps = 0;
    nSwaps += mergeSort(arr: &arr2, arr2: &arr, low: low, high: mid)
    nSwaps += mergeSort(arr: &arr2, arr2: &arr, low: mid+1, high: high)
    nSwaps += merge(arr: &arr, arr2: &arr2, low: low, mid: mid, high: high)

    return nSwaps
}

var arrayToSort: [Int] = [2, 1, 3, 1, 2]
let nSwaps = mergeSort(arr: &arrayToSort)

print(arrayToSort) // [1, 1, 2, 2, 3]
print(nSwaps) // 4

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

This is my solution, it is very similar to the previous one:

<dependency>
        <groupId>com.google.android</groupId>
        <artifactId>support-v7</artifactId>
        <scope>system</scope>
        <systemPath>${android.home}/support/v7/appcompat/libs/android-support-v7-appcompat.jar</systemPath>
        <version>19.0.1</version>
</dependency>

Where {android.home} is the root directory of the Android SDK and it uses systemPath instead of repository.

SQL to generate a list of numbers from 1 to 100

Using Oracle's sub query factory clause: "WITH", you can select numbers from 1 to 100:

WITH t(n) AS (
  SELECT 1 from dual
  UNION ALL
    SELECT n+1 FROM t WHERE n < 100
)
SELECT * FROM t;

What's the best way to build a string of delimited items in Java?

//Note: if you have access to Java5+, 
//use StringBuilder in preference to StringBuffer.  
//All that has to be replaced is the class name.  
//StringBuffer will work in Java 1.4, though.

appendWithDelimiter( StringBuffer buffer, String addition, 
    String delimiter ) {
    if ( buffer.length() == 0) {
        buffer.append(addition);
    } else {
        buffer.append(delimiter);
        buffer.append(addition);
    }
}


StringBuffer parameterBuffer = new StringBuffer();
if ( condition ) { 
    appendWithDelimiter(parameterBuffer, "elementName", "," );
}
if ( anotherCondition ) {
    appendWithDelimiter(parameterBuffer, "anotherElementName", "," );
}

//Finally, to return a string representation, call toString() when returning.
return parameterBuffer.toString(); 

How to install Flask on Windows?

First install flask using pip,

pip install Flask

* If pip is not installed then install pip

Then copy below program (hello.py)

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()

Now, run the program

python hello.py

Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Just copy paste the above address line in your browser.

Reference: http://flask.pocoo.org/

.trim() in JavaScript not working in IE

Add the following code to add trim functionality to the string.

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

How do I solve this "Cannot read property 'appendChild' of null" error?

For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.

<html>
    <head>
        <script>
                var div, container = document.getElementById("container")
                for(var i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>

    </head>
    <body>
        <div id="container"></div>
    </body>
 </html>

https://codepen.io/pcwanderer/pen/MMEREr

Looking at the error in the console for the above code.

Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.

<html>
    <head>
        <style>
        #container{
            height: 200px;
            width: 700px;
            background-color: red;
            margin: 10px;
        }


        div{
            height: 100px;
            width: 100px;
            background-color: purple;
            margin: 20px;
            display: inline-block;
        }
        </style>
    </head>
    <body>
        <div id="container"></div>
        <script>
                var div, container = document.getElementById("container")
                for(let i=0;i<5;i++){
                    div = document.createElement("div");
                    div.onclick = function() { 
                        alert("This is a box #"+i);
                    };
                    container.appendChild(div);
                }
            </script>
    </body>
</html>

https://codepen.io/pcwanderer/pen/pXWBQL

I hope this helps. :)

Python unittest - opposite of assertRaises?

I've found it useful to monkey-patch unittest as follows:

def assertMayRaise(self, exception, expr):
  if exception is None:
    try:
      expr()
    except:
      info = sys.exc_info()
      self.fail('%s raised' % repr(info[0]))
  else:
    self.assertRaises(exception, expr)

unittest.TestCase.assertMayRaise = assertMayRaise

This clarifies intent when testing for the absence of an exception:

self.assertMayRaise(None, does_not_raise)

This also simplifies testing in a loop, which I often find myself doing:

# ValueError is raised only for op(x,x), op(y,y) and op(z,z).
for i,(a,b) in enumerate(itertools.product([x,y,z], [x,y,z])):
  self.assertMayRaise(None if i%4 else ValueError, lambda: op(a, b))

How to put a tooltip on a user-defined function

Unfortunately there is no way to add Tooltips for UDF Arguments.
To extend Remou's reply you can find a fuller but more complex approach to descriptions for the Function Wizard at
http://www.jkp-ads.com/Articles/RegisterUDF00.asp

Restrict SQL Server Login access to only one database

I think this is what we like to do very much.

--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;


-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello; 


 -- step 3 (then authorized the user for that specific database , you have to use the  master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO

If you already created a user and assigned to that database before by doing

USE [yourDB] 
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo] 
GO

then kindly delete it by doing below and follow the steps

   USE yourDB;
   GO
   DROP USER newlogin;
   GO

For more information please follow the links:

Hiding databases for a login on Microsoft Sql Server 2008R2 and above

How to combine class and ID in CSS selector?

There are differences between #header .callout and #header.callout in css.

Here is the "plain English" of #header .callout:
Select all elements with the class name callout that are descendants of the element with an ID of header.

And #header.callout means:
Select the element which has an ID of header and also a class name of callout.

You can read more here css tricks

How do I convert Long to byte[] and back in java

Kotlin extensions for Long and ByteArray types:

fun Long.toByteArray() = numberToByteArray(Long.SIZE_BYTES) { putLong(this@toByteArray) }

private inline fun numberToByteArray(size: Int, bufferFun: ByteBuffer.() -> ByteBuffer): ByteArray =
    ByteBuffer.allocate(size).bufferFun().array()

@Throws(NumberFormatException::class)
fun ByteArray.toLong(): Long = toNumeric(Long.SIZE_BYTES) { long }

@Throws(NumberFormatException::class)
private inline fun <reified T: Number> ByteArray.toNumeric(size: Int, bufferFun: ByteBuffer.() -> T): T {
    if (this.size != size) throw NumberFormatException("${T::class.java.simpleName} value must contains $size bytes")

    return ByteBuffer.wrap(this).bufferFun()
}

You can see full code in my library https://github.com/ArtemBotnev/low-level-extensions

How do I clear a search box with an 'x' in bootstrap 3?

Thanks unwired your solution was very clean. I was using horizontal bootstrap forms and made a couple modifications to allow for a single handler and form css.

html: - UPDATED to use Bootstrap's has-feedback and form-control-feedback

 <div class="container">
  <form class="form-horizontal">
   <div class="form-group has-feedback">
    <label for="txt1" class="col-sm-2 control-label">Label 1</label>
    <div class="col-sm-10">
     <input id="txt1" type="text" class="form-control hasclear" placeholder="Textbox 1">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt2" class="col-sm-2 control-label">Label 2</label>
    <div class="col-sm-10">
      <input id="txt2" type="text" class="form-control hasclear" placeholder="Textbox 2">
      <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>
   </div>
   <div class="form-group has-feedback">
    <label for="txt3" class="col-sm-2 control-label">Label 3</label>
    <div class="col-sm-10">
     <input id="txt3" type="text" class="form-control hasclear" placeholder="Textbox 3">
     <span class="clearer glyphicon glyphicon-remove-circle form-control-feedback"></span>
    </div>   
   </div>
  </form>
 </div>

javascript:

$(".hasclear").keyup(function () {
    var t = $(this);
    t.next('span').toggle(Boolean(t.val()));
});
$(".clearer").hide($(this).prev('input').val());
$(".clearer").click(function () {
    $(this).prev('input').val('').focus();
    $(this).hide();
});

example: http://www.bootply.com/130682

How to bundle vendor scripts separately and require them as needed with Webpack?

Also not sure if I fully understand your case, but here is config snippet to create separate vendor chunks for each of your bundles:

entry: {
  bundle1: './build/bundles/bundle1.js',
  bundle2: './build/bundles/bundle2.js',
  'vendor-bundle1': [
    'react',
    'react-router'
  ],
  'vendor-bundle2': [
    'react',
    'react-router',
    'flummox',
    'immutable'
  ]
},

plugins: [
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle1',
    chunks: ['bundle1'],
    filename: 'vendor-bundle1.js',
    minChunks: Infinity
  }),
  new webpack.optimize.CommonsChunkPlugin({
    name: 'vendor-bundle2',
    chunks: ['bundle2'],
    filename: 'vendor-bundle2-whatever.js',
    minChunks: Infinity
  }),
]

And link to CommonsChunkPlugin docs: http://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin

INNER JOIN same table

Your query should work fine, but you have to use the alias parent to show the values of the parent table like this:

select 
  CONCAT(user.user_fname, ' ', user.user_lname) AS 'User Name',
  CONCAT(parent.user_fname, ' ', parent.user_lname) AS 'Parent Name'
from users as user
inner join users as parent on parent.user_parent_id = user.user_id
where user.user_id = $_GET[id];

Handling click events on a drawable within an EditText

Here's my simple solution, just place ImageButton over EditText:

<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content">

  <EditText android:id="@+id/editTextName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionSearch"
    android:inputType="text"/>

  <ImageButton android:id="@+id/imageViewSearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_action_search"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"/>

</RelativeLayout>

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

How to delete a folder in C++?

Delete folder (sub_folders and files) in Windows (VisualC++) not using Shell APIs, this is the best working sample:

#include <string>
#include <iostream>

#include <windows.h>
#include <conio.h>


int DeleteDirectory(const std::string &refcstrRootDirectory,
                    bool              bDeleteSubdirectories = true)
{
  bool            bSubdirectory = false;       // Flag, indicating whether
                                               // subdirectories have been found
  HANDLE          hFile;                       // Handle to directory
  std::string     strFilePath;                 // Filepath
  std::string     strPattern;                  // Pattern
  WIN32_FIND_DATA FileInformation;             // File information


  strPattern = refcstrRootDirectory + "\\*.*";
  hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
  if(hFile != INVALID_HANDLE_VALUE)
  {
    do
    {
      if(FileInformation.cFileName[0] != '.')
      {
        strFilePath.erase();
        strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;

        if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        {
          if(bDeleteSubdirectories)
          {
            // Delete subdirectory
            int iRC = DeleteDirectory(strFilePath, bDeleteSubdirectories);
            if(iRC)
              return iRC;
          }
          else
            bSubdirectory = true;
        }
        else
        {
          // Set file attributes
          if(::SetFileAttributes(strFilePath.c_str(),
                                 FILE_ATTRIBUTE_NORMAL) == FALSE)
            return ::GetLastError();

          // Delete file
          if(::DeleteFile(strFilePath.c_str()) == FALSE)
            return ::GetLastError();
        }
      }
    } while(::FindNextFile(hFile, &FileInformation) == TRUE);

    // Close handle
    ::FindClose(hFile);

    DWORD dwError = ::GetLastError();
    if(dwError != ERROR_NO_MORE_FILES)
      return dwError;
    else
    {
      if(!bSubdirectory)
      {
        // Set directory attributes
        if(::SetFileAttributes(refcstrRootDirectory.c_str(),
                               FILE_ATTRIBUTE_NORMAL) == FALSE)
          return ::GetLastError();

        // Delete directory
        if(::RemoveDirectory(refcstrRootDirectory.c_str()) == FALSE)
          return ::GetLastError();
      }
    }
  }

  return 0;
}


int main()
{
  int         iRC                  = 0;
  std::string strDirectoryToDelete = "c:\\mydir";


  // Delete 'c:\mydir' without deleting the subdirectories
  iRC = DeleteDirectory(strDirectoryToDelete, false);
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

  // Delete 'c:\mydir' and its subdirectories
  iRC = DeleteDirectory(strDirectoryToDelete);
  if(iRC)
  {
    std::cout << "Error " << iRC << std::endl;
    return -1;
  }

  // Wait for keystroke
  _getch();

  return 0;
}

Source: http://www.codeguru.com/forum/showthread.php?t=239271

How to find the minimum value of a column in R?

Since it is a numeric operation, we should be converting it to numeric form first. This operation cannot take place if the data is in factor data type.
Check the data type of the columns using str().

min(as.numeric(data[,2]))

Where are static variables stored in C and C++?

The answer might very well depend on the compiler, so you probably want to edit your question (I mean, even the notion of segments is not mandated by ISO C nor ISO C++). For instance, on Windows an executable doesn't carry symbol names. One 'foo' would be offset 0x100, the other perhaps 0x2B0, and code from both translation units is compiled knowing the offsets for "their" foo.

HttpWebRequest using Basic authentication

For those using RestSharp, it might fail when using SimpleAuthenticator (possibly due to not using ISO-8859-1 behind the scene). I managed to get it done by explicitly sending Basic Authentication headers:

string username = "...";
string password = "...";

public IRestResponse GetResponse(string url, Method method = Method.GET)
{
    string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"));
    var client = new RestClient(url);
    var request = new RestRequest(method );
    request.AddHeader("Authorization", $"Basic {encoded}");
    IRestResponse response = client.Execute(request);
    return response;
}

var response = GetResponse(url);
txtResult.Text = response.Content;

Increment a database field by 1

You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column

create table logins (userid int auto_increment primary key, 
  username varchar(30), password varchar(30));

then no special code is needed on insert. Just

insert into logins (username, password) values ('user','pass');

The MySQL API has functions to tell you what userid was created when you execute this statement in client code.

Java heap terminology: young, old and permanent generations?

The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

Safely remove migration In Laravel

 php artisan migrate:fresh

Should do the job, if you are in development and the desired outcome is to start all over.

In production, that maybe not the desired thing, so you should be adverted. (The migrate:fresh command will drop all tables from the database and then execute the migrate command).

c# replace \" characters

Try it like this:

Replace("\\\"","");

This will replace occurrences of \" with empty string.

Ex:

string t = "\\\"the dog is my friend\\\"";
t = t.Replace("\\\"","");

This will result in:

the dog is my friend

SELECT INTO a table variable in T-SQL

You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:

WITH userData (name, oldlocation)
AS
(
  SELECT name, location 
  FROM   myTable    INNER JOIN 
         otherTable ON ...
  WHERE  age>30
)
SELECT * 
FROM   userData -- you can also reuse the recordset in subqueries and joins

IntelliJ does not show project folders

I have that little while earlier and solved it by following the steps provided below:

a. Right-click on the `External Libraries` and select the `Load/ Unload modules` button

enter image description here

b. If you see the modules are already loaded, perform the load/unload again. 

enter image description here

After I have done that, I see the project again in the top of the External Libraries section. I use Linux machine, BTW

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

Unioning two tables with different number of columns

if only 1 row, you can use join

Select t1.Col1, t1.Col2, t1.Col3, t2.Col4, t2.Col5 from Table1 t1 join Table2 t2;

getting "No column was specified for column 2 of 'd'" in sql server cte?

I had a similar query and a similar issue.

SELECT
    *
FROM
    Users ru
    LEFT OUTER JOIN 
    (
        SELECT ru1.UserID, COUNT(*)
        FROM Referral r
        LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
        GROUP BY ru1.UserID
    ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

I found that SQL Server was choking on the COUNT(*) column, and was giving me the error No column was specified for column 2.

Putting an alias on the COUNT(*) column fixed the issue.

  SELECT
        *
    FROM
        Users ru
        LEFT OUTER JOIN 
        (
            SELECT ru1.UserID, COUNT(*) AS -->MyCount<--
            FROM Referral r
            LEFT OUTER JOIN Users ru1 ON r.ReferredUserId = ru1.UserID
            GROUP BY ru1.UserID
        ) ReferralTotalCount ON ru.UserID = ReferralTotalCount.UserID

How to find if directory exists in Python

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Alternatively, you can use pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Read a variable in bash with a default value

Code:

IN_PATH_DEFAULT="/tmp/input.txt"
read -p "Please enter IN_PATH [$IN_PATH_DEFAULT]: " IN_PATH
IN_PATH="${IN_PATH:-$IN_PATH_DEFAULT}"

OUT_PATH_DEFAULT="/tmp/output.txt"
read -p "Please enter OUT_PATH [$OUT_PATH_DEFAULT]: " OUT_PATH
OUT_PATH="${OUT_PATH:-$OUT_PATH_DEFAULT}"

echo "Input: $IN_PATH Output: $OUT_PATH"

Sample run:

Please enter IN_PATH [/tmp/input.txt]: 
Please enter OUT_PATH [/tmp/output.txt]: ~/out.txt
Input: /tmp/input.txt Output: ~/out.txt

LINQ Using Max() to select a single row

More one example:

Follow:

 qryAux = (from q in qryAux where
            q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
            == q.FieldPk select pp.OrdSeq).Max() select q);

Equals:

 select t.*   from nametable t  where t.OrdSeq =
        (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

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

Take This as an alternate to startActivityforResult.But keep in mind that for such cases this approach can be expensive in terms of performance but in some cases you might need to use.

In Activity2,

@Override
public void onBackPressed() {
String data = mEditText.getText();
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
Editor editor = sp.edit();
editor.putString("email",data);
editor.commit();
}

In Activity1,

 @Override
public void onResume() {
SharedPreferences sp = getSharedPreferences("LoginInfos", 0);
String  dataFromOtherAct= sp.getString("email", "no email");
} 

What is the best way to paginate results in SQL Server

This is a duplicate of the 2012 old SO question: efficient way to implement paging

FROM [TableX] ORDER BY [FieldX] OFFSET 500 ROWS FETCH NEXT 100 ROWS ONLY

Here the topic is discussed in greater details, and with alternate approaches.

How can I measure the actual memory usage of an application or process?

While this question seems to be about examining currently running processes, I wanted to see the peak memory used by an application from start to finish. Besides Valgrind, you can use tstime, which is much simpler. It measures the "highwater" memory usage (RSS and virtual). From this answer.

Is it possible to pass parameters programmatically in a Microsoft Access update query?

You can also use TempVars - note '!' syntax is essential You can also use TempVars - note '!' syntax is essential

Importing the private-key/public-certificate pair in the Java KeyStore

A keystore needs a keystore file. The KeyStore class needs a FileInputStream. But if you supply null (instead of FileInputStream instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool.

Following code creates an empty keystore with empty password

  KeyStore ks2 = KeyStore.getInstance("jks");
  ks2.load(null,"".toCharArray());
  FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore");
  ks2.store(out, "".toCharArray());

Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

Printing prime numbers from 1 through 100

Finding primes up to a 100 is especially nice and easy:

    printf("2 3 ");                        // first two primes are 2 and 3
    int m5 = 25, m7 = 49, i = 5, d = 4;
    for( ; i < 25; i += (d=6-d) )
    {
        printf("%d ", i);                  // all 6-coprimes below 5*5 are prime
    }
    for( ; i < 49; i += (d=6-d) )
    {
        if( i != m5) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            // no multiples of 5 below 7*7 allowed!
    }
    for( ; i < 100; i += (d=6-d) )         // from 49 to 100,
    {
        if( i != m5 && i != m7) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            //   sieve by multiples of 5,
        if( m7 <= i ) m7 += 14;            //                       and 7, too
    }

The square root of 100 is 10, and so this rendition of the sieve of Eratosthenes with the 2-3 wheel uses the multiples of just the primes above 3 that are not greater than 10 -- viz. 5 and 7 alone! -- to sieve the 6-coprimes below 100 in an incremental fashion.

How to transfer some data to another Fragment?

To extend the previous answer even more, like Ankit was saying, for complex objects you need to implement Serializable. For example, for the simple object:

public class MyClass implements Serializable {
    private static final long serialVersionUID = -2163051469151804394L;
    private int id;
    private String created;
}

In you FromFragment:

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment toFragment = new ToFragment();
toFragment.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.body, toFragment, TAG_TO_FRAGMENT)
    .addToBackStack(TAG_TO_FRAGMENT).commit();

in your ToFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    Bundle args = getArguments();
    MyClass myClass = (MyClass) args
        .getSerializable(TAG_MY_CLASS);

How to implement Rate It feature in Android App

My one using DialogFragment:

public class RateItDialogFragment extends DialogFragment {
    private static final int LAUNCHES_UNTIL_PROMPT = 10;
    private static final int DAYS_UNTIL_PROMPT = 3;
    private static final int MILLIS_UNTIL_PROMPT = DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000;
    private static final String PREF_NAME = "APP_RATER";
    private static final String LAST_PROMPT = "LAST_PROMPT";
    private static final String LAUNCHES = "LAUNCHES";
    private static final String DISABLED = "DISABLED";

    public static void show(Context context, FragmentManager fragmentManager) {
        boolean shouldShow = false;
        SharedPreferences sharedPreferences = getSharedPreferences(context);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        long currentTime = System.currentTimeMillis();
        long lastPromptTime = sharedPreferences.getLong(LAST_PROMPT, 0);
        if (lastPromptTime == 0) {
            lastPromptTime = currentTime;
            editor.putLong(LAST_PROMPT, lastPromptTime);
        }

        if (!sharedPreferences.getBoolean(DISABLED, false)) {
            int launches = sharedPreferences.getInt(LAUNCHES, 0) + 1;
            if (launches > LAUNCHES_UNTIL_PROMPT) {
                if (currentTime > lastPromptTime + MILLIS_UNTIL_PROMPT) {
                    shouldShow = true;
                }
            }
            editor.putInt(LAUNCHES, launches);
        }

        if (shouldShow) {
            editor.putInt(LAUNCHES, 0).putLong(LAST_PROMPT, System.currentTimeMillis()).commit();
            new RateItDialogFragment().show(fragmentManager, null);
        } else {
            editor.commit();
        }
    }

    private static SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, 0);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
                .setTitle(R.string.rate_title)
                .setMessage(R.string.rate_message)
                .setPositiveButton(R.string.rate_positive, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getActivity().getPackageName())));
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                })
                .setNeutralButton(R.string.rate_remind_later, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dismiss();
                    }
                })
                .setNegativeButton(R.string.rate_never, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSharedPreferences(getActivity()).edit().putBoolean(DISABLED, true).commit();
                        dismiss();
                    }
                }).create();
    }
}

Then use it in onCreate() of your main FragmentActivity:

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

    RateItDialogFragment.show(this, getFragmentManager());

}

ldap_bind: Invalid Credentials (49)

I don't see an obvious problem with the above.

It's possible your ldap.conf is being overridden, but the command-line options will take precedence, ldapsearch will ignore BINDDN in the main ldap.conf, so the only parameter that could be wrong is the URI. (The order is ETCDIR/ldap.conf then ~/ldaprc or ~/.ldaprc and then ldaprc in the current directory, though there environment variables which can influence this too, see man ldapconf.)

Try an explicit URI:

ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost

or prevent defaults with:

LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd binary for these):

  • make sure your slapd.conf is being used and is correct (as root)

    slapd -T test -f slapd.conf -d 65535

    You may have a left-over or default slapd.d configuration directory which takes preference over your slapd.conf (unless you specify your config explicitly with -f, slapd.conf is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.

  • stop OpenLDAP, then manually start slapd in a separate terminal/console with debug enabled (as root, ^C to quit)

    slapd -h ldap://localhost -d 481

    then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd without the -u/-g options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap )

  • if debug is enabled, then try also

    ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base

php.ini: which one?

Generally speaking, the cli/php.ini file is used when the PHP binary is called from the command-line.
You can check that running php --ini from the command-line.

fpm/php.ini will be used when PHP is run as FPM -- which is the case with an nginx installation.
And you can check that calling phpinfo() from a php page served by your webserver.

cgi/php.ini, in your situation, will most likely not be used.


Using two distinct php.ini files (one for CLI, and the other one to serve pages from your webserver) is done quite often, and has one main advantages : it allows you to have different configuration values in each case.

Typically, in the php.ini file that's used by the web-server, you'll specify a rather short max_execution_time : web pages should be served fast, and if a page needs more than a few dozen seconds (30 seconds, by default), it's probably because of a bug -- and the page's generation should be stopped.
On the other hand, you can have pretty long scripts launched from your crontab (or by hand), which means the php.ini file that will be used is the one in cli/. For those scripts, you'll specify a much longer max_execution_time in cli/php.ini than you did in fpm/php.ini.

max_execution_time is a common example ; you could do the same with several other configuration directives, of course.

can we use xpath with BeautifulSoup?

Maybe you can try the following without XPath

from simplified_scrapy.simplified_doc import SimplifiedDoc 
html = '''
<html>
<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
'''
# What XPath can do, so can it
doc = SimplifiedDoc(html)
# The result is the same as doc.getElementByTag('body').getElementByTag('div').getElementByTag('h1').text
print (doc.body.div.h1.text)
print (doc.div.h1.text)
print (doc.h1.text) # Shorter paths will be faster
print (doc.div.getChildren())
print (doc.div.getChildren('p'))

What does "request for member '*******' in something not a structure or union" mean?

It may also happen in the following case:

eg. if we consider the push function of a stack:

typedef struct stack
{
    int a[20];
    int head;
}stack;

void push(stack **s)
{
    int data;
    printf("Enter data:");
    scanf("%d",&(*s->a[++*s->head])); /* this is where the error is*/
}

main()
{
    stack *s;
    s=(stack *)calloc(1,sizeof(stack));
    s->head=-1;
    push(&s);
    return 0;
}

The error is in the push function and in the commented line. The pointer s has to be included within the parentheses. The correct code:

scanf("%d",&( (*s)->a[++(*s)->head]));

WCF timeout exception detailed investigation

Looks like this exception message is quite generic and can be received due to a variety of reasons. We ran into this while deploying the client on Windows 8.1 machines. Our WCF client runs inside of a windows service and continuously polls the WCF service. The windows service runs under a non-admin user. The issue was fixed by setting the clientCredentialType to "Windows" in the WCF configuration to allow the authentication to pass-through, as in the following:

      <security mode="None">
        <transport clientCredentialType="Windows" proxyCredentialType="None"
          realm="" />
        <message clientCredentialType="UserName" algorithmSuite="Default" />
      </security>

How to Generate Unique Public and Private Key via RSA

What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:

public static string ConvertToNewKey(string oldPrivateKey)
{

    // get the current container name from the database...

    rsa.PersistKeyInCsp = false;
    rsa.Clear();
    rsa = null;

    string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...

       // re-encrypt existing data to use the new keys and write to database...

    return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
     string containerName = DateTime.Now.Ticks.ToString();
     // create the new key...
     // saves container name and public key to database...
     // and returns Private Key XML.
}

before creating the new key.

How to give spacing between buttons using bootstrap

You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1 set the margin or padding to $spacer * .25.

Example:

<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>

You can read more at Bootstrap Spacing.

Tricks to manage the available memory in an R session

You also can get some benefit using knitr and puting your script in Rmd chuncks.

I usually divide the code in different chunks and select which one will save a checkpoint to cache or to a RDS file, and

Over there you can set a chunk to be saved to "cache", or you can decide to run or not a particular chunk. In this way, in a first run you can process only "part 1", another execution you can select only "part 2", etc.

Example:

part1
```{r corpus, warning=FALSE, cache=TRUE, message=FALSE, eval=TRUE}
corpusTw <- corpus(twitter)  # build the corpus
```
part2
```{r trigrams, warning=FALSE, cache=TRUE, message=FALSE, eval=FALSE}
dfmTw <- dfm(corpusTw, verbose=TRUE, removeTwitter=TRUE, ngrams=3)
```

As a side effect, this also could save you some headaches in terms of reproducibility :)

InvalidKeyException : Illegal Key Size - Java code throwing exception for encryption class - how to fix?

So the problem must be with your JCE Unlimited Strength installation.

Be sure you overwrite the local_policy.jar and US_export_policy.jar in both your JDK's jdk1.6.0_25\jre\lib\security\ and in your JRE's lib\security\ folder.

In my case I would place the new .jars in:

C:\Program Files\Java\jdk1.6.0_25\jre\lib\security

and

C:\Program Files\Java\jre6\lib\security


If you are running Java 8 and you encounter this issue. Below steps should help!

Go to your JRE installation (e.g - jre1.8.0_181\lib\security\policy\unlimited) copy local_policy.jar and replace it with 'local_policy.jar' in your JDK installation directory (e.g - jdk1.8.0_141\jre\lib\security).

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

Error happens in your function declarations,look the following sentence!You need a semicolon!


AST_NODE* Statement(AST_NODE* node)

How to pass a variable from Activity to Fragment, and pass it back?

Sending data from Activity to a Fragment

Activity:

Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();

Fragment:

Reading the value in fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    String myValue = this.getArguments().getString("message");
    ...
    ...
    ...
}

But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments

How to add a default "Select" option to this ASP.NET DropDownList control?

If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.

chai test array equality doesn't work as expected

You can use .deepEqual()

const { assert } = require('chai');

assert.deepEqual([0,0], [0,0]);

Redirect all output to file in Bash

Credits to osexp2003 and j.a. …


Instead of putting:

&>> your_file.log

behind a line in:

crontab -e

I use:

#!/bin/bash
exec &>> your_file.log
…

at the beginning of a BASH script.

Advantage: You have the log definitions within your script. Good for Git etc.

SQLite select where empty?

Maybe you mean

select x
from some_table
where some_column is null or some_column = ''

but I can't tell since you didn't really ask a question.

Difference between res.send and res.json in Express.js

Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json

edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.

Python: how can I check whether an object is of type datetime.date?

In Python 3.5, isinstance(x, date) works to me:

>>> from datetime import date
>>> x = date(2012, 9, 1)
>>> type(x)
<class 'datetime.date'>
>>> isinstance(x, date)
True
>>> type(x) is date
True

Why is json_encode adding backslashes?

I just came across this issue in some of my scripts too, and it seemed to be happening because I was applying json_encode to an array wrapped inside another array which was also json encoded. It's easy to do if you have multiple foreach loops in a script that creates the data. Always apply json_encode at the end.

Here is what was happening. If you do:

$data[] = json_encode(['test' => 'one', 'test' => '2']);
$data[] = json_encode(['test' => 'two', 'test' => 'four']);
echo json_encode($data);

The result is:

["{\"test\":\"2\"}","{\"test\":\"four\"}"]

So, what you actually need to do is:

$data[] = ['test' => 'one', 'test' => '2'];
$data[] = ['test' => 'two', 'test' => 'four'];
echo json_encode($data);

And this will return

[{"test":"2"},{"test":"four"}]

val() doesn't trigger change() in jQuery

No you might need to trigger it manually after setting the value:

$('#mytext').change();

or:

$('#mytext').trigger('change');

Attaching click event to a JQuery object not yet added to the DOM

Complement of information for those people who use .on() to listen to events bound on inputs inside lately loaded table cells; I managed to bind event handlers to such table cells by using delegate(), but .on() wouldn't work.

I bound the table id to .delegate() and used a selector that describes the inputs.

e.g.

HTML

<table id="#mytable">
  <!-- These three lines below were loaded post-DOM creation time, using a live callback for example -->
  <tr><td><input name="qty_001" /></td></tr>
  <tr><td><input name="qty_002" /></td></tr>
  <tr><td><input name="qty_003" /></td></tr>
</table>

jQuery

$('#mytable').delegate('click', 'name^=["qty_"]', function() {
    console.log("you clicked cell #" . $(this).attr("name"));
});

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to make 'submit' button disabled?

May be below code can help:

<button type="submit" [attr.disabled]="!ngForm.valid ? true : null">Submit</button>

Fastest JavaScript summation

You should be able to use reduce.

var sum = array.reduce(function(pv, cv) { return pv + cv; }, 0);

Source

And with arrow functions introduced in ES6, it's even simpler:

sum = array.reduce((pv, cv) => pv + cv, 0);

Implement an input with a mask

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

_x000D_
_x000D_
Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);_x000D_
_x000D_
function applyDataMask(field) {_x000D_
    var mask = field.dataset.mask.split('');_x000D_
    _x000D_
    // For now, this just strips everything that's not a number_x000D_
    function stripMask(maskedData) {_x000D_
        function isDigit(char) {_x000D_
            return /\d/.test(char);_x000D_
        }_x000D_
        return maskedData.split('').filter(isDigit);_x000D_
    }_x000D_
    _x000D_
    // Replace `_` characters with characters from `data`_x000D_
    function applyMask(data) {_x000D_
        return mask.map(function(char) {_x000D_
            if (char != '_') return char;_x000D_
            if (data.length == 0) return char;_x000D_
            return data.shift();_x000D_
        }).join('')_x000D_
    }_x000D_
    _x000D_
    function reapplyMask(data) {_x000D_
        return applyMask(stripMask(data));_x000D_
    }_x000D_
    _x000D_
    function changed() {   _x000D_
        var oldStart = field.selectionStart;_x000D_
        var oldEnd = field.selectionEnd;_x000D_
        _x000D_
        field.value = reapplyMask(field.value);_x000D_
        _x000D_
        field.selectionStart = oldStart;_x000D_
        field.selectionEnd = oldEnd;_x000D_
    }_x000D_
    _x000D_
    field.addEventListener('click', changed)_x000D_
    field.addEventListener('keyup', changed)_x000D_
}
_x000D_
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>_x000D_
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>
_x000D_
_x000D_
_x000D_

(View in JSFiddle)

There are also a number of libraries out there which perform this function. Some examples include:

Is an entity body allowed for an HTTP DELETE request?

It appears to me that RFC 2616 does not specify this.

From section 4.3:

The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests. A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

And section 9.7:

The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.

If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.c

So it's not explicitly allowed or disallowed, and there's a chance that a proxy along the way might remove the message body (although it SHOULD read and forward it).

Angular 5, HTML, boolean on checkbox is checked

You can use this:

<input type="checkbox" [checked]="record.status" (change)="changeStatus(record.id,$event)">

Here, record is the model for current row and status is boolean value.

Get selected option from select element

To know number of selected elements use

$("select option:selected").length

To Get the value of all selected elements use

    var str = "";
  $("select option:selected").each(function () {
        str += $(this).text() + " ";
      });

nodejs npm global config missing on windows

For me (being on Windows 10) the npmrc file was located in:

%USERPROFILE%\.npmrc

Tested with:

  • npm v4.2.0
  • Node.js v7.8.0

C compiler for Windows?

I use either BloodShed's DEV C++, CygWin, or Visual C++ Express. All of which are free and work well. I have found that for me, DEV C++ worked the best and was the least quirky. Each compiler has it's own quirks and deifferences, you need to try out a few and find the one with which you are most comfortable. I also liked the fact that DEV C++ allowed me to change the fonts that are used in the editor. I like Proggy Programming fonts!

NotificationCenter issue on Swift 3

Swift 3 & 4

Swift 3, and now Swift 4, have replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. For more details see the now legacy Migrating to Swift 3 guide

Swift 2.2 usage:

// Define identifier
let notificationIdentifier: String = "NotificationIdentifier"

// Register to receive notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)

// Post a notification
NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)

Swift 3 & 4 usage:

// Define identifier
let notificationName = Notification.Name("NotificationIdentifier")

// Register to receive notification
NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)

// Post notification
NotificationCenter.default.post(name: notificationName, object: nil)

// Stop listening notification
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil)

All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

// Definition:
extension Notification.Name {
    static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)

Swift 4.2 usage:

Same as Swift 4, except now system notifications names are part of UIApplication. So in order to stay consistent with the system notifications you can extend UIApplication with your own custom notifications instead of Notification.Name :

// Definition:
UIApplication {
    public static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
}

// Usage:
NotificationCenter.default.post(name: UIApplication.yourCustomNotificationName, object: nil)

Convert image from PIL to openCV format

use this:

pil_image = PIL.Image.open('Image.jpg').convert('RGB') 
open_cv_image = numpy.array(pil_image) 
# Convert RGB to BGR 
open_cv_image = open_cv_image[:, :, ::-1].copy() 

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

I have resolved the same issue in the following manner.

Bitmap b = null;
Drawable d;
ImageView i = new ImageView(mContext);
try {
    b = Bitmap.createBitmap(320,424,Bitmap.Config.RGB_565);
    b.eraseColor(0xFFFFFFFF);
    Rect r = new Rect(0, 0,320 , 424);
    Canvas c = new Canvas(b);
    Paint p = new Paint();
    p.setColor(0xFFC0C0C0);
    c.drawRect(r, p);
    d = mContext.getResources().getDrawable(mImageIds[position]);
    d.setBounds(r);
    d.draw(c);

    /*   
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inTempStorage = new byte[128*1024];
        b = BitmapFactory.decodeStream(mContext.getResources().openRawResource(mImageIds[position]), null, o2);
        o2.inSampleSize=16;
        o2.inPurgeable = true;
    */
} catch (Exception e) {

}
i.setImageBitmap(b);

Error: "The sandbox is not in sync with the Podfile.lock..." after installing RestKit with cocoapods

I encountered this issue with a misconfigured xcconfig file.

The Pods-generated xcconfig was not correctly #included in the customise xcconfig that I was using. This caused $PODS_ROOT to not be set resulting in the failure of diff "/../Podfile.lock" "/Manifest.lock", for obvious reasons, which Pods misinterprets as a sync issue.

how to list all sub directories in a directory

FolderBrowserDialog fbd = new FolderBrowserDialog();

        DialogResult result = fbd.ShowDialog();

        string[] files = Directory.GetFiles(fbd.SelectedPath);
        string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

        foreach (string item2 in dirs)
        {
            FileInfo f = new FileInfo(item2);

            listBox1.Items.Add(f.Name);

        }

        foreach (string item in files)
        {
            FileInfo f = new FileInfo(item);

            listBox1.Items.Add(f.Name);

        }

How to add a recyclerView inside another recyclerView

I ran into similar problem a while back and what was happening in my case was the outer recycler view was working perfectly fine but the the adapter of inner/second recycler view had minor issues all the methods like constructor got initiated and even getCount() method was being called, although the final methods responsible to generate view ie..

1. onBindViewHolder() methods never got called. --> Problem 1.

2. When it got called finally it never show the list items/rows of recycler view. --> Problem 2.

Reason why this happened :: When you put a recycler view inside another recycler view, then height of the first/outer recycler view is not auto adjusted. It is defined when the first/outer view is created and then it remains fixed. At that point your second/inner recycler view has not yet loaded its items and thus its height is set as zero and never changes even when it gets data. Then when onBindViewHolder() in your second/inner recycler view is called, it gets items but it doesn't have the space to show them because its height is still zero. So the items in the second recycler view are never shown even when the onBindViewHolder() has added them to it.

Solution :: you have to create your custom LinearLayoutManager for the second recycler view and that is it. To create your own LinearLayoutManager: Create a Java class with the name CustomLinearLayoutManager and paste the code below into it. NO CHANGES REQUIRED

public class CustomLinearLayoutManager extends LinearLayoutManager {

    private static final String TAG = CustomLinearLayoutManager.class.getSimpleName();

    public CustomLinearLayoutManager(Context context) {
        super(context);

    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    private int[] mMeasuredDimension = new int[2];

    @Override
    public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {

        final int widthMode = View.MeasureSpec.getMode(widthSpec);
        final int heightMode = View.MeasureSpec.getMode(heightSpec);
        final int widthSize = View.MeasureSpec.getSize(widthSpec);
        final int heightSize = View.MeasureSpec.getSize(heightSpec);

        int width = 0;
        int height = 0;
        for (int i = 0; i < getItemCount(); i++) {
            measureScrapChild(recycler, i, View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);


            if (getOrientation() == HORIZONTAL) {
                width = width + mMeasuredDimension[0];
                if (i == 0) {
                    height = mMeasuredDimension[1];
                }
            } else {
                height = height + mMeasuredDimension[1];
                if (i == 0) {
                    width = mMeasuredDimension[0];
                }
            }
        }
        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    }

    private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                                   int heightSpec, int[] measuredDimension) {
        try {
            View view = recycler.getViewForPosition(position);

            if (view != null) {
                RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();

                int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                        getPaddingLeft() + getPaddingRight(), p.width);

                int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                        getPaddingTop() + getPaddingBottom(), p.height);

                view.measure(childWidthSpec, childHeightSpec);
                measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
                measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
                recycler.recycleView(view);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

SQL error "ORA-01722: invalid number"

As this error comes when you are trying to insert non-numeric value into a numeric column in db it seems that your last field might be numeric and you are trying to send it as a string in database. check your last value.

Can't install any package with node npm

This means the npm command is getting an HTML document instead of whatever format it is looking for. In my case, I was using sinopia. When I no longer wanted to use it, I accidentally used this command to reset the registry:

npm config set registry https://www.npmjs.com/

which was wrong, and it should have been the command already mentioned here. Read this if none of the answers solve this problem, and you can probably figure out where the incorrect URL is present and clear it off, and set the registry to the correct URL:

npm config set registry https://registry.npmjs.org

How do I (or can I) SELECT DISTINCT on multiple columns?

SELECT DISTINCT a,b,c FROM t

is roughly equivalent to:

SELECT a,b,c FROM t GROUP BY a,b,c

It's a good idea to get used to the GROUP BY syntax, as it's more powerful.

For your query, I'd do it like this:

UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1 
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )

How can I find where I will be redirected using cURL?

To make cURL follow a redirect, use:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

Erm... I don't think you're actually executing the curl... Try:

curl_exec($ch);

...after setting the options, and before the curl_getinfo() call.

EDIT: If you just want to find out where a page redirects to, I'd use the advice here, and just use Curl to grab the headers and extract the Location: header from them:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (preg_match('~Location: (.*)~i', $result, $match)) {
   $location = trim($match[1]);
}

Questions every good Java/Java EE Developer should be able to answer?

Difference between and web server and a web container

How to do something before on submit?

If you have a form as such:

<form id="myform">
...
</form>

You can use the following jQuery code to do something before the form is submitted:

$('#myform').submit(function() {
    // DO STUFF...
    return true; // return false to cancel form action
});

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
}
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...
}

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems