Programs & Examples On #Uploader

Could not find module "@angular-devkit/build-angular"

Try this first

npm install --save-dev @angular-devkit/build-angular

If some error come again for missing packages try

npm install

File Upload In Angular?

To upload image with form fields

SaveFileWithData(article: ArticleModel,picture:File): Observable<ArticleModel> 
{

    let headers = new Headers();
    // headers.append('Content-Type', 'multipart/form-data');
    // headers.append('Accept', 'application/json');

let requestoptions = new RequestOptions({
  method: RequestMethod.Post,
  headers:headers
    });



let formData: FormData = new FormData();
if (picture != null || picture != undefined) {
  formData.append('files', picture, picture.name);
}
 formData.append("article",JSON.stringify(article));

return this.http.post("url",formData,requestoptions)
  .map((response: Response) => response.json() as ArticleModel);
} 

In my case I needed .NET Web Api in C#

// POST: api/Articles
[ResponseType(typeof(Article))]
public async Task<IHttpActionResult> PostArticle()
{
    Article article = null;
    try
    {

        HttpPostedFile postedFile = null;
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count == 1)
        {
            postedFile = httpRequest.Files[0];
            var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
            postedFile.SaveAs(filePath);
        }
        var json = httpRequest.Form["article"];
         article = JsonConvert.DeserializeObject <Article>(json);

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        article.CreatedDate = DateTime.Now;
        article.CreatedBy = "Abbas";

        db.articles.Add(article);
        await db.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        int a = 0;
    }
    return CreatedAtRoute("DefaultApi", new { id = article.Id }, article);
}

React eslint error missing in props validation

Issue: 'id1' is missing in props validation, eslintreact/prop-types

<div id={props.id1} >
    ...
</div>

Below solution worked, in a function component:

let { id1 } = props;

<div id={id1} >
    ...
</div>

Hope that helps.

Reading Excel file using node.js

There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.

Node-xlsx

Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.

node-xlsx project page

Example for parsing file

var xlsx = require('node-xlsx');

var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file

var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer

ExcelJS

Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.

exceljs project page

Code example:

// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
    .then(function() {
        // use workbook
    });

// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());

File uploading with Express 4.0: req.files undefined

It looks like body-parser did support uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency

After looking through some of the modules in mscdex's answer, I found that express-busboy was a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.

console.log(req.files) using body-parser (Express 3) output an object that looked like this:

{ file: 
   { fieldName: 'file',
     originalFilename: '360px-Cute_Monkey_cropped.jpg',
     name: '360px-Cute_Monkey_cropped.jpg'
     path: 'uploads/6323-16v7rc.jpg',
     type: 'image/jpeg',
     headers: 
      { 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
        'content-type': 'image/jpeg' },
     ws: 
      WriteStream { /* ... */ },
     size: 48614 } }

compared to console.log(req.files) using express-busboy (Express 4):

{ file: 
   { field: 'file',
     filename: '360px-Cute_Monkey_cropped.jpg',
     file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
     mimetype: 'image/jpeg',
     encoding: '7bit',
     truncated: false
     uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }

Node.js: what is ENOSPC error and how to solve?

If you're using VS Code then it'll should unable to watch in large workspace error.

"Visual Studio Code is unable to watch for file changes in this large workspace" (error ENOSPC)

It indicates that the VS Code file watcher is running out of handles because the workspace is large and contains many files. The current limit can be viewed by running:

cat /proc/sys/fs/inotify/max_user_watches

The limit can be increased to its maximum by editing /etc/sysctl.conf and adding this line to the end of the file:

fs.inotify.max_user_watches=524288

The new value can then be loaded in by running sudo sysctl -p.

Note: 524288 is the max value to watch the files. Though you can watch any no of files but is also recommended to watch upto that limit only.

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

Using Spring MVC Test to unit test multipart POST request

Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(
            classes = EmailControllerBootApplication.class
        )
    public class SendEmailTest {

        @Autowired
        private WebApplicationContext webApplicationContext;

        @Test
        public void testSend() throws Exception{
            String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
                    + "\"CDM - Spring Boot email service with attachment\","
                    + "\"body\": \"Email body will contain  test results, with screenshot\"}";

            Resource fileResource = new ClassPathResource(
                    "screen-shots/HomePage-attachment.png");

            assertNotNull(fileResource);

            MockMultipartFile firstFile = new MockMultipartFile( 
                       "attachments",fileResource.getFilename(),
                        MediaType.MULTIPART_FORM_DATA_VALUE,
                        fileResource.getInputStream());  
                        assertNotNull(firstFile);


            MockMvc mockMvc = MockMvcBuilders.
                  webAppContextSetup(webApplicationContext).build();

            mockMvc.perform(MockMvcRequestBuilders
                   .multipart("/api/v1/email/send")
                    .file(firstFile)
                    .param("data", jsonStr))
                    .andExpect(status().is(200));
            }
        }

Postman Request

Fatal error: Namespace declaration statement has to be the very first statement in the script in

Sometimes this issue come because of space in PHP start tag of controller facing same issue just removed whitespace in:

<?php 
namespace App\Http\Controllers\Auth;

removing the space resolved my error

JQuery Validate input file type

So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.

So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your tag in addition to the answer above and it should work.

YouTube API to fetch all videos on a channel

Here is the code that will return all video ids under your channel

<?php 
    $baseUrl = 'https://www.googleapis.com/youtube/v3/';
    // https://developers.google.com/youtube/v3/getting-started
    $apiKey = 'API_KEY';
    // If you don't know the channel ID see below
    $channelId = 'CHANNEL_ID';

    $params = [
        'id'=> $channelId,
        'part'=> 'contentDetails',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'channels?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $playlist = $json['items'][0]['contentDetails']['relatedPlaylists']['uploads'];

    $params = [
        'part'=> 'snippet',
        'playlistId' => $playlist,
        'maxResults'=> '50',
        'key'=> $apiKey
    ];
    $url = $baseUrl . 'playlistItems?' . http_build_query($params);
    $json = json_decode(file_get_contents($url), true);

    $videos = [];
    foreach($json['items'] as $video)
        $videos[] = $video['snippet']['resourceId']['videoId'];

    while(isset($json['nextPageToken'])){
        $nextUrl = $url . '&pageToken=' . $json['nextPageToken'];
        $json = json_decode(file_get_contents($nextUrl), true);
        foreach($json['items'] as $video)
            $videos[] = $video['snippet']['resourceId']['videoId'];
    }
    print_r($videos);

Note: You can get channel id at https://www.youtube.com/account_advanced after logged in.

Can someone explain how to implement the jQuery File Upload plugin?

Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

How to make <input type="file"/> accept only these types?

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif, or a notation like image/* that refers to all image types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

ORA-00984: column not allowed here

Replace double quotes with single ones:

INSERT
INTO    MY.LOGFILE
        (id,severity,category,logdate,appendername,message,extrainfo)
VALUES  (
       'dee205e29ec34',
       'FATAL',
       'facade.uploader.model',
       '2013-06-11 17:16:31',
       'LOGDB',
       NULL,
       NULL
       )

In SQL, double quotes are used to mark identifiers, not string constants.

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

In my case it was something else: the object I was saving should first have an id(e.g. save() should be called) before I could set any kind of relationship with it.

how to get files from <input type='file' .../> (Indirect) with javascript

Based on Ray Nicholus's answer :

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

using this will also work :

inputElement.onchange = function(event) {
   var fileList = event.target.files;
   //TODO do something with fileList.  
}

Jquery and HTML FormData returns "Uncaught TypeError: Illegal invocation"

jQuery processes the data attribute and converts the values into strings.

Adding processData: false to your options object fixes the error, but I'm not sure if it fixes the problem.

Demo: http://jsfiddle.net/eHmSr/1/

Using curl to upload POST data with files

if you are uploading binary file such as csv, use below format to upload file

curl -X POST \
    'http://localhost:8080/workers' \
    -H 'authorization: eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyIsInR5cGUiOiJhY2Nlc3MifQ.eyJ1c2VySWQiOjEsImFjY291bnRJZCI6MSwiaWF0IjoxNTExMzMwMzg5LCJleHAiOjE1MTM5MjIzODksImF1ZCI6Imh0dHBzOi8veW91cmRvbWFpbi5jb20iLCJpc3MiOiJmZWF0aGVycyIsInN1YiI6ImFub255bW91cyJ9.HWk7qJ0uK6SEi8qSeeB6-TGslDlZOTpG51U6kVi8nYc' \
    -H 'content-type: application/x-www-form-urlencoded' \
    --data-binary '@/home/limitless/Downloads/iRoute Masters - Workers.csv'

Setting PHP tmp dir - PHP upload not working

create php-file with:

<?php
    print shell_exec( 'whoami' );
?>

or

<?php echo exec('whoami'); ?>

try the output in your web-browser. if the output is not your user example: www-data then proceed to next step

open as root:

/etc/apache2/envvars

look for these lines:

export APACHE_RUN_USER=user-name

export APACHE_RUN_GROUP=group-name

example:

export APACHE_RUN_USER=www-data

export APACHE_RUN_GROUP=www-data

where:

username = your username that has access to the folder you are using group = group you've given read+write+execute access

change it to:

export APACHE_RUN_USER="username"

export APACHE_RUN_GROUP="group"

if your user have no access yet:

sudo chmod 775 -R "directory of folder you want to give r/w/x access"

Why is json_encode adding backslashes?

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

If a folder does not exist, create it

A fancy way is to extend the FileUpload with the method you want.

Add this:

public static class FileUploadExtension
{
    public static void SaveAs(this FileUpload, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.SaveAs(destination);
    }
}

Then use it:

FileUpload file;
...
file.SaveAs(path,true);

Clear text area

I agree with @Jakub Arnold's answer. The problem should be somewhere else. I could not figure out the problem but found a work around.

Wrap your concerned element with a parent element and cause its html to create a new element with the id you are concerned with. See below

<div id="theParent">
    <div id="vinanghinguyen_images_bbocde"></div>
</div>

'onSelect'    : function(event,ID,fileObj) {
 $("#theParent").html("<div id='vinanghinguyen_images_bbocde'></div>");
 $("#vinanghinguyen_result").hide();
 $(".uploadifyQueue").height(315);
}

Android file chooser

I used AndExplorer for this purpose and my solution is popup a dialog and then redirect on the market to install the misssing application:

My startCreation is trying to call external file/directory picker. If it is missing call show installResultMessage function.

private void startCreation(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_PICK);
    Uri startDir = Uri.fromFile(new File("/sdcard"));

    intent.setDataAndType(startDir,
            "vnd.android.cursor.dir/lysesoft.andexplorer.file");
    intent.putExtra("browser_filter_extension_whitelist", "*.csv");
    intent.putExtra("explorer_title", getText(R.string.andex_file_selection_title));
    intent.putExtra("browser_title_background_color",
            getText(R.string.browser_title_background_color));
    intent.putExtra("browser_title_foreground_color",
            getText(R.string.browser_title_foreground_color));
    intent.putExtra("browser_list_background_color",
            getText(R.string.browser_list_background_color));
    intent.putExtra("browser_list_fontscale", "120%");
    intent.putExtra("browser_list_layout", "2");

    try{
         ApplicationInfo info = getPackageManager()
                                 .getApplicationInfo("lysesoft.andexplorer", 0 );

            startActivityForResult(intent, PICK_REQUEST_CODE);
    } catch( PackageManager.NameNotFoundException e ){
        showInstallResultMessage(R.string.error_install_andexplorer);
    } catch (Exception e) {
        Log.w(TAG, e.getMessage());
    }
}

This methos is just pick up a dialog and if user wants install the external application from market

private void showInstallResultMessage(int msg_id) {
    AlertDialog dialog = new AlertDialog.Builder(this).create();
    dialog.setMessage(getText(msg_id));
    dialog.setButton(getText(R.string.button_ok),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    dialog.setButton2(getText(R.string.button_install),
            new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse("market://details?id=lysesoft.andexplorer"));
                    startActivity(intent);
                    finish();
                }
            });
    dialog.show();
}

Convert Data URI to File then append to FormData

toDataURL gives you a string and you can put that string to a hidden input.

python exception message capturing

You have to define which type of exception you want to catch. So write except Exception, e: instead of except, e: for a general exception (that will be logged anyway).

Other possibility is to write your whole try/except code this way:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e: # work on python 2.x
    logger.error('Failed to upload to ftp: '+ str(e))

in Python 3.x and modern versions of Python 2.x use except Exception as e instead of except Exception, e:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

Only variables should be passed by reference

end(...[explode('.', $file_name)]) has worked since PHP 5.6. This is documented in the RFC although not in PHP docs themselves.

jQuery change method on input type="file"

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). Refer: http://api.jquery.com/on/

$('#imageFile').on("change", function(){ uploadFile(); });

How can you integrate a custom file browser/uploader with CKEditor?

I spent a while trying to figure this one out and here is what I did. I've broken it down very simply as that is what I needed.

Directly below your ckeditor text area, enter the upload file like this >>>>

<form action="welcomeeditupload.asp" method="post" name="deletechecked">
    <div align="center">
        <br />
        <br />
        <label></label>
        <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"><%=(rslegschedule.Fields.Item("welcomevar").Value)%></textarea>
        <script type="text/javascript">
        //<![CDATA[
            CKEDITOR.replace( 'editor1',
            {
                filebrowserUploadUrl : 'updateimagedone.asp'
            });
        //]]>
        </script>
        <br />
        <br />
        <br />
        <input type="submit" value="Update">
    </div>
</form>

'and then add your upload file, here is mine which is written in ASP. If you're using PHP, etc. simply replace the ASP with your upload script but make sure the page outputs the same thing.

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<%
    if Request("CKEditorFuncNum")=1 then
        Set Upload = Server.CreateObject("Persits.Upload")
        Upload.OverwriteFiles = False
        Upload.SetMaxSize 5000000, True
        Upload.CodePage = 65001

        On Error Resume Next
        Upload.Save "d:\hosting\belaullach\senate\legislation"

        Dim picture
        For Each File in Upload.Files
            Ext = UCase(Right(File.Path, 3))
            If Ext <> "JPG" Then
                    If Ext <> "BMP" Then
                    Response.Write "File " & File.Path & " is not a .jpg or .bmp file." & "<BR>"
                    Response.write "You can only upload .jpg or .bmp files." & "<BR>" & "<BR>"
                    End if
            Else
                File.SaveAs Server.MapPath(("/senate/legislation") & "/" & File.fileName)
                f1=File.fileName
            End If
        Next
    End if

    fnm="/senate/legislation/"&f1
    imgop = "<html><body><script type=""text/javascript"">window.parent.CKEDITOR.tools.callFunction('1','"&fnm&"');</script></body></html>;"
    'imgop="callFunction('1','"&fnm&"',"");"
    Response.write imgop
%>

How to call a Web Service Method?

In visual studio, use the "Add Web Reference" feature and then enter in the URL of your web service.

By adding a reference to the DLL, you not referencing it as a web service, but simply as an assembly.

When you add a web reference it create a proxy class in your project that has the same or similar methods/arguments as your web service. That proxy class communicates with your web service via SOAP but hides all of the communications protocol stuff so you don't have to worry about it.

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

Upload Progress Bar in PHP

HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers

Filter Extensions in HTML form upload

The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.

Additionally, it appears that most browsers may not honor this attribute.

The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.

Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.

Convert an integer to an array of digits

Use:

public static void main(String[] args)
{
    int num = 1234567;
    int[] digits = Integer.toString(num).chars().map(c -> c-'0').toArray();
    for(int d : digits)
        System.out.print(d);
}

The main idea is

  1. Convert the int to its String value

    Integer.toString(num);
    
  2. Get a stream of int that represents the ASCII value of each char(~digit) composing the String version of our integer

    Integer.toString(num).chars();
    
  3. Convert the ASCII value of each character to its value. To get the actual int value of a character, we have to subtract the ASCII code value of the character '0' from the ASCII code of the actual character. To get all the digits of our number, this operation has to be applied on each character (corresponding to the digit) composing the string equivalent of our number which is done by applying the map function below to our IntStream.

    Integer.toString(num).chars().map(c -> c-'0');
    
  4. Convert the stream of int to an array of int using toArray()

     Integer.toString(num).chars().map(c -> c-'0').toArray();
    

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

In my case the situation was this: I had an offline server on which I had to perform the build. For that I had compiled everything locally first and then transferred repository folder to the offline server.

Problem - build works locally but not on the server, even thou they both have same maven version, same repository folder, same JDK.

Cause: on my local machine I had additional custom "" entry in settings.xml. When I added same to the settings.xml on the server then my issues disappeared.

How to use boolean 'and' in Python

In python, use and instead of && like this:

#!/usr/bin/python
foo = True;
bar = True;
if foo and bar:
    print "both are true";

This prints:

both are true

Access Form - Syntax error (missing operator) in query expression

I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

How to create a data file for gnuplot?

Create your Datafile like this:

# X      Y
10000.0 0.01
100000.0 0.05
1000000.0 0.45

And plot it with

$ gnuplot -p -e "plot 'filename.dat'"

There is a good tutorial: http://www.gnuplotting.org/introduction/plotting-data/

Can I pass a JavaScript variable to another browser window?

Yes, it can be done as long as both windows are on the same domain. The window.open() function will return a handle to the new window. The child window can access the parent window using the DOM element "opener".

Add or change a value of JSON key with jquery or javascript

It seems if your key is saved in a variable. data.key = value won't work.

You should use data[key] = value

Example:

data = {key1:'v1', key2:'v2'};

var mykey = 'key1'; 
data.mykey = 'newv1';
data[mykey] = 'newV2';

console.log(data);

Result:

{
  "key1": "newV2",
  "key2": "v2",
  "mykey": "newv1"
}

2 column div layout: right column with fixed width, left fluid

I have simplified it : I have edited jackjoe's answer. The height auto etc not required I think.

CSS:

#container {
position: relative;
margin:0 auto;
width: 1000px;
background: #C63;
padding: 10px;
}

#leftCol {
background: #e8f6fe;
width: auto;
}

#rightCol {
float:right;
width:30%;
background: #aafed6;
}

.box {
position:relative;
clear:both;
background:#F39;
 }
</style>

HTML:

<div id="container">

  <div id="rightCol"> 
   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
 </div>

 <div id="leftCol">

   <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.

</div>

</div>

<div class="box">
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>

  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  <p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

SQL SERVER: Check if variable is null and then assign statement for Where Clause

is null can be used to check whether null data is coming from a query as in following example:

 declare @Mem varchar(20),@flag int
select @mem=MemberClub from [dbo].[UserMaster] where UserID=@uid
if(@Mem is null)
begin
    set @flag= 0;
end
else
begin
    set @flag=1;
end
return @flag;

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

If none of the answers worked for you. You might be in the wrong "Window". I was in "Package explorer" and switching to "Project Explorer" showed me the folders.

How do I compile with -Xlint:unchecked?

other way to compile using -Xlint:unchecked through command line

javac abc.java -Xlint:unchecked

it will show the unchecked and unsafe warnings.

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

compare two files in UNIX

I got the solution by using comm

comm -23 file1 file2 

will give you the desired output.

The files need to be sorted first anyway.

SQL Server - Create a copy of a database table and place it in the same database?

Copy Schema (Generate DDL) through SSMS UI

In SSMS expand your database in Object Explorer, go to Tables, right click on the table you're interested in and select Script Table As, Create To, New Query Editor Window. Do a find and replace (CTRL + H) to change the table name (i.e. put ABC in the Find What field and ABC_1 in the Replace With then click OK).

Copy Schema through T-SQL

The other answers showing how to do this by SQL also work well, but the difference with this method is you'll also get any indexes, constraints and triggers.

Copy Data

If you want to include data, after creating this table run the below script to copy all data from ABC (keeping the same ID values if you have an identity field):

set identity_insert ABC_1 on
insert into ABC_1 (column1, column2) select column1, column2 from ABC
set identity_insert ABC_1 off

Default settings Raspberry Pi /etc/network/interfaces

For my Raspberry Pi 3B model it was

auto lo
iface lo inet loopback

auto eth0
iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

How can I declare and define multiple variables in one line using C++?

As others have mentioned, from C++17 onwards you can make use of structured bindings for multiple variable assignments.

Combining this with std::array and template argument deduction we can write a function that assigns a value to an arbitrary number of variables without repeating the type or value.

#include <iostream>
#include <array>

template <int N, typename T> auto assign(T value)
{
    std::array<T, N> out;
    out.fill(value);
    return out;
}

int main()
{
    auto [a, b, c] = assign<3>(1);

    for (const auto& v : {a, b, c})
    {
        std::cout << v << std::endl;
    }

    return 0;
}

Demo

Check if XML Element exists

You can validate that and much more by using an XML schema language, like XSD.

If you mean conditionally, within code, then XPath is worth a look as well.

Text-align class for inside a table

Here is the simplest solution

You can assign the classes like text-center, left or right. The text will align accordingly to these classes. You do not have to make classes separately. These classes are inbuilt in BootStrap 3

    <h1 class="text-center"> Heading 1 </h1> 
    <h1 class="text-left"> Heading 2 </h1> 
    <h1 class="text-right"> Heading 3 </h1>

Check here: Demo

JavaScript Array to Set

By definition "A Set is a collection of values, where each value may occur only once." So, if your array has repeated values then only one value among the repeated values will be added to your Set.

var arr = [1, 2, 3];
var set = new Set(arr);
console.log(set); // {1,2,3}


var arr = [1, 2, 1];
var set = new Set(arr);
console.log(set); // {1,2}

So, do not convert to set if you have repeated values in your array.

What is the best Java library to use for HTTP POST, GET etc.?

I agree httpclient is something of a standard - but I guess you are looking for options so...

Restlet provides a http client specially designed for interactong with Restful web services.

Example code:

    Client client = new Client(Protocol.HTTP);
    Request r = new Request();
    r.setResourceRef("http://127.0.0.1:8182/sample");
    r.setMethod(Method.GET);
    r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
    client.handle(r).getEntity().write(System.out);

See http://www.restlet.org/ for more details

Doctrine and LIKE query

you can also do it like that :

$ver = $em->getRepository('GedDocumentBundle:version')->search($val);

$tail = sizeof($ver);

How to get the current working directory in Java?

On Linux when you run a jar file from terminal, these both will return the same String: "/home/CurrentUser", no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.

Paths.get("").toAbsolutePath().toString();

System.getProperty("user.dir");

If your Class with main would be called MainClass, then try:

MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();

This will return a String with absolute path of the jar file.

How to allow user to pick the image with Swift?

@IBAction func ImportImage(_ sender: Any)
{
    let image = UIImagePickerController()
    image.delegate = self

    image.sourceType = UIImagePickerController.SourceType.photoLibrary

    image.allowsEditing = false

    self.present(image, animated: true)
    {
        //After it is complete
    }


}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    {
        myimage.image = image
    }
    else{
        //
    }
    self.dismiss(animated: true, completion: nil)

    do {
        try context.save()
    } catch {
        print("Could not save. \(error), \(error.localizedDescription)")
    }

}

Add UINavigationControllerDelegate, UIImagePickerControllerDelegate delegates in the class definition

How to change angular port from 4200 to any other

You can change your application port by using below command:-

ng serve --port 4400

Note:-In my case desired port number is 4400.It can be anything of your choice.

To see the changes:-

Just launch browser with: http://localhost:4400/

jQuery toggle CSS?

You can do by maintaining the state as below:

$('#user_button').on('click',function(){
    if($(this).attr('data-click-state') == 1) {
        $(this).attr('data-click-state', 0);
        $(this).css('background-color', 'red')
      }
    else {
      $(this).attr('data-click-state', 1);
      $(this).css('background-color', 'orange')
    }
  });

Take a reference from hear codepen example

Algorithm to find Largest prime factor of a number

n = abs(number);
result = 1;
if (n mod 2 == 0) {
  result = 2;
  while (n mod 2 = 0) n /= 2;
}
for(i=3; i<sqrt(n); i+=2) {
  if (n mod i == 0) {
    result = i;
    while (n mod i = 0)  n /= i;
  }
}
return max(n,result)

There are some modulo tests that are superflous, as n can never be divided by 6 if all factors 2 and 3 have been removed. You could only allow primes for i, which is shown in several other answers here.

You could actually intertwine the sieve of Eratosthenes here:

  • First create the list of integers up to sqrt(n).
  • In the for loop mark all multiples of i up to the new sqrt(n) as not prime, and use a while loop instead.
  • set i to the next prime number in the list.

Also see this question.

Recursively list files in Java

    private void fillFilesRecursively(File file, List<File> resultFiles) {
        if (file.isFile()) {
            resultFiles.add(file);
        } else {
            for (File child : file.listFiles()) {
                fillFilesRecursively(child, resultFiles);
            }
        }
    }

MVC razor form with multiple different submit buttons?

Didn't see an answer using tag helpers (Core MVC), so here it goes (for a delete action):

On HTML:

<form action="" method="post" role="form">
<table>
@for (var i = 0; i < Model.List.Count(); i++)
{
    <tr>
        <td>@Model.List[i].ItemDescription</td>
        <td>
            <input type="submit" value="REMOVE" class="btn btn-xs btn-danger" 
             asp-controller="ControllerName" asp-action="delete" asp-route-idForDeleteItem="@Model.List[i].idForDeleteItem" />
        </td>
    </tr>
}
</table>
</form>

On Controller:

[HttpPost("[action]/{idForDeleteItem}"), ActionName("Delete")]
public async Task<IActionResult> DeleteConfirmed(long idForDeleteItem)
{
    ///delete with param id goes here
}

Don't forget to use [Route("[controller]")] BEFORE the class declaration - on controller.

org.xml.sax.SAXParseException: Content is not allowed in prolog

Just an additional thought on this one for the future. Getting this bug could be the case that one simply hits the delete key or some other key randomly when they have an XML window as the active display and are not paying attention. This has happened to me before with the struts.xml file in my web application. Clumsy elbows ...

center image in div with overflow hidden

Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)

HTML

<div class="wrapper">
   <img src="image.jpg" />
</div>

CSS

div.wrapper {
  height:200px;
  line-height:200px;
  overflow:hidden;
  text-align:center;
  width:200px;
}
div.wrapper img {
  margin:-100%;
}

Center any size image in div
Used with rounded wrapper and different sized images.

CSS

.item-image {
    border: 5px solid #ccc;
    border-radius: 100%;
    margin: 0 auto;
    height: 200px;
    width: 200px;
    overflow: hidden;
    text-align: center;
}
.item-image img {
    height: 200px;    
    margin: -100%;
    max-width: none;
    width: auto;    
}

Working example here codepen

Is there a TRY CATCH command in Bash

Below is an complete copy of the simplified script used in my other answer. Beyond additional error checking, there is an alias which allows the user to change the name of an existing alias. The syntax is given below. If the new_alias parameter is omitted, then the alias is removed.

ChangeAlias old_alias [new_alias]

The complete script is given below.

common.GetAlias() {
    local "oldname=${1:-0}"
    if [[ $oldname =~ ^[0-9]+$ && oldname+1 -lt ${#FUNCNAME[@]} ]]; then
        oldname="${FUNCNAME[oldname + 1]}"
    fi
    name="common_${oldname#common.}"
    echo "${!name:-$oldname}"
}

common.Alias() {
    if [[ $# -ne 2 || -z $1 || -z $2 ]]; then
        echo "$(common.GetAlias): The must be only two parameters of nonzero length" >&2
        return 1;
    fi
    eval "alias $1='$2'"
    local "f=${2##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ -n ${!v:-} ]]; then
        echo "$(common.GetAlias): $1: Function \`$f' already paired with name \`${!v}'" >&2
        return 1;
    fi
    shopt -s expand_aliases
    eval "$v=\"$1\""
}

common.ChangeAlias() {
    if [[ $# -lt 1 || $# -gt 2 ]]; then
        echo "usage: $(common.GetAlias) old_name [new_name]" >&2
        return "1"
    elif ! alias "$1" &>"/dev/null"; then
        echo "$(common.GetAlias): $1: Name not found" >&2
        return 1;
    fi
    local "s=$(alias "$1")" 
    s="${s#alias $1=\'}"
    s="${s%\'}"
    local "f=${s##*common.}"
    f="${f%%;*}"
    local "v=common_$f"
    f="common.$f"
    if [[ ${!v:-} != "$1" ]]; then
        echo "$(common.GetAlias): $1: Name not paired with a function \`$f'" >&2
        return 1;
    elif [[ $# -gt 1 ]]; then
        eval "alias $2='$s'"
        eval "$v=\"$2\""
    else
        unset "$v"
    fi
    unalias "$1"
}

common.Alias exception             'common.Exception'
common.Alias throw                 'common.Throw'
common.Alias try                   '{ if common.Try; then'
common.Alias yrt                   'common.EchoExitStatus; fi; common.yrT; }'
common.Alias catch                 '{ while common.Catch'
common.Alias hctac                 'common.hctaC -r; done; common.hctaC; }'
common.Alias finally               '{ if common.Finally; then'
common.Alias yllanif               'fi; common.yllaniF; }'
common.Alias caught                'common.Caught'
common.Alias EchoExitStatus        'common.EchoExitStatus'
common.Alias EnableThrowOnError    'common.EnableThrowOnError'
common.Alias DisableThrowOnError   'common.DisableThrowOnError'
common.Alias GetStatus             'common.GetStatus'
common.Alias SetStatus             'common.SetStatus'
common.Alias GetMessage            'common.GetMessage'
common.Alias MessageCount          'common.MessageCount'
common.Alias CopyMessages          'common.CopyMessages'
common.Alias TryCatchFinally       'common.TryCatchFinally'
common.Alias DefaultErrHandler     'common.DefaultErrHandler'
common.Alias DefaultUnhandled      'common.DefaultUnhandled'
common.Alias CallStack             'common.CallStack'
common.Alias ChangeAlias           'common.ChangeAlias'
common.Alias TryCatchFinallyAlias  'common.Alias'

common.CallStack() {
    local -i "i" "j" "k" "subshell=${2:-0}" "wi" "wl" "wn"
    local "format= %*s  %*s  %-*s  %s\n" "name"
    eval local "lineno=('' ${BASH_LINENO[@]})"
    for (( i=${1:-0},j=wi=wl=wn=0; i<${#FUNCNAME[@]}; ++i,++j )); do  
        name="$(common.GetAlias "$i")"
        let "wi = ${#j} > wi ? wi = ${#j} : wi"
        let "wl = ${#lineno[i]} > wl ? wl = ${#lineno[i]} : wl"
        let "wn = ${#name} > wn ? wn = ${#name} : wn"
    done
    for (( i=${1:-0},j=0; i<${#FUNCNAME[@]}; ++i,++j )); do
        ! let "k = ${#FUNCNAME[@]} - i - 1"
        name="$(common.GetAlias "$i")"
        printf "$format" "$wi" "$j" "$wl" "${lineno[i]}" "$wn" "$name" "${BASH_SOURCE[i]}"
    done
}

common.Echo() {
    [[ $common_options != *d* ]] || echo "$@" >"$common_file"
}

common.DefaultErrHandler() {
    echo "Orginal Status: $common_status"
    echo "Exception Type: ERR"
}

common.Exception() {
    common.TryCatchFinallyVerify || return
    if [[ $# -eq 0 ]]; then
        echo "$(common.GetAlias): At least one parameter is required" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
    shift
    common_messages=()
    for message in "$@"; do
        common_messages+=("$message")
    done
    if [[ $common_options == *c* ]]; then
        echo "Call Stack:" >"$common_fifo"
        common.CallStack "2" >"$common_fifo"
    fi
}

common.Throw() {
    common.TryCatchFinallyVerify || return
    local "message"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias): No Try-Catch-Finally exists" >&2
        return "1"        
    elif [[ $# -eq 0 && common_status -eq 0 ]]; then
        echo "$(common.GetAlias): No previous unhandled exception" >&2 
        return "1"
    elif [[ $# -gt 0 && ( ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ) ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    common.Echo -n "In Throw ?=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL #=$#"
    if [[ $common_options == *k* ]]; then
        common.CallStack "2" >"$common_file"
    fi
    if [[ $# -gt 0 ]]; then
        let "common_status = 10#$1"
        shift
        for message in "$@"; do
            echo "$message" >"$common_fifo"
        done
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
    elif [[ ${#common_messages[@]} -gt 0 ]]; then
        for message in "${common_messages[@]}"; do
            echo "$message" >"$common_fifo"
        done
    fi
    chmod "0400" "$common_fifo"
    common.Echo "Still in Throw $=$common_status subshell=$BASH_SUBSHELL #=$# -=$-"
    exit "$common_status"
}

common.ErrHandler() {
    common_status=$?
    trap ERR
    common.Echo -n "In ErrHandler ?=$common_status debug=$common_options "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL order=$common_order"
    if [[ -w "$common_fifo" ]]; then
        if [[ $common_options != *e* ]]; then
            common.Echo "ErrHandler is ignoring"
            common_status="0"
            return "$common_status" # value is ignored
        fi
        if [[ $common_options == *k* ]]; then
            common.CallStack "2" >"$common_file"
        fi
        common.Echo "Calling ${common_errHandler:-}"
        eval "${common_errHandler:-} \"${BASH_LINENO[0]}\" \"${BASH_SOURCE[1]}\" \"${FUNCNAME[1]}\" >$common_fifo <$common_fifo"
        if [[ $common_options == *c* ]]; then
            echo "Call Stack:" >"$common_fifo"
            common.CallStack "2" >"$common_fifo"
        fi
        chmod "0400" "$common_fifo"
    fi
    common.Echo "Still in ErrHandler $=$common_status subshell=$BASH_SUBSHELL -=$-"
    if [[ common_trySubshell -eq BASH_SUBSHELL ]]; then
        return "$common_status" # value is ignored   
    else
        exit "$common_status"
    fi
}

common.Token() {
    local "name"
    case $1 in
    b) name="before";;
    t) name="$common_Try";;
    y) name="$common_yrT";;
    c) name="$common_Catch";;
    h) name="$common_hctaC";;
    f) name="$common_yllaniF";;
    l) name="$common_Finally";;
    *) name="unknown";;
    esac
    echo "$name"
}

common.TryCatchFinallyNext() {
    common.ShellInit
    local "previous=$common_order" "errmsg"
    common_order="$2"
    if [[ $previous != $1 ]]; then
        errmsg="${BASH_SOURCE[2]}: line ${BASH_LINENO[1]}: syntax error_near unexpected token \`$(common.Token "$2")'"
        echo "$errmsg" >&2
        [[ /dev/fd/2 -ef $common_file ]] || echo "$errmsg" >"$common_file"
        kill -s INT 0
        return "1"        
    fi
}

common.ShellInit() {
    if [[ common_initSubshell -ne BASH_SUBSHELL ]]; then
        common_initSubshell="$BASH_SUBSHELL"
        common_order="b"
    fi
}

common.Try() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[byhl]" "t" || return 
    common_status="0"
    common_subshell="$common_trySubshell"
    common_trySubshell="$BASH_SUBSHELL"
    common_messages=()
    common.Echo "-------------> Setting try=$common_trySubshell at subshell=$BASH_SUBSHELL"
}

common.yrT() {
    local "status=$?"
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[t]" "y" || return 
    common.Echo -n "Entered yrT ?=$status status=$common_status "
    common.Echo "try=$common_trySubshell subshell=$BASH_SUBSHELL"
    if [[ common_status -ne 0 ]]; then    

        common.Echo "Build message array. ?=$common_status, subshell=$BASH_SUBSHELL"
        local "message=" "eof=TRY_CATCH_FINALLY_END_OF_MESSAGES_$RANDOM"
        chmod "0600" "$common_fifo"
        echo "$eof" >"$common_fifo"
        common_messages=()
        while read "message"; do

            common.Echo "----> $message"

            [[ $message != *$eof ]] || break
            common_messages+=("$message")
        done <"$common_fifo"
    fi

    common.Echo "In ytT status=$common_status"
    common_trySubshell="$common_subshell"
}

common.Catch() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[yh]" "c" || return 
    [[ common_status -ne 0 ]] || return "1"
    local "parameter" "pattern" "value"
    local "toggle=true" "compare=p" "options=$-"
    local -i "i=-1" "status=0"
    set -f
    for parameter in "$@"; do
        if "$toggle"; then
            toggle="false"
            if [[ $parameter =~ ^-[notepr]$ ]]; then
                compare="${parameter#-}"
                continue 
            fi
        fi
        toggle="true"
        while "true"; do
            eval local "patterns=($parameter)"
            if [[ ${#patterns[@]} -gt 0 ]]; then
                for pattern in "${patterns[@]}"; do
                    [[ i -lt ${#common_messages[@]} ]] || break
                    if [[ i -lt 0 ]]; then
                        value="$common_status"
                    else
                        value="${common_messages[i]}"
                    fi
                    case $compare in
                    [ne]) [[ ! $value == "$pattern" ]] || break 2;;
                    [op]) [[ ! $value == $pattern ]] || break 2;;
                    [tr]) [[ ! $value =~ $pattern ]] || break 2;;
                    esac
                done
            fi
            if [[ $compare == [not] ]]; then
                let "++i,1"
                continue 2
            else
                status="1"
                break 2
            fi
        done
        if [[ $compare == [not] ]]; then
            status="1"
            break
        else
            let "++i,1"
        fi
    done
    [[ $options == *f* ]] || set +f
    return "$status"
} 

common.hctaC() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[c]" "h" || return 
    [[ $# -ne 1 || $1 != -r ]] || common_status="0"
}

common.Finally() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[ych]" "f" || return 
}

common.yllaniF() {
    common.TryCatchFinallyVerify || return
    common.TryCatchFinallyNext "[f]" "l" || return 
    [[ common_status -eq 0 ]] || common.Throw
}

common.Caught() {
    common.TryCatchFinallyVerify || return
    [[ common_status -eq 0 ]] || return 1
}

common.EchoExitStatus() {
    return "${1:-$?}"
}

common.EnableThrowOnError() {
    common.TryCatchFinallyVerify || return
    [[ $common_options == *e* ]] || common_options+="e"
}

common.DisableThrowOnError() {
    common.TryCatchFinallyVerify || return
    common_options="${common_options/e}"
}

common.GetStatus() {
    common.TryCatchFinallyVerify || return
    echo "$common_status"
}

common.SetStatus() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -lt 1 || 10#$1 -gt 255 ]]; then
        echo "$(common.GetAlias): $1: First parameter was not an integer between 1 and 255" >&2
        return "1"
    fi
    let "common_status = 10#$1"
}

common.GetMessage() {
    common.TryCatchFinallyVerify || return
    local "upper=${#common_messages[@]}"
    if [[ upper -eq 0 ]]; then
        echo "$(common.GetAlias): $1: There are no messages" >&2
        return "1"
    elif [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#1} -gt 16 || -n ${1%%[0-9]*} || 10#$1 -ge upper ]]; then
        echo "$(common.GetAlias): $1: First parameter was an invalid index" >&2
        return "1"
    fi
    echo "${common_messages[$1]}"
}

common.MessageCount() {
    common.TryCatchFinallyVerify || return
    echo "${#common_messages[@]}"
}

common.CopyMessages() {
    common.TryCatchFinallyVerify || return
    if [[ $# -ne 1 ]]; then
        echo "$(common.GetAlias): $#: Wrong number of parameters" >&2
        return "1"         
    elif [[ ${#common_messages} -gt 0 ]]; then
        eval "$1=(\"\${common_messages[@]}\")"
    else
        eval "$1=()"
    fi
}

common.TryCatchFinallyExists() {
    [[ ${common_fifo:-u} != u ]]
}

common.TryCatchFinallyVerify() {
    local "name"
    if ! common.TryCatchFinallyExists; then
        echo "$(common.GetAlias "1"): No Try-Catch-Finally exists" >&2
        return "2"        
    fi
}

common.GetOptions() {
    local "opt"
    local "name=$(common.GetAlias "1")"
    if common.TryCatchFinallyExists; then
        echo "$name: A Try-Catch-Finally already exists" >&2
        return "1"        
    fi
    let "OPTIND = 1"
    let "OPTERR = 0"
    while getopts ":cdeh:ko:u:v:" opt "$@"; do
        case $opt in
        c)  [[ $common_options == *c* ]] || common_options+="c";;
        d)  [[ $common_options == *d* ]] || common_options+="d";;
        e)  [[ $common_options == *e* ]] || common_options+="e";;
        h)  common_errHandler="$OPTARG";;
        k)  [[ $common_options == *k* ]] || common_options+="k";;
        o)  common_file="$OPTARG";;
        u)  common_unhandled="$OPTARG";;
        v)  common_command="$OPTARG";;
        \?) #echo "Invalid option: -$OPTARG" >&2
            echo "$name: Illegal option: $OPTARG" >&2
            return "1";;
        :)  echo "$name: Option requires an argument: $OPTARG" >&2
            return "1";;
        *)  echo "$name: An error occurred while parsing options." >&2
            return "1";;
        esac
    done

    shift "$((OPTIND - 1))"
    if [[ $# -lt 1 ]]; then
        echo "$name: The fifo_file parameter is missing" >&2
        return "1"
    fi
    common_fifo="$1"
    if [[ ! -p $common_fifo ]]; then
        echo "$name: $1: The fifo_file is not an open FIFO" >&2
        return "1"  
    fi

    shift
    if [[ $# -lt 1 ]]; then
        echo "$name: The function parameter is missing" >&2
        return "1"
    fi
    common_function="$1"
    if ! chmod "0600" "$common_fifo"; then
        echo "$name: $common_fifo: Can not change file mode to 0600" >&2
        return "1"
    fi

    local "message=" "eof=TRY_CATCH_FINALLY_END_OF_FILE_$RANDOM"
    { echo "$eof" >"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not write" >&2
        return "1"
    fi   
    { while [[ $message != *$eof ]]; do
        read "message"
    done <"$common_fifo"; } 2>"/dev/null"
    if [[ $? -ne 0 ]]; then
        echo "$name: $common_fifo: Can not read" >&2
        return "1"
    fi   

    return "0"
}

common.DefaultUnhandled() {
    local -i "i"
    echo "-------------------------------------------------"
    echo "$(common.GetAlias "common.TryCatchFinally"): Unhandeled exception occurred"
    echo "Status: $(GetStatus)"
    echo "Messages:"
    for ((i=0; i<$(MessageCount); i++)); do
        echo "$(GetMessage "$i")"
    done
    echo "-------------------------------------------------"
}

common.TryCatchFinally() {
    local "common_file=/dev/fd/2"
    local "common_errHandler=common.DefaultErrHandler"
    local "common_unhandled=common.DefaultUnhandled"
    local "common_options="
    local "common_fifo="
    local "common_function="
    local "common_flags=$-"
    local "common_trySubshell=-1"
    local "common_initSubshell=-1"
    local "common_subshell"
    local "common_status=0"
    local "common_order=b"
    local "common_command="
    local "common_messages=()"
    local "common_handler=$(trap -p ERR)"
    [[ -n $common_handler ]] || common_handler="trap ERR"

    common.GetOptions "$@" || return "$?"
    shift "$((OPTIND + 1))"

    [[ -z $common_command ]] || common_command+="=$"
    common_command+='("$common_function" "$@")'

    set -E
    set +e
    trap "common.ErrHandler" ERR
    if true; then
        common.Try 
        eval "$common_command"
        common.EchoExitStatus
        common.yrT
    fi
    while common.Catch; do
        "$common_unhandled" >&2
        break
        common.hctaC -r
    done
    common.hctaC
    [[ $common_flags == *E* ]] || set +E
    [[ $common_flags != *e* ]] || set -e
    [[ $common_flags != *f* || $- == *f* ]] || set -f
    [[ $common_flags == *f* || $- != *f* ]] || set +f
    eval "$common_handler"
    return "$((common_status?2:0))"
}

Shortcut to create properties in Visual Studio?

When you write in Visual Studio,

public ServiceTypesEnum Type { get; set; }
public string TypeString { get { return this.Type.ToString();}}

ReSharper will keep suggesting to convert it to:

public string TypeString => Type.ToString();

Java program to find the largest & smallest number in n numbers without using arrays

import java.util.Scanner;

public class LargestSmallestNumbers {

    private static Scanner input;

    public static void main(String[] args) {
       int count,items;
       int newnum =0 ;
       int highest=0;
       int lowest =0;

       input = new Scanner(System.in);
       System.out.println("How many numbers you want to enter?");
       items = input.nextInt();

       System.out.println("Enter "+items+" numbers: ");


       for (count=0; count<items; count++){
           newnum = input.nextInt();               
           if (highest<newnum)
               highest=newnum;

           if (lowest==0)
               lowest=newnum;

           else if (newnum<=lowest)
               lowest=newnum;
           }

       System.out.println("The highest number is "+highest);
       System.out.println("The lowest number is "+lowest);
    }
}

Automatically create an Enum based on values in a database lookup table?

Using dynamic enums is bad no matter which way. You will have to go through the trouble of "duplicating" the data to ensure clear and easy code easy to maintain in the future.

If you start introducing automatic generated libraries, you are for sure causing more confusion to future developers having to upgrade your code than simply making your enum coded within the appropriate class object.

The other examples given sound nice and exciting, but think about the overhead on code maintenance versus what you get from it. Also, are those values going to change that frequently?

CSS : center form in page horizontally and vertically

if you use a negative translateX/Y width and height are not necessary and the style is really short

_x000D_
_x000D_
#form_login {
    left      : 50%;
    top       : 50%;
    position  : absolute;
    transform : translate(-50%, -50%);
}
_x000D_
<form id="form_login">
  <p> 
      <input type="text" id="username" placeholder="username" />
  </p>
  <p>
      <input type="password" id="password" placeholder="password" />
  </p>
  <p>
      <input type="text" id="server" placeholder="server" />
  </p>
  <p>
      <button id="submitbutton" type="button">Se connecter</button>
  </p>
</form>
_x000D_
_x000D_
_x000D_


Alternatively you could use display: grid (check the full page view)

_x000D_
_x000D_
body {
   margin        : 0;
   padding       : 0;
   display       : grid;
   place-content : center;
   min-height    : 100vh;
}
_x000D_
<form id="form_login">
  <p> 
      <input type="text" id="username" placeholder="username" />
  </p>
  <p>
      <input type="password" id="password" placeholder="password" />
  </p>
  <p>
      <input type="text" id="server" placeholder="server" />
  </p>
  <p>
      <button id="submitbutton" type="button">Se connecter</button>
  </p>
</form>
_x000D_
_x000D_
_x000D_

Checking if a field contains a string

This should do the work

db.users.find({ username: { $in: [ /son/i ] } });

The i is just there to prevent restrictions of matching single cases of letters.

You can check the $regex documentation on MongoDB documentation. Here's a link: https://docs.mongodb.com/manual/reference/operator/query/regex/

Converting user input string to regular expression

Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:

var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';

var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);

log.debug ('strFilterRegEx: ' + strFilterRegEx);

strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');

What tool to use to draw file tree diagram

Copying and pasting from the MS-DOS tree command might also work for you. Examples:

tree

C:\Foobar>tree
C:.
+---FooScripts
+---barconfig
+---Baz
¦   +---BadBaz
¦   +---Drop
...

tree /F

C:\Foobar>tree
C:.
+---FooScripts
¦    foo.sh
+---barconfig
¦    bar.xml
+---Baz
¦   +---BadBaz
¦   ¦    badbaz.xml
¦   +---Drop
...

tree /A

C:\Foobar>tree /A
C:.
+---FooScripts
+---barconfig
+---Baz
¦   +---BadBaz
¦   \---Drop
...

tree /F /A

C:\Foobar>tree /A
C:.
+---FooScripts
¦    foo.sh
+---barconfig
¦    bar.xml
+---Baz
¦   +---BadBaz
¦   ¦    badbaz.xml
¦   \---Drop
...

Syntax [source]

tree [drive:][path] [/F] [/A]

drive:\path — Drive and directory containing disk for display of directory structure, without listing files.

/F — Include all files living in every directory.

/A — Replace graphic characters used for linking lines with ext characters , instead of graphic characters. /a is used with code pages that do not support graphic characters and to send output to printers that do not properly interpret graphic characters.

Using jquery to delete all elements with a given id

You should be using a class for multiple elements as an id is meant to be only a single element. To answer your question on the .each() syntax though, this is what it would look like:

$('#myID').each(function() {
    $(this).remove();
});

Official JQuery documentation here.

Serialize form data to JSON

You can do this:

_x000D_
_x000D_
function onSubmit( form ){_x000D_
  var data = JSON.stringify( $(form).serializeArray() ); //  <-----------_x000D_
_x000D_
  console.log( data );_x000D_
  return false; //don't submit_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form onsubmit='return onSubmit(this)'>_x000D_
  <input name='user' placeholder='user'><br>_x000D_
  <input name='password' type='password' placeholder='password'><br>_x000D_
  <button type='submit'>Try</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

see this: http://www.json.org/js.html

How to recover MySQL database from .myd, .myi, .frm files

If these are MyISAM tables, then plopping the .FRM, .MYD, and .MYI files into a database directory (e.g., /var/lib/mysql/dbname) will make that table available. It doesn't have to be the same database as they came from, the same server, the same MySQL version, or the same architecture. You may also need to change ownership for the folder (e.g., chown -R mysql:mysql /var/lib/mysql/dbname)

Note that permissions (GRANT, etc.) are part of the mysql database. So they won't be restored along with the tables; you may need to run the appropriate GRANT statements to create users, give access, etc. (Restoring the mysql database is possible, but you need to be careful with MySQL versions and any needed runs of the mysql_upgrade utility.)

Actually, you probably just need the .FRM (table structure) and .MYD (table data), but you'll have to repair table to rebuild the .MYI (indexes).

The only constraint is that if you're downgrading, you'd best check the release notes (and probably run repair table). Newer MySQL versions add features, of course.

[Although it should be obvious, if you mix and match tables, the integrity of relationships between those tables is your problem; MySQL won't care, but your application and your users may. Also, this method does not work at all for InnoDB tables. Only MyISAM, but considering the files you have, you have MyISAM]

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

The static keyword and its various uses in C++

Variables:

static variables exist for the "lifetime" of the translation unit that it's defined in, and:

  • If it's in a namespace scope (i.e. outside of functions and classes), then it can't be accessed from any other translation unit. This is known as "internal linkage" or "static storage duration". (Don't do this in headers except for constexpr. Anything else, and you end up with a separate variable in each translation unit, which is crazy confusing)
  • If it's a variable in a function, it can't be accessed from outside of the function, just like any other local variable. (this is the local they mentioned)
  • class members have no restricted scope due to static, but can be addressed from the class as well as an instance (like std::string::npos). [Note: you can declare static members in a class, but they should usually still be defined in a translation unit (cpp file), and as such, there's only one per class]

locations as code:

static std::string namespaceScope = "Hello";
void foo() {
    static std::string functionScope= "World";
}
struct A {
   static std::string classScope = "!";
};

Before any function in a translation unit is executed (possibly after main began execution), the variables with static storage duration (namespace scope) in that translation unit will be "constant initialized" (to constexpr where possible, or zero otherwise), and then non-locals are "dynamically initialized" properly in the order they are defined in the translation unit (for things like std::string="HI"; that aren't constexpr). Finally, function-local statics will be initialized the first time execution "reaches" the line where they are declared. All static variables all destroyed in the reverse order of initialization.

The easiest way to get all this right is to make all static variables that are not constexpr initialized into function static locals, which makes sure all of your statics/globals are initialized properly when you try to use them no matter what, thus preventing the static initialization order fiasco.

T& get_global() {
    static T global = initial_value();
    return global;
}

Be careful, because when the spec says namespace-scope variables have "static storage duration" by default, they mean the "lifetime of the translation unit" bit, but that does not mean it can't be accessed outside of the file.

Functions

Significantly more straightforward, static is often used as a class member function, and only very rarely used for a free-standing function.

A static member function differs from a regular member function in that it can be called without an instance of a class, and since it has no instance, it cannot access non-static members of the class. Static variables are useful when you want to have a function for a class that definitely absolutely does not refer to any instance members, or for managing static member variables.

struct A {
    A() {++A_count;}
    A(const A&) {++A_count;}
    A(A&&) {++A_count;}
    ~A() {--A_count;}

    static int get_count() {return A_count;}
private:
    static int A_count;
}

int main() {
    A var;

    int c0 = var.get_count(); //some compilers give a warning, but it's ok.
    int c1 = A::get_count(); //normal way
}

A static free-function means that the function will not be referred to by any other translation unit, and thus the linker can ignore it entirely. This has a small number of purposes:

  • Can be used in a cpp file to guarantee that the function is never used from any other file.
  • Can be put in a header and every file will have it's own copy of the function. Not useful, since inline does pretty much the same thing.
  • Speeds up link time by reducing work
  • Can put a function with the same name in each translation unit, and they can all do different things. For instance, you could put a static void log(const char*) {} in each cpp file, and they could each all log in a different way.

SQL Sum Multiple rows into one

If you don't want to group your result, use a window function.

You didn't state your DBMS, but this is ANSI SQL:

SELECT AccountNumber, 
       Bill, 
       BillDate, 
       SUM(Bill) over (partition by accountNumber) as account_total
FROM Table1
order by AccountNumber, BillDate;

Here is an SQLFiddle: http://sqlfiddle.com/#!15/2c35e/1

You can even add a running sum, by adding:

sum(bill) over (partition by account_number order by bill_date) as sum_to_date

which will give you the total up to the current's row date.

Change New Google Recaptcha (v2) Width

unfortunately none of the above worked. I finally could do it using the following stuffs: This solution works 100% (adapt it to your need)

_x000D_
_x000D_
.g-recaptcha-wrapper {_x000D_
    position: relative;_x000D_
    border: 1px solid #ededed;_x000D_
    background: #f9f9f9;_x000D_
    border-radius: 4px;_x000D_
    padding: 0;_x000D_
    #topHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        height: 2px !important;_x000D_
        width: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #rightHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 295px;_x000D_
        height: 100% !important;_x000D_
        width: 15px;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #leftHider {_x000D_
        position: absolute;_x000D_
        top: 0;_x000D_
        left: 0;_x000D_
        height: 100% !important;_x000D_
        width: 2px;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
    #bottomHider {_x000D_
        position: absolute;_x000D_
        bottom: 1px;_x000D_
        left: 0;_x000D_
        height: 2px !important;_x000D_
        width: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
    }_x000D_
}
_x000D_
<div class="g-recaptcha-wrapper">_x000D_
  <re-captcha #captchaRef="reCaptcha" (resolved)="onCaptchaResolved($event)" siteKey="{{captchaSiteKey}}"></re-captcha>_x000D_
  <div id="topHider"></div>_x000D_
  <div id="rightHider"></div>_x000D_
  <div id="bottomHider"></div>_x000D_
  <div id="leftHider"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Result enter image description here

how to draw smooth curve through N points using javascript HTML5 canvas?

The first answer will not pass through all the points. This graph will exactly pass through all the points and will be a perfect curve with the points as [{x:,y:}] n such points.

var points = [{x:1,y:1},{x:2,y:3},{x:3,y:4},{x:4,y:2},{x:5,y:6}] //took 5 example points
ctx.moveTo((points[0].x), points[0].y);

for(var i = 0; i < points.length-1; i ++)
{

  var x_mid = (points[i].x + points[i+1].x) / 2;
  var y_mid = (points[i].y + points[i+1].y) / 2;
  var cp_x1 = (x_mid + points[i].x) / 2;
  var cp_x2 = (x_mid + points[i+1].x) / 2;
  ctx.quadraticCurveTo(cp_x1,points[i].y ,x_mid, y_mid);
  ctx.quadraticCurveTo(cp_x2,points[i+1].y ,points[i+1].x,points[i+1].y);
}

replacing text in a file with Python

This should do it

replacements = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

with open('path/to/input/file') as infile, open('path/to/output/file', 'w') as outfile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        outfile.write(line)

EDIT: To address Eildosa's comment, if you wanted to do this without writing to another file, then you'll end up having to read your entire source file into memory:

lines = []
with open('path/to/input/file') as infile:
    for line in infile:
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        lines.append(line)
with open('path/to/input/file', 'w') as outfile:
    for line in lines:
        outfile.write(line)

Edit: If you are using Python 3.x, use replacements.items() instead of replacements.iteritems()

How can I remove a button or make it invisible in Android?

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/activity_register_header"
    android:minHeight="50dp"
    android:orientation="vertical"
    android:visibility="gone" />

Try This Code

Visibility works fine in this code

How can I create a table with borders in Android?

I have to agree with Brad. That was an awful answer. The Android documentation states that TableLayout containers do not display border lines, so sending them to the Android site wont help them a bit. I was able to find a "dirty" solution on droidnova, which involves setting a background color for the TableLayout, then setting a different background color for the TableRow and adding layout_margin to the row. I'm not fond of this solution, but it does work for row borders. I guess you could do the same thing with the items composing each "cell" item but I haven't verified.

An example similar to the one on DroidNova:

<TableLayout android:background="#000000"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
  <TableRow android:background="#FFFFFF"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:layout_margin="1dp">
     ...
  </TableRow>
</TableLayout>

How to calculate the time interval between two time strings

Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):

#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta

def time_diff(start, end):
    if isinstance(start, datetime_time): # convert to datetime
        assert isinstance(end, datetime_time)
        start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
    if start <= end: # e.g., 10:33:26-11:15:49
        return end - start
    else: # end < start e.g., 23:55:00-00:25:00
        end += timedelta(1) # +day
        assert end > start
        return end - start

for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
    s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
    print(time_diff(s, e))
    assert time_diff(s, e) == time_diff(s.time(), e.time())

Output

0:42:23
0:30:00

time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:

#!/usr/bin/env python
from datetime import timedelta

def mean(data, start=timedelta(0)):
    """Find arithmetic average."""
    return sum(data, start) / len(data)

data = [timedelta(minutes=42, seconds=23), # 0:42:23
        timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds

The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.

rbind error: "names do not match previous names"

easy enough to use the unname() function:

data.frame <- unname(data.frame)

Get the Selected value from the Drop down box in PHP

You have to give a name attribute on your <select /> element, and then use it from the $_POST or $_GET (depending on how you transmit data) arrays in PHP. Be sure to sanitize user input, though.

What is it exactly a BLOB in a DBMS context

A BLOB is a Binary Large OBject. It is used to store large quantities of binary data in a database.

You can use it to store any kind of binary data that you want, includes images, video, or any other kind of binary data that you wish to store.

Different DBMSes treat BLOBs in different ways; you should read the documentation of the databases you are interested in to see how (and if) they handle BLOBs.

How do I create a new class in IntelliJ without using the mouse?

If you are already in the Project View, press Alt+Insert (New) | Class. Project View can be activated via Alt+1.

To create a new class in the same directory as the current one use Ctrl+Alt+Insert (New...).

You can also do it from the Navigation Bar, press Alt+Home, then choose package with arrow keys, then press Alt+Insert.

Another useful shortcut is View | Select In (Alt+F1), Project (1), then Alt+Insert to create a class near the existing one or use arrow keys to navigate through the packages.

And yet another way is to just type the class name in the existing code where you want to use it, IDEA will highlight it in red as it doesn't exist yet, then press Alt+Enter for the Intention Actions pop-up, choose Create Class.

How to place Text and an Image next to each other in HTML?

You can use vertical-align and floating.

In most cases you want to vertical-align: middle, the image.

Here is a test: http://www.w3schools.com/cssref/tryit.asp?filename=trycss_vertical-align

vertical-align: baseline|length|sub|super|top|text-top|middle|bottom|text-bottom|initial|inherit;

For middle, the definition is: The element is placed in the middle of the parent element.

So you might want to apply that to all elements within the element.

In Android EditText, how to force writing uppercase?

Try using any one of the below code may solve your issue.

programatically:

editText.filters = editText.filters + InputFilter.AllCaps()

XML :

android:inputType="textCapCharacters" with Edittext

The property 'Id' is part of the object's key information and cannot be modified

You should add

 db.Entry(contact).State = EntityState.Detached;

After the .SaveChanges();

JavaScript and Threads

With the HTML5 "side-specs" no need to hack javascript anymore with setTimeout(), setInterval(), etc.

HTML5 & Friends introduces the javascript Web Workers specification. It is an API for running scripts asynchronously and independently.

Links to the specification and a tutorial.

How do I initialize a TypeScript Object with a JSON-Object?

This is my approach (very simple):

const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);

for (const key in jsonObj) {
  if (!jsonObj.hasOwnProperty(key)) {
    continue;
  }

  console.log(key); // Key
  console.log(jsonObj[key]); // Value
  // Your logic...
}

ImportError: No module named 'MySQL'

The silly mistake I had done was keeping mysql.py in same dir. Try renaming mysql.py to another name so python don't consider that as module.

How to find elements by class

A straight forward way would be :

soup = BeautifulSoup(sdata)
for each_div in soup.findAll('div',{'class':'stylelist'}):
    print each_div

Make sure you take of the casing of findAll, its not findall

Killing a process using Java

AFAIU java.lang.Process is the process created by java itself (like Runtime.exec('firefox'))

You can use system-dependant commands like

 Runtime rt = Runtime.getRuntime();
  if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) 
     rt.exec("taskkill " +....);
   else
     rt.exec("kill -9 " +....);

I can't access http://localhost/phpmyadmin/

Make sure that both apache webserver and MySQL server are running. I had the same failure because I forgot to start my webserver.

Delete/Reset all entries in Core Data?

you're all making this seem complicated. You can just send your NSManagedObjectContext the reset method

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

Email address validation using ASP.NET MVC data type attributes

if you aren't yet using .net 4.5:

/// <summary>
/// TODO: AFTER WE UPGRADE TO .NET 4.5 THIS WILL NO LONGER BE NECESSARY.
/// </summary>
public class EmailAnnotation : RegularExpressionAttribute
{
    static EmailAnnotation()
    {
        DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAnnotation), typeof(RegularExpressionAttributeAdapter));
    }

    /// <summary>
    /// from: http://stackoverflow.com/a/6893571/984463
    /// </summary>
    public EmailAnnotation()
        : base(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*"
            + "@"
            + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$") { }

    public override string FormatErrorMessage(string name)
    {
        return "E-mail is not valid";
    }
}

Then you can do this:

    public class ContactEmailAddressDto
    {
        public int ContactId { get; set; }
        [Required]
        [Display(Name = "New Email Address")]
        [EmailAnnotation] //**<----- Nifty.**
        public string EmailAddressToAdd { get; set; }
    }

Replacing .NET WebBrowser control with a better browser, like Chrome?

Chrome uses (a fork of) Webkit if you didn't know, which is also used by Safari. Here's a few questions that are of the same vein:

The webkit one isn't great as the other answer states, one version no longer works (the google code one) and the Mono one is experimental. It'd be nice if someone made the effort to make a decent .NET wrapper for it but it's not something anyone seems to want to do - which is surprising given it now has support for HTML5 and so many other features that the IE(8) engine lacks.

Update (2014)

There's new dual-licensed project that allows you embed Chrome into your .NET applications called Awesomium. It comes with a .NET api but requires quite a few hacks for rendering (the examples draw the browser window to a buffer, paint the buffer as an image and refresh on a timer).

I think this is the browser used by Origin in Battlefield 3.

Update (2016)

There is now DotnetBrowser, a commercial alternative to Awesomium. It's based off Chromium.

JSON datetime between Python and JavaScript

If you're certain that only Javascript will be consuming the JSON, I prefer to pass Javascript Date objects directly.

The ctime() method on datetime objects will return a string that the Javascript Date object can understand.

import datetime
date = datetime.datetime.today()
json = '{"mydate":new Date("%s")}' % date.ctime()

Javascript will happily use that as an object literal, and you've got your Date object built right in.

Angularjs prevent form submission when input validation fails

I know this is an old thread but I thought I'd also make a contribution. My solution being similar to the post already marked as an answer. Some inline JavaScript checks does the trick.

ng-click="form.$invalid ? alert('Please correct the form') : saveTask(task)"

Add shadow to custom shape on Android

If you don't mind doing some custom drawing with the Canvas API, check out this answer about drop shadows. Here's a follow-up question to that one which fixes a problem in the original.

Autonumber value of last inserted row - MS Access / VBA

Private Function addInsert(Media As String, pagesOut As Integer) As Long


    Set rst = db.OpenRecordset("tblenccomponent")
    With rst
        .AddNew
        !LeafletCode = LeafletCode
        !LeafletName = LeafletName
        !UNCPath = "somePath\" + LeafletCode + ".xml"
        !Media = Media
        !CustomerID = cboCustomerID.Column(0)
        !PagesIn = PagesIn
        !pagesOut = pagesOut
        addInsert = CLng(rst!enclosureID) 'ID is passed back to calling routine
        .Update
    End With
    rst.Close

End Function

DateTime vs DateTimeOffset

There's a few places where DateTimeOffset makes sense. One is when you're dealing with recurring events and daylight savings time. Let's say I want to set an alarm to go off at 9am every day. If I use the "store as UTC, display as local time" rule, then the alarm will be going off at a different time when daylight savings time is in effect.

There are probably others, but the above example is actually one that I've run into in the past (this was before the addition of DateTimeOffset to the BCL - my solution at the time was to explicitly store the time in the local timezone, and save the timezone information along side it: basically what DateTimeOffset does internally).

Find row in datatable with specific id

Hello just create a simple function that looks as shown below.. That returns all rows where the call parameter entered is valid or true.

 public  DataTable SearchRecords(string Col1, DataTable RecordDT_, int KeyWORD)
    {
        TempTable = RecordDT_;
        DataView DV = new DataView(TempTable);
        DV.RowFilter = string.Format(string.Format("Convert({0},'System.String')",Col1) + " LIKE '{0}'", KeyWORD);
        return DV.ToTable();
    }

and simply call it as shown below;

  DataTable RowsFound=SearchRecords("IdColumn", OriginalTable,5);

where 5 is the ID. Thanks..

Angular - res.json() is not a function

You can remove the entire line below:

 .map((res: Response) => res.json());

No need to use the map method at all.

How can I programmatically get the MAC address of an iphone

It's not possible anymore on devices running iOS 7.0 or later, thus unavailable to get MAC address in Swift.

As Apple stated:

In iOS 7 and later, if you ask for the MAC address of an iOS device, the system returns the value 02:00:00:00:00:00. If you need to identify the device, use the identifierForVendor property of UIDevice instead. (Apps that need an identifier for their own advertising purposes should consider using the advertisingIdentifier property of ASIdentifierManager instead.)

What’s the best way to load a JSONObject from a json text file?

Thanks @Kit Ho for your answer. I used your code and found that I kept running into errors where my InputStream was always null and ClassNotFound exceptions when the JSONObject was being created. Here's my version of your code which does the trick for me:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;

import org.json.JSONObject;
public class JSONParsing {
    public static void main(String[] args) throws Exception {
        File f = new File("file.json");
        if (f.exists()){
            InputStream is = new FileInputStream("file.json");
            String jsonTxt = IOUtils.toString(is, "UTF-8");
            System.out.println(jsonTxt);
            JSONObject json = new JSONObject(jsonTxt);       
            String a = json.getString("1000");
            System.out.println(a);   
        }
    }
}

I found this answer to be enlightening about the difference between FileInputStream and getResourceAsStream. Hope this helps someone else too.

Reverse Y-Axis in PyPlot

Alternatively, you can use the matplotlib.pyplot.axis() function, which allows you inverting any of the plot axis

ax = matplotlib.pyplot.axis()
matplotlib.pyplot.axis((ax[0],ax[1],ax[3],ax[2]))

Or if you prefer to only reverse the X-axis, then

matplotlib.pyplot.axis((ax[1],ax[0],ax[2],ax[3]))

Indeed, you can invert both axis:

matplotlib.pyplot.axis((ax[1],ax[0],ax[3],ax[2]))

How do you check for permissions to write to a directory or file?

When your code does the following:

  1. Checks the current user has permission to do something.
  2. Carries out the action that needs the entitlements checked in 1.

You run the risk that the permissions change between 1 and 2 because you can't predict what else will be happening on the system at runtime. Therefore, your code should handle the situation where an UnauthorisedAccessException is thrown even if you have previously checked permissions.

Note that the SecurityManager class is used to check CAS permissions and doesn't actually check with the OS whether the current user has write access to the specified location (through ACLs and ACEs). As such, IsGranted will always return true for locally running applications.

Example (derived from Josh's example):

//1. Provide early notification that the user does not have permission to write.
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if(!SecurityManager.IsGranted(writePermission))
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

//2. Attempt the action but handle permission changes.
try
{
    using (FileStream fstream = new FileStream(filename, FileMode.Create))
    using (TextWriter writer = new StreamWriter(fstream))
    {
        writer.WriteLine("sometext");
    }
}
catch (UnauthorizedAccessException ex)
{
    //No permission. 
    //Either throw an exception so this can be handled by a calling function
    //or inform the user that they do not have permission to write to the folder and return.
}

It's tricky and not recommended to try to programatically calculate the effective permissions from the folder based on the raw ACLs (which are all that are available through the System.Security.AccessControl classes). Other answers on Stack Overflow and the wider web recommend trying to carry out the action to know whether permission is allowed. This post sums up what's required to implement the permission calculation and should be enough to put you off from doing this.

CSS endless rotation animation

Without any prefixes, e.g. at it's simplest:

.loading-spinner {
  animation: rotate 1.5s linear infinite;
}

@keyframes rotate {
  to {
    transform: rotate(360deg);
  }
}

How do I compare two strings in python?

If you want to know if both the strings are equal, you can simply do

print string1 == string2

But if you want to know if they both have the same set of characters and they occur same number of times, you can use collections.Counter, like this

>>> string1, string2 = "abc def ghi", "def ghi abc"
>>> from collections import Counter
>>> Counter(string1) == Counter(string2)
True

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How do you change the character encoding of a postgres database?

First off, Daniel's answer is the correct, safe option.

For the specific case of changing from SQL_ASCII to something else, you can cheat and simply poke the pg_database catalogue to reassign the database encoding. This assumes you've already stored any non-ASCII characters in the expected encoding (or that you simply haven't used any non-ASCII characters).

Then you can do:

update pg_database set encoding = pg_char_to_encoding('UTF8') where datname = 'thedb'

This will not change the collation of the database, just how the encoded bytes are converted into characters (so now length('£123') will return 4 instead of 5). If the database uses 'C' collation, there should be no change to ordering for ASCII strings. You'll likely need to rebuild any indices containing non-ASCII characters though.

Caveat emptor. Dumping and reloading provides a way to check your database content is actually in the encoding you expect, and this doesn't. And if it turns out you did have some wrongly-encoded data in the database, rescuing is going to be difficult. So if you possibly can, dump and reinitialise.

MySQL JOIN ON vs USING?

Database tables

To demonstrate how the USING and ON clauses work, let's assume we have the following post and post_comment database tables, which form a one-to-many table relationship via the post_id Foreign Key column in the post_comment table referencing the post_id Primary Key column in the post table:

SQL USING vs ON clauses table relationship

The parent post table has 3 rows:

| post_id | title     |
|---------|-----------|
| 1       | Java      |
| 2       | Hibernate |
| 3       | JPA       |

and the post_comment child table has the 3 records:

| post_comment_id | review    | post_id |
|-----------------|-----------|---------|
| 1               | Good      | 1       |
| 2               | Excellent | 1       |
| 3               | Awesome   | 2       |

The JOIN ON clause using a custom projection

Traditionally, when writing an INNER JOIN or LEFT JOIN query, we happen to use the ON clause to define the join condition.

For example, to get the comments along with their associated post title and identifier, we can use the following SQL projection query:

SELECT
   post.post_id,
   title,
   review
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

And, we get back the following result set:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The JOIN USING clause using a custom projection

When the Foreign Key column and the column it references have the same name, we can use the USING clause, like in the following example:

SELECT
  post_id,
  title,
  review
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

And, the result set for this particular query is identical to the previous SQL query that used the ON clause:

| post_id | title     | review    |
|---------|-----------|-----------|
| 1       | Java      | Good      |
| 1       | Java      | Excellent |
| 2       | Hibernate | Awesome   |

The USING clause works for Oracle, PostgreSQL, MySQL, and MariaDB. SQL Server doesn't support the USING clause, so you need to use the ON clause instead.

The USING clause can be used with INNER, LEFT, RIGHT, and FULL JOIN statements.

SQL JOIN ON clause with SELECT *

Now, if we change the previous ON clause query to select all columns using SELECT *:

SELECT *
FROM post
INNER JOIN post_comment ON post.post_id = post_comment.post_id
ORDER BY post.post_id, post_comment_id

We are going to get the following result set:

| post_id | title     | post_comment_id | review    | post_id |
|---------|-----------|-----------------|-----------|---------|
| 1       | Java      | 1               | Good      | 1       |
| 1       | Java      | 2               | Excellent | 1       |
| 2       | Hibernate | 3               | Awesome   | 2       |

As you can see, the post_id is duplicated because both the post and post_comment tables contain a post_id column.

SQL JOIN USING clause with SELECT *

On the other hand, if we run a SELECT * query that features the USING clause for the JOIN condition:

SELECT *
FROM post
INNER JOIN post_comment USING(post_id)
ORDER BY post_id, post_comment_id

We will get the following result set:

| post_id | title     | post_comment_id | review    |
|---------|-----------|-----------------|-----------|
| 1       | Java      | 1               | Good      |
| 1       | Java      | 2               | Excellent |
| 2       | Hibernate | 3               | Awesome   |

You can see that this time, the post_id column is deduplicated, so there is a single post_id column being included in the result set.

Conclusion

If the database schema is designed so that Foreign Key column names match the columns they reference, and the JOIN conditions only check if the Foreign Key column value is equal to the value of its mirroring column in the other table, then you can employ the USING clause.

Otherwise, if the Foreign Key column name differs from the referencing column or you want to include a more complex join condition, then you should use the ON clause instead.

How to display pandas DataFrame of floats using a format string for columns?

You can also set locale to your region and set float_format to use a currency format. This will automatically set $ sign for currency in USA.

import locale

locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

pd.set_option("float_format", locale.currency)

df = pd.DataFrame(
    [123.4567, 234.5678, 345.6789, 456.7890],
    index=["foo", "bar", "baz", "quux"],
    columns=["cost"],
)
print(df)

        cost
foo  $123.46
bar  $234.57
baz  $345.68
quux $456.79

What are the Differences Between "php artisan dump-autoload" and "composer dump-autoload"?

composer dump-autoload

PATH vendor/composer/autoload_classmap.php
  • Composer dump-autoload won’t download a thing.
  • It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php).
  • Ideal for when you have a new class inside your project.
  • autoload_classmap.php also includes the providers in config/app.php

php artisan dump-autoload

  • It will call Composer with the optimize flag
  • It will 'recompile' loads of files creating the huge bootstrap/compiled.php

Linq style "For Each"

Using the ToList() extension method is your best option:

someValues.ToList().ForEach(x => list.Add(x + 1));

There is no extension method in the BCL that implements ForEach directly.


Although there's no extension method in the BCL that does this, there is still an option in the System namespace... if you add Reactive Extensions to your project:

using System.Reactive.Linq;

someValues.ToObservable().Subscribe(x => list.Add(x + 1));

This has the same end result as the above use of ToList, but is (in theory) more efficient, because it streams the values directly to the delegate.

Convert Object to JSON string

Convert JavaScript object to json data

$("form").submit(function(event){
  event.preventDefault();
  var formData = $("form").serializeArray(); // Create array of object
  var jsonConvertedData = JSON.stringify(formData);  // Convert to json
  consol.log(jsonConvertedData);
});

You can validate json data using http://jsonlint.com

Accessing MVC's model property from Javascript

Contents of the Answer

1) How to access Model data in Javascript/Jquery code block in .cshtml file

2) How to access Model data in Javascript/Jquery code block in .js file

How to access Model data in Javascript/Jquery code block in .cshtml file

There are two types of c# variable (Model) assignments to JavaScript variable.

  1. Property assignment - Basic datatypes like int, string, DateTime (ex: Model.Name)
  2. Object assignment - Custom or inbuilt classes (ex: Model, Model.UserSettingsObj)

Lets look into the details of these two assignments.

For the rest of the answer lets consider the below AppUser Model as an example.

public class AppUser
{
    public string Name { get; set; }
    public bool IsAuthenticated { get; set; }
    public DateTime LoginDateTime { get; set; }
    public int Age { get; set; }
    public string UserIconHTML { get; set; }
}

And the values we assign this Model are

AppUser appUser = new AppUser
{
    Name = "Raj",
    IsAuthenticated = true,
    LoginDateTime = DateTime.Now,
    Age = 26,
    UserIconHTML = "<i class='fa fa-users'></i>"
};

Property assignment

Lets use different syntax for assignment and observe the results.

1) Without wrapping property assignment in quotes.

var Name = @Model.Name;  
var Age = @Model.Age;
var LoginTime = @Model.LoginDateTime; 
var IsAuthenticated = @Model.IsAuthenticated;   
var IconHtml = @Model.UserIconHTML;  

enter image description here

As you can see there are couple of errors, Raj and True is considered to be javascript variables and since they dont exist its an variable undefined error. Where as for the dateTime varialble the error is unexpected number numbers cannot have special characters, The HTML tags are converted into its entity names so that the browser doesn't mix up your values and the HTML markup.

2) Wrapping property assignment in Quotes.

var Name = '@Model.Name';
var Age = '@Model.Age';
var LoginTime = '@Model.LoginDateTime';
var IsAuthenticated = '@Model.IsAuthenticated';
var IconHtml = '@Model.UserIconHTML'; 

enter image description here

The results are valid, So wrapping the property assignment in quotes gives us valid syntax. But note that the Number Age is now a string, So if you dont want that we can just remove the quotes and it will be rendered as a number type.

3) Using @Html.Raw but without wrapping it in quotes

 var Name = @Html.Raw(Model.Name);
 var Age = @Html.Raw(Model.Age);
 var LoginTime = @Html.Raw(Model.LoginDateTime);
 var IsAuthenticated = @Html.Raw(Model.IsAuthenticated);
 var IconHtml = @Html.Raw(Model.UserIconHTML);

enter image description here

The results are similar to our test case 1. However using @Html.Raw()on the HTML string did show us some change. The HTML is retained without changing to its entity names.

From the docs Html.Raw()

Wraps HTML markup in an HtmlString instance so that it is interpreted as HTML markup.

But still we have errors in other lines.

4) Using @Html.Raw and also wrapping it within quotes

var Name ='@Html.Raw(Model.Name)';
var Age = '@Html.Raw(Model.Age)';
var LoginTime = '@Html.Raw(Model.LoginDateTime)';
var IsAuthenticated = '@Html.Raw(Model.IsAuthenticated)';
var IconHtml = '@Html.Raw(Model.UserIconHTML)';

enter image description here

The results are good with all types. But our HTML data is now broken and this will break the scripts. The issue is because we are using single quotes ' to wrap the the data and even the data has single quotes.

We can overcome this issue with 2 approaches.

1) use double quotes " " to wrap the HTML part. As the inner data has only single quotes. (Be sure that after wrapping with double quotes there are no " within the data too)

  var IconHtml = "@Html.Raw(Model.UserIconHTML)";

2) Escape the character meaning in your server side code. Like

  UserIconHTML = "<i class=\"fa fa-users\"></i>"

Conclusion of property assignment

  • Use quotes for non numeric dataType.
  • Do Not use quotes for numeric dataType.
  • Use Html.Raw to interpret your HTML data as is.
  • Take care of your HTML data to either escape the quotes meaning in server side, Or use a different quote than in data during assignment to javascript variable.

Object assignment

Lets use different syntax for assignment and observe the results.

1) Without wrapping object assignment in quotes.

  var userObj = @Model; 

enter image description here

When you assign a c# object to javascript variable the value of the .ToString() of that oject will be assigned. Hence the above result.

2 Wrapping object assignment in quotes

var userObj = '@Model'; 

enter image description here

3) Using Html.Raw without quotes.

   var userObj = @Html.Raw(Model); 

enter image description here

4) Using Html.Raw along with quotes

   var userObj = '@Html.Raw(Model)'; 

enter image description here

The Html.Raw was of no much use for us while assigning a object to variable.

5) Using Json.Encode() without quotes

var userObj = @Json.Encode(Model); 

//result is like
var userObj = {&quot;Name&quot;:&quot;Raj&quot;,
               &quot;IsAuthenticated&quot;:true,
               &quot;LoginDateTime&quot;:&quot;\/Date(1482572875150)\/&quot;,
               &quot;Age&quot;:26,
               &quot;UserIconHTML&quot;:&quot;\u003ci class=\&quot;fa fa-users\&quot;\u003e\u003c/i\u003e&quot;
              };

We do see some change, We see our Model is being interpreted as a object. But we have those special characters changed into entity names. Also wrapping the above syntax in quotes is of no much use. We simply get the same result within quotes.

From the docs of Json.Encode()

Converts a data object to a string that is in the JavaScript Object Notation (JSON) format.

As you have already encountered this entity Name issue with property assignment and if you remember we overcame it with the use of Html.Raw. So lets try that out. Lets combine Html.Raw and Json.Encode

6) Using Html.Raw and Json.Encode without quotes.

var userObj = @Html.Raw(Json.Encode(Model));

Result is a valid Javascript Object

 var userObj = {"Name":"Raj",
     "IsAuthenticated":true,
     "LoginDateTime":"\/Date(1482573224421)\/",
     "Age":26,
     "UserIconHTML":"\u003ci class=\"fa fa-users\"\u003e\u003c/i\u003e"
 };

enter image description here

7) Using Html.Raw and Json.Encode within quotes.

var userObj = '@Html.Raw(Json.Encode(Model))';

enter image description here

As you see wrapping with quotes gives us a JSON data

Conslusion on Object assignment

  • Use Html.Raw and Json.Encode in combintaion to assign your object to javascript variable as JavaScript object.
  • Use Html.Raw and Json.Encode also wrap it within quotes to get a JSON

Note: If you have observed the DataTime data format is not right. This is because as said earlier Converts a data object to a string that is in the JavaScript Object Notation (JSON) format and JSON does not contain a date type. Other options to fix this is to add another line of code to handle this type alone using javascipt Date() object

var userObj.LoginDateTime = new Date('@Html.Raw(Model.LoginDateTime)'); 
//without Json.Encode


How to access Model data in Javascript/Jquery code block in .js file

Razor syntax has no meaning in .js file and hence we cannot directly use our Model insisde a .js file. However there is a workaround.

1) Solution is using javascript Global variables.

We have to assign the value to a global scoped javascipt variable and then use this variable within all code block of your .cshtml and .js files. So the syntax would be

<script type="text/javascript">
  var userObj = @Html.Raw(Json.Encode(Model)); //For javascript object
  var userJsonObj = '@Html.Raw(Json.Encode(Model))'; //For json data
</script>

With this in place we can use the variables userObj and userJsonObj as and when needed.

Note: I personally dont suggest using global variables as it gets very hard for maintainance. However if you have no other option then you can use it with having a proper naming convention .. something like userAppDetails_global.

2) Using function() or closure Wrap all the code that is dependent on the model data in a function. And then execute this function from the .cshtml file .

external.js

 function userDataDependent(userObj){
  //.... related code
 }

.cshtml file

 <script type="text/javascript">
  userDataDependent(@Html.Raw(Json.Encode(Model))); //execute the function     
</script>

Note: Your external file must be referenced prior to the above script. Else the userDataDependent function is undefined.

Also note that the function must be in global scope too. So either solution we have to deal with global scoped players.

Convert Uri to String and String to Uri

I am not sure if you got this resolved. To follow up on "CommonsWare's" comment.

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Change

Uri uri=Uri.parse("/external/images/media/470939");

to

Uri uri=Uri.parse("content://external/images/media/470939");

in my case

Uri uri = Uri.parse("content://media/external/images/media/6562");

Bash script to run php script

If you have PHP installed as a command line tool (try issuing php to the terminal and see if it works), your shebang (#!) line needs to look like this:

#!/usr/bin/php

Put that at the top of your script, make it executable (chmod +x myscript.php), and make a Cron job to execute that script (same way you'd execute a bash script).

You can also use php myscript.php.

How to debug a GLSL shader?

The GLSL Shader source code is compiled and linked by the graphics driver and executed on the GPU.
If you want to debug the shader, then you have to use graphics debugger like RenderDoc or NVIDIA Nsight.

Android getting value from selected radiobutton

RadioGroup in XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Java"/>

    </RadioGroup>
</RelativeLayout>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:layout_marginLeft="100dp"
        android:textSize="18dp"
        android:text="Select Your Course"
        android:textStyle="bold"
        android:id="@+id/txtView"/>
<RadioGroup
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/rdGroup"
    android:layout_below="@+id/txtView">
    <RadioButton
        android:id="@+id/rdbJava"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Java"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbPython"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Python"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAndroid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="Android"
        android:onClick="onRadioButtonClicked"/>
    <RadioButton
        android:id="@+id/rdbAngular"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginLeft="100dp"
        android:text="AngularJS"
        android:onClick="onRadioButtonClicked"/>
</RadioGroup>
    <Button
        android:id="@+id/getBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_below="@+id/rdGroup"
        android:text="Get Course" />
</RelativeLayout>

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    RadioButton android, java, angular, python;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android = (RadioButton)findViewById(R.id.rdbAndroid);
        angular = (RadioButton)findViewById(R.id.rdbAngular);
        java = (RadioButton)findViewById(R.id.rdbJava);
        python = (RadioButton)findViewById(R.id.rdbPython);
        Button btn = (Button)findViewById(R.id.getBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String result = "Selected Course: ";
                result+= (android.isChecked())?"Android":(angular.isChecked())?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
                Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
            }
        });
    }
    public void onRadioButtonClicked(View view) {
        boolean checked = ((RadioButton) view).isChecked();
        String str="";
        // Check which radio button was clicked
        switch(view.getId()) {
            case R.id.rdbAndroid:
                if(checked)
                str = "Android Selected";
                break;
            case R.id.rdbAngular:
                if(checked)
                str = "AngularJS Selected";
                break;
            case R.id.rdbJava:
                if(checked)
                str = "Java Selected";
                break;
            case R.id.rdbPython:
                if(checked)
                str = "Python Selected";
                break;
        }
        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
    }
}

what is the size of an enum type data in C++?

The size is four bytes because the enum is stored as an int. With only 12 values, you really only need 4 bits, but 32 bit machines process 32 bit quantities more efficiently than smaller quantities.

0 0 0 0  January
0 0 0 1  February
0 0 1 0  March
0 0 1 1  April
0 1 0 0  May
0 1 0 1  June
0 1 1 0  July
0 1 1 1  August
1 0 0 0  September
1 0 0 1  October
1 0 1 0  November
1 0 1 1  December
1 1 0 0  ** unused **
1 1 0 1  ** unused **
1 1 1 0  ** unused **
1 1 1 1  ** unused **

Without enums, you might be tempted to use raw integers to represent the months. That would work and be efficient, but it would make your code hard to read. With enums, you get efficient storage and readability.

Installing Python packages from local file system folder to virtualenv with pip

An option --find-links does the job and it works from requirements.txt file!

You can put package archives in some folder and take the latest one without changing the requirements file, for example requirements:

.
+---requirements.txt
+---requirements
    +---foo_bar-0.1.5-py2.py3-none-any.whl
    +---foo_bar-0.1.6-py2.py3-none-any.whl
    +---wiz_bang-0.7-py2.py3-none-any.whl
    +---wiz_bang-0.8-py2.py3-none-any.whl
    +---base.txt
    +---local.txt
    +---production.txt

Now in requirements/base.txt put:

--find-links=requirements
foo_bar
wiz_bang>=0.8

A neat way to update proprietary packages, just drop new one in the folder

In this way you can install packages from local folder AND pypi with the same single call: pip install -r requirements/production.txt

PS. See my cookiecutter-djangopackage fork to see how to split requirements and use folder based requirements organization.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

How to flip background image using CSS?

According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

HTML:

<footer>
<p><a href="page">Footer Link</a></p>
<p>&copy; 2014 Company</p>
</footer>

CSS:

footer {
background:url(/img/headerbg.png) repeat-x 0 0;

/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

HTML form input tag name element array with JavaScript

Try this something like this:

var p_ids = document.forms[0].elements["p_id[]"];
alert(p_ids.length);
for (var i = 0, len = p_ids.length; i < len; i++) {
  alert(p_ids[i].value);
}

Can I make dynamic styles in React Native?

You can bind state value directly to style object. Here is an example:

class Timer extends Component{
 constructor(props){
 super(props);
 this.state = {timer: 0, color: '#FF0000'};
 setInterval(() => {
   this.setState({timer: this.state.timer + 1, color: this.state.timer % 2 == 0 ? '#FF0000' : '#0000FF'});
 }, 1000);
}

render(){
 return (
   <View>

    <Text>Timer:</Text>
    <Text style={{backgroundColor: this.state.color}}>{this.state.timer}</Text>
  </View>
 );
 }
}

How can I replace newline or \r\n with <br/>?

nl2br() as you have it should work fine:

$description = nl2br($description);

It's more likely that the unclosed ' on the first line of your example code is causing your issue. Remove the ' after $description...

...$description');

Vue.js toggle class on click

This example is using Lists: When clicking in some li it turn red

html:

<div id="app">
  <ul>
    <li @click="activate(li.id)" :class="{ active : active_el == li.id }" v-for="li in lista">{{li.texto}}</li>   
  </ul>
</div>

JS:

var app = new Vue({
  el:"#app",
  data:{
    lista:[{"id":"1","texto":"line 1"},{"id":"2","texto":"line 2"},{"id":"3","texto":"line 3"},{"id":"4","texto":"line 4"},{"id":"5","texto":"line 5"}],
    active_el:0
  },
  methods:{
    activate:function(el){
        this.active_el = el;
    }
  }
});

css

ul > li:hover {
  cursor:pointer;
}
.active {
  color:red;
  font-weight:bold;
}

Fiddle:

https://jsfiddle.net/w37vLL68/158/

How can I update the current line in a C# Windows Console App?

From the Console docs in MSDN:

You can solve this problem by setting the TextWriter.NewLine property of the Out or Error property to another line termination string. For example, the C# statement, Console.Error.NewLine = "\r\n\r\n";, sets the line termination string for the standard error output stream to two carriage return and line feed sequences. Then you can explicitly call the WriteLine method of the error output stream object, as in the C# statement, Console.Error.WriteLine();

So - I did this:

Console.Out.Newline = String.Empty;

Then I am able to control the output myself;

Console.WriteLine("Starting item 1:");
    Item1();
Console.WriteLine("OK.\nStarting Item2:");

Another way of getting there.

Byte Array to Image object

Since it sounds like you already know what format the byte[] array is in (e.g. RGB, ARGB, BGR etc.) you might be able to use BufferedImage.setRGB(...), or a combination of BufferedImage.getRaster() and WritableRaster.setPixels(...) or WritableRaster.setSamples(...). Unforunately both of these methods require you transform your byte[] into one of int[], float[] or double[] depending on the image format.

Duplicate / Copy records in the same MySQL table

Alex's answer needs some care (e.g. locking or a transaction) in multi-client environments.

Assuming the AUTO ID field is the first one in the table (a usual case), we can make use of implicit transactions.

    CREATE TEMPORARY TABLE tmp SELECT * from invoices WHERE ...;
    ALTER TABLE tmp drop ID; # drop autoincrement field
    # UPDATE tmp SET ...; # just needed to change other unique keys
    INSERT INTO invoices SELECT 0,tmp.* FROM tmp;
    DROP TABLE tmp;

From the MySQL docs:

Using AUTO_INCREMENT: You can also explicitly assign NULL or 0 to the column to generate sequence numbers.

Creating a new directory in C

Look at stat for checking if the directory exists,

And mkdir, to create a directory.

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

struct stat st = {0};

if (stat("/some/directory", &st) == -1) {
    mkdir("/some/directory", 0700);
}

You can see the manual of these functions with the man 2 stat and man 2 mkdir commands.

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

jQuery ajax upload file in asp.net mvc

AJAX file uploads are now possible by passing a FormData object to the data property of the $.ajax request.

As the OP specifically asked for a jQuery implementation, here you go:

<form id="upload" enctype="multipart/form-data" action="@Url.Action("JsonSave", "Survey")" method="POST">
    <input type="file" name="fileUpload" id="fileUpload" size="23" /><br />
    <button>Upload!</button>
</form>
$('#upload').submit(function(e) {
    e.preventDefault(); // stop the standard form submission

    $.ajax({
        url: this.action,
        type: this.method,
        data: new FormData(this),
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            console.log(data.UploadedFileCount + ' file(s) uploaded successfully');
        },
        error: function(xhr, error, status) {
            console.log(error, status);
        }
    });
});
public JsonResult Survey()
{
    for (int i = 0; i < Request.Files.Count; i++)
    {
        var file = Request.Files[i];
        // save file as required here...
    }
    return Json(new { UploadedFileCount = Request.Files.Count });
}

More information on FormData at MDN

How to get an object's properties in JavaScript / jQuery?

To get listing of object properties/values:

  1. In Firefox - Firebug:

    console.dir(<object>);
    
  2. Standard JS to get object keys borrowed from Slashnick:

       var fGetKeys = function(obj){
          var keys = [];
          for(var key in obj){
             keys.push(key);
          }
          return keys;
       }
    
    // Example to call it:
    
       var arrKeys = fGetKeys(document);
    
       for (var i=0, n=arrKeys.length; i<n; i++){
          console.log(i+1 + " - " + arrKeys[i] + document[arrKeys[i]] + "\n");
       }
    

Edits:

  1. <object> in the above is to be replaced with the variable reference to the object.
  2. console.log() is to be used in the console, if you're unsure what that is, you can replace it with an alert()

jQuery replace one class with another

To do this efficiently using jQuery, you can chain it like so:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

For modern browsers (See this to see which browsers I'm calling modern)

(assuming one element with class theClassThatsThereNow)

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

c# Image resizing to different size while preserving aspect ratio

I just wrote this cos none of the answers already here were simple enough. You can replace the hardcoded 128 for whatever you want or base them off the size of the original image. All i wanted was to rescale the image into a 128x128 image, keeping the aspect ratio and centering the result in the new image.

    private Bitmap CreateLargeIconForImage(Bitmap src)
    {
        Bitmap bmp = new Bitmap(128, 128);
        Graphics g = Graphics.FromImage(bmp);

        float scale = Math.Max((float)src.Width / 128.0f, (float)src.Height / 128.0f);
        PointF p = new PointF(128.0f - ((float)src.Width / scale), 128.0f - ((float)src.Height / scale));
        SizeF size = new SizeF((float)src.Width / scale, (float)src.Height / scale);

        g.DrawImage(src, new RectangleF(p, size));

        return bmp;
    }

importing pyspark in python shell

In the case of DSE (DataStax Cassandra & Spark) The following location needs to be added to PYTHONPATH

export PYTHONPATH=/usr/share/dse/resources/spark/python:$PYTHONPATH

Then use the dse pyspark to get the modules in path.

dse pyspark

How to resize a custom view programmatically?

I used this way to increase width of custom view

customDrawingView.post(new Runnable() {
                            @Override
                            public void run() {
                                View view_instance = customDrawingView;
                                android.view.ViewGroup.LayoutParams params = view_instance
                                        .getLayoutParams();
                                int newLayoutWidth = customDrawingView
                                        .getWidth()
                                        + customDrawingView.getWidth();
                                params.width = newLayoutWidth;
                                view_instance.setLayoutParams(params);
                                screenWidthBackup = params.width;
                            }
                        });

Extracting numbers from vectors of strings

Or simply:

as.numeric(gsub("\\D", "", years))
# [1] 20  1

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

Facebook Like-Button - hide count?

If you do overflow:hidden then keep in mind that it will also hide the comment box that comes up in XFBML version... after user likes it. So best if you do this...

/* make the like button smaller */
.fb_edge_widget_with_comment iframe
{
    width:47px !important;
}

/* but make the span that holds the comment box larger */
span.fb_edge_comment_widget.fb_iframe_widget iframe
{
    width:401px !important;
}

What is the http-header "X-XSS-Protection"?

X-XSS-Protection is a HTTP header understood by Internet Explorer 8 (and newer versions). This header lets domains toggle on and off the "XSS Filter" of IE8, which prevents some categories of XSS attacks. IE8 has the filter activated by default, but servers can switch if off by setting

   X-XSS-Protection: 0

See also http://blogs.msdn.com/b/ieinternals/archive/2011/01/31/controlling-the-internet-explorer-xss-filter-with-the-x-xss-protection-http-header.aspx

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

How to validate IP address in Python?

The IPy module (a module designed for dealing with IP addresses) will throw a ValueError exception for invalid addresses.

>>> from IPy import IP
>>> IP('127.0.0.1')
IP('127.0.0.1')
>>> IP('277.0.0.1')
Traceback (most recent call last):
 ...
ValueError: '277.0.0.1': single byte must be 0 <= byte < 256
>>> IP('foobar')
Traceback (most recent call last):
 ...
ValueError: invalid literal for long() with base 10: 'foobar'

However, like Dustin's answer, it will accept things like "4" and "192.168" since, as mentioned, these are valid representations of IP addresses.

If you're using Python 3.3 or later, it now includes the ipaddress module:

>>> import ipaddress
>>> ipaddress.ip_address('127.0.0.1')
IPv4Address('127.0.0.1')
>>> ipaddress.ip_address('277.0.0.1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: '277.0.0.1' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('foobar')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.3/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'foobar' does not appear to be an IPv4 or IPv6 address

For Python 2, you can get the same functionality using ipaddress if you install python-ipaddress:

pip install ipaddress

This module is compatible with Python 2 and provides a very similar API to that of the ipaddress module included in the Python Standard Library since Python 3.3. More details here. In Python 2 you will need to explicitly convert the IP address string to unicode: ipaddress.ip_address(u'127.0.0.1').

How to set the locale inside a Debian/Ubuntu Docker container?

Rather than resetting the locale after the installation of the locales package you can answer the questions you would normally get asked (which is disabled by noninteractive) before installing the package so that the package scripts setup the locale correctly, this example sets the locale to english (British, UTF-8):

RUN echo locales locales/default_environment_locale select en_GB.UTF-8 | debconf-set-selections
RUN echo locales locales/locales_to_be_generated select "en_GB.UTF-8 UTF-8" | debconf-set-selections

RUN \
  apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y locales && \
  rm -rf /var/lib/apt/lists/*

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Split Div Into 2 Columns Using CSS

You can use flexbox to control the layout of your div element:

_x000D_
_x000D_
* { box-sizing: border-box; }_x000D_
_x000D_
#content {_x000D_
  background-color: rgba(210, 210, 210, 0.5);_x000D_
  border: 1px solid #000;_x000D_
  padding: 0.5rem;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
#left,_x000D_
#right {_x000D_
  background-color: rgba(10, 10, 10, 0.5);_x000D_
  border: 1px solid #fff;_x000D_
  padding: 0.5rem;_x000D_
  flex-grow: 1;_x000D_
  color: #fff;_x000D_
}
_x000D_
<div id="content">_x000D_
  <div id="left">_x000D_
     <div id="object1">lorem ipsum</div>_x000D_
     <div id="object2">dolor site amet</div>_x000D_
  </div>_x000D_
_x000D_
  <div id="right">_x000D_
     <div id="object3">lorem ipsum</div>_x000D_
     <div id="object4">dolor site amet</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Reading in from System.in - Java

You can call java myProg arg1 arg2 ... :

public static void main (String args[]) {
    BufferedReader in = new BufferedReader(new FileReader(args[0]));
}

AFNetworking Post Request

For AFNetworking 3.0 (iOS9 or greter)

 NSString *strURL = @"https://exampleWeb.com/webserviceOBJ";
    NSDictionary *dictParamiters = @{@"user[height]": height,@"user[weight]": weight};

    NSString *aStrParams = [self getFormDataStringWithDictParams:dictParamiters];

    NSData *aData = [aStrParams dataUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *aRequest = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strURL]];
    [aRequest setHTTPMethod:@"POST"];
    [aRequest setHTTPBody:aData];

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
    [aRequest setHTTPBody:aData];

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:aRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        //
        if (error ==nil) {
            NSString *aStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"ResponseString:%@",aStr);
            NSMutableDictionary *aMutDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            dispatch_async(dispatch_get_main_queue(), ^{
                    completionBlock(aMutDict);

                NSLog(@"responce:%@",aMutDict)

            });
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"error:%@",error.locali)
            });
        }
    }];

    [postDataTask resume];

and Add

-(NSString *)getFormDataStringWithDictParams:(NSDictionary *)aDict
{
    NSMutableString *aMutStr = [[NSMutableString alloc]initWithString:@""];
    for (NSString *aKey in aDict.allKeys) {
        [aMutStr appendFormat:@"%@=%@&",aKey,aDict[aKey]];
    }
    NSString *aStrParam;
    if (aMutStr.length>2) {
        aStrParam = [aMutStr substringWithRange:NSMakeRange(0, aMutStr.length-1)];

    }
    else
        aStrParam = @"";

    return aStrParam;
}

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

Force youtube embed to start in 720p

Youtube doesn't support playback quality anymore

Youtube doesn't support playback quality anymore

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

How to get the error message from the error code returned by GetLastError()?

GetLastError returns a numerical error code. To obtain a descriptive error message (e.g., to display to a user), you can call FormatMessage:

// This functions fills a caller-defined character buffer (pBuffer)
// of max length (cchBufferLength) with the human-readable error message
// for a Win32 error code (dwErrorCode).
// 
// Returns TRUE if successful, or FALSE otherwise.
// If successful, pBuffer is guaranteed to be NUL-terminated.
// On failure, the contents of pBuffer are undefined.
BOOL GetErrorMessage(DWORD dwErrorCode, LPTSTR pBuffer, DWORD cchBufferLength)
{
    if (cchBufferLength == 0)
    {
        return FALSE;
    }

    DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                 NULL,  /* (not used with FORMAT_MESSAGE_FROM_SYSTEM) */
                                 dwErrorCode,
                                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                 pBuffer,
                                 cchBufferLength,
                                 NULL);
    return (cchMsg > 0);
}

In C++, you can simplify the interface considerably by using the std::string class:

#include <Windows.h>
#include <system_error>
#include <memory>
#include <string>
typedef std::basic_string<TCHAR> String;

String GetErrorMessage(DWORD dwErrorCode)
{
    LPTSTR psz{ nullptr };
    const DWORD cchMsg = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
                                         | FORMAT_MESSAGE_IGNORE_INSERTS
                                         | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                                       NULL, // (not used with FORMAT_MESSAGE_FROM_SYSTEM)
                                       dwErrorCode,
                                       MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                                       reinterpret_cast<LPTSTR>(&psz),
                                       0,
                                       NULL);
    if (cchMsg > 0)
    {
        // Assign buffer to smart pointer with custom deleter so that memory gets released
        // in case String's c'tor throws an exception.
        auto deleter = [](void* p) { ::LocalFree(p); };
        std::unique_ptr<TCHAR, decltype(deleter)> ptrBuffer(psz, deleter);
        return String(ptrBuffer.get(), cchMsg);
    }
    else
    {
        auto error_code{ ::GetLastError() };
        throw std::system_error( error_code, std::system_category(),
                                 "Failed to retrieve error message string.");
    }
}

NOTE: These functions also work for HRESULT values. Just change the first parameter from DWORD dwErrorCode to HRESULT hResult. The rest of the code can remain unchanged.


These implementations provide the following improvements over the existing answers:

  • Complete sample code, not just a reference to the API to call.
  • Provides both C and C++ implementations.
  • Works for both Unicode and MBCS project settings.
  • Takes the error code as an input parameter. This is important, as a thread's last error code is only valid at well defined points. An input parameter allows the caller to follow the documented contract.
  • Implements proper exception safety. Unlike all of the other solutions that implicitly use exceptions, this implementation will not leak memory in case an exception is thrown while constructing the return value.
  • Proper use of the FORMAT_MESSAGE_IGNORE_INSERTS flag. See The importance of the FORMAT_MESSAGE_IGNORE_INSERTS flag for more information.
  • Proper error handling/error reporting, unlike some of the other answers, that silently ignore errors.


This answer has been incorporated from Stack Overflow Documentation. The following users have contributed to the example: stackptr, Ajay, Cody Gray?, IInspectable.

execute function after complete page load

This way you can handle the both cases - if the page is already loaded or not:

document.onreadystatechange = function(){
    if (document.readyState === "complete") {
       myFunction();
    }
    else {
       window.onload = function () {
          myFunction();
       };
    };
}

Bootstrap 3 Gutter Size

You can keep the default behaviour (with gutter) and add a class to your CSS stylesheet for tasks like yours:

.no-gutter > [class*='col-'] {
    padding-right:0;
    padding-left:0;
}

And here’s how you can use it in your HTML:

<div class="row no-gutter">
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
    <div class="col-md-4">
        ...
    </div>
</div>

Formatting struct timespec

The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.

It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.

Example output: 2021-01-19T04:50:01.435561072Z

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int utc_system_timestamp(char[]);

int main(void) {
    char buf[31];
    utc_system_timestamp(buf);
    printf("%s\n", buf);
}

// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
        const int bufsize = 31;
        struct timespec now;
        struct tm tm;
        int retval = clock_gettime(CLOCK_REALTIME, &now);
        gmtime_r(&now.tv_sec, &tm);
        strftime(buf, bufsize, "%Y-%m-%dT%H:%M:%S.", &tm);
        sprintf(buf, "%s%09luZ", buf, now.tv_nsec);
        return retval;
}

How to convert a UTF-8 string into Unicode?

I have string that displays UTF-8 encoded characters

There is no such thing in .NET. The string class can only store strings in UTF-16 encoding. A UTF-8 encoded string can only exist as a byte[]. Trying to store bytes into a string will not come to a good end; UTF-8 uses byte values that don't have a valid Unicode codepoint. The content will be destroyed when the string is normalized. So it is already too late to recover the string by the time your DecodeFromUtf8() starts running.

Only handle UTF-8 encoded text with byte[]. And use UTF8Encoding.GetString() to convert it.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

Closing a Userform with Unload Me doesn't work

Unload Me only works when its called from userform self. If you want to close a form from another module code (or userform), you need to use the Unload function + userformtoclose name.

I hope its helps

Force sidebar height 100% using CSS (with a sticky bottom image)?

I would use css tables to achieve a 100% sidebar height.

The basic idea is to wrap the sidebar and main divs in a container.

Give the container a display:table

And give the 2 child divs (sidebar and main) a display: table-cell

Like so..

#container {
display: table;
}
#main {
display: table-cell;
vertical-align: top;
}
#sidebar {
display: table-cell;
vertical-align: top;
} 

Take a look at this LIVE DEMO where I have modified your initial markup using the above technique (I have used background colors for the different divs so that you can see which ones are which)

Posting raw image data as multipart/form-data in curl

As of PHP 5.6 @$filePath will not work in CURLOPT_POSTFIELDS without CURLOPT_SAFE_UPLOAD being set and it is completely removed in PHP 7. You will need to use a CurlFile object, RFC here.

$fields = [
    'name' => new \CurlFile($filePath, 'image/png', 'filename.png')
];
curl_setopt($resource, CURLOPT_POSTFIELDS, $fields);

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

How are software license keys generated?

All of the CD only copy protection algorithms inconvience honest users while providing no protection against piracy whatsoever.

The "pirate" only need to have access to one legitimate cd and its access code, he can then make n copies and distribute them.

It does not matter how cryptographically secure you make the code, you need to supply this with the CD in plain text or an legitimate user cannot activite the software.

Most secure schemes involve either the user providing the software supplier with some details of the machine which will run the software (cpu serial numbers, mac addresses, Ip address etc.), or, require online access to register the software on the suppliers website and in return receive an activitation token. The first option requires a lot of manual administration and is only worth it for very high value software, the, second option can be spoofed and is absolutly infuriating if you have limited network access or you are stuck behind a firewall.

On the whole its much easier to establish a trust relationship with your customers!

How do I create/edit a Manifest file?

Go to obj folder in you app folder, then Debug. In there delete the manifest file and build again. It worked for me.

mongodb/mongoose findMany - find all documents with IDs listed in array

Combining Daniel's and snnsnn's answers:

_x000D_
_x000D_
let ids = ['id1','id2','id3']
let data = await MyModel.find(
  {'_id': { $in: ids}}
);
_x000D_
_x000D_
_x000D_

Simple and clean code. It works and tested against:

"mongodb": "^3.6.0", "mongoose": "^5.10.0",

How to rebase local branch onto remote master

First fetch the new master from the upstream repository, then rebase your work branch on that:

git fetch origin            # Updates origin/master
git rebase origin/master    # Rebases current branch onto origin/master

Update: Please see Paul Draper's answer for a more concise way to do the same - recent Git versions provide a simpler way to do the equivalent of the above two commands.

Keeping session alive with Curl and PHP

This is how you do CURL with sessions

//initial request with login data

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/login.php');
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=XXXXX&password=XXXXX");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-name');  //could be empty, but cause problems on some hosts
curl_setopt($ch, CURLOPT_COOKIEFILE, '/var/www/ip4.x/file/tmp');  //could be empty, but cause problems on some hosts
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

//another request preserving the session

curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/profile');
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

I've seen this on ImpressPages

How to extract text from an existing docx file using python-docx

Without Installing python-docx

docx is basically is a zip file with several folders and files within it. In the link below you can find a simple function to extract the text from docx file, without the need to rely on python-docx and lxml the latter being sometimes hard to install:

http://etienned.github.io/posts/extract-text-from-word-docx-simply/

How can I return NULL from a generic method in C#?

Your other option would be to to add this to the end of your declaration:

    where T : class
    where T: IList

That way it will allow you to return null.

Where can I download JSTL jar

If youre using Maven, here's something for your pom.xml file

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

'this' implicitly has type 'any' because it does not have a type annotation

For method decorator declaration with configuration "noImplicitAny": true, you can specify type of this variable explicitly depends on @tony19's answer

function logParameter(this:any, target: Object, propertyName: string) {
  //...
}

Java JDBC connection status

The low-cost method, regardless of the vendor implementation, would be to select something from the process memory or the server memory, like the DB version or the name of the current database. IsClosed is very poorly implemented.

Example:

java.sql.Connection conn = <connect procedure>;
conn.close();
try {
  conn.getMetaData();
} catch (Exception e) {
  System.out.println("Connection is closed");
}

How can I make an entire HTML form "readonly"?

Have all the form id's numbered and run a for loop in JS.

 for(id = 0; id<NUM_ELEMENTS; id++)
   document.getElementById(id).disabled = false; 

Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?

Just call Canvas.drawColor(Color.BLACK), or whatever color you want to clear your Canvas with.

And: how can I update just a part of the screen ?

There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.

So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor() method.

How to get active user's UserDetails

And if you need authorized user in templates (e.g. JSP) use

<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<sec:authentication property="principal.yourCustomField"/>

together with

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>${spring-security.version}</version>
    </dependency>

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

How to get whole and decimal part of a number?

Not seen a simple modulus here...

$number         = 1.25;
$wholeAsFloat   = floor($number);   // 1.00
$wholeAsInt     = intval($number);  // 1
$decimal        = $number % 1;      // 0.25

In this case getting both $wholeAs? and $decimal don't depend on the other. (You can just take 1 of the 3 outputs independently.) I've shown $wholeAsFloat and $wholeAsInt because floor() returns a float type number even though the number it returns will always be whole. (This is important if you're passing the result into a type-hinted function parameter.)

I wanted this to split a floating point number of hours/minutes, e.g. 96.25, into hours and minutes separately for a DateInterval instance as 96 hours 15 minutes. I did this as follows:

$interval = new \DateInterval(sprintf("PT%dH%dM", intval($hours), (($hours % 1) * 60)));

I didn't care about seconds in my case.

macro - open all files in a folder

You can use Len(StrFile) > 0 in loop check statement !

Sub openMyfile()

    Dim Source As String
    Dim StrFile As String

    'do not forget last backslash in source directory.
    Source = "E:\Planning\03\"
    StrFile = Dir(Source)

    Do While Len(StrFile) > 0                        
        Workbooks.Open Filename:=Source & StrFile
        StrFile = Dir()
    Loop
End Sub

How to redirect and append both stdout and stderr to a file with Bash?

This should work fine:

your_command 2>&1 | tee -a file.txt

It will store all logs in file.txt as well as dump them on terminal.

'const string' vs. 'static readonly string' in C#

OQ asked about static string vs const. Both have different use cases (although both are treated as static).

Use const only for truly constant values (e.g. speed of light - but even this varies depending on medium). The reason for this strict guideline is that the const value is substituted into the uses of the const in assemblies that reference it, meaning you can have versioning issues should the const change in its place of definition (i.e. it shouldn't have been a constant after all). Note this even affects private const fields because you might have base and subclass in different assemblies and private fields are inherited.

Static fields are tied to the type they are declared within. They are used for representing values that need to be the same for all instances of a given type. These fields can be written to as many times as you like (unless specified readonly).

If you meant static readonly vs const, then I'd recommend static readonly for almost all cases because it is more future proof.

FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)

if your JVM Cli is: -agentlib:jdwp=transport=dt_socket,address=60000,server=n,suspend=n and JDK version is 7, change "server=n" to "server=y" will be OK.

'python3' is not recognized as an internal or external command, operable program or batch file

Python3.exe is not defined in windows

Specify the path for required version of python when you need to used it by creating virtual environment for your project

Python 3

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

Python2

virtualenv --python=C:\PATH_TO_PYTHON\python.exe environment

then activate the environment using

.\environment\Scripts\activate.ps1

Get Folder Size from Windows Command Line

I guess this would only work if the directory is fairly static and its contents don't change between the execution of the two dir commands. Maybe a way to combine this into one command to avoid that, but this worked for my purpose (I didn't want the full listing; just the summary).

GetDirSummary.bat Script:

@echo off
rem  get total number of lines from dir output
FOR /F "delims=" %%i IN ('dir /S %1 ^| find "asdfasdfasdf" /C /V') DO set lineCount=%%i
rem  dir summary is always last 3 lines; calculate starting line of summary info
set /a summaryStart="lineCount-3"
rem  now output just the last 3 lines
dir /S %1 | more +%summaryStart%

Usage:

GetDirSummary.bat c:\temp

Output:

 Total Files Listed:
          22 File(s)         63,600 bytes
           8 Dir(s)  104,350,330,880 bytes free

Determine project root from a running node.js application

All these "root dirs" mostly need to resolve some virtual path to a real pile path, so may be you should look at path.resolve?

var path= require('path');
var filePath = path.resolve('our/virtual/path.ext');

Is it possible to sort a ES6 map object?

One way is to get the entries array, sort it, and then create a new Map with the sorted array:

let ar = [...myMap.entries()];
sortedArray = ar.sort();
sortedMap = new Map(sortedArray);

But if you don't want to create a new object, but to work on the same one, you can do something like this:

// Get an array of the keys and sort them
let keys = [...myMap.keys()];
sortedKeys = keys.sort();

sortedKeys.forEach((key)=>{
  // Delete the element and set it again at the end
  const value = this.get(key);
  this.delete(key);
  this.set(key,value);
})

How to check if String value is Boolean type in Java?

return value.equals("false") || value.equals("true");

How to convert a number to string and vice versa in C++

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   string s="000101";
   cout<<s<<"\n";
   int a = stoi(s);
   cout<<a<<"\n";
   s=to_string(a);
   s+='1';
   cout<<s;
   return 0;
}

Output:

  • 000101
  • 101
  • 1011

In log4j, does checking isDebugEnabled before logging improve performance?

Since Log4j version 2.4 (orslf4j-api 2.0.0-alpha1) it's much better to use fluent API (or Java 8 lambda support for lazy logging), supporting Supplier<?> for log message argument, that can be given by lambda:

log.debug("Debug message with expensive data : {}", 
           () -> doExpensiveCalculation());

OR with slf4j API:

log.atDebug()
            .addArgument(() -> doExpensiveCalculation())
            .log("Debug message with expensive data : {}");

Remove Safari/Chrome textinput/textarea glow

Edit (11 years later): Don't do this unless you're going to provide a fallback to indicate which element is active. Otherwise, this harms accessibility as it essentially removes the indication showing which element in a document has focus. Imagine being a keyboard user and not really knowing what element you can interact with. Let accessibility trump aesthetics here.

textarea, select, input, button { outline: none; }

Although, it's been argued that keeping the glow/outline is actually beneficial for accessibility as it can help users see which Element is currently focused.

You can also use the pseudo-element ':focus' to only target the inputs when the user has them selected.

Demo: https://jsfiddle.net/JohnnyWalkerDesign/xm3zu0cf/

How to capture the android device screen content?

You can try the following library: Android Screenshot Library (ASL) enables to programmatically capture screenshots from Android devices without requirement of having root access privileges. Instead, ASL utilizes a native service running in the background, started via the Android Debug Bridge (ADB) once per device boot.

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

How to get current date in jquery?

you can use this code:

var nowDate     = new Date();
var nowDay      = ((nowDate.getDate().toString().length) == 1) ? '0'+(nowDate.getDate()) : (nowDate.getDate());
var nowMonth    = ((nowDate.getMonth().toString().length) == 1) ? '0'+(nowDate.getMonth()+1) : (nowDate.getMonth()+1);
var nowYear     = nowDate.getFullYear();
var formatDate  = nowDay + "." + nowMonth + "." + nowYear;

you can find a working demo here

Looping over a list in Python

Do this instead:

values = [[1,2,3],[4,5]]
for x in values:
    if len(x) == 3:
       print(x)

URL Encoding using C#

Levi Botelho commented that the table of encodings that was previously generated is no longer accurate for .NET 4.5, since the encodings changed slightly between .NET 4.0 and 4.5. So I've regenerated the table for .NET 4.5:

Unencoded UrlEncoded UrlEncodedUnicode UrlPathEncoded WebUtilityUrlEncoded EscapedDataString EscapedUriString HtmlEncoded HtmlAttributeEncoded WebUtilityHtmlEncoded HexEscaped
A         A          A                 A              A                    A                 A                A           A                    A                     %41
B         B          B                 B              B                    B                 B                B           B                    B                     %42

a         a          a                 a              a                    a                 a                a           a                    a                     %61
b         b          b                 b              b                    b                 b                b           b                    b                     %62

0         0          0                 0              0                    0                 0                0           0                    0                     %30
1         1          1                 1              1                    1                 1                1           1                    1                     %31

[space]   +          +                 %20            +                    %20               %20              [space]     [space]              [space]               %20
!         !          !                 !              !                    %21               !                !           !                    !                     %21
"         %22        %22               "              %22                  %22               %22              &quot;      &quot;               &quot;                %22
#         %23        %23               #              %23                  %23               #                #           #                    #                     %23
$         %24        %24               $              %24                  %24               $                $           $                    $                     %24
%         %25        %25               %              %25                  %25               %25              %           %                    %                     %25
&         %26        %26               &              %26                  %26               &                &amp;       &amp;                &amp;                 %26
'         %27        %27               '              %27                  %27               '                &#39;       &#39;                &#39;                 %27
(         (          (                 (              (                    %28               (                (           (                    (                     %28
)         )          )                 )              )                    %29               )                )           )                    )                     %29
*         *          *                 *              *                    %2A               *                *           *                    *                     %2A
+         %2b        %2b               +              %2B                  %2B               +                +           +                    +                     %2B
,         %2c        %2c               ,              %2C                  %2C               ,                ,           ,                    ,                     %2C
-         -          -                 -              -                    -                 -                -           -                    -                     %2D
.         .          .                 .              .                    .                 .                .           .                    .                     %2E
/         %2f        %2f               /              %2F                  %2F               /                /           /                    /                     %2F
:         %3a        %3a               :              %3A                  %3A               :                :           :                    :                     %3A
;         %3b        %3b               ;              %3B                  %3B               ;                ;           ;                    ;                     %3B
<         %3c        %3c               <              %3C                  %3C               %3C              &lt;        &lt;                 &lt;                  %3C
=         %3d        %3d               =              %3D                  %3D               =                =           =                    =                     %3D
>         %3e        %3e               >              %3E                  %3E               %3E              &gt;        >                    &gt;                  %3E
?         %3f        %3f               ?              %3F                  %3F               ?                ?           ?                    ?                     %3F
@         %40        %40               @              %40                  %40               @                @           @                    @                     %40
[         %5b        %5b               [              %5B                  %5B               [                [           [                    [                     %5B
\         %5c        %5c               \              %5C                  %5C               %5C              \           \                    \                     %5C
]         %5d        %5d               ]              %5D                  %5D               ]                ]           ]                    ]                     %5D
^         %5e        %5e               ^              %5E                  %5E               %5E              ^           ^                    ^                     %5E
_         _          _                 _              _                    _                 _                _           _                    _                     %5F
`         %60        %60               `              %60                  %60               %60              `           `                    `                     %60
{         %7b        %7b               {              %7B                  %7B               %7B              {           {                    {                     %7B
|         %7c        %7c               |              %7C                  %7C               %7C              |           |                    |                     %7C
}         %7d        %7d               }              %7D                  %7D               %7D              }           }                    }                     %7D
~         %7e        %7e               ~              %7E                  ~                 ~                ~           ~                    ~                     %7E

A         %c4%80     %u0100            %c4%80         %C4%80               %C4%80            %C4%80           A           A                    A                     [OoR]
a         %c4%81     %u0101            %c4%81         %C4%81               %C4%81            %C4%81           a           a                    a                     [OoR]
E         %c4%92     %u0112            %c4%92         %C4%92               %C4%92            %C4%92           E           E                    E                     [OoR]
e         %c4%93     %u0113            %c4%93         %C4%93               %C4%93            %C4%93           e           e                    e                     [OoR]
I         %c4%aa     %u012a            %c4%aa         %C4%AA               %C4%AA            %C4%AA           I           I                    I                     [OoR]
i         %c4%ab     %u012b            %c4%ab         %C4%AB               %C4%AB            %C4%AB           i           i                    i                     [OoR]
O         %c5%8c     %u014c            %c5%8c         %C5%8C               %C5%8C            %C5%8C           O           O                    O                     [OoR]
o         %c5%8d     %u014d            %c5%8d         %C5%8D               %C5%8D            %C5%8D           o           o                    o                     [OoR]
U         %c5%aa     %u016a            %c5%aa         %C5%AA               %C5%AA            %C5%AA           U           U                    U                     [OoR]
u         %c5%ab     %u016b            %c5%ab         %C5%AB               %C5%AB            %C5%AB           u           u                    u                     [OoR]

The columns represent encodings as follows:

  • UrlEncoded: HttpUtility.UrlEncode
  • UrlEncodedUnicode: HttpUtility.UrlEncodeUnicode
  • UrlPathEncoded: HttpUtility.UrlPathEncode
  • WebUtilityUrlEncoded: WebUtility.UrlEncode
  • EscapedDataString: Uri.EscapeDataString
  • EscapedUriString: Uri.EscapeUriString
  • HtmlEncoded: HttpUtility.HtmlEncode
  • HtmlAttributeEncoded: HttpUtility.HtmlAttributeEncode
  • WebUtilityHtmlEncoded: WebUtility.HtmlEncode
  • HexEscaped: Uri.HexEscape

NOTES:

  1. HexEscape can only handle the first 255 characters. Therefore it throws an ArgumentOutOfRange exception for the Latin A-Extended characters (eg A).

  2. This table was generated in .NET 4.5 (see answer https://stackoverflow.com/a/11236038/216440 for the encodings relevant to .NET 4.0 and below).

EDIT:

  1. As a result of Discord's answer I added the new WebUtility UrlEncode and HtmlEncode methods, which were introduced in .NET 4.5.

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

How to remove line breaks from a file in Java?

String text = readFileAsString("textfile.txt").replaceAll("\n", "");

Even though the definition of trim() in oracle website is "Returns a copy of the string, with leading and trailing whitespace omitted."

the documentation omits to say that new line characters (leading and trailing) will also be removed.

In short String text = readFileAsString("textfile.txt").trim(); will also work for you. (Checked with Java 6)

How can I run a php without a web server?

For windows system you should be able to run php by following below steps:

  1. Download php version you want to use and put it in c:\php.
  2. append ;c:\php to your system path using cmd or gui.
  3. call $ php -S localhost:8000 command in a folder which you want to serve the pages from.

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

This is what i used to add addtional worksheet

Workbook workbook = null;
Worksheet worksheet = null;

workbook = app.Workbooks.Add(1);
workbook.Sheets.Add();

Worksheet additionalWorksheet = workbook.ActiveSheet;

How do I create a readable diff of two spreadsheets using git diff?

Use Altova DiffDog

Use diffdog's XML diff mode and Grid View to review the differences in an easy to read tabular format. Text diff'ing is MUCH HARDER for spreadsheets of any complexity. With this tool, at least two methods are viable under various circumstances.

  1. Save As .xml

    To detect the differences of a simple, one sheet spreadsheet, save the Excel spreadsheets to compare as XML Spreadsheet 2003 with a .xml extension.

  2. Save As .xlsx

    To detect the differences of most spreadsheets in a modularized document model, save the Excel spreadsheets to compare as an Excel Workbook in .xlsx form. Open the files to diff with diffdog. It informs you that the file is a ZIP archive, and asks if you want to open it for directory comparison. Upon agreeing to directory comparison, it becomes a relatively simple matter of double-clicking logical parts of the document to diff them (with the XML diff mode). Most parts of the .xslx document are XML-formatted data. The Grid View is extremely useful. It is trivial to diff individual sheets to focus the analysis on areas that are known to have changed.

Excel's propensity to tweak certain attribute names with every save is annoying, but diffdog's XML diff'ing capabilities include the ability to filter certain kinds of differences. For example, Excel spreadsheets in XML form contain row and c elements that have s attributes (style) that rename with every save. Setting up a filter like c:s makes it much easier to view only content changes.

diffdog has a lot of diff'ing capability. I've listed the XML diff modes only simply because I haven't used another tool that I liked better when it comes to differencing Excel documents.

Error in Python script "Expected 2D array, got 1D array instead:"?

I faced the same problem. You just have to make it an array and moreover you have to put double squared brackets to make it a single element of the 2D array as first bracket initializes the array and the second makes it an element of that array.

So simply replace the last statement by:

print(clf.predict(np.array[[0.58,0.76]]))

expand/collapse table rows with JQuery

I expanded one of the answers, however my functionality is a bit different. In my version, different rows form different groups. And "header" row triggers collapsing/expanding of that particular group. Also, each individual subgroup memorizes state that its in. It might sound a bit confusing, you can test drive my version using jsfiddle. Hope this code snippets will be helpful to someone out there!

HTML

<table border="0">
  <tr>
      <th>Header 1</th>
      <th>Header 2</th>
  </tr>
  <tr>
    <td class='group1'>Group 1</td>
    <td>data 2</td>
  </tr>
  <tr class='group1'>
    <td>data 3</td>
    <td>data 4</td>
  </tr>
  <tr>
    <td class='group2'>Group 2</td>
    <td>data 2</td>
  </tr>
  <tr class='group2'>
    <td>data 3</td>
    <td>data 4</td>
  </tr>
  <tr class='group2'>
    <td class='sub_group1'>Sub Group 1</td>
    <td>data 6</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td>data 7</td>
    <td>data 8</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td>data 9</td>
    <td>data 10</td>
  </tr>
  <tr class='group2 sub_group1'>
    <td class='sub_sub_group1'>Sub Sub Group 1</td>
    <td>data 11</td>
  </tr>
  <tr class='group2 sub_group1 sub_sub_group1'>
    <td>data 12</td>
    <td>data 13</td>
  </tr>
  <tr class='group2 sub_group1 sub_sub_group1'>
    <td>data 14</td>
    <td>data 15</td>
  </tr>
  <tr class='group2'>
    <td class='sub_group2'>Sub Group 2</td>
    <td>data 11</td>
  </tr>
  <tr class='group2 sub_group2'>
    <td>data 12</td>
    <td>data 13</td>
  </tr>
  <tr class='group2 sub_group2'>
    <td>data 14</td>
    <td>data 15</td>
  </tr>
</table>

CSS

table, tr, td, th
{
    border: 1px solid black;
    border-collapse:collapse;
}

img.button_open{
  content:url('http://code.stephenmorley.org/javascript/collapsible-lists/button-open.png');
  cursor:pointer;
}

img.button_closed{
  content: url('http://code.stephenmorley.org/javascript/collapsible-lists/button-closed.png');
  cursor:pointer;
}

JS

function CreateGroup(group_name)
{
    // Create Button(Image)
    $('td.' + group_name).prepend("<img class='" + group_name + " button_closed'> ");
    // Add Padding to Data
    $('tr.' + group_name).each(function () {
        var first_td = $(this).children('td').first();
        var padding_left = parseInt($(first_td).css('padding-left'));
        $(first_td).css('padding-left', String(padding_left + 25) + 'px');
    });
    RestoreGroup(group_name);

    // Tie toggle function to the button
    $('img.' + group_name).click(function(){
        ToggleGroup(group_name);
    });
}

function ToggleGroup(group_name)
{
    ToggleButton($('img.' + group_name));
    RestoreGroup(group_name);
}

function RestoreGroup(group_name)
{
    if ($('img.' + group_name).hasClass('button_open'))
    {
        // Open everything
        $('tr.' + group_name).show();

        // Close subgroups that been closed
        $('tr.' + group_name).find('img.button_closed').each(function () {
            sub_group_name = $(this).attr('class').split(/\s+/)[0];
            //console.log(sub_group_name);
            RestoreGroup(sub_group_name);
        });
    }

    if ($('img.' + group_name).hasClass('button_closed'))
    {
        // Close everything
        $('tr.' + group_name).hide();
    }
}

function ToggleButton(button)
{
    $(button).toggleClass('button_open');
    $(button).toggleClass('button_closed');
}

CreateGroup('group1');
CreateGroup('group2');
CreateGroup('sub_group1');
CreateGroup('sub_group2');
CreateGroup('sub_sub_group1');

DEMO

An efficient way to transpose a file in Bash

Another bash variant

$ cat file 
XXXX    col1    col2    col3
row1    0       1       2
row2    3       4       5
row3    6       7       8
row4    9       10      11

Script

#!/bin/bash

I=0
while read line; do
    i=0
    for item in $line; { printf -v A$I[$i] $item; ((i++)); }
    ((I++))
done < file
indexes=$(seq 0 $i)

for i in $indexes; {
    J=0
    while ((J<I)); do
        arr="A$J[$i]"
        printf "${!arr}\t"
        ((J++))
    done
    echo
}

Output

$ ./test 
XXXX    row1    row2    row3    row4    
col1    0       3       6       9   
col2    1       4       7       10  
col3    2       5       8       11

Can't install via pip because of egg_info error

Having the same error trying to install matplotlib for Python 3, those solutions didn't work for me. It was just a matter of dependencies, though it wasn't clear in the error message.

I used sudo apt-get build-dep python3-matplotlib then sudo pip3 install matplotlib and it worked.

Hope it'll help !

Extract filename and extension in Bash

Based largely off of @mklement0's excellent, and chock-full of random, useful bashisms - as well as other answers to this / other questions / "that darn internet"... I wrapped it all up in a little, slightly more comprehensible, reusable function for my (or your) .bash_profile that takes care of what (I consider) should be a more robust version of dirname/basename / what have you..

function path { SAVEIFS=$IFS; IFS=""   # stash IFS for safe-keeping, etc.
    [[ $# != 2 ]] && echo "usage: path <path> <dir|name|fullname|ext>" && return    # demand 2 arguments
    [[ $1 =~ ^(.*/)?(.+)?$ ]] && {     # regex parse the path
        dir=${BASH_REMATCH[1]}
        file=${BASH_REMATCH[2]}
        ext=$([[ $file = *.* ]] && printf %s ${file##*.} || printf '')
        # edge cases for extensionless files and files like ".nesh_profile.coffee"
        [[ $file == $ext ]] && fnr=$file && ext='' || fnr=${file:0:$((${#file}-${#ext}))}
        case "$2" in
             dir) echo      "${dir%/*}"; ;;
            name) echo      "${fnr%.*}"; ;;
        fullname) echo "${fnr%.*}.$ext"; ;;
             ext) echo           "$ext"; ;;
        esac
    }
    IFS=$SAVEIFS
}     

Usage examples...

SOMEPATH=/path/to.some/.random\ file.gzip
path $SOMEPATH dir        # /path/to.some
path $SOMEPATH name       # .random file
path $SOMEPATH ext        # gzip
path $SOMEPATH fullname   # .random file.gzip                     
path gobbledygook         # usage: -bash <path> <dir|name|fullname|ext>

How to hide Android soft keyboard on EditText

You need to add the following attribute for the Activity in your AndroidManifest.xml.

<activity
    ...
    android:windowSoftInputMode="stateHidden|adjustResize"
    ...
/>

Is there a quick change tabs function in Visual Studio Code?

Another way to quickly change tabs would be in VSCode 1.45 (April 2020)

Switch tabs using mouse wheel

When you use the mouse wheel to scroll over editor tabs, you can currently not switch to the tab, only reveal tabs that are out of view.

Now with a new setting workbench.editor.scrollToSwitchTabs this behaviour can be changed if you change it to true.

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_45/scroll-tabs.gif

Note: you can also press and hold the Shift key while scrolling to get the opposite behaviour (i.e. you can switch to tabs even with this setting being turned off).

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

The real reason you want to use NVARCHAR is when you have different languages in the same column, you need to address the columns in T-SQL without decoding, you want to be able to see the data "natively" in SSMS, or you want to standardize on Unicode.

If you treat the database as dumb storage, it is perfectly possible to store wide strings and different (even variable-length) encodings in VARCHAR (for instance UTF-8). The problem comes when you are attempting to encode and decode, especially if the code page is different for different rows. It also means that the SQL Server will not be able to deal with the data easily for purposes of querying within T-SQL on (potentially variably) encoded columns.

Using NVARCHAR avoids all this.

I would recommend NVARCHAR for any column which will have user-entered data in it which is relatively unconstrained.

I would recommend VARCHAR for any column which is a natural key (like a vehicle license plate, SSN, serial number, service tag, order number, airport callsign, etc) which is typically defined and constrained by a standard or legislation or convention. Also VARCHAR for user-entered, and very constrained (like a phone number) or a code (ACTIVE/CLOSED, Y/N, M/F, M/S/D/W, etc). There is absolutely no reason to use NVARCHAR for those.

So for a simple rule:

VARCHAR when guaranteed to be constrained NVARCHAR otherwise

How to refresh app upon shaking the device?

Working with me v.good Reference

public class ShakeEventListener implements SensorEventListener {
public final static int SHAKE_LIMIT = 15;
public final static int LITTLE_SHAKE_LIMIT = 5;

private SensorManager mSensorManager;
private float mAccel = 0.00f;
private float mAccelCurrent = SensorManager.GRAVITY_EARTH;
private float mAccelLast = SensorManager.GRAVITY_EARTH;

private ShakeListener listener;

public interface ShakeListener {
    public void onShake();
    public void onLittleShake();
}

public ShakeEventListener(ShakeListener l) {
    Activity a = (Activity) l;
    mSensorManager = (SensorManager) a.getSystemService(Context.SENSOR_SERVICE);
    listener = l;
    registerListener();
}

public ShakeEventListener(Activity a, ShakeListener l) {
    mSensorManager = (SensorManager) a.getSystemService(Context.SENSOR_SERVICE);
    listener = l;
    registerListener();
}

public void registerListener() {
    mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

public void unregisterListener() {
    mSensorManager.unregisterListener(this);
}

public void onSensorChanged(SensorEvent se) {
    float x = se.values[0];
    float y = se.values[1];
    float z = se.values[2];
    mAccelLast = mAccelCurrent;
    mAccelCurrent = (float) FloatMath.sqrt(x*x + y*y + z*z);
    float delta = mAccelCurrent - mAccelLast;
    mAccel = mAccel * 0.9f + delta;
    if(mAccel > SHAKE_LIMIT)
        listener.onShake();
    else if(mAccel > LITTLE_SHAKE_LIMIT)
        listener.onLittleShake();
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}

Jquery, checking if a value exists in array or not

    if ($.inArray('yourElement', yourArray) > -1)
    {
        //yourElement in yourArray
        //code here

    }

Reference: Jquery Array

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

How to scroll to the bottom of a UITableView on the iPhone before the view appears

No need for any scrolling you can just do it by using this code:

[YOURTABLEVIEWNAME setContentOffset:CGPointMake(0, CGFLOAT_MAX)];

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

Recursive file search using PowerShell

To add to @user3303020 answer and output the search results into a file, you can run

Get-ChildItem V:\MyFolder -name -recurse *.CopyForbuild.bat > path_to_results_filename.txt

It may be easier to search for the correct file that way.

How to delete last character in a string in C#?

Personally I would go with Rob's suggestion, but if you want to remove one (or more) specific trailing character(s) you can use TrimEnd. E.g.

paramstr = paramstr.TrimEnd('&');

Android Left to Right slide animation

Use this xml in res/anim/

This is for left to right animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate android:fromXDelta="-100%" android:toXDelta="0%"
             android:fromYDelta="0%" android:toYDelta="0%"
             android:duration="700"/>
</set>

This is for right to left animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="0%" android:toXDelta="100%"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="700" />
</set>

In your coding use intent like for left to right:

this.overridePendingTransition(R.anim.animation_enter,
                   R.anim.animation_leave);

In your coding use intent like for right to left

this.overridePendingTransition(R.anim.animation_leave,
                               R.anim.animation_enter);

How to convert DateTime to VarChar

With Microsoft Sql Server:

--
-- Create test case
--
DECLARE @myDateTime DATETIME
SET @myDateTime = '2008-05-03'

--
-- Convert string
--
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)

How to reference image resources in XAML?

  1. Add folders to your project and add images to these through "Existing Item".
  2. XAML similar to this: <Image Source="MyRessourceDir\images\addButton.png"/>
  3. F6 (Build)

How to change the MySQL root account password on CentOS7?

For me work like this: 1. Stop mysql: systemctl stop mysqld

  1. Set the mySQL environment option systemctl set-environment MYSQLD_OPTS="--skip-grant-tables"

  2. Start mysql usig the options you just set systemctl start mysqld

  3. Login as root mysql -u root

  4. After login I use FLUSH PRIVILEGES; tell the server to reload the grant tables so that account-management statements work. If i don't do that i receive this error trying to update the password: "Can't find any matching row in the user table"

Stylesheet not updating

I had the same problem and it was due to the browser caching the stylesheet. Try refreshing the Cache:

    Cmd + Shift + r (on a mac) OR Ctrl + F5 (on windows)

This will do a hard refresh, and should use the new stylesheet that you uploaded to the server.

handle textview link click in my android app

if there are multiple links in the text view . For example textview has "https://" and "tel no" we can customise the LinkMovement method and handle clicks for words based on a pattern. Attached is the customised Link Movement Method.

public class CustomLinkMovementMethod extends LinkMovementMethod
{

private static Context movementContext;

private static CustomLinkMovementMethod linkMovementMethod = new CustomLinkMovementMethod();

public boolean onTouchEvent(android.widget.TextView widget, android.text.Spannable buffer, android.view.MotionEvent event)
{
    int action = event.getAction();

    if (action == MotionEvent.ACTION_UP)
    {
        int x = (int) event.getX();
        int y = (int) event.getY();

        x -= widget.getTotalPaddingLeft();
        y -= widget.getTotalPaddingTop();

        x += widget.getScrollX();
        y += widget.getScrollY();

        Layout layout = widget.getLayout();
        int line = layout.getLineForVertical(y);
        int off = layout.getOffsetForHorizontal(line, x);

        URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
        if (link.length != 0)
        {
            String url = link[0].getURL();
            if (url.startsWith("https"))
            {
                Log.d("Link", url);
                Toast.makeText(movementContext, "Link was clicked", Toast.LENGTH_LONG).show();
            } else if (url.startsWith("tel"))
            {
                Log.d("Link", url);
                Toast.makeText(movementContext, "Tel was clicked", Toast.LENGTH_LONG).show();
            } else if (url.startsWith("mailto"))
            {
                Log.d("Link", url);
                Toast.makeText(movementContext, "Mail link was clicked", Toast.LENGTH_LONG).show();
            }
            return true;
        }
    }

    return super.onTouchEvent(widget, buffer, event);
}

public static android.text.method.MovementMethod getInstance(Context c)
{
    movementContext = c;
    return linkMovementMethod;
}

This should be called from the textview in the following manner:

textViewObject.setMovementMethod(CustomLinkMovementMethod.getInstance(context));