Programs & Examples On #Kohana orm

ORM module of Kohana HMVC PHP5 Framework

Read file data without saving it in Flask

In case we want to dump the in memory file to disk. This code can be used

  if isinstanceof(obj,SpooledTemporaryFile):
    obj.rollover()

How do I add a Font Awesome icon to input field?

For those, who are wondering how to get FontAwesome icons to drupal input, you have to decode_entities first like so:

$form['submit'] = array(
'#type' => 'submit',
'#value' => decode_entities(''), // code for FontAwesome trash icon
// etc.
);

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

C++ String Concatenation operator<<

First of all it is unclear what type name has. If it has the type std::string then instead of

string nametext;
nametext = "Your name is" << name;

you should write

std::string nametext = "Your name is " + name;

where operator + serves to concatenate strings.

If name is a character array then you may not use operator + for two character arrays (the string literal is also a character array), because character arrays in expressions are implicitly converted to pointers by the compiler. In this case you could write

std::string nametext( "Your name is " );
nametext.append( name );

or

std::string nametext( "Your name is " );
nametext += name;

updating Google play services in Emulator

Update your google play services or just create the new emulator. When you install the new emulator this problem will automatically be solved. Happy coding :)

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

Get the index of a certain value in an array in PHP

If you're only doing a few of them (and/or the array size is large), then you were on the right track with array_search:

$list = array('string1', 'string2', 'string3');
$k = array_search('string2', $list); //$k = 1;

If you want all (or a lot of them), a loop will prob do you better:

foreach ($list as $key => $value) {
    echo $value . " in " . $key . ", ";
}
// Prints "string1 in 0, string2 in 1, string3 in 2, "

What is the difference between readonly="true" & readonly="readonly"?

I'm not sure how they're functionally different. My current batch of OS X browsers don't show any difference.

I would assume they are all functionally the same due to legacy HTML attribute handling. Back in the day, any flag (Boolean) attribute need only be present, sans value, eg

<input readonly>
<option selected>

When XHTML came along, this syntax wasn't valid and values were required. Whilst the W3 specified using the attribute name as the value, I'm guessing most browser vendors decided to simply check for attribute existence.

How to clear Facebook Sharer cache?

I just posted a simple solution that takes 5 seconds here on a related post here - Facebook debugger: Clear whole site cache

short answer... change your permalinks on a worpdress site in the permalinks settings to a custom one. I just added an underscore.
/_%postname%/
then facebook scrapes them all as new urls, new posts.

How to read files and stdout from a running Docker container

Sharing files between a docker container and the host system, or between separate containers is best accomplished using volumes.

Having your app running in another container is probably your best solution since it will ensure that your whole application can be well isolated and easily deployed. What you're trying to do sounds very close to the setup described in this excellent blog post, take a look!

Create whole path automatically when writing to a new file

Since Java 1.7 you can use Files.createFile:

Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);

Reading an Excel file in PHP

Try this...

I have used following code to read "xls and xlsx"

    <?php
    include 'excel_reader.php';       // include the class
    $excel = new PhpExcelReader;      // creates object instance of the class
    $excel->read('excel_file.xls');   // reads and stores the excel file data

    // Test to see the excel data stored in $sheets property
    echo '<pre>';
    var_export($excel->sheets);

    echo '</pre>';

    or 

 echo '<pre>';
    print_r($excel->sheets);

    echo '</pre>';

Reference:http://coursesweb.net/php-mysql/read-excel-file-data-php_pc

Read and write to binary files in C?

this questions is linked with the question How to write binary data file on C and plot it using Gnuplot by CAMILO HG. I know that the real problem have two parts: 1) Write the binary data file, 2) Plot it using Gnuplot.

The first part has been very clearly answered here, so I do not have something to add.

For the second, the easy way is send the people to the Gnuplot manual, and I sure someone find a good answer, but I do not find it in the web, so I am going to explain one solution (which must be in the real question, but I new in stackoverflow and I can not answer there):

After write your binary data file using fwrite(), you should create a very simple program in C, a reader. The reader only contains the same structure as the writer, but you use fread() instead fwrite(). So it is very ease to generate this program: copy in the reader.c file the writing part of your original code and change write for read (and "wb" for "rb"). In addition, you could include some checks for the data, for example, if the length of the file is correct. And finally, your program need to print the data in the standard output using a printf().

For be clear: your program run like this

$ ./reader data.dat

X_position Y_position  (it must be a comment for Gnuplot)*

1.23 2.45

2.54 3.12

5.98 9.52

Okey, with this program, in Gnuplot you only need to pipe the standard output of the reader to the Gnuplot, something like this:

plot '< ./reader data.dat'

This line, run the program reader, and the output is connected with Gnuplot and it plot the data.

*Because Gnuplot is going to read the output of the program, you must know what can Gnuplot read and plot and what can not.

Selenium C# WebDriver: Wait until element is present

// Wait up to 5 seconds with no minimum for a UI element to be found
WebDriverWait wait = new WebDriverWait(_pagedriver, TimeSpan.FromSeconds(5));
IWebElement title = wait.Until<IWebElement>((d) =>
{
    return d.FindElement(By.ClassName("MainContentHeader"));
});

How to make a transparent HTML button?

<div class="button_style">
This is your button value
</div>

.button_style{   
background-color: Transparent;
border: none;             /* Your can add different style/properties of button Here*/
cursor:pointer;    
}

JUnit tests pass in Eclipse but fail in Maven Surefire

This doesn't exactly apply to your situation, but I had the same thing -- tests that would pass in Eclipse failed when the test goal from Maven was run.

It turned out to be a test earlier in my suite, in a different package. This took me a week to solve!

An earlier test was testing some Logback classes, and created a Logback context from a config file.

The later test was testing a subclass of Spring's SimpleRestTemplate, and somehow, the earlier Logback context was held, with DEBUG on. This caused extra calls to be made in RestTemplate to log HttpStatus, etc.

It's another thing to check if one ever gets into this situation. I fixed my problem by injecting some Mocks into my Logback test class, so that no real Logback contexts were created.

What is inf and nan?

nan means "not a number", a float value that you get if you perform a calculation whose result can't be expressed as a number. Any calculations you perform with NaN will also result in NaN.

inf means infinity.

For example:

>>> 2*float("inf")
inf
>>> -2*float("inf")
-inf
>>> float("inf")-float("inf")
nan

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

I would always use sp_executesql these days, all it really is is a wrapper for EXEC which handles parameters & variables.

However do not forget about OPTION RECOMPILE when tuning queries on very large databases, especially where you have data spanned over more than one database and are using a CONSTRAINT to limit index scans.

Unless you use OPTION RECOMPILE, SQL server will attempt to create a "one size fits all" execution plan for your query, and will run a full index scan each time it is run.

This is much less efficient than a seek, and means it is potentially scanning entire indexes which are constrained to ranges which you are not even querying :@

How to view the assembly behind the code using Visual C++?

In Visual C++ the project options under, Output Files I believe has an option for outputing the ASM listing with source code. So you will see the C/C++ source code and the resulting ASM all in the same file.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

In most cases, it is enough just to hide the element, for example in this way:

export default class ErrorBoxComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isHidden: false
        }
    }

    dismiss() {
        this.setState({
            isHidden: true
        })
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className={ "alert-box error-box " + (this.state.isHidden ? 'DISPLAY-NONE-CLASS' : '') }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Or you may render/rerender/not render via parent component like this

export default class ParentComponent extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            isErrorShown: true
        }
    }

    dismiss() {
        this.setState({
            isErrorShown: false
        })
    }

    showError() {
        if (this.state.isErrorShown) {
            return <ErrorBox 
                error={ this.state.error }
                dismiss={ this.dismiss.bind(this) }
            />
        }

        return null;
    }

    render() {

        return (
            <div>
                { this.showError() }
            </div>
        );
    }
}

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.props.dismiss();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box">
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Finally, there is a way to remove html node, but i really dont know is it a good idea. Maybe someone who knows React from internal will say something about this.

export default class ErrorBoxComponent extends React.Component {
    dismiss() {
        this.el.remove();
    }

    render() {
        if (!this.props.error) {
            return null;
        }

        return (
            <div data-alert className="alert-box error-box" ref={ (el) => { this.el = el} }>
                { this.props.error }
                <a href="#" className="close" onClick={ this.dismiss.bind(this) }>&times;</a>
            </div>
        );
    }
}

Is there a way to collapse all code blocks in Eclipse?

Just to sum up:

  1. anycode:
    • ctrl + shift + NUMPAD_divide = collapse all
    • NUMPAD_multiply = exand all
  2. pydev:
    • -ctrl + 0 = collapse all
    • -ctrl + 9 = exand all

Generating PDF files with JavaScript

Even if you could generate the PDF in-memory in JavaScript, you would still have the issue of how to transfer that data to the user. It's hard for JavaScript to just push a file at the user.

To get the file to the user, you would want to do a server submit in order to get the browser to bring up the save dialog.

With that said, it really isn't too hard to generate PDFs. Just read the spec.

Windows batch script launch program and exit console

Use start notepad.exe.

More info with start /?.

What does %>% mean in R

matrix multiplication, see the following example:

> A <- matrix (c(1,3,4, 5,8,9, 1,3,3), 3,3)
> A
     [,1] [,2] [,3]
[1,]    1    5    1
[2,]    3    8    3
[3,]    4    9    3
> 
> B <- matrix (c(2,4,5, 8,9,2, 3,4,5), 3,3)
> 
> B
     [,1] [,2] [,3]
[1,]    2    8    3
[2,]    4    9    4
[3,]    5    2    5
> 
> 
> A %*% B
     [,1] [,2] [,3]
[1,]   27   55   28
[2,]   53  102   56
[3,]   59  119   63

> B %*% A
     [,1] [,2] [,3]
[1,]   38  101   35
[2,]   47  128   43
[3,]   31   86   26

Also see:

http://en.wikipedia.org/wiki/Matrix_multiplication

If this does not follow the size of matrix rule you will get the error:

> A <- matrix(c(1,2,3,4,5,6), 3,2)
    > A
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

> B <- matrix (c(3,1,3,4,4,4,4,4,3), 3,3)

> B
         [,1] [,2] [,3]
    [1,]    3    4    4
    [2,]    1    4    4
    [3,]    3    4    3
    > A%*%B
    Error in A %*% B : non-conformable arguments

PHP mySQL - Insert new record into table with auto-increment on primary key

Use the DEFAULT keyword:

$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";

Also, you can specify the columns, (which is better practice):

$query = "INSERT INTO myTable
          (fname, lname, website)
          VALUES
          ('fname', 'lname', 'website')";

Reference:

Changing the browser zoom level

as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

how to add a day to a date using jquery datepicker

This answer really helped me get started (noob) - but I encountered some weird behavior when I set a start date of 12/31/2014 and added +1 to default the end date. Instead of giving me an end date of 01/01/2015 I was getting 02/01/2015 (!!!). This version parses the components of the start date to avoid these end of year oddities.


 $( "#date_start" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
         $("#date_end").datepicker("option","minDate", selected); //  mindate on the End datepicker cannot be less than start date already selected.
         var date = $(this).datepicker('getDate');
         var tempStartDate = new Date(date);
         var default_end = new Date(tempStartDate.getFullYear(), tempStartDate.getMonth(), tempStartDate.getDate()+1); //this parses date to overcome new year date weirdness
         $('#date_end').datepicker('setDate', default_end); // Set as default                           
   }

 });

 $( "#date_end" ).datepicker({

   minDate: 0,
   dateFormat: "mm/dd/yy",

   onSelect: function(selected) {
     $("#date_start").datepicker("option","maxDate", selected); //  maxdate on the Start datepicker cannot be more than end date selected.

  }

});

How to get annotations of a member variable?

Or you could try this

try {
    BeanInfo bi = Introspector.getBeanInfo(User.getClass());
    PropertyDescriptor[] properties = bi.getPropertyDescriptors();
    for(PropertyDescriptor property : properties) {
        //One way
        for(Annotation annotation : property.getAnnotations()){
            if(annotation instanceof Column) {
                String string = annotation.name();
            }
        }
        //Other way
        Annotation annotation = property.getAnnotation(Column.class);
        String string = annotation.name();
    }
}catch (IntrospectonException ie) {
    ie.printStackTrace();
}

Hope this will help.

SQL query for a carriage return in a string and ultimately removing carriage return

If you are considering creating a function, try this: DECLARE @schema sysname = 'dbo' , @tablename sysname = 'mvtEST' , @cmd NVarchar(2000) , @ColName sysname

    DECLARE @NewLine Table
    (ColumnName Varchar(100)
    ,Location Int
    ,ColumnValue Varchar(8000)
    )

    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE  TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'

    DECLARE looper CURSOR FAST_FORWARD for
    SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = @schema AND TABLE_NAME =  @tablename AND DATA_TYPE LIKE '%CHAR%'
    OPEN looper
    FETCH NEXT FROM looper INTO @ColName

    WHILE @@fetch_status = 0
    BEGIN
    SELECT @cmd = 'select ''' +@ColName+    ''',  CHARINDEX(Char(10),  '+  @ColName +') , '+ @ColName + ' from '+@schema + '.'+@tablename +' where CHARINDEX(Char(10),  '+  @ColName +' ) > 0 or CHARINDEX(CHAR(13), '+@ColName +') > 0'
    PRINT @cmd
    INSERT @NewLine ( ColumnName, Location, ColumnValue )
    EXEC sp_executesql @cmd
    FETCH NEXT FROM looper INTO @ColName
    end
    CLOSE looper
    DEALLOCATE looper


    SELECT * FROM  @NewLine

How do I find numeric columns in Pandas?

Following codes will return list of names of the numeric columns of a data set.

cnames=list(marketing_train.select_dtypes(exclude=['object']).columns)

here marketing_train is my data set and select_dtypes() is function to select data types using exclude and include arguments and columns is used to fetch the column name of data set output of above code will be following:

['custAge',
     'campaign',
     'pdays',
     'previous',
     'emp.var.rate',
     'cons.price.idx',
     'cons.conf.idx',
     'euribor3m',
     'nr.employed',
     'pmonths',
     'pastEmail']

Thanks

How do you cache an image in Javascript

I always prefer to use the example mentioned in Konva JS: Image Events to load images.

  1. You need to have a list of image URLs as object or array, for example:

    var sources = { lion: '/assets/lion.png', monkey: '/assets/monkey.png' };

  2. Define the Function definition, where it receives list of image URLs and a callback function in its arguments list, so when it finishes loading image you can start excution on your web page:

_x000D_
_x000D_
    function loadImages(sources, callback) {_x000D_
                var images = {};_x000D_
                var loadedImages = 0;_x000D_
                var numImages = 0;_x000D_
                for (var src in sources) {_x000D_
                    numImages++;_x000D_
                }_x000D_
                for (var src in sources) {_x000D_
                    images[src] = new Image();_x000D_
                    images[src].onload = function () {_x000D_
                        if (++loadedImages >= numImages) {_x000D_
                            callback(images);_x000D_
                        }_x000D_
                    };_x000D_
                    images[src].src = sources[src];_x000D_
                }_x000D_
            }
_x000D_
_x000D_
_x000D_

  1. Lastly, you need to call the function. You can call it for example from jQuery's Document Ready

$(document).ready(function (){ loadImages(sources, buildStage); });

Representing EOF in C code?

This is system dependent but often -1. See here

Taking pictures with camera on Android programmatically

Take and store image in desired folder

 //Global Variables
   private static final int CAMERA_IMAGE_REQUEST = 101;
    private String imageName;

Take picture function

 public void captureImage() {

            // Creating folders for Image
            String imageFolderPath = Environment.getExternalStorageDirectory().toString()
                    + "/AutoFare";
            File imagesFolder = new File(imageFolderPath);
            imagesFolder.mkdirs();

            // Generating file name
            imageName = new Date().toString() + ".png";

            // Creating image here
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(imageFolderPath, imageName)));
            startActivityForResult(takePictureIntent,
                    CAMERA_IMAGE_REQUEST);

        }

Broadcast new image added otherwise pic will not be visible in image gallery

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
                // TODO Auto-generated method stub
                super.onActivityResult(requestCode, resultCode, data);

                if (resultCode == Activity.RESULT_OK && requestCode == CAMERA_IMAGE_REQUEST) {

                    Toast.makeText(getActivity(), "Success",
                            Toast.LENGTH_SHORT).show();

 //Scan new image added
                    MediaScannerConnection.scanFile(getActivity(), new String[]{new File(Environment.getExternalStorageDirectory()
                            + "/AutoFare/" + imageName).getPath()}, new String[]{"image/png"}, null);


 // Work in few phones
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

                        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(Environment.getExternalStorageDirectory()
                                + "/AutoFare/" + imageName)));

                    } else {
                        getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse(Environment.getExternalStorageDirectory()
                                + "/AutoFare/" + imageName)));
                    }
                } else {
                    Toast.makeText(getActivity(), "Take Picture Failed or canceled",
                            Toast.LENGTH_SHORT).show();
                }
            }

Permissions

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Is there a way to use shell_exec without waiting for the command to complete?

If it's off of a web page, I recommend generating a signal of some kind (dropping a file in a directory, perhaps) and having a cron job pick up the work that needs to be done. Otherwise, we're likely to get into the territory of using pcntl_fork() and exec() from inside an Apache process, and that's just bad mojo.

Format a JavaScript string using placeholders and an object of substitutions?

How about using ES6 template literals?

var a = "cat";
var b = "fat";
console.log(`my ${a} is ${b}`); //notice back-ticked string

More about template literals...

Calculating time difference between 2 dates in minutes

I think you could use TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2) something like

select * from MyTab T where
TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20

what do these symbolic strings mean: %02d %01d?

http://www.cplusplus.com/reference/clibrary/cstdio/printf/

the same rules should apply to Java.

in your case it means output of integer values in 2 or more digits, the first being zero if number less than or equal to 9

Use mysql_fetch_array() with foreach() instead of while()

There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

$result_list = array();
while($row = mysql_fetch_array($result_select)) {
   result_list[] = $row;
}

foreach($result_list as $row) {
   ...
}

But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

How should I set the default proxy to use default credentials?

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.

Some examples:

./mdb_to_mysql.sh database.mdb > data.sql

./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p

Here is the modified script (save to mdb_to_mysql.sh)

#!/bin/bash
TABLES=$(mdb-tables -1 $1)

for t in $TABLES
do
    echo "DROP TABLE IF EXISTS $t;"
done

mdb-schema $1 mysql

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done

How to get all registered routes in Express?

Hacky copy/paste answer courtesy of Doug Wilson on the express github issues. Dirty but works like a charm.

function print (path, layer) {
  if (layer.route) {
    layer.route.stack.forEach(print.bind(null, path.concat(split(layer.route.path))))
  } else if (layer.name === 'router' && layer.handle.stack) {
    layer.handle.stack.forEach(print.bind(null, path.concat(split(layer.regexp))))
  } else if (layer.method) {
    console.log('%s /%s',
      layer.method.toUpperCase(),
      path.concat(split(layer.regexp)).filter(Boolean).join('/'))
  }
}

function split (thing) {
  if (typeof thing === 'string') {
    return thing.split('/')
  } else if (thing.fast_slash) {
    return ''
  } else {
    var match = thing.toString()
      .replace('\\/?', '')
      .replace('(?=\\/|$)', '$')
      .match(/^\/\^((?:\\[.*+?^${}()|[\]\\\/]|[^.*+?^${}()|[\]\\\/])*)\$\//)
    return match
      ? match[1].replace(/\\(.)/g, '$1').split('/')
      : '<complex:' + thing.toString() + '>'
  }
}

app._router.stack.forEach(print.bind(null, []))

Produces

screengrab

Using jQuery, Restricting File Size Before Uploading

I encountered the same issue. You have to use ActiveX or Flash (or Java). The good thing is that it doesn't have to be invasive. I have a simple ActiveX method that will return the size of the to-be-uploaded file.

If you go with Flash, you can even do some fancy js/css to cusomize the uploading experience--only using Flash (as a 1x1 "movie") to access it's file uploading features.

Write bytes to file

If I understand you correctly, this should do the trick. You'll need add using System.IO at the top of your file if you don't already have it.

public bool ByteArrayToFile(string fileName, byte[] byteArray)
{
    try
    {
        using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
        {
            fs.Write(byteArray, 0, byteArray.Length);
            return true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("Exception caught in process: {0}", ex);
        return false;
    }
}

Defining custom attrs

if you omit the format attribute from the attr element, you can use it to reference a class from XML layouts.

  • example from attrs.xml.
  • Android Studio understands that the class is being referenced from XML
    • i.e.
      • Refactor > Rename works
      • Find Usages works
      • and so on...

don't specify a format attribute in .../src/main/res/values/attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="MyCustomView">
        ....
        <attr name="give_me_a_class"/>
        ....
    </declare-styleable>

</resources>

use it in some layout file .../src/main/res/layout/activity__main_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <!-- make sure to use $ dollar signs for nested classes -->
    <MyCustomView
        app:give_me_a_class="class.type.name.Outer$Nested/>

    <MyCustomView
        app:give_me_a_class="class.type.name.AnotherClass/>

</SomeLayout>

parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt

class MyCustomView(
        context:Context,
        attrs:AttributeSet)
    :View(context,attrs)
{
    // parse XML attributes
    ....
    private val giveMeAClass:SomeCustomInterface
    init
    {
        context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
        {
            try
            {
                // very important to use the class loader from the passed-in context
                giveMeAClass = context::class.java.classLoader!!
                        .loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
                        .newInstance() // instantiate using 0-args constructor
                        .let {it as SomeCustomInterface}
            }
            finally
            {
                recycle()
            }
        }
    }

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

docker unauthorized: authentication required - upon push with successful login

I have received similar error for sudo docker push /sudo docker pull on ecr repository.This is because aws cli installed in my user(abc) and docker installed in root user.I have tried to run sudo docker push on my user(abc)

Fixed this by installed aws cli in root , configured aws using aws configure in root and run sudo docker push to ecr on root user

Login failed for user 'NT AUTHORITY\NETWORK SERVICE'

If the error message is just

"Login failed for user 'NT AUTHORITY\NETWORK SERVICE'.", then grant the login permission for 'NT AUTHORITY\NETWORK SERVICE'

by using

"sp_grantlogin 'NT AUTHORITY\NETWORK SERVICE'" 

else if the error message is like

"Cannot open database "Phaeton.mdf" requested by the login. The login failed. Login failed for user 'NT AUTHORITY\NETWORK SERVICE'."

try using

"EXEC sp_grantdbaccess 'NT AUTHORITY\NETWORK SERVICE'" 

under your "Phaeton" database.

How to set timer in android?

If anyone is interested, I started playing around with creating a standard object to run on an activities UI thread. Seems to work ok. Comments welcome. I'd love this to be available on the layout designer as a component to drag onto an Activity. Can't believe something like that doesn't already exist.

package com.example.util.timer;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;

public class ActivityTimer {

    private Activity m_Activity;
    private boolean m_Enabled;
    private Timer m_Timer;
    private long m_Delay;
    private long m_Period;
    private ActivityTimerListener m_Listener;
    private ActivityTimer _self;
    private boolean m_FireOnce;

    public ActivityTimer() {
        m_Delay = 0;
        m_Period = 100;
        m_Listener = null;
        m_FireOnce = false;
        _self = this;
    }

    public boolean isEnabled() {
        return m_Enabled;
    }

    public void setEnabled(boolean enabled) {
        if (m_Enabled == enabled)
            return;

        // Disable any existing timer before we enable a new one
        Disable();

        if (enabled) {
            Enable();
        }
    }

    private void Enable() {
        if (m_Enabled)
            return;

        m_Enabled = true;

        m_Timer = new Timer();
        if (m_FireOnce) {
            m_Timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    OnTick();
                }
            }, m_Delay);
        } else {
            m_Timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    OnTick();
                }
            }, m_Delay, m_Period);
        }
    }

    private void Disable() {
        if (!m_Enabled)
            return;

        m_Enabled = false;

        if (m_Timer == null)
            return;

        m_Timer.cancel();
        m_Timer.purge();
        m_Timer = null;
    }

    private void OnTick() {
        if (m_Activity != null && m_Listener != null) {
            m_Activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_Listener.OnTimerTick(m_Activity, _self);
                }
            });
        }
        if (m_FireOnce)
            Disable();
    }

    public long getDelay() {
        return m_Delay;
    }

    public void setDelay(long delay) {
        m_Delay = delay;
    }

    public long getPeriod() {
        return m_Period;
    }

    public void setPeriod(long period) {
        if (m_Period == period)
            return;
        m_Period = period;
    }

    public Activity getActivity() {
        return m_Activity;
    }

    public void setActivity(Activity activity) {
        if (m_Activity == activity)
            return;
        m_Activity = activity;
    }

    public ActivityTimerListener getActionListener() {
        return m_Listener;
    }

    public void setActionListener(ActivityTimerListener listener) {
        m_Listener = listener;
    }

    public void start() {
        if (m_Enabled)
            return;
        Enable();
    }

    public boolean isFireOnlyOnce() {
        return m_FireOnce;
    }

    public void setFireOnlyOnce(boolean fireOnce) {
        m_FireOnce = fireOnce;
    }
}

In the activity, I have this onStart:

@Override
protected void onStart() {
    super.onStart();

    m_Timer = new ActivityTimer();
    m_Timer.setFireOnlyOnce(true);
    m_Timer.setActivity(this);
    m_Timer.setActionListener(this);
    m_Timer.setDelay(3000);
    m_Timer.start();
}

Add shadow to custom shape on Android

I think this method produces very good results:

<!-- Drop Shadow Stack -->
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#00CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#10CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#20CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#30CCCCCC"/>
    </shape>
</item>
<item>
    <shape>
        <padding
                android:top="1dp"
                android:right="1dp"
                android:bottom="1dp"
                android:left="1dp"/>
        <solid android:color="#50CCCCCC"/>
    </shape>
</item>

<item>

    <shape android:shape="rectangle">
        <stroke android:color="#CCC" android:width="1dp"/>
        <solid android:color="#FFF" />
        <corners android:radius="2dp" />

    </shape>

</item>

Location of hibernate.cfg.xml in project?

Give the path relative to your project.

Create a folder called resources in your src and put your config file there.

   configuration.configure("/resources/hibernate.cfg.xml");

And If you check your code

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return new Configuration().configure().buildSessionFactory();

In two lines you are creating two configuration objects.

That should work(haven't tested) if you write,

Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
return  configuration.buildSessionFactory();

But It fails after you deploy on the server,Since you are using system path than project relative path.

Change color of PNG image via CSS?

Answering because I was looking for a solution for this.

the pen in @chrscblls answer works well if you have a white or black background, but mine wasn't. Aslo, the images were generated with ng-repeat, so I couldn't have their url in my css AND you can't use ::after on img tags.

So, I figured a work around and thought it might help people if they too stumble here.

So what I did is pretty much the same with three main differences:

  • the url being in my img tag, I put it(and a label) in another div on which ::after will work.
  • the 'mix-blend-mode' is set at 'difference' instead of 'multiply' or 'screen'.
  • I added a ::before with exactly the same value so the ::after would do the 'difference' of the 'difference' made by the ::before and cancelled it-self.

To change it from black to white or white to black the background color need to be white. From black to colors, you can choose whatever color. From white to colors tho, you'll need to choose the opposite color of the one you want.

.divClass{
   position: relative;
   width: 100%;
   height: 100%;
   text-align: left;
}
.divClass:hover::after, .divClass:hover::before{
   position: absolute;
   width: 100%;
   height: 100%;
   background: #FFF;
   mix-blend-mode: difference;
   content: "";
}

https://codepen.io/spaceplant/pen/oZyMYG

How can I run dos2unix on an entire directory?

If there is no sub-directory, you can also take

ls | xargs -I {} dos2unix "{}"

node and Error: EMFILE, too many open files

Use the latest fs-extra.

I had that problem on Ubuntu (16 and 18) with plenty of file/socket-descriptors space (count with lsof |wc -l). Used fs-extra version 8.1.0. After the update to 9.0.0 the "Error: EMFILE, too many open files" vanished.

I've experienced diverse problems on diverse OS' with node handling filesystems. Filesystems are obviously not trivial.

Left align and right align within div in Bootstrap

Bootstrap v4 introduces flexbox support

<div class="d-flex justify-content-end">
  <div class="mr-auto p-2">Flex item</div>
  <div class="p-2">Flex item</div>
  <div class="p-2">Flex item</div>
</div>

Learn more at https://v4-alpha.getbootstrap.com/utilities/flexbox/

How do I convert speech to text?

Dragon NaturallySpeaking seems to support MP3 input.

If you want an open source version (I think there are some Asterisk integration projects based on this one).

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I know this thread is a year old now but having experienced the same problem I managed to solve the problem by setting a target server for my project.

i.e. right-click on your project and select 'Properties' -> 'Targeted Runtimes' and select the server you going to run your web app on (Tomcat 6 or 7).

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

How to sanity check a date in Java

Building on Aravind's answer to fix the problem pointed out by ceklock in his comment, I added a method to verify that the dateString doesn't contain any invalid character.

Here is how I do:

private boolean isDateCorrect(String dateString) {
    try {
        Date date = mDateFormatter.parse(dateString);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return matchesOurDatePattern(dateString);    //added my method
    }
    catch (ParseException e) {
        return false;
    }
}

/**
 * This will check if the provided string matches our date format
 * @param dateString
 * @return true if the passed string matches format 2014-1-15 (YYYY-MM-dd)
 */
private boolean matchesDatePattern(String dateString) {
    return dateString.matches("^\\d+\\-\\d+\\-\\d+");
}

What is the difference between JavaScript and ECMAScript?

What is ECMAScript i.e. ES?

ECMAScript is a standard for a scripting language and the Javascript language is based on the ECMAScript standard.

Is Javascript exactly the same as ECMAScript?

  • No, Javascript is not exactly equivalent to ECMAScript.
  • The core features of Javascript are based on the ECMAScript standard, but Javascript also has other additional features that are not in the ECMA specifications/standard.

JavaScript = ECMAScript + DOM API;

DOM API like: document.getElementById('id');

Do other languages use the ECMAScript standard?

  • Yes, there are languages other than JavaScript that also implement the ECMAScript Standard as their core.
  • ActionScript (used by Adobe Flash) and JScript (used by Microsoft) are both languages that implement the ECMAScript standard.

Why is it called ECMAScript?

  • Javascript was originally created at Netscape, and they wanted to standardize the language. So, they submitted the language to the European Computer Manufacturer’s Association (ECMA) for standardization.
  • But, there were trademark issues with the name Javascript, and the standard became called ECMAScript, which is the name it holds today as well.
  • Because of trademark issues, Microsoft’s version of the language is called JScript – even though JScript is, at its core, the same language as Javascript.

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

How do you read CSS rule values with JavaScript?

I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.

getStylesBySelector('.pure-form-html', true);

returns:

{
    ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
    ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}

from:

.pure-form-html body {
    padding: 0;
    margin: 0;
    font-size: 14px;
    font-family: tahoma;
}

.pure-form-html h1 {
    margin: 0;
    font-size: 18px;
    font-family: tahoma;
}

The code:

/**
 * Get all CSS style blocks matching a CSS selector from stylesheets
 * @param {string} className - class name to match
 * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
 * @example getStylesBySelector('pure-form .pure-form-html ')
 * @returns {object} key/value object containing matching styles otherwise null
 */
function getStylesBySelector(className, startingWith) {

    if (!className || className === '') throw new Error('Please provide a css class name');

    var styleSheets = window.document.styleSheets;
    var result = {};

    // go through all stylesheets in the DOM
    for (var i = 0, l = styleSheets.length; i < l; i++) {

        var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];

        // go through all classes in each document
        for (var x = 0, ll = classes.length; x < ll; x++) {

            var selector = classes[x].selectorText || '';
            var content = classes[x].cssText || classes[x].style.cssText || '';

            // if the selector matches
            if ((startingWith && selector.indexOf(className) === 0) || selector === className) {

                // create an object entry with selector as key and value as content
                result[selector] = content.split(/(?:{|})/)[1].trim();
            }
        }
    }

    // only return object if we have values, otherwise null
    return Object.keys(result).length > 0 ? result : null;
}

I'm using this in production as part of the pure-form project. Hope it helps.

Dynamically load a JavaScript file

jquery resolved this for me with its .append() function - used this to load the complete jquery ui package

/*
 * FILENAME : project.library.js
 * USAGE    : loads any javascript library
 */
    var dirPath = "../js/";
    var library = ["functions.js","swfobject.js","jquery.jeditable.mini.js","jquery-ui-1.8.8.custom.min.js","ui/jquery.ui.core.min.js","ui/jquery.ui.widget.min.js","ui/jquery.ui.position.min.js","ui/jquery.ui.button.min.js","ui/jquery.ui.mouse.min.js","ui/jquery.ui.dialog.min.js","ui/jquery.effects.core.min.js","ui/jquery.effects.blind.min.js","ui/jquery.effects.fade.min.js","ui/jquery.effects.slide.min.js","ui/jquery.effects.transfer.min.js"];

    for(var script in library){
        $('head').append('<script type="text/javascript" src="' + dirPath + library[script] + '"></script>');
    }

To Use - in the head of your html/php/etc after you import jquery.js you would just include this one file like so to load in the entirety of your library appending it to the head...

<script type="text/javascript" src="project.library.js"></script>

String format currency

Use this it works and so simple :

  var price=22.5m;
  Console.WriteLine(
     "the price: {0}",price.ToString("C", new System.Globalization.CultureInfo("en-US")));

SOAP request in PHP with CURL

Tested and working!

  • with https, user & password

     <?php 
     //Data, connection, auth
     $dataFromTheForm = $_POST['fieldName']; // request data from the form
     $soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
     $soapUser = "username";  //  username
     $soapPassword = "password"; // password
    
     // xml post structure
    
     $xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
                         <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                           <soap:Body>
                             <GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
                               <PRICE>'.$dataFromTheForm.'</PRICE> 
                             </GetItemPrice >
                           </soap:Body>
                         </soap:Envelope>';   // data from the form, e.g. some ID number
    
        $headers = array(
                     "Content-type: text/xml;charset=\"utf-8\"",
                     "Accept: text/xml",
                     "Cache-Control: no-cache",
                     "Pragma: no-cache",
                     "SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice", 
                     "Content-length: ".strlen($xml_post_string),
                 ); //SOAPAction: your op URL
    
         $url = $soapUrl;
    
         // PHP cURL  for https connection with auth
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
         curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
         curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
         // converting
         $response = curl_exec($ch); 
         curl_close($ch);
    
         // converting
         $response1 = str_replace("<soap:Body>","",$response);
         $response2 = str_replace("</soap:Body>","",$response1);
    
         // convertingc to XML
         $parser = simplexml_load_string($response2);
         // user $parser to get your data out of XML response and to display it. 
     ?>
    

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

Insert NULL value into INT column

2 ways to do it

insert tbl (other, col1, intcol) values ('abc', 123, NULL)

or just omit it from the column list

insert tbl (other, col1) values ('abc', 123)

How to get row index number in R?

It not quite clear what exactly you are trying to do.

To reference a row in a data frame use df[row,]

To get the first position in a vector of something use match(item,vector), where the vector could be one of the columns of your data frame, eg df$cname if the column name is cname.

Edit:

To combine these you would write:

df[match(item,df$cname),]

Note that the match gives you the first item in the list, so if you are not looking for a unique reference number, you may want to consider something else.

Array slices in C#

If you don't want to add LINQ or other extensions just do:

float[] subArray = new List<float>(myArray).GetRange(0, 8).ToArray();

SVG drop shadow using css3

Black text with white shadow

Another way, I used for white shadow (on text): create a clone for shadow:

Note: This require xmlns:xlink="http://www.w3.org/1999/xlink" at SVG declaration.

Real text value is located in <defs> section, with position and style, but without a fill definition.

The text is cloned two times: first for shadow and second for the text itself.

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="70"_x000D_
    xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
  <defs>_x000D_
  <filter id="Blur"><feGaussianBlur stdDeviation="0.8" /></filter>_x000D_
  <text style="font-family:sans,helvetica;font-weight:bold;font-size:12pt"_x000D_
      id="Text"><tspan x="12" y="19">_x000D_
        Black text with white shadow_x000D_
    </tspan></text>_x000D_
  </defs>_x000D_
  <rect style="fill:#8AB" width="640" height="70" />_x000D_
  <use style="fill:white;" filter="url(#Blur)" xlink:href="#Text"_x000D_
      transform="translate(1.8,.9)"/>_x000D_
  <use style="fill:black;" xlink:href="#Text"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

More distant shadow with biggest value as blur deviation:

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="640" height="70"_x000D_
    xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
  <defs>_x000D_
  <filter id="Blur"><feGaussianBlur stdDeviation="3" /></filter>_x000D_
  <text style="font-family:sans,helvetica;font-weight:bold;font-size:12pt"_x000D_
      id="Text"><tspan x="12" y="19">_x000D_
        Black text with white shadow_x000D_
    </tspan></text>_x000D_
  </defs>_x000D_
  <rect style="fill:#8AB" width="640" height="70" />_x000D_
  <use style="fill:white;" filter="url(#Blur)" xlink:href="#Text"_x000D_
      transform="translate(7,5)"/>_x000D_
  <use style="fill:black;" xlink:href="#Text"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

You can use this same approach with regular SVG objects.

With same requirement: No fill definition at <defs> section!

_x000D_
_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="364" height="172"_x000D_
    xmlns:xlink="http://www.w3.org/1999/xlink">_x000D_
  <defs>_x000D_
    <filter id="Blur"><feGaussianBlur stdDeviation="0.8" /></filter>_x000D_
    <g transform="matrix(.7,0,0,.7,-117.450795,-335.320895)" id="Img">_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,389.30313,662.04015)">_x000D_
            <path d="m 0,0 -1.107,0 c -0.039,0 -0.067,0.044 -0.067,0.086 0,0.015 0.589,1.914 0.589,1.914 0.021,0.071 0.023,0.073 0.031,0.073 l 0.001,0 c 0.009,0 0.01,-0.002 0.031,-0.073 0,0 0.589,-1.899 0.589,-1.914 C 0.067,0.044 0.037,0 0,0 M 1.493,4.345 C 1.482,4.383 1.448,4.411 1.408,4.414 l -4.065,0 C -2.698,4.41 -2.731,4.383 -2.742,4.346 c 0,0 -2.247,-7.418 -2.247,-7.432 0,-0.037 0.029,-0.067 0.067,-0.067 l 2.687,0 c 0.021,0.008 0.037,0.028 0.042,0.051 l 0.313,1 c 0.01,0.025 0.033,0.042 0.061,0.043 l 2.479,0.002 c 0.027,-0.002 0.051,-0.021 0.061,-0.045 l 0.32,-1 c 0.005,-0.023 0.021,-0.044 0.042,-0.052 0,0 2.642,10e-4 2.644,10e-4 0.037,0 0.068,0.028 0.068,0.065 0,0.013 -2.302,7.433 -2.302,7.433" />_x000D_
        </g>_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,508.27177,644.93113)">_x000D_
            <path d="m 0,0 -1.651,-0.001 c 0,0 -0.044,0.013 -0.044,0.063 l -10e-4,0.833 c 0,0.05 0.044,0.063 0.044,0.063 l 1.514,0 C 0.038,0.958 0.394,0.87 0.394,0.463 0.394,0.056 0,0 0,0 m 7.916,0.645 3.741,0 0,2.453 -4.81,0 C 6.397,3.098 5.764,2.866 5.401,2.597 5.038,2.328 4.513,1.715 4.513,0.87 c 0,-0.845 0.513,-1.502 0.513,-1.502 0.263,-0.326 0.925,-1.005 0.925,-1.005 0.015,-0.016 0.024,-0.037 0.024,-0.061 0,-0.051 -0.041,-0.092 -0.092,-0.092 l -3.705,0 c -0.451,0.002 -0.482,0.181 -0.482,0.207 0,0.046 0.056,0.075 0.056,0.075 0.169,0.081 0.514,0.35 0.514,0.35 0.732,0.57 0.82,1.352 0.82,1.771 0,0.42 -0.063,1.163 -0.814,1.814 C 1.521,3.078 0.57,3.096 0.57,3.096 l -5.287,0 c 0,0 0,-7.52 0,-7.522 0,-0.024 0.022,-0.043 0.046,-0.043 l 2.943,0 0,2.11 c 0,0.037 0.057,0 0.057,0 l 1.533,-1.54 c 0.545,-0.551 1.446,-0.57 1.446,-0.57 l 5.796,0.001 c 0.989,0 1.539,0.538 1.69,0.688 0.15,0.151 0.651,0.714 0.651,1.647 0,0.932 -0.426,1.409 -0.608,1.628 C 8.675,-0.309 8.029,0.375 7.894,0.517 7.878,0.53 7.868,0.55 7.868,0.572 c 0,0.033 0.019,0.064 0.048,0.073" />_x000D_
        </g>_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,306.99861,703.01559)">_x000D_
            <path d="m 0,0 c 0.02,0 0.034,0.014 0.04,0.036 0,0 2.277,7.479 2.277,7.486 0,0.02 -0.012,0.042 -0.031,0.044 0,0 -2.805,0 -2.807,0 -0.014,0 -0.023,-0.011 -0.026,-0.026 0,-0.001 -0.581,-1.945 -0.581,-1.946 -0.004,-0.016 -0.012,-0.026 -0.026,-0.026 -0.014,0 -0.026,0.014 -0.028,0.026 L -1.79,7.541 c -0.002,0.013 -0.012,0.025 -0.026,0.025 -10e-4,0 -3.1,0.001 -3.1,0.001 -0.009,-0.002 -0.017,-0.01 -0.02,-0.018 0,0 -0.545,-1.954 -0.545,-1.954 -0.003,-0.017 -0.012,-0.027 -0.027,-0.027 -0.013,0 -0.024,0.01 -0.026,0.023 l -0.578,1.952 c -0.001,0.012 -0.011,0.022 -0.023,0.024 l -2.992,0 c -0.024,0 -0.044,-0.02 -0.044,-0.045 0,-0.004 10e-4,-0.012 10e-4,-0.012 0,0 2.31,-7.471 2.311,-7.474 C -6.853,0.014 -6.839,0 -6.819,0 c 0.003,0 2.485,-0.001 2.485,-0.001 0.015,0.002 0.03,0.019 0.034,0.037 10e-4,0 0.865,2.781 0.865,2.781 0.005,0.017 0.012,0.027 0.026,0.027 0.015,0 0.023,-0.012 0.027,-0.026 L -2.539,0.024 C -2.534,0.01 -2.521,0 -2.505,0 -2.503,0 0,0 0,0" />_x000D_
        </g>_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,278.90126,499.03369)">_x000D_
            <path d="m 0,0 c -0.451,0 -1.083,-0.232 -1.446,-0.501 -0.363,-0.269 -0.888,-0.882 -0.888,-1.727 0,-0.845 0.513,-1.502 0.513,-1.502 0.263,-0.326 0.925,-1.01 0.925,-1.01 0.015,-0.016 0.024,-0.037 0.024,-0.06 0,-0.051 -0.041,-0.093 -0.092,-0.093 -0.008,0 -6.046,0 -6.046,0 l 0,-2.674 7.267,0 c 0.988,0 1.539,0.538 1.69,0.689 0.15,0.15 0.65,0.713 0.65,1.646 0,0.932 -0.425,1.414 -0.607,1.633 -0.162,0.196 -0.808,0.876 -0.943,1.017 -0.016,0.014 -0.026,0.034 -0.026,0.056 0,0.033 0.019,0.063 0.048,0.073 l 3.5,0 0,-5.114 2.691,0 0,5.101 3.267,0 0,2.466 L 0,0 Z" />_x000D_
        </g>_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,583.96822,539.30215)">_x000D_
            <path d="m 0,0 -1.651,-0.001 c 0,0 -0.044,0.013 -0.044,0.063 l -10e-4,0.833 c 0,0.05 0.044,0.063 0.044,0.063 l 1.514,0 C 0.038,0.958 0.394,0.87 0.394,0.463 0.394,0.056 0,0 0,0 m 2.178,-1.79 c -0.45,0.002 -0.482,0.181 -0.482,0.207 0,0.046 0.056,0.075 0.056,0.075 0.169,0.081 0.514,0.35 0.514,0.35 0.732,0.57 0.82,1.352 0.82,1.771 0,0.42 -0.063,1.163 -0.814,1.814 C 1.521,3.078 0.57,3.098 0.57,3.098 l -5.287,0 c 0,0 0,-7.522 0,-7.524 0,-0.024 0.022,-0.043 0.046,-0.043 0.005,0 2.943,0 2.943,0 l 0,2.109 c 0,0.038 0.057,0 0.057,0 l 1.533,-1.539 c 0.545,-0.551 1.446,-0.57 1.446,-0.57 l 4.525,0 0,2.679 -3.655,0 z" />_x000D_
        </g>_x000D_
        <g transform="matrix(12.997776,0,0,-12.997776,466.86346,556.40203)">_x000D_
            <path d="m 0,0 -1.107,0 c -0.041,0 -0.067,0.044 -0.067,0.086 0,0.016 0.589,1.914 0.589,1.914 0.021,0.071 0.027,0.073 0.031,0.073 l 0.001,0 c 0.004,0 0.01,-0.002 0.031,-0.073 0,0 0.589,-1.898 0.589,-1.914 C 0.067,0.044 0.04,0 0,0 M 1.49,4.347 C 1.479,4.385 1.446,4.412 1.405,4.414 l -4.065,0 C -2.7,4.412 -2.734,4.385 -2.745,4.348 c 0,0 -2.245,-7.42 -2.245,-7.434 0,-0.037 0.03,-0.067 0.067,-0.067 l 2.687,0 c 0.022,0.007 0.038,0.028 0.043,0.051 l 0.313,1.001 c 0.01,0.024 0.033,0.041 0.061,0.042 l 2.478,0 C 0.687,-2.061 0.71,-2.078 0.721,-2.102 l 0.32,-1 c 0.005,-0.023 0.021,-0.044 0.042,-0.052 0,0 2.642,10e-4 2.644,10e-4 0.037,0 0.067,0.028 0.067,0.066 0,0.012 -2.304,7.434 -2.304,7.434" />_x000D_
        </g>_x000D_
    </g>_x000D_
  </defs>_x000D_
  <rect style="fill:#8AB" width="364" height="172" />_x000D_
  <use style="fill:white;" filter="url(#Blur)" xlink:href="#Img"_x000D_
    transform="translate(1.8,.9)"/>_x000D_
  <use style="fill:black;" xlink:href="#Img"/>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

How can I convert a string to a float in mysql?

This will convert to a numeric value without the need to cast or specify length or digits:

STRING_COL+0.0

If your column is an INT, can leave off the .0 to avoid decimals:

STRING_COL+0

How to generate a Dockerfile from an image?

How to generate or reverse a Dockerfile from an image?

You can.

alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage"
dfimage -sV=1.36 nginx:latest

It will pull the target docker image automaticlaly and export Dockerfile. Parameter -sV=1.36 is not always required.

Reference: https://hub.docker.com/repository/docker/alpine/dfimage

below is the old answer, it doesn't work any more.

$ docker pull centurylink/dockerfile-from-image
$ alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm centurylink/dockerfile-from-image"
$ dfimage --help
Usage: dockerfile-from-image.rb [options] <image_id>
    -f, --full-tree                  Generate Dockerfile for all parent layers
    -h, --help                       Show this message

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

Numpy - add row to array

As this question is been 7 years before, in the latest version which I am using is numpy version 1.13, and python3, I am doing the same thing with adding a row to a matrix, remember to put a double bracket to the second argument, otherwise, it will raise dimension error.

In here I am adding on matrix A

1 2 3
4 5 6

with a row

7 8 9

same usage in np.r_

A= [[1, 2, 3], [4, 5, 6]]
np.append(A, [[7, 8, 9]], axis=0)

    >> array([[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9]])
#or 
np.r_[A,[[7,8,9]]]

Just to someone's intersted, if you would like to add a column,

array = np.c_[A,np.zeros(#A's row size)]

following what we did before on matrix A, adding a column to it

np.c_[A, [2,8]]

>> array([[1, 2, 3, 2],
          [4, 5, 6, 8]])

Retrieving the COM class factory for component failed

I can understand your pain. In my case the error got resolved by performing below steps:

  1. Start > Run > dcomcnfg.
  2. Open the folder DCOM Config and Select Component Services > Computers > My Computer > DCOM Config.
  3. Select “Microsoft Office Word 97 – 2003 document”/”Microsoft Excel Application” and go to its properties.
  4. In "Security" tab set “Launch and Activation Permissions” need to be Customize (Authorized user).
  5. Now go to IIS and select application pool of the Web and go to its Advanced Settings and select “NETWORK SERVICE” as identity user.

Hope this helps.

How to avoid .pyc files?

You could make the directories that your modules exist in read-only for the user that the Python interpreter is running as.

I don't think there's a more elegant option. PEP 304 appears to have been an attempt to introduce a simple option for this, but it appears to have been abandoned.

I imagine there's probably some other problem you're trying to solve, for which disabling .py[co] would appear to be a workaround, but it'll probably be better to attack whatever this original problem is instead.

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

How to increase buffer size in Oracle SQL Developer to view all records?

after you retrieve the first 50 rows in the query windows, simply click a column to get focus on the query window, then once selected do ctrl + pagedown

This will load the full result set (all rows)

When should I use UNSIGNED and SIGNED INT in MySQL?

I don't not agree with vipin cp.

The true is that first bit is used for represent the sign. But 1 is for negative and 0 is for positive values. More over negative values are coded in different way (two's complement). Example with TINYINT:

The sign bit
|
1000 0000b = -128d  
...  
1111 1101b = -3d  
1111 1110b = -2d  
1111 1111b = -1d  

0000 0000b = 0d  
0000 0001b = 1d  
0000 0010b = 2d  
...  
0111 1111b = 127d  

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

How to install node.js as windows service?

I'm not addressing the question directly, but providing an alternative that might also meet your requirement in a more node.js fashion way.

Functionally the requirements are:

  1. Have the logic (app) running in the background
  2. Be able to start/stop the logic
  3. Automatically start the logic when system boots up

These requirements can be satisfied by using a process manager (PM) and making the process manager start on system startup. Two good PMs that are Windows-friendly are:

To make the PM start automatically, the most simple way is to create a scheduled task with a "At Startup" trigger:

enter image description here

How do I prevent a form from being resized by the user?

//Set fixed border
yourForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D

//Set the state of your form to maximized       
yourForm.WindowState = FormWindowState.Maximized

//Disable the minimize box and the maximize box
yourForm.MinimizeBox = False
yourForm.MaximizeBox = False

How to build and use Google TensorFlow C++ api

If you don't mind using CMake, there is also tensorflow_cc project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. The project README contains an example and Dockerfiles you can easily follow.

Min / Max Validator in Angular 2 Final

I found a library implementing a lot of custom validators - ng2-validation - that can be used with template-driven forms (attribute directives). Example:

<input type="number" [(ngModel)]="someNumber" name="someNumber" #field="ngModel" [range]="[10, 20]"/>
<p *ngIf="someNumber.errors?.range">Must be in range</p>

JList add/remove Item

The best and easiest way to clear a JLIST is:

myJlist.setListData(new String[0]);

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

What is the right way to treat argparse.Namespace() as a dictionary?

Straight from the horse's mouth:

If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars():

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo')
>>> args = parser.parse_args(['--foo', 'BAR'])
>>> vars(args)
{'foo': 'BAR'}

— The Python Standard Library, 16.4.4.6. The Namespace object

How to check if a float value is a whole number

You could use this:

if k == int(k):
    print(str(k) + " is a whole number!")

How to do associative array/hashing in JavaScript

https://gist.github.com/alexhawkins/f6329420f40e5cafa0a4

var HashTable = function() {
  this._storage = [];
  this._count = 0;
  this._limit = 8;
}


HashTable.prototype.insert = function(key, value) {

  // Create an index for our storage location by passing
  // it through our hashing function
  var index = this.hashFunc(key, this._limit);

  // Retrieve the bucket at this particular index in
  // our storage, if one exists
  //[[ [k,v], [k,v], [k,v] ] , [ [k,v], [k,v] ]  [ [k,v] ] ]
  var bucket = this._storage[index]

  // Does a bucket exist or do we get undefined
  // when trying to retrieve said index?
  if (!bucket) {
    // Create the bucket
    var bucket = [];
    // Insert the bucket into our hashTable
    this._storage[index] = bucket;
  }

  var override = false;

  // Now iterate through our bucket to see if there are any conflicting
  // key value pairs within our bucket. If there are any, override them.
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {

      // Override value stored at this key
      tuple[1] = value;
      override = true;
    }
  }

  if (!override) {
    // Create a new tuple in our bucket.
    // Note that this could either be the new empty bucket we created above
    // or a bucket with other tupules with keys that are different than
    // the key of the tuple we are inserting. These tupules are in the same
    // bucket because their keys all equate to the same numeric index when
    // passing through our hash function.
    bucket.push([key, value]);
    this._count++

    // Now that we've added our new key/val pair to our storage
    // let's check to see if we need to resize our storage
    if (this._count > this._limit * 0.75) {
      this.resize(this._limit * 2);
    }
  }
  return this;
};


HashTable.prototype.remove = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];
  if (!bucket) {
    return null;
  }

  // Iterate over the bucket
  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];

    // Check to see if key is inside bucket
    if (tuple[0] === key) {

      // If it is, get rid of this tuple
      bucket.splice(i, 1);
      this._count--;
      if (this._count < this._limit * 0.25) {
        this._resize(this._limit / 2);
      }
      return tuple[1];
    }
  }
};


HashTable.prototype.retrieve = function(key) {
  var index = this.hashFunc(key, this._limit);
  var bucket = this._storage[index];

  if (!bucket) {
    return null;
  }

  for (var i = 0; i < bucket.length; i++) {
    var tuple = bucket[i];
    if (tuple[0] === key) {
      return tuple[1];
    }
  }

  return null;
};


HashTable.prototype.hashFunc = function(str, max) {
  var hash = 0;
  for (var i = 0; i < str.length; i++) {
    var letter = str[i];
    hash = (hash << 5) + letter.charCodeAt(0);
    hash = (hash & hash) % max;
  }
  return hash;
};


HashTable.prototype.resize = function(newLimit) {
  var oldStorage = this._storage;

  this._limit = newLimit;
  this._count = 0;
  this._storage = [];

  oldStorage.forEach(function(bucket) {
    if (!bucket) {
      return;
    }
    for (var i = 0; i < bucket.length; i++) {
      var tuple = bucket[i];
      this.insert(tuple[0], tuple[1]);
    }
  }.bind(this));
};


HashTable.prototype.retrieveAll = function() {
  console.log(this._storage);
  //console.log(this._limit);
};

/******************************TESTS*******************************/

var hashT = new HashTable();

hashT.insert('Alex Hawkins', '510-599-1930');
//hashT.retrieve();
//[ , , , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Boo Radley', '520-589-1970');
//hashT.retrieve();
//[ , [ [ 'Boo Radley', '520-589-1970' ] ], , [ [ 'Alex Hawkins', '510-599-1930' ] ] ]
hashT.insert('Vance Carter', '120-589-1970').insert('Rick Mires', '520-589-1970').insert('Tom Bradey', '520-589-1970').insert('Biff Tanin', '520-589-1970');
//hashT.retrieveAll();
/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '520-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '520-589-1970' ] ] ]
*/

// Override example (Phone Number Change)
//
hashT.insert('Rick Mires', '650-589-1970').insert('Tom Bradey', '818-589-1970').insert('Biff Tanin', '987-589-1970');
//hashT.retrieveAll();

/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Tom Bradey', '818-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Rick Mires', '650-589-1970' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

hashT.remove('Rick Mires');
hashT.remove('Tom Bradey');
//hashT.retrieveAll();

/*
[ ,
  [ [ 'Boo Radley', '520-589-1970' ] ],
  ,
  [ [ 'Alex Hawkins', '510-599-1930' ] ],
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]


*/

hashT.insert('Dick Mires', '650-589-1970').insert('Lam James', '818-589-1970').insert('Ricky Ticky Tavi', '987-589-1970');
hashT.retrieveAll();


/* NOTICE HOW THE HASH TABLE HAS NOW DOUBLED IN SIZE UPON REACHING 75% CAPACITY, i.e. 6/8. It is now size 16.
 [,
  ,
  [ [ 'Vance Carter', '120-589-1970' ] ],
  [ [ 'Alex Hawkins', '510-599-1930' ],
    [ 'Dick Mires', '650-589-1970' ],
    [ 'Lam James', '818-589-1970' ] ],
  ,
  ,
  ,
  ,
  ,
  [ [ 'Boo Radley', '520-589-1970' ],
    [ 'Ricky Ticky Tavi', '987-589-1970' ] ],
  ,
  ,
  ,
  ,
  [ [ 'Biff Tanin', '987-589-1970' ] ] ]

*/

console.log(hashT.retrieve('Lam James'));  // 818-589-1970
console.log(hashT.retrieve('Dick Mires')); // 650-589-1970
console.log(hashT.retrieve('Ricky Ticky Tavi')); //987-589-1970
console.log(hashT.retrieve('Alex Hawkins')); // 510-599-1930
console.log(hashT.retrieve('Lebron James')); // null

NSString property: copy or retain?

@interface TTItem : NSObject    
@property (nonatomic, copy) NSString *name;
@end

{
    TTItem *item = [[TTItem alloc] init];    
    NSString *test1 = [NSString stringWithFormat:@"%d / %@", 1, @"Go go go"];  
    item.name = test1;  
    NSLog(@"-item.name: point = %p, content = %@; test1 = %p", item.name, item.name, test1);  
    test1 = [NSString stringWithFormat:@"%d / %@", 2, @"Back back back"];  
    NSLog(@"+item.name: point = %p, content = %@, test1 = %p", item.name, item.name, test1);
}

Log:  
    -item.name: point = 0x9a805a0, content = 1 / Go go go; test1 = 0x9a805a0  
    +item.name: point = 0x9a805a0, content = 1 / Go go go, test1 = 0x9a84660

"relocation R_X86_64_32S against " linking Error

Assuming you are generating a shared library, most probably what happens is that the variant of liblog4cplus.a you are using wasn't compiled with -fPIC. In linux, you can confirm this by extracting the object files from the static library and checking their relocations:

ar -x liblog4cplus.a  
readelf --relocs fileappender.o | egrep '(GOT|PLT|JU?MP_SLOT)'

If the output is empty, then the static library is not position-independent and cannot be used to generate a shared object.

Since the static library contains object code which was already compiled, providing the -fPIC flag won't help.

You need to get ahold of a version of liblog4cplus.a compiled with -fPIC and use that one instead.

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Collapse all methods in Visual Studio Code

  • Fold All:

    • Windows: Ctrl + K + 0
    • Mac: ? + K + 0
  • Unfold All:

    • Windows: Ctrl + K + J
    • Mac: ? + K + J

To see all available shortcuts in the editor:

  • Windows: Ctrl + K + S
  • Mac: ? + K + S

Screenshot of Visual Studio keyboard shortcuts

All shortcuts kept up to date by the Visual Studio Code team: Visual Studio Code Shortcuts

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

Viewing contents of a .jar file

You could try JarNavigator to view and search contents of a jar file.

Undoing a 'git push'

git revert is less dangerous than some of the approaches suggested here:

prompt> git revert 35f6af6f77f116ef922e3d75bc80a4a466f92650
[master 71738a9] Revert "Issue #482 - Fixed bug."
 4 files changed, 30 insertions(+), 42 deletions(-)
prompt> git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
prompt>

Replace 35f6af6f77f116ef922e3d75bc80a4a466f92650 with your own commit.

What is the use of verbose in Keras while validating the model?

The order of details provided with verbose flag are as

Less details.... More details

0 < 2 < 1

Default is 1

For production environment, 2 is recommended

How to pip or easy_install tkinter on Windows

If you are using virtualenv, it is fine to install tkinter using sudo apt-get install python-tk(python2), sudo apt-get install python3-tk(python3), and and it will work fine in the virtual environment

How can I get the active screen dimensions?

I wanted to have the screen resolution before opening the first of my windows, so here a quick solution to open an invisible window before actually measuring screen dimensions (you need to adapt the window parameters to your window in order to ensure that both are openend on the same screen - mainly the WindowStartupLocation is important)

Window w = new Window();
w.ResizeMode = ResizeMode.NoResize;
w.WindowState = WindowState.Normal;
w.WindowStyle = WindowStyle.None;
w.Background = Brushes.Transparent;
w.Width = 0;
w.Height = 0;
w.AllowsTransparency = true;
w.IsHitTestVisible = false;
w.WindowStartupLocation = WindowStartupLocation.Manual;
w.Show();
Screen scr = Screen.FromHandle(new WindowInteropHelper(w).Handle);
w.Close();

Copy folder recursively in Node.js

I tried fs-extra and copy-dir to copy-folder-recursively. but I want it to

  1. work normally (copy-dir throws an unreasonable error)
  2. provide two arguments in filter: filepath and filetype (fs-extra does't tell filetype)
  3. have a dir-to-subdir check and a dir-to-file check

So I wrote my own:

// Node.js module for Node.js 8.6+
var path = require("path");
var fs = require("fs");

function copyDirSync(src, dest, options) {
  var srcPath = path.resolve(src);
  var destPath = path.resolve(dest);
  if(path.relative(srcPath, destPath).charAt(0) != ".")
    throw new Error("dest path must be out of src path");
  var settings = Object.assign(Object.create(copyDirSync.options), options);
  copyDirSync0(srcPath, destPath, settings);
  function copyDirSync0(srcPath, destPath, settings) {
    var files = fs.readdirSync(srcPath);
    if (!fs.existsSync(destPath)) {
      fs.mkdirSync(destPath);
    }else if(!fs.lstatSync(destPath).isDirectory()) {
      if(settings.overwrite)
        throw new Error(`Cannot overwrite non-directory '${destPath}' with directory '${srcPath}'.`);
      return;
    }
    files.forEach(function(filename) {
      var childSrcPath = path.join(srcPath, filename);
      var childDestPath = path.join(destPath, filename);
      var type = fs.lstatSync(childSrcPath).isDirectory() ? "directory" : "file";
      if(!settings.filter(childSrcPath, type))
        return;
      if (type == "directory") {
        copyDirSync0(childSrcPath, childDestPath, settings);
      } else {
        fs.copyFileSync(childSrcPath, childDestPath, settings.overwrite ? 0 : fs.constants.COPYFILE_EXCL);
        if(!settings.preserveFileDate)
          fs.futimesSync(childDestPath, Date.now(), Date.now());
      }
    });
  }
}
copyDirSync.options = {
  overwrite: true,
  preserveFileDate: true,
  filter: function(filepath, type) {
    return true;
  }
};

And a similar function, mkdirs, which is an alternative to mkdirp:

function mkdirsSync(dest) {
  var destPath = path.resolve(dest);
  mkdirsSync0(destPath);
  function mkdirsSync0(destPath) {
    var parentPath = path.dirname(destPath);
    if(parentPath == destPath)
      throw new Error(`cannot mkdir ${destPath}, invalid root`);
    if (!fs.existsSync(destPath)) {
      mkdirsSync0(parentPath);
      fs.mkdirSync(destPath);
    }else if(!fs.lstatSync(destPath).isDirectory()) {
      throw new Error(`cannot mkdir ${destPath}, a file already exists there`);
    }
  }
}

Case vs If Else If: Which is more efficient?

Many programming language optimize the switch statement so that it is much faster than a standard if-else if structure provided the cases are compiler constants. Many languages use a jump table or indexed branch table to optimize switch statements. Wikipedia has a good discussion of the switch statement. Also, here is a discussion of switch optimization in C.

One thing to note is that switch statements can be abused and, depending on the case, it may be preferable to use polymorphism instead of switch statements. See here for an example.

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

How to produce an csv output file from stored procedure in SQL Server

I think it is possible to use bcp command. I am also new to this command but I followed this link and it worked for me.

Better/Faster to Loop through set or list?

set is what you want, so you should use set. Trying to be clever introduces subtle bugs like forgetting to add one tomax(mylist)! Code defensively. Worry about what's faster when you determine that it is too slow.

range(min(mylist), max(mylist) + 1)  # <-- don't forget to add 1

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );

Confused about stdin, stdout and stderr?

Here is a lengthy article on stdin, stdout and stderr:

To summarize:

Streams Are Handled Like Files

Streams in Linux—like almost everything else—are treated as though they were files. You can read text from a file, and you can write text into a file. Both of these actions involve a stream of data. So the concept of handling a stream of data as a file isn’t that much of a stretch.

Each file associated with a process is allocated a unique number to identify it. This is known as the file descriptor. Whenever an action is required to be performed on a file, the file descriptor is used to identify the file.

These values are always used for stdin, stdout, and stderr:

0: stdin
1: stdout
2: stderr

Ironically I found this question on stack overflow and the article above because I was searching for information on abnormal / non-standard streams. So my search continues.

MySQL and PHP - insert NULL rather than empty string

Check the variables before building the query, if they are empty, change them to the string NULL

Upload files from Java client to a HTTP server

You'd normally use java.net.URLConnection to fire HTTP requests. You'd also normally use multipart/form-data encoding for mixed POST content (binary and character data). Click the link, it contains information and an example how to compose a multipart/form-data request body. The specification is in more detail described in RFC2388.

Here's a kickoff example:

String url = "http://example.com/upload";
String charset = "UTF-8";
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.

URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

try (
    OutputStream output = connection.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
    // Send normal param.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
    writer.append(CRLF).append(param).append(CRLF).flush();

    // Send text file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
    writer.append(CRLF).flush();
    Files.copy(textFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    Files.copy(binaryFile.toPath(), output);
    output.flush(); // Important before continuing with writer!
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.

    // End of multipart/form-data.
    writer.append("--" + boundary + "--").append(CRLF).flush();
}

// Request is lazily fired whenever you need to obtain information about response.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode); // Should be 200

This code is less verbose when you use a 3rd party library like Apache Commons HttpComponents Client.

The Apache Commons FileUpload as some incorrectly suggest here is only of interest in the server side. You can't use and don't need it at the client side.

See also

How to resolve Value cannot be null. Parameter name: source in linq?

System.ArgumentNullException: Value cannot be null. Parameter name: value

This error message is not very helpful!

You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.

As a generic way to solve this, look at the stack trace or call stack:

Test method GetApiModel threw exception: 
System.ArgumentNullException: Value cannot be null.
Parameter name: value
    at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

You can see that the parameter name value is the first parameter for DeserializeObject. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.

You can change the code to check for null.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How to Make A Chevron Arrow Using CSS?

This can be solved much easier than the other suggestions.

Simply draw a square and apply a border property to just 2 joining sides.

Then rotate the square according to the direction you want the arrow to point, for exaple: transform: rotate(<your degree here>)

_x000D_
_x000D_
.triangle {_x000D_
    border-right: 10px solid; _x000D_
    border-bottom: 10px solid;_x000D_
    height: 30px;_x000D_
    width: 30px;_x000D_
    transform: rotate(-45deg);_x000D_
}
_x000D_
<div class="triangle"></div>
_x000D_
_x000D_
_x000D_

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
{
    book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");

No resource found that matches the given name '@style/Theme.AppCompat.Light'

The steps described above do work, however I've encountered this problem on IntelliJ IDEA and have found that I'm having these problems with existing projects and the only solution is to remove the 'appcompat' module (not the library) and re-import it.

Store images in a MongoDB database

Please see the GridFS docs for details on storing such binary data.

Support for your specific language should be linked to at the bottom of the screen.

How do I uninstall a Windows service if the files do not exist anymore?

Notes on using "sc delete" in Windows 8:

1) Open a CMD window with elevated privileges. [Windows Key-X to bring up a menu with the option; select "Command Prompt (Admin)".]
2) Use the parenthetical name from the list in Services [for example, I used "sc delete gupdate" when, in Services, it read "Google Update (gupdate)"]

Your project contains error(s), please fix it before running it

Yes, this is a rather cryptic message. If you've got a faulty project (say one you've been working on in the past) then you'll get this message (and no messages in your current project's Problems / Error Log panes).

You may just want to run your current project. This may be perfectly fine. Just click on the down arrow to the right of the Run button to select your project.

Why does JPA have a @Transient annotation?

As others have said, @Transient is used to mark fields which shouldn't be persisted. Consider this short example:

public enum Gender { MALE, FEMALE, UNKNOWN }

@Entity
public Person {
    private Gender g;
    private long id;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

    public Gender getGender() { return g; }    
    public void setGender(Gender g) { this.g = g; }

    @Transient
    public boolean isMale() {
        return Gender.MALE.equals(g);
    }

    @Transient
    public boolean isFemale() {
        return Gender.FEMALE.equals(g);
    }
}

When this class is fed to the JPA, it persists the gender and id but doesn't try to persist the helper boolean methods - without @Transient the underlying system would complain that the Entity class Person is missing setMale() and setFemale() methods and thus wouldn't persist Person at all.

Twitter Bootstrap dropdown menu

It actually requires inclusion of Twitter Bootstrap's dropdown.js

http://getbootstrap.com/2.3.2/components.html

What does "<>" mean in Oracle

It just means "different of", some languages uses !=, others (like SQL) <>

How to get multiple select box values using jQuery?

Just use this

$('#multipleSelect').change(function() {
    var selectedValues = $(this).val();  
});

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

What's the difference between ASCII and Unicode?

Storage

Given numbers are only for storing 1 character

  • ASCII ? 27 bits (1 byte)
  • Extended ASCII ? 28 bits (1 byte)
  • UTF-8 ? minimum 28, maximum 232 bits (min 1, max 4 bytes)
  • UTF-16 ? minimum 216, maximum 232 bits (min 2, max 4 bytes)
  • UTF-32 ? 232 bits (4 bytes)

Usage (as of Feb 2020)

Percentages of websites using various character encodings

How do I debug jquery AJAX calls?

Install Firebig to see where your error is happening. You could also set up a callback in your ajax call to return your error messages from your PHP. Eg.

error: function(e){
     alert(e);
     }

Convert a object into JSON in REST service by Spring MVC

Spring framework itself handles json conversion when controller is annotated properly.

For eg:

   @PutMapping(produces = {"application/json"})
        @ResponseBody
        public UpdateResponse someMethod(){ //do something
return UpdateResponseInstance;
}

Here spring internally converts the UpdateResponse object to corresponding json string and returns it. In order to do it spring internally uses Jackson library.

If you require a json representation of a model object anywhere apart from controller then you can use objectMapper provided by jackson. Model should be properly annotated for this to work.

Eg:

ObjectMapper mapper = new ObjectMapper();
SomeModelClass someModelObject = someModelRepository.findById(idValue).get();
mapper.writeValueAsString(someModelObject);

how to print an exception using logger?

You should probably clarify which logger are you using.

org.apache.commons.logging.Log interface has method void error(Object message, Throwable t) (and method void info(Object message, Throwable t)), which logs the stack trace together with your custom message. Log4J implementation has this method too.

So, probably you need to write:

logger.error("BOOM!", e);

If you need to log it with INFO level (though, it might be a strange use case), then:

logger.info("Just a stack trace, nothing to worry about", e);

Hope it helps.

C# loop - break vs. continue

All have given a very good explanation. I am still posting my answer just to give an example if that can help.

// break statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        break; // It will force to come out from the loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed]

So 3[Printed] & 4[Printed] will not be displayed as there is break when i == 3

//continue statement
for (int i = 0; i < 5; i++) {
    if (i == 3) {
        continue; // It will take the control to start point of loop
    }

    lblDisplay.Text = lblDisplay.Text + i + "[Printed] ";
}

Here is the output:

0[Printed] 1[Printed] 2[Printed] 4[Printed]

So 3[Printed] will not be displayed as there is continue when i == 3

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

Save attachments to a folder and rename them

I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.

I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
        saveFolder = "C:\PathToDirectory\"
    Dim dateFormat As String
        dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Thanks a ton for the other solutions, many of them go above an beyond :)

How do I check if a cookie exists?

Note that if a cookie is secure, you cannot check in client side for its existence using document.cookie (which all of the answers are using). Such cookie can be checked only at sever side.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I experienced a similar error reply while using the openssl command line interface, while having the correct binary key (-K). The option "-nopad" resolved the issue:

Example generating the error:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 | od -t x1

Result:

bad decrypt
140181876450560:error:06065064:digital envelope 
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:535:
0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38

Example with correct result:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 -nopad | od -t x1

Result:

0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38
0000060 30 30 30 34 31 33 31 2f 2f 2f 2f 2f 2f 2f 2f 2f
0000100

How to get a complete list of object's methods and attributes?

This is how I do it, useful for simple custom objects to which you keep adding attributes:

Given an object created with obj = type("Obj",(object,),{}), or by simply:

class Obj: pass
obj = Obj()

Add some attributes:

obj.name = 'gary'
obj.age = 32

then, to obtain a dictionary with only the custom attributes:

{key: value for key, value in obj.__dict__.items() if not key.startswith("__")}

# {'name': 'gary', 'age': 32}

The ResourceConfig instance does not contain any root resource classes

Main cause of this Exception is:

You have not given the proper package name where you using the @Path or forgot to configure in web.xml / Configuration file(Rest API Class File package Name, Your Class Package Name)

Check this Configuration inside <init-param>

Multiple HttpPost method in Web API controller

It is Possible to add Multiple Get and Post methods in the same Web API Controller. Here default Route is Causing the Issue. Web API checks for Matching Route from Top to Bottom and Hence Your Default Route Matches for all Requests. As per default route only one Get and Post Method is possible in one controller. Either place the following code on top or Comment Out/Delete Default Route

    config.Routes.MapHttpRoute("API Default", 
                               "api/{controller}/{action}/{id}",
                               new { id = RouteParameter.Optional });

How to make <input type="date"> supported on all browsers? Any alternatives?

best easy and working solution i have found is, working on following browsers

  1. Google Chrome
  2. Firefox
  3. Microsoft Edge
  4. Safari

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>
    </head>
    
    <body>
    <h2>Poly Filler Script for Date/Time</h2>
    <form method="post" action="">
        <input type="date" />
        <br/><br/>
        <input type="time" />
    </form>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/extras/modernizr-custom.js"></script>
    <script src="http://cdn.jsdelivr.net/webshim/1.12.4/polyfiller.js"></script>
    <script>
      webshims.setOptions('waitReady', false);
      webshims.setOptions('forms-ext', {type: 'date'});
      webshims.setOptions('forms-ext', {type: 'time'});
      webshims.polyfill('forms forms-ext');
    </script>
    
    </body>
    </html>
    

How to auto adjust the <div> height according to content in it?

<div> should expand automatically. I guess that the problem is that you're using fixed height:100px;, try replacing it with min-height:100px;

C# Interfaces. Implicit implementation versus Explicit implementation

One important use of explicit interface implementation is when in need to implement interfaces with mixed visibility.

The problem and solution are well explained in the article C# Internal Interface.

For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

Disable cache for some images

Browser caching strategies can be controlled by HTTP headers. Remember that they are just a hint, really. Since browsers are terribly inconsistent in this (and any other) field, you'll need several headers to get the desired effect on a range of browsers.

header ("Pragma-directive: no-cache");
header ("Cache-directive: no-cache");
header ("Cache-control: no-cache");
header ("Pragma: no-cache");
header ("Expires: 0");

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The short answer: there is no difference.

The long answer: CHARACTER VARYING is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR is a shorter alias which all modern databases also support. I prefer VARCHAR because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump and \d will output character varying.

Fatal error: Call to undefined function mcrypt_encrypt()

Check and install php5-mcrypt:

sudo apt-get install php5-mcrypt

Button text toggle in jquery

If you're setting the button text by using the 'value' attribute you'll need to set

  • $(this).val()

instead of:

  • $(this).text()

Also in my situation it worked better to add the JQuery direct to the onclick event of the button:

onclick="$(this).val(function (i, text) { return text == 'PUSH ME' ? 'DON'T PUSH ME' : 'PUSH ME'; });"

Python str vs unicode types

unicode is meant to handle text. Text is a sequence of code points which may be bigger than a single byte. Text can be encoded in a specific encoding to represent the text as raw bytes(e.g. utf-8, latin-1...).

Note that unicode is not encoded! The internal representation used by python is an implementation detail, and you shouldn't care about it as long as it is able to represent the code points you want.

On the contrary str in Python 2 is a plain sequence of bytes. It does not represent text!

You can think of unicode as a general representation of some text, which can be encoded in many different ways into a sequence of binary data represented via str.

Note: In Python 3, unicode was renamed to str and there is a new bytes type for a plain sequence of bytes.

Some differences that you can see:

>>> len(u'à')  # a single code point
1
>>> len('à')   # by default utf-8 -> takes two bytes
2
>>> len(u'à'.encode('utf-8'))
2
>>> len(u'à'.encode('latin1'))  # in latin1 it takes one byte
1
>>> print u'à'.encode('utf-8')  # terminal encoding is utf-8
à
>>> print u'à'.encode('latin1') # it cannot understand the latin1 byte
?

Note that using str you have a lower-level control on the single bytes of a specific encoding representation, while using unicode you can only control at the code-point level. For example you can do:

>>> 'àèìòù'
'\xc3\xa0\xc3\xa8\xc3\xac\xc3\xb2\xc3\xb9'
>>> print 'àèìòù'.replace('\xa8', '')
à?ìòù

What before was valid UTF-8, isn't anymore. Using a unicode string you cannot operate in such a way that the resulting string isn't valid unicode text. You can remove a code point, replace a code point with a different code point etc. but you cannot mess with the internal representation.

Rails DateTime.now without Time

Figured it out. This works:

DateTime.now.in_time_zone.midnight

How to get the first column of a pandas DataFrame as a Series?

From v0.11+, ... use df.iloc.

In [7]: df.iloc[:,0]
Out[7]: 
0    1
1    2
2    3
3    4
Name: x, dtype: int64

String is immutable. What exactly is the meaning?

A string is a char[] containing a series of UTF-16 code units, an int offset into that array, and an int length.

For example.

String s

It creates space for a string reference. Assigning copies references around but does not modify the objects to which those references refer.

You should also be aware that

new String(s)

doesn't really do anything useful. It merely creates another instance backed by the same array, offset, and length as s. There is very rarely a reason to do this so it is considered bad practice by most Java programmers.

Java double quoted strings like "my string" are really references to interned String instances so "bar" is a reference to the same String instance regardless of how many times it appears in your code.


The "hello" creates one instance that is pooled, and the new String(...) creates a non-pooled instance. Try System.out.println(("hello" == "hello") + "," + (new String("hello") == "hello") + "," + (new String("hello") == new String("hello"))); and you should see true,false,false

What is the difference between Nexus and Maven?

Sonatype Nexus and Apache Maven are two pieces of software that often work together but they do very different parts of the job. Nexus provides a repository while Maven uses a repository to build software.

Here's a quote from "What is Nexus?":

Nexus manages software "artifacts" required for development. If you develop software, your builds can download dependencies from Nexus and can publish artifacts to Nexus creating a new way to share artifacts within an organization. While Central repository has always served as a great convenience for developers you shouldn't be hitting it directly. You should be proxying Central with Nexus and maintaining your own repositories to ensure stability within your organization. With Nexus you can completely control access to, and deployment of, every artifact in your organization from a single location.

And here is a quote from "Maven and Nexus Pro, Made for Each Other" explaining how Maven uses repositories:

Maven leverages the concept of a repository by retrieving the artifacts necessary to build an application and deploying the result of the build process into a repository. Maven uses the concept of structured repositories so components can be retrieved to support the build. These components or dependencies include libraries, frameworks, containers, etc. Maven can identify components in repositories, understand their dependencies, retrieve all that are needed for a successful build, and deploy its output back to repositories when the build is complete.

So, when you want to use both you will have a repository managed by Nexus and Maven will access this repository.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

How to cd into a directory with space in the name?

try

DOCS="/cygdrive/c/Users/my\ dir/Documents";

cd "$DOCS"

How to get numbers after decimal point?

See what I often do to obtain numbers after the decimal point in python 3:

a=1.22
dec=str(a).split('.')
dec= int(dec[1])

jQuery select child element by class with unknown path

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector) is the fastest and most efficient way to do this.

Mongoimport of json file

I have used below command for export DB

mongodump --db database_name --collection collection_name

and below command worked for me to import DB

mongorestore --db database_name path_to_bson_file

Disable pasting text into HTML form

I did something similar to this for http://bookmarkchamp.com - there I wanted to detect when a user copied something into an HTML field. The implementation I came up with was to check the field constantly to see if at any time there was suddenly a whole lot of text in there.

In other words: if once milisecond ago there was no text, and now there are more than 5 chars... then the user probably pasted something in the field.

If you want to see this working in Bookmarkchamp (you need to be registered), paste a URL into the URL field (or drag and drop a URL in there).

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

After struggling with all available options, I ended up writing a JWT token based SessionStore provider (the session travels inside a cookie, and no backend storage is needed).

http://www.drupalonwindows.com/en/content/token-sessionstate

Advantages:

  • Drop-in replacement, no changes to your code are needed
  • Scale better than any other centralized store, as no session storage backend is needed.
  • Faster than any other session storage, as no data needs to be retrieved from any session storage
  • Consumes no server resources for session storage.
  • Default non-blocking implementation: concurrent request won't block each other and hold a lock on the session
  • Horizontally scale your application: because the session data travels with the request itself you can have multiple web heads without worrying about session sharing.

Compile to stand alone exe for C# app in Visual Studio 2010

I am using visual studio 2010 to make a program on SMSC Server. What you have to do is go to build-->publish. you will be asked be asked to few simple things and the location where you want to store your application, browse the location where you want to put it.

I hope this is what you are looking for

Merge 2 DataTables and store in a new one

The Merge method takes the values from the second table and merges them in with the first table, so the first will now hold the values from both.

If you want to preserve both of the original tables, you could copy the original first, then merge:

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo);

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

What is the effect of extern "C" in C++?

Decompile a g++ generated binary to see what is going on

main.cpp

void f() {}
void g();

extern "C" {
    void ef() {}
    void eg();
}

/* Prevent g and eg from being optimized away. */
void h() { g(); eg(); }

Compile and disassemble the generated ELF output:

g++ -c -std=c++11 -Wall -Wextra -pedantic -o main.o main.cpp
readelf -s main.o

The output contains:

     8: 0000000000000000     7 FUNC    GLOBAL DEFAULT    1 _Z1fv
     9: 0000000000000007     7 FUNC    GLOBAL DEFAULT    1 ef
    10: 000000000000000e    17 FUNC    GLOBAL DEFAULT    1 _Z1hv
    11: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _GLOBAL_OFFSET_TABLE_
    12: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND _Z1gv
    13: 0000000000000000     0 NOTYPE  GLOBAL DEFAULT  UND eg

Interpretation

We see that:

  • ef and eg were stored in symbols with the same name as in the code

  • the other symbols were mangled. Let's unmangle them:

    $ c++filt _Z1fv
    f()
    $ c++filt _Z1hv
    h()
    $ c++filt _Z1gv
    g()
    

Conclusion: both of the following symbol types were not mangled:

  • defined
  • declared but undefined (Ndx = UND), to be provided at link or run time from another object file

So you will need extern "C" both when calling:

  • C from C++: tell g++ to expect unmangled symbols produced by gcc
  • C++ from C: tell g++ to generate unmangled symbols for gcc to use

Things that do not work in extern C

It becomes obvious that any C++ feature that requires name mangling will not work inside extern C:

extern "C" {
    // Overloading.
    // error: declaration of C function ‘void f(int)’ conflicts with
    void f();
    void f(int i);

    // Templates.
    // error: template with C linkage
    template <class C> void f(C i) { }
}

Minimal runnable C from C++ example

For the sake of completeness and for the newbs out there, see also: How to use C source files in a C++ project?

Calling C from C++ is pretty easy: each C function only has one possible non-mangled symbol, so no extra work is required.

main.cpp

#include <cassert>

#include "c.h"

int main() {
    assert(f() == 1);
}

c.h

#ifndef C_H
#define C_H

/* This ifdef allows the header to be used from both C and C++ 
 * because C does not know what this extern "C" thing is. */
#ifdef __cplusplus
extern "C" {
#endif
int f();
#ifdef __cplusplus
}
#endif

#endif

c.c

#include "c.h"

int f(void) { return 1; }

Run:

g++ -c -o main.o -std=c++98 main.cpp
gcc -c -o c.o -std=c89 c.c
g++ -o main.out main.o c.o
./main.out

Without extern "C" the link fails with:

main.cpp:6: undefined reference to `f()'

because g++ expects to find a mangled f, which gcc did not produce.

Example on GitHub.

Minimal runnable C++ from C example

Calling C++ from C is a bit harder: we have to manually create non-mangled versions of each function we want to expose.

Here we illustrate how to expose C++ function overloads to C.

main.c

#include <assert.h>

#include "cpp.h"

int main(void) {
    assert(f_int(1) == 2);
    assert(f_float(1.0) == 3);
    return 0;
}

cpp.h

#ifndef CPP_H
#define CPP_H

#ifdef __cplusplus
// C cannot see these overloaded prototypes, or else it would get confused.
int f(int i);
int f(float i);
extern "C" {
#endif
int f_int(int i);
int f_float(float i);
#ifdef __cplusplus
}
#endif

#endif

cpp.cpp

#include "cpp.h"

int f(int i) {
    return i + 1;
}

int f(float i) {
    return i + 2;
}

int f_int(int i) {
    return f(i);
}

int f_float(float i) {
    return f(i);
}

Run:

gcc -c -o main.o -std=c89 -Wextra main.c
g++ -c -o cpp.o -std=c++98 cpp.cpp
g++ -o main.out main.o cpp.o
./main.out

Without extern "C" it fails with:

main.c:6: undefined reference to `f_int'
main.c:7: undefined reference to `f_float'

because g++ generated mangled symbols which gcc cannot find.

Example on GitHub.

Where is the extern "c" when I include C headers from C++?

Tested in Ubuntu 18.04.

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

In my case, the servlet-api.jar file in jre/lib/ext in the jdk directory conflicts with the servlet-api.jar file in tomcat, removing the servlet-api.jar in jre/lib/ext in the jdk directory can solve the problem.

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

HAX kernel module is not installed

Try installing it again with the stand alone installer https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement - assuming you have a CPU that supports Virtualization, have turned off antivirus and any hypervisor.

Printing Lists as Tabular Data

A simple way to do this is to loop over all columns, measure their width, create a row_template for that max width, and then print the rows. It's not exactly what you are looking for, because in this case, you first have to put your headings inside the table, but I'm thinking it might be useful to someone else.

table = [
    ["", "Man Utd", "Man City", "T Hotspur"],
    ["Man Utd", 1, 0, 0],
    ["Man City", 1, 1, 0],
    ["T Hotspur", 0, 1, 2],
]
def print_table(table):
    longest_cols = [
        (max([len(str(row[i])) for row in table]) + 3)
        for i in range(len(table[0]))
    ]
    row_format = "".join(["{:>" + str(longest_col) + "}" for longest_col in longest_cols])
    for row in table:
        print(row_format.format(*row))

You use it like this:

>>> print_table(table)

            Man Utd   Man City   T Hotspur
  Man Utd         1          0           0
 Man City         1          1           0
T Hotspur         0          1           2

What is the equivalent of ngShow and ngHide in Angular 2+?

Sorry, I have to disagree with binding to hidden which is considered to be unsafe when using Angular 2. This is because the hidden style could be overwritten easily for example using

display: flex;

The recommended approach is to use *ngIf which is safer. For more details, please refer to the official Angular blog. 5 Rookie Mistakes to Avoid with Angular 2

<div *ngIf="showGreeting">
   Hello, there!
</div>

Styling input buttons for iPad and iPhone

Use the below css

_x000D_
_x000D_
input[type="submit"] {_x000D_
  font-size: 20px;_x000D_
  background: pink;_x000D_
  border: none;_x000D_
  padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
   appearance: none;_x000D_
   border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  margin: 25px 0 10px;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
_x000D_
_x000D_

google-services.json for different productFlavors

Simplifying what @Scotti said. You need to create Multiples apps with different package name for a particular Project depending on the product flavor.

Suppose your Project is ABC having different product flavors X,Y where X has a package name com.x and Y has a package name com.y then in the firebase console you need to create a project ABC in which you need to create 2 apps with the package names com.x and com.y. Then you need to download the google-services.json file in which there will be 2 client-info objects which will contain those pacakges and you will be good to go.

Snippet of the json would be something like this

{
  "client": [
    {
      "client_info": {
        "android_client_info": {
          "package_name": "com.x"
        }

    {
      "client_info": {
        "android_client_info": {
          "package_name": "com.y"
        }
      ]

    }

Value cannot be null. Parameter name: source

In case anyone else ends up here with my issue with a DB First Entity Framework setup.

Long story short, I needed to overload the Entities constructor to accept a connection string, the reason being the ability to use Asp.Net Core dependency injection container pulling the connection string from appsettings.json, rather than magically getting it from the App.config file when calling the parameterless constructor.

I forgot to add the calls to initialize my DbSets in the new overload. So the auto-generated parameter-less constructor looked something like this:

    public MyEntities()
        : base("name=MyEntity")
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

And my new overload looked like this:

    public MyEntities(string connectionString)
        : base(connectionString)
    {
    }

The solution was to add those initializers that the auto-generated code takes care of, a simple missed step:

     public MyEntities(string connectionString)
        : base(connectionString)
    {
        Set1 = Set<MyDbSet1>();
        Set2 = Set<MyDbSet2>();
    }

This really threw me for a loop because some calls in our Respository that used the DbContext worked fine (the ones that didn't need those initialized DBSets), and the others throw the runtime error described in the OP.

In python, how do I cast a class object to a dict

I am trying to write a class that is "both" a list or a dict. I want the programmer to be able to both "cast" this object to a list (dropping the keys) or dict (with the keys).

Looking at the way Python currently does the dict() cast: It calls Mapping.update() with the object that is passed. This is the code from the Python repo:

def update(self, other=(), /, **kwds):
    ''' D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
        If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
        If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
        In either case, this is followed by: for k, v in F.items(): D[k] = v
    '''
    if isinstance(other, Mapping):
        for key in other:
            self[key] = other[key]
    elif hasattr(other, "keys"):
        for key in other.keys():
            self[key] = other[key]
    else:
        for key, value in other:
            self[key] = value
    for key, value in kwds.items():
        self[key] = value

The last subcase of the if statement, where it is iterating over other is the one most people have in mind. However, as you can see, it is also possible to have a keys() property. That, combined with a __getitem__() should make it easy to have a subclass be properly casted to a dictionary:

class Wharrgarbl(object):
    def __init__(self, a, b, c, sum, version='old'):
        self.a = a
        self.b = b
        self.c = c
        self.sum = 6
        self.version = version

    def __int__(self):
        return self.sum + 9000

    def __keys__(self):
        return ["a", "b", "c"]

    def __getitem__(self, key):
        # have obj["a"] -> obj.a
        return self.__getattribute__(key)

Then this will work:

>>> w = Wharrgarbl('one', 'two', 'three', 6)
>>> dict(w)
{'a': 'one', 'c': 'three', 'b': 'two'}

How to put a jpg or png image into a button in HTML

you can also try something like this as well

<input type="button" value="text" name="text" onClick="{action}; return false" class="fwm_button">

and CSS class

.fwm_button {
   color: white;
   font-weight: bold;
   background-color: #6699cc;
   border: 2px outset;
   border-top-color: #aaccff;
   border-left-color: #aaccff;
   border-right-color: #003366;
   border-bottom-color: #003366;
 }

An example is given here

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

SQL grouping by month and year

If you want to stay having the field in datetime datatype, try using this:

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order] o
WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)

It it also easy to change to group by hours, days, weeks, years...
I hope it is of use to someone,

Regards!

Writing MemoryStream to Response Object

I had the same problem and the only solution that worked was:

Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
Response.BinaryWrite(myMemoryStream.ToArray());
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
Response.End();

Difference between adjustResize and adjustPan in android?

You can use android:windowSoftInputMode="stateAlwaysHidden|adjustResize" in AndroidManifest.xml for your current activity, and use android:fitsSystemWindows="true" in styles or rootLayout.

Python loop counter in a for loop

enumerate is what you are looking for.

You might also be interested in unpacking:

# The pattern
x, y, z = [1, 2, 3]

# also works in loops:
l = [(28, 'M'), (4, 'a'), (1990, 'r')]
for x, y in l:
    print(x)  # prints the numbers 28, 4, 1990

# and also
for index, (x, y) in enumerate(l):
    print(x)  # prints the numbers 28, 4, 1990

Also, there is itertools.count() so you could do something like

import itertools

for index, el in zip(itertools.count(), [28, 4, 1990]):
    print(el)  # prints the numbers 28, 4, 1990

Android ListView not refreshing after notifyDataSetChanged

adapter.setNotifyDataChanged()

should do the trick.

What is an .axd file?

An AXD file is a file used by ASP.NET applications for handling embedded resource requests. It contains instructions for retrieving embedded resources, such as images, JavaScript (.JS) files, and.CSS files. AXD files are used for injecting resources into the client-side webpage and access them on the server in a standard way.

PYTHONPATH vs. sys.path

Along with the many other reasons mentioned already, you could also point outh that hard-coding

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

is brittle because it presumes the location of script.py -- it will only work if script.py is located in Project/package. It will break if a user decides to move/copy/symlink script.py (almost) anywhere else.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

ES6 Map in Typescript

EDIT (Jun 5 2019): While the idea that "TypeScript supports Map natively" is still true, since version 2.1 TypeScript supports something called Record.

type MyMapLikeType = Record<string, IPerson>;
const peopleA: MyMapLikeType = {
    "a": { name: "joe" },
    "b": { name: "bart" },
};

Unfortunately the first generic parameter (key type) is still not fully respected: even with a string type, something like peopleA[0] (a number) is still valid.


EDIT (Apr 25 2016): The answer below is old and should not be considered the best answer. TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6. For ES5, it does not provide polyfills; you need to embed them yourself.

For more information, refer to mohamed hegazy's answer below for a more modern answer, or even this reddit comment for a short version.


As of 1.5.0 beta, TypeScript does not yet support Maps. It is not yet part of the roadmap, either.

The current best solution is an object with typed key and value (sometimes called a hashmap). For an object with keys of type string, and values of type number:

var arr : { [key:string]:number; } = {};

Some caveats, however:

  1. keys can only be of type string or number
  2. It actually doesn't matter what you use as the key type, since numbers/strings are still accepted interchangeably (only the value is enforced).

With the above example:

// OK:
arr["name"] = 1; // String key is fine
arr[0] = 0; // Number key is fine too

// Not OK:
arr[{ a: "a" }] = 2; // Invalid key
arr[3] = "name"; // Invalid value

How to scale images to screen size in Pygame

If you scale 1600x900 to 1280x720 you have

scale_x = 1280.0/1600
scale_y = 720.0/900

Then you can use it to find button size, and button position

button_width  = 300 * scale_x
button_height = 300 * scale_y

button_x = 1440 * scale_x
button_y = 860  * scale_y

If you scale 1280x720 to 1600x900 you have

scale_x = 1600.0/1280
scale_y = 900.0/720

and rest is the same.


I add .0 to value to make float - otherwise scale_x, scale_y will be rounded to integer - in this example to 0 (zero) (Python 2.x)

How do I merge my local uncommitted changes into another Git branch?

If it were about committed changes, you should have a look at git-rebase, but as pointed out in comment by VonC, as you're talking about local changes, git-stash would certainly be the good way to do this.

Create a .txt file if doesn't exist, and if it does append a new line

File.AppendAllText adds a string to a file. It also creates a text file if the file does not exist. If you don't need to read content, it's very efficient. The use case is logging.

File.AppendAllText("C:\\log.txt", "hello world\n");

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u

chmod +x test.py
./test.py
moçambique
moçambique

./test.py > output.txt
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    print u
UnicodeEncodeError: 'ascii' codec can't encode character 
u'\xe7' in position 2: ordinal not in range(128)

on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

import sys
if (sys.stdout.encoding is None):            
    print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
    exit(1)


so, using same example:

export PYTHONIOENCODING=UTF-8
./test.py > output.txt

will work

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Convert array to string in NodeJS

In node, you can just say

console.log(aa)

and it will format it as it should.

If you need to use the resulting string you should use

JSON.stringify(aa)

numpy max vs amax vs maximum

np.maximum not only compares elementwise but also compares array elementwise with single value

>>>np.maximum([23, 14, 16, 20, 25], 18)
array([23, 18, 18, 20, 25])

Verifying a specific parameter with Moq

I've been verifying calls in the same manner - I believe it is the right way to do it.

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => mo.Id == 5 && mo.description == "test")
  ), Times.Once());

If your lambda expression becomes unwieldy, you could create a function that takes MyObject as input and outputs true/false...

mockSomething.Verify(ms => ms.Method(
    It.IsAny<int>(), 
    It.Is<MyObject>(mo => MyObjectFunc(mo))
  ), Times.Once());

private bool MyObjectFunc(MyObject myObject)
{
  return myObject.Id == 5 && myObject.description == "test";
}

Also, be aware of a bug with Mock where the error message states that the method was called multiple times when it wasn't called at all. They might have fixed it by now - but if you see that message you might consider verifying that the method was actually called.

EDIT: Here is an example of calling verify multiple times for those scenarios where you want to verify that you call a function for each object in a list (for example).

foreach (var item in myList)
  mockRepository.Verify(mr => mr.Update(
    It.Is<MyObject>(i => i.Id == item.Id && i.LastUpdated == item.LastUpdated),
    Times.Once());

Same approach for setup...

foreach (var item in myList) {
  var stuff = ... // some result specific to the item
  this.mockRepository
    .Setup(mr => mr.GetStuff(item.itemId))
    .Returns(stuff);
}

So each time GetStuff is called for that itemId, it will return stuff specific to that item. Alternatively, you could use a function that takes itemId as input and returns stuff.

this.mockRepository
    .Setup(mr => mr.GetStuff(It.IsAny<int>()))
    .Returns((int id) => SomeFunctionThatReturnsStuff(id));

One other method I saw on a blog some time back (Phil Haack perhaps?) had setup returning from some kind of dequeue object - each time the function was called it would pull an item from a queue.

How to escape single quotes in MySQL

Use this code:

<?php
    $var = "This is Ashok's Pen.";

    mysql_real_escape_string($var);
?>

This will solve your problem, because the database can't detect the special characters of a string.

How to unpack pkl file?

The pickle (and gzip if the file is compressed) module need to be used

NOTE: These are already in the standard Python library. No need to install anything new

Excel tab sheet names vs. Visual Basic sheet names

Perhaps I am wrong, but you can open a workbook, and select a worksheet and change its property (Name) to whatever you need it to be. This overrides the "Sheetx" naming convention. These names are also displayed in the VBA Editor.

How to do this manually: 1. Select the sheet in a workbook (I tend to create templates). 2. Set its tab name to whatever you like ("foo"). 3. Click on the Developer menu (which you previously enabled, right?). 4. Locate "Properties" and click on it, bringing up that worksheet's properties window. 5. The very first item in the Alphabetic listing is (Name) and at the right of (Name) is "Sheetx".
6. Click on that field and change it (how about we use "MyFav"). 7. Close the properties window. 8. Go to the Visual Basic editor. 9. Review the sheets in the workbook you just modified. 10. Observe that the MicroSoft Excel Objects shows the name you just changed "MyFav", and to the right of that, in parenthesis, the worksheet tab name ("foo").

You can change the .CodeName programmatically if you would rather. I use non-Sheet names to facilitate my template manipulation. You are not forced to use the generic default of "Sheetx".

Sys is undefined

In my case, I've found a very hidden reason ... There was this page route with in Global.ascx.cs which doesn't appear in my tests in sub-folders but returns the question error all the time .. another day with strange issues.

routes.MapPageRoute("siteDefault", "{culture}/", "~/default.aspx", false, new RouteValueDictionary(new { culture = "(\\w{2})|(\\w{2}-\\w{2})" }));

How to create a numeric vector of zero length in R

If you read the help for vector (or numeric or logical or character or integer or double, 'raw' or complex etc ) then you will see that they all have a length (or length.out argument which defaults to 0

Therefore

numeric()
logical()
character()
integer()
double()
raw()
complex() 
vector('numeric')
vector('character')
vector('integer')
vector('double')
vector('raw')
vector('complex')

All return 0 length vectors of the appropriate atomic modes.

# the following will also return objects with length 0
list()
expression()
vector('list')
vector('expression')

encrypt and decrypt md5

Hashes can not be decrypted check this out.

If you want to encrypt-decrypt, use a two way encryption function of your database like - AES_ENCRYPT (in MySQL).

But I'll suggest CRYPT_BLOWFISH algorithm for storing password. Read this- http://php.net/manual/en/function.crypt.php and http://us2.php.net/manual/en/function.password-hash.php

For Blowfish by crypt() function -

crypt('String', '$2a$07$twentytwocharactersalt$');

password_hash will be introduced in PHP 5.5.

$options = [
    'cost' => 7,
    'salt' => 'BCryptRequires22Chrcts',
];
password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);

Once you have stored the password, you can then check if the user has entered correct password by hashing it again and comparing it with the stored value.

HTML5 - mp4 video does not play in IE9

Dan has one of the best answers up there and I'd suggest you use html5test.com on your target browsers to see the video formats that are supported.

As stated above, no single format works and what I use is MP4 encoded to H.264, WebM, and a flash fallback. This let's me show video on the following:

Win 7 - IE9, Chrome, Firefox, Safari, Opera

Win XP - IE7, IE8, Chrome, Firefox, Safari, Opera

MacBook OS X - Chrome, Firefox, Safari, Opera

iPad 2, iPad 3

Linux - Android 2.3, Android 3

<video width="980" height="540" controls>
        <source src="images/placeholdername.mp4" type="video/mp4" />
        <source src="images/placeholdername.webm" type="video/webm" />
        <embed src="images/placeholdername.mp4" type="application/x-shockwave-flash" width="980" height="570" allowscriptaccess="always" allowfullscreen="true" autoplay="false"></embed>  <!--IE 8 - add 25-30 pixels to vid height to allow QT player controls-->    
    </video>

Note: The .mp4 video should be coded in h264 basic profile, so that it plays on all mobile devices.

Update: added autoplay="false" to the Flash fallback. This prevents the MP4 from starting to play right away when the page loads on IE8, it will start to play once the play button is pushed.

Search for all files in project containing the text 'querystring' in Eclipse

press Ctrl + H . Then choose "File Search" tab.

additional search options

search for resources: Ctrl + Shift + R

search for Java types: Ctrl + Shift + T

How to get the number of characters in a string

There are several ways to get a string length:

package main

import (
    "bytes"
    "fmt"
    "strings"
    "unicode/utf8"
)

func main() {
    b := "?????"
    len1 := len([]rune(b))
    len2 := bytes.Count([]byte(b), nil) -1
    len3 := strings.Count(b, "") - 1
    len4 := utf8.RuneCountInString(b)
    fmt.Println(len1)
    fmt.Println(len2)
    fmt.Println(len3)
    fmt.Println(len4)

}

How to link to part of the same document in Markdown?

Github automatically parses anchor tags out of your headers. So you can do the following:

[Custom foo description](#foo)

# Foo

In the above case, the Foo header has generated an anchor tag with the name foo

Note: just one # for all heading sizes, no space between # and anchor name, anchor tag names must be lowercase, and delimited by dashes if multi-word.

[click on this link](#my-multi-word-header)

### My Multi Word Header

Update

Works out of the box with pandoc too.