Programs & Examples On #Periodformatter

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

For windows :

Package.json

  "scripts": {
    "start": "nodemon app.js",
    "test": "mocha"
  },

then run the command

npm run test

Could not find main class HelloWorld

You are not setting a classpath that includes your compiled class! java can't find any classes if you don't tell it where to look.

java -cp [compiler outpur dir] HelloWorld

Incidentally you do not need to set CLASSPATH the way you have done.

Why can't DateTime.Parse parse UTC date

It's not a valid format, however "Tue, 1 Jan 2008 00:00:00 GMT" is.

The documentation says like this:

A string that includes time zone information and conforms to ISO 8601. For example, the first of the following two strings designates the Coordinated Universal Time (UTC); the second designates the time in a time zone seven hours earlier than UTC:

2008-11-01T19:35:00.0000000Z

A string that includes the GMT designator and conforms to the RFC 1123 time format. For example:

Sat, 01 Nov 2008 19:35:00 GMT

A string that includes the date and time along with time zone offset information. For example:

03/01/2009 05:42:00 -5:00

Is there a difference between PhoneGap and Cordova commands?

they re both identical, except that phonegap cli can help you build your application on PhoneGap Build. My suggestion is to use the cordova CLI if you don't use the PhoneGap build service.

How do you subtract Dates in Java?

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());

Count table rows

As mentioned by Santosh, I think this query is suitably fast, while not querying all the table.

To return integer result of number of data records, for a specific tablename in a particular database:

select TABLE_ROWS from information_schema.TABLES where TABLE_SCHEMA = 'database' 
AND table_name='tablename';

Default values in a C Struct

You could address the problem with an X-Macro

You would change your struct definition into:

#define LIST_OF_foo_MEMBERS \
    X(int,id) \
    X(int,route) \
    X(int,backup_route) \
    X(int,current_route)


#define X(type,name) type name;
struct foo {
    LIST_OF_foo_MEMBERS 
};
#undef X

And then you would be able to easily define a flexible function that sets all fields to dont_care.

#define X(type,name) in->name = dont_care;    
void setFooToDontCare(struct foo* in) {
    LIST_OF_foo_MEMBERS 
}
#undef X

Following the discussion here, one could also define a default value in this way:

#define X(name) dont_care,
const struct foo foo_DONT_CARE = { LIST_OF_STRUCT_MEMBERS_foo };
#undef X

Which translates into:

const struct foo foo_DONT_CARE = {dont_care, dont_care, dont_care, dont_care,};

And use it as in hlovdal answer, with the advantage that here maintenance is easier, i.e. changing the number of struct members will automatically update foo_DONT_CARE. Note that the last "spurious" comma is acceptable.

I first learned the concept of X-Macros when I had to address this problem.

It is extremely flexible to new fields being added to the struct. If you have different data types, you could define different dont_care values depending on the data type: from here, you could take inspiration from the function used to print the values in the second example.

If you are ok with an all int struct, then you could omit the data type from LIST_OF_foo_MEMBERS and simply change the X function of the struct definition into #define X(name) int name;

Auto populate columns in one sheet from another sheet

Below code will look for last used row in sheet1 and copy the entire range from A1 upto last used row in column A to Sheet2 at exact same location.

Sub test()

    Dim lastRow As Long
    lastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
    Sheets("Sheet2").Range("A1:A" & lastRow).Value = Sheets("Sheet1").Range("A1:A" & lastRow).Value

End Sub

Save text file UTF-8 encoded with VBA

You can use CreateTextFile or OpenTextFile method, both have an attribute "unicode" usefull for encoding settings.

object.CreateTextFile(filename[, overwrite[, unicode]])        
object.OpenTextFile(filename[, iomode[, create[, format]]])

Example: Overwrite:

CreateTextFile:
 fileName = "filename"
 Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.CreateTextFile(fileName, True, True)
 out.WriteLine ("Hello world!")
 ...
 out.close

Example: Append:

 OpenTextFile Set fso = CreateObject("Scripting.FileSystemObject")
 Set out = fso.OpenTextFile("filename", ForAppending, True, 1)
 out.Write "Hello world!"
 ...
 out.Close

See more on MSDN docs

PHP import Excel into database (xls & xlsx)

This is best plugin with proper documentation and examples

https://github.com/PHPOffice/PHPExcel

Plus point: you can ask for help in its discussion forum and you will get response within a day from the author itself, really impressive.

How do I get logs/details of ansible-playbook module executions?

There is also other way to generate log file.

Before running ansible-playbook run the following commands to enable logging:

  • Specify the location for the log file.

    export ANSIBLE_LOG_PATH=~/ansible.log

  • Enable Debug

    export ANSIBLE_DEBUG=True

  • To check that generated log file.

    less $ANSIBLE_LOG_PATH

Is 'bool' a basic datatype in C++?

C++ does lots of automatic casting for you - that is, if you have a variable of type bool and pass it to something expecting an int, it will make it into an int for you - 0 for false and 1 for true.

I don't have my standard around to see if this is guaranteed, but every compiler I've used does this (so one can assume it will always work).

However, relying on this conversion is a bad idea. Code can stop compiling if a new method is added that overloads the int signature, etc.

What's the difference between xsd:include and xsd:import?

Use xsd:include to bring in an XSD from the same or no namespace.

Use xsd:import to bring in an XSD from a different namespace.

Listing contents of a bucket with boto3

It can also be done as follows:

csv_files = s3.list_objects_v2(s3_bucket_path)
    for obj in csv_files['Contents']:
        key = obj['Key']

Can I set max_retries for requests.request?

After struggling a bit with some of the answers here, I found a library called backoff that worked better for my situation. A basic example:

import backoff

@backoff.on_exception(
    backoff.expo,
    requests.exceptions.RequestException,
    max_tries=5,
    giveup=lambda e: e.response is not None and e.response.status_code < 500
)
def publish(self, data):
    r = requests.post(url, timeout=10, json=data)
    r.raise_for_status()

I'd still recommend giving the library's native functionality a shot, but if you run into any problems or need broader control, backoff is an option.

Spring 3 MVC accessing HttpRequest from controller

Spring MVC will give you the HttpRequest if you just add it to your controller method signature:

For instance:

/**
 * Generate a PDF report...
 */
@RequestMapping(value = "/report/{objectId}", method = RequestMethod.GET)
public @ResponseBody void generateReport(
        @PathVariable("objectId") Long objectId, 
        HttpServletRequest request, 
        HttpServletResponse response) {

    // ...
    // Here you can use the request and response objects like:
    // response.setContentType("application/pdf");
    // response.getOutputStream().write(...);

}

As you see, simply adding the HttpServletRequest and HttpServletResponse objects to the signature makes Spring MVC to pass those objects to your controller method. You'll want the HttpSession object too.

EDIT: It seems that HttpServletRequest/Response are not working for some people under Spring 3. Try using Spring WebRequest/WebResponse objects as Eduardo Zola pointed out.

I strongly recommend you to have a look at the list of supported arguments that Spring MVC is able to auto-magically inject to your handler methods.

Java abstract interface

Well 'Abstract Interface' is a Lexical construct: http://en.wikipedia.org/wiki/Lexical_analysis.

It is required by the compiler, you could also write interface.

Well don't get too much into Lexical construct of the language as they might have put it there to resolve some compilation ambiguity which is termed as special cases during compiling process or for some backward compatibility, try to focus on core Lexical construct.

The essence of `interface is to capture some abstract concept (idea/thought/higher order thinking etc) whose implementation may vary ... that is, there may be multiple implementation.

An Interface is a pure abstract data type that represents the features of the Object it is capturing or representing.

Features can be represented by space or by time. When they are represented by space (memory storage) it means that your concrete class will implement a field and method/methods that will operate on that field or by time which means that the task of implementing the feature is purely computational (requires more cpu clocks for processing) so you have a trade off between space and time for feature implementation.

If your concrete class does not implement all features it again becomes abstract because you have a implementation of your thought or idea or abstractness but it is not complete , you specify it by abstract class.

A concrete class will be a class/set of classes which will fully capture the abstractness you are trying to capture class XYZ.

So the Pattern is

Interface--->Abstract class/Abstract classes(depends)-->Concrete class

Turn on torch/flash on iPhone

//import fremework in .h file 

#import <AVFoundation/AVFoundation.h>
{
 AVCaptureSession *torchSession;
}

@property(nonatomic,retain)AVCaptureSession *torchSession;


-(IBAction)onoff:(id)sender;

//implement in .m file

@synthesize torchSession;

-(IBAction)onoff:(id)sender
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch] && [device hasFlash])
    {
        if (device.torchMode == AVCaptureTorchModeOff) 
        {
            [button setTitle:@"OFF" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];

            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];
            AVCaptureSession *session = [[AVCaptureSession alloc] init];

            [session beginConfiguration];
            [device lockForConfiguration:nil];
            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];
            [session addInput:flashInput];
            [session addOutput:output];
            [device unlockForConfiguration];
            [output release];
            [session commitConfiguration];
            [session startRunning];
            [self setTorchSession:session];
            [session release];
        }
        else 
        {
            [button setTitle:@"ON" forState:UIControlStateNormal];
            [torchSession stopRunning];
        }
    }
}

- (void)dealloc
{
    [torchSession release];
    [super dealloc];
}

How would I stop a while loop after n amount of time?

I want to share the one I am using:

import time
# provide a waiting-time list:
lst = [1,2,7,4,5,6,4,3]
# set the timeout limit
timeLimit = 4

for i in lst:
    timeCheck = time.time()
    while True:
        time.sleep(i)
        if time.time() <= timeCheck + timeLimit:
            print ([i,'looks ok'])
            break
        else:
            print ([i,'too long'])
            break

Then you will get:

[1, 'looks ok']
[2, 'looks ok']
[7, 'too long']
[4, 'looks ok']
[5, 'too long']
[6, 'too long']
[4, 'looks ok']
[3, 'looks ok']

Make outer div be automatically the same height as its floating content

You may want to try self-closing floats, as detailed on http://www.sitepoint.com/simple-clearing-of-floats/

So perhaps try either overflow: auto (usually works), or overflow: hidden, as alex said.

Could not autowire field in spring. why?

When you get this error some annotation is missing. I was missing @service annotation on service. When I added that annotation it worked fine for me.

How to prevent Screen Capture in Android

I used this solution to allow manual snapshot in app while disallowing screen capture when the app goes in background, hope it helps.

@Override
protected void onResume() {
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    super.onResume();
}

@Override
protected void onPause() {
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    super.onPause();
}

How do function pointers in C work?

Since function pointers are often typed callbacks, you might want to have a look at type safe callbacks. The same applies to entry points, etc of functions that are not callbacks.

C is quite fickle and forgiving at the same time :)

Using DISTINCT and COUNT together in a MySQL Query

I would do something like this:

Select count(*), productid
from products
where keyword = '$keyword'
group by productid

that will give you a list like

count(*)    productid  
----------------------
 5           12345   
 3           93884   
 9           93493    

This allows you to see how many of each distinct productid ID is associated with the keyword.

What is the meaning of Bus: error 10 in C

Your code attempts to overwrite a string literal. This is undefined behaviour.

There are several ways to fix this:

  1. use malloc() then strcpy() then free();
  2. turn str into an array and use strcpy();
  3. use strdup().

WiX tricks and tips

  1. Keep variables in a separate wxi include file. Enables re-use, variables are faster to find and (if needed) allows for easier manipulation by an external tool.

  2. Define Platform variables for x86 and x64 builds

    <!-- Product name as you want it to appear in Add/Remove Programs-->
    <?if $(var.Platform) = x64 ?>
      <?define ProductName = "Product Name (64 bit)" ?>
      <?define Win64 = "yes" ?>
      <?define PlatformProgramFilesFolder = "ProgramFiles64Folder" ?>
    <?else ?>
      <?define ProductName = "Product Name" ?>
      <?define Win64 = "no" ?>
      <?define PlatformProgramFilesFolder = "ProgramFilesFolder" ?>
    <?endif ?>
    
  3. Store the installation location in the registry, enabling upgrades to find the correct location. For example, if a user sets custom install directory.

     <Property Id="INSTALLLOCATION">
        <RegistrySearch Id="RegistrySearch" Type="raw" Root="HKLM" Win64="$(var.Win64)"
                  Key="Software\Company\Product" Name="InstallLocation" />
     </Property>
    

    Note: WiX guru Rob Mensching has posted an excellent blog entry which goes into more detail and fixes an edge case when properties are set from the command line.

    Examples using 1. 2. and 3.

    <?include $(sys.CURRENTDIR)\Config.wxi?>
    <Product ... >
      <Package InstallerVersion="200" InstallPrivileges="elevated"
               InstallScope="perMachine" Platform="$(var.Platform)"
               Compressed="yes" Description="$(var.ProductName)" />
    

    and

    <Directory Id="TARGETDIR" Name="SourceDir">
      <Directory Id="$(var.PlatformProgramFilesFolder)">
        <Directory Id="INSTALLLOCATION" Name="$(var.InstallName)">
    
  4. The simplest approach is always do major upgrades, since it allows both new installs and upgrades in the single MSI. UpgradeCode is fixed to a unique Guid and will never change, unless we don't want to upgrade existing product.

    Note: In WiX 3.5 there is a new MajorUpgrade element which makes life even easier!

  5. Creating an icon in Add/Remove Programs

    <Icon Id="Company.ico" SourceFile="..\Tools\Company\Images\Company.ico" />
    <Property Id="ARPPRODUCTICON" Value="Company.ico" />
    <Property Id="ARPHELPLINK" Value="http://www.example.com/" />
    
  6. On release builds we version our installers, copying the msi file to a deployment directory. An example of this using a wixproj target called from AfterBuild target:

    <Target Name="CopyToDeploy" Condition="'$(Configuration)' == 'Release'">
      <!-- Note we append AssemblyFileVersion, changing MSI file name only works with Major Upgrades -->
      <Copy SourceFiles="$(OutputPath)$(OutputName).msi" 
            DestinationFiles="..\Deploy\Setup\$(OutputName) $(AssemblyFileVersion)_$(Platform).msi" />
    </Target>
    
  7. Use heat to harvest files with wildcard (*) Guid. Useful if you want to reuse WXS files across multiple projects (see my answer on multiple versions of the same product). For example, this batch file automatically harvests RoboHelp output.

    @echo off  
    robocopy ..\WebHelp "%TEMP%\WebHelpTemp\WebHelp" /E /NP /PURGE /XD .svn  
    "%WIX%bin\heat" dir "%TEMP%\WebHelp" -nologo -sfrag -suid -ag -srd -dir WebHelp -out WebHelp.wxs -cg WebHelpComponent -dr INSTALLLOCATION -var var.WebDeploySourceDir 
    

    There's a bit going on, robocopy is stripping out Subversion working copy metadata before harvesting; the -dr root directory reference is set to our installation location rather than default TARGETDIR; -var is used to create a variable to specify the source directory (web deployment output).

  8. Easy way to include the product version in the welcome dialog title by using Strings.wxl for localization. (Credit: saschabeaumont. Added as this great tip is hidden in a comment)

    <WixLocalization Culture="en-US" xmlns="http://schemas.microsoft.com/wix/2006/localization">
        <String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
    </WixLocalization>
    
  9. Save yourself some pain and follow Wim Coehen's advice of one component per file. This also allows you to leave out (or wild-card *) the component GUID.

  10. Rob Mensching has a neat way to quickly track down problems in MSI log files by searching for value 3. Note the comments regarding internationalization.

  11. When adding conditional features, it's more intuitive to set the default feature level to 0 (disabled) and then set the condition level to your desired value. If you set the default feature level >= 1, the condition level has to be 0 to disable it, meaning the condition logic has to be the opposite to what you'd expect, which can be confusing :)

    <Feature Id="NewInstallFeature" Level="0" Description="New installation feature" Absent="allow">
      <Condition Level="1">NOT UPGRADEFOUND</Condition>
    </Feature>
    <Feature Id="UpgradeFeature" Level="0" Description="Upgrade feature" Absent="allow">
      <Condition Level="1">UPGRADEFOUND</Condition>
    </Feature>
    

The name 'ViewBag' does not exist in the current context

After trying all approaches, none of them worked for me since all I have was correct configurations. finally

Deleting all files from "temp" and "%temp%" from system helped to resolve this issue.

Open Run command(Windows+R) and type above strings and delete all temporary files.

How to apply font anti-alias effects in CSS?

Short answer: You can't.

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

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

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

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

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

One possibility is, if you are familiar with PDF format:

  1. Create some simply PDF with one page (Page should be contained within one object)
  2. Copy object multiply times
  3. Add references to the copied objects to the page catalog
  4. Fix xref table

You get an valid document of any size, entire file will be processed by a reader.

error: use of deleted function

In the current C++0x standard you can explicitly disable default constructors with the delete syntax, e.g.

MyClass() = delete;

Gcc 4.6 is the first version to support this syntax, so maybe that is the problem...

How to get the version of ionic framework?

on your terminal run this command on your ionic project folder ionic info and you will get the following :

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.2
    ionic (Ionic CLI) : 3.20.0

global packages:

    cordova (Cordova CLI) : 8.0.0

local packages:

    @ionic/app-scripts : 3.1.8
    Cordova Platforms  : android 7.0.0 ios 4.5.5
    Ionic Framework    : ionic-angular 3.9.2

System:

    Node  : v8.9.3
    npm   : 6.1.0
    OS    : macOS
    Xcode : Xcode 10.1 Build version 10B61

Environment Variables:

    ANDROID_HOME : not set

Misc:

    backend : pro

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

Closing Bootstrap modal onclick

Close the modal with universal $().hide() method:

$('#product-options').hide();

How do I remove the top margin in a web page?

I had this exact same problem. For me, this was the only thing that worked:

div.mainContainer { padding-top: 1px; }

It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me. I also had an h1 at the top of my page

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

You could convert your values into a 'Decimal' datetime and convert it then to a real datetime column:

select cast(rtrim(year *10000+ month *100+ day) as datetime) as Date from DateTable

See here as well for more info.

Is there a command line utility for rendering GitHub flavored Markdown?

pip3 install --user markdown
python3 -m markdown readme.md > readme.html

It doesn't handle GitHub extensions, but it is better than nothing. I believe you can extend the module to handle the GitHub additions.

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

JSON.stringify output to div in pretty print way

for those who want to show collapsible json can use renderjson

Here is the example by embedding the render js javascript in html

<!DOCTYPE html>
<html>

<head>
    <script type="application/javascript">
        // Copyright © 2013-2014 David Caldwell <[email protected]>
        //
        // Permission to use, copy, modify, and/or distribute this software for any
        // purpose with or without fee is hereby granted, provided that the above
        // copyright notice and this permission notice appear in all copies.
        //
        // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
        // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
        // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
        // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
        // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
        // OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
        // CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

        // Usage
        // -----
        // The module exports one entry point, the `renderjson()` function. It takes in
        // the JSON you want to render as a single argument and returns an HTML
        // element.
        //
        // Options
        // -------
        // renderjson.set_icons("+", "-")
        //   This Allows you to override the disclosure icons.
        //
        // renderjson.set_show_to_level(level)
        //   Pass the number of levels to expand when rendering. The default is 0, which
        //   starts with everything collapsed. As a special case, if level is the string
        //   "all" then it will start with everything expanded.
        //
        // renderjson.set_max_string_length(length)
        //   Strings will be truncated and made expandable if they are longer than
        //   `length`. As a special case, if `length` is the string "none" then
        //   there will be no truncation. The default is "none".
        //
        // renderjson.set_sort_objects(sort_bool)
        //   Sort objects by key (default: false)
        //
        // Theming
        // -------
        // The HTML output uses a number of classes so that you can theme it the way
        // you'd like:
        //     .disclosure    ("?", "?")
        //     .syntax        (",", ":", "{", "}", "[", "]")
        //     .string        (includes quotes)
        //     .number
        //     .boolean
        //     .key           (object key)
        //     .keyword       ("null", "undefined")
        //     .object.syntax ("{", "}")
        //     .array.syntax  ("[", "]")

        var module;
        (module || {}).exports = renderjson = (function () {
            var themetext = function (/* [class, text]+ */) {
                var spans = [];
                while (arguments.length)
                    spans.push(append(span(Array.prototype.shift.call(arguments)),
                        text(Array.prototype.shift.call(arguments))));
                return spans;
            };
            var append = function (/* el, ... */) {
                var el = Array.prototype.shift.call(arguments);
                for (var a = 0; a < arguments.length; a++)
                    if (arguments[a].constructor == Array)
                        append.apply(this, [el].concat(arguments[a]));
                    else
                        el.appendChild(arguments[a]);
                return el;
            };
            var prepend = function (el, child) {
                el.insertBefore(child, el.firstChild);
                return el;
            }
            var isempty = function (obj) {
                for (var k in obj) if (obj.hasOwnProperty(k)) return false;
                return true;
            }
            var text = function (txt) { return document.createTextNode(txt) };
            var div = function () { return document.createElement("div") };
            var span = function (classname) {
                var s = document.createElement("span");
                if (classname) s.className = classname;
                return s;
            };
            var A = function A(txt, classname, callback) {
                var a = document.createElement("a");
                if (classname) a.className = classname;
                a.appendChild(text(txt));
                a.href = '#';
                a.onclick = function () { callback(); return false; };
                return a;
            };

            function _renderjson(json, indent, dont_indent, show_level, max_string, sort_objects) {
                var my_indent = dont_indent ? "" : indent;

                var disclosure = function (open, placeholder, close, type, builder) {
                    var content;
                    var empty = span(type);
                    var show = function () {
                        if (!content) append(empty.parentNode,
                            content = prepend(builder(),
                                A(renderjson.hide, "disclosure",
                                    function () {
                                        content.style.display = "none";
                                        empty.style.display = "inline";
                                    })));
                        content.style.display = "inline";
                        empty.style.display = "none";
                    };
                    append(empty,
                        A(renderjson.show, "disclosure", show),
                        themetext(type + " syntax", open),
                        A(placeholder, null, show),
                        themetext(type + " syntax", close));

                    var el = append(span(), text(my_indent.slice(0, -1)), empty);
                    if (show_level > 0)
                        show();
                    return el;
                };

                if (json === null) return themetext(null, my_indent, "keyword", "null");
                if (json === void 0) return themetext(null, my_indent, "keyword", "undefined");

                if (typeof (json) == "string" && json.length > max_string)
                    return disclosure('"', json.substr(0, max_string) + " ...", '"', "string", function () {
                        return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));
                    });

                if (typeof (json) != "object") // Strings, numbers and bools
                    return themetext(null, my_indent, typeof (json), JSON.stringify(json));

                if (json.constructor == Array) {
                    if (json.length == 0) return themetext(null, my_indent, "array syntax", "[]");

                    return disclosure("[", " ... ", "]", "array", function () {
                        var as = append(span("array"), themetext("array syntax", "[", null, "\n"));
                        for (var i = 0; i < json.length; i++)
                            append(as,
                                _renderjson(json[i], indent + "    ", false, show_level - 1, max_string, sort_objects),
                                i != json.length - 1 ? themetext("syntax", ",") : [],
                                text("\n"));
                        append(as, themetext(null, indent, "array syntax", "]"));
                        return as;
                    });
                }

                // object
                if (isempty(json))
                    return themetext(null, my_indent, "object syntax", "{}");

                return disclosure("{", "...", "}", "object", function () {
                    var os = append(span("object"), themetext("object syntax", "{", null, "\n"));
                    for (var k in json) var last = k;
                    var keys = Object.keys(json);
                    if (sort_objects)
                        keys = keys.sort();
                    for (var i in keys) {
                        var k = keys[i];
                        append(os, themetext(null, indent + "    ", "key", '"' + k + '"', "object syntax", ': '),
                            _renderjson(json[k], indent + "    ", true, show_level - 1, max_string, sort_objects),
                            k != last ? themetext("syntax", ",") : [],
                            text("\n"));
                    }
                    append(os, themetext(null, indent, "object syntax", "}"));
                    return os;
                });
            }

            var renderjson = function renderjson(json) {
                var pre = append(document.createElement("pre"), _renderjson(json, "", false, renderjson.show_to_level, renderjson.max_string_length, renderjson.sort_objects));
                pre.className = "renderjson";
                return pre;
            }
            renderjson.set_icons = function (show, hide) {
                renderjson.show = show;
                renderjson.hide = hide;
                return renderjson;
            };
            renderjson.set_show_to_level = function (level) {
                renderjson.show_to_level = typeof level == "string" &&
                    level.toLowerCase() === "all" ? Number.MAX_VALUE
                    : level;
                return renderjson;
            };
            renderjson.set_max_string_length = function (length) {
                renderjson.max_string_length = typeof length == "string" &&
                    length.toLowerCase() === "none" ? Number.MAX_VALUE
                    : length;
                return renderjson;
            };
            renderjson.set_sort_objects = function (sort_bool) {
                renderjson.sort_objects = sort_bool;
                return renderjson;
            };
            // Backwards compatiblity. Use set_show_to_level() for new code.
            renderjson.set_show_by_default = function (show) {
                renderjson.show_to_level = show ? Number.MAX_VALUE : 0;
                return renderjson;
            };
            renderjson.set_icons('?', '?');
            renderjson.set_show_by_default(false);
            renderjson.set_sort_objects(false);
            renderjson.set_max_string_length("none");
            return renderjson;
        })();
    </script>

</head>


<body>
    <div id="dest"></div>
</body>
<script type="application/javascript">
    document.getElementById("dest").appendChild(
        renderjson.set_show_by_default(true)
            //.set_show_to_level(2)
            //.set_sort_objects(true)
            //.set_icons('+', '-')
            .set_max_string_length(100)
            ([
                {
                    "glossary": {
                        "title": "example glossary",
                        "GlossDiv": {
                            "title": "S",
                            "GlossList": {
                                "GlossEntry": {
                                    "ID": "SGML",
                                    "SortAs": "SGML",
                                    "GlossTerm": "Standard Generalized Markup Language",
                                    "Acronym": "SGML",
                                    "Abbrev": "ISO 8879:1986",
                                    "GlossDef": {
                                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                                        "GlossSeeAlso": ["GML", "XML"]
                                    },
                                    "GlossSee": "markup"
                                }
                            }
                        }
                    }
                },
                {
                    "menu": {
                        "id": "file",
                        "value": "File",
                        "popup": {
                            "menuitem": [
                                { "value": "New", "onclick": "CreateNewDoc()" },
                                { "value": "Open", "onclick": "OpenDoc()" },
                                { "value": "Close", "onclick": "CloseDoc()" }
                            ]
                        }
                    }
                },

                {
                    "widget": {
                        "debug": "on",
                        "window": {
                            "title": "Sample Konfabulator Widget",
                            "name": "main_window",
                            "width": 500,
                            "height": 500
                        },
                        "image": {
                            "src": "Images/Sun.png",
                            "name": "sun1",
                            "hOffset": 250,
                            "vOffset": 250,
                            "alignment": "center"
                        },
                        "text": {
                            "data": "Click Here",
                            "size": 36,
                            "style": "bold",
                            "name": "text1",
                            "hOffset": 250,
                            "vOffset": 100,
                            "alignment": "center",
                            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
                        }
                    }
                },

                {
                    "web-app": {
                        "servlet": [
                            {
                                "servlet-name": "cofaxCDS",
                                "servlet-class": "org.cofax.cds.CDSServlet",
                                "init-param": {
                                    "configGlossary:installationAt": "Philadelphia, PA",
                                    "configGlossary:adminEmail": "[email protected]",
                                    "configGlossary:poweredBy": "Cofax",
                                    "configGlossary:poweredByIcon": "/images/cofax.gif",
                                    "configGlossary:staticPath": "/content/static",
                                    "templateProcessorClass": "org.cofax.WysiwygTemplate",
                                    "templateLoaderClass": "org.cofax.FilesTemplateLoader",
                                    "templatePath": "templates",
                                    "templateOverridePath": "",
                                    "defaultListTemplate": "listTemplate.htm",
                                    "defaultFileTemplate": "articleTemplate.htm",
                                    "useJSP": false,
                                    "jspListTemplate": "listTemplate.jsp",
                                    "jspFileTemplate": "articleTemplate.jsp",
                                    "cachePackageTagsTrack": 200,
                                    "cachePackageTagsStore": 200,
                                    "cachePackageTagsRefresh": 60,
                                    "cacheTemplatesTrack": 100,
                                    "cacheTemplatesStore": 50,
                                    "cacheTemplatesRefresh": 15,
                                    "cachePagesTrack": 200,
                                    "cachePagesStore": 100,
                                    "cachePagesRefresh": 10,
                                    "cachePagesDirtyRead": 10,
                                    "searchEngineListTemplate": "forSearchEnginesList.htm",
                                    "searchEngineFileTemplate": "forSearchEngines.htm",
                                    "searchEngineRobotsDb": "WEB-INF/robots.db",
                                    "useDataStore": true,
                                    "dataStoreClass": "org.cofax.SqlDataStore",
                                    "redirectionClass": "org.cofax.SqlRedirection",
                                    "dataStoreName": "cofax",
                                    "dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
                                    "dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
                                    "dataStoreUser": "sa",
                                    "dataStorePassword": "dataStoreTestQuery",
                                    "dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
                                    "dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
                                    "dataStoreInitConns": 10,
                                    "dataStoreMaxConns": 100,
                                    "dataStoreConnUsageLimit": 100,
                                    "dataStoreLogLevel": "debug",
                                    "maxUrlLength": 500
                                }
                            },
                            {
                                "servlet-name": "cofaxEmail",
                                "servlet-class": "org.cofax.cds.EmailServlet",
                                "init-param": {
                                    "mailHost": "mail1",
                                    "mailHostOverride": "mail2"
                                }
                            },
                            {
                                "servlet-name": "cofaxAdmin",
                                "servlet-class": "org.cofax.cds.AdminServlet"
                            },

                            {
                                "servlet-name": "fileServlet",
                                "servlet-class": "org.cofax.cds.FileServlet"
                            },
                            {
                                "servlet-name": "cofaxTools",
                                "servlet-class": "org.cofax.cms.CofaxToolsServlet",
                                "init-param": {
                                    "templatePath": "toolstemplates/",
                                    "log": 1,
                                    "logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
                                    "logMaxSize": "",
                                    "dataLog": 1,
                                    "dataLogLocation": "/usr/local/tomcat/logs/dataLog.log",
                                    "dataLogMaxSize": "",
                                    "removePageCache": "/content/admin/remove?cache=pages&id=",
                                    "removeTemplateCache": "/content/admin/remove?cache=templates&id=",
                                    "fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
                                    "lookInContext": 1,
                                    "adminGroupID": 4,
                                    "betaServer": true
                                }
                            }],
                        "servlet-mapping": {
                            "cofaxCDS": "/",
                            "cofaxEmail": "/cofaxutil/aemail/*",
                            "cofaxAdmin": "/admin/*",
                            "fileServlet": "/static/*",
                            "cofaxTools": "/tools/*"
                        },

                        "taglib": {
                            "taglib-uri": "cofax.tld",
                            "taglib-location": "/WEB-INF/tlds/cofax.tld"
                        }
                    }
                },

                {
                    "menu": {
                        "header": "SVG Viewer",
                        "items": [
                            { "id": "Open" },
                            { "id": "OpenNew", "label": "Open New" },
                            null,
                            { "id": "ZoomIn", "label": "Zoom In" },
                            { "id": "ZoomOut", "label": "Zoom Out" },
                            { "id": "OriginalView", "label": "Original View" },
                            null,
                            { "id": "Quality" },
                            { "id": "Pause" },
                            { "id": "Mute" },
                            null,
                            { "id": "Find", "label": "Find..." },
                            { "id": "FindAgain", "label": "Find Again" },
                            { "id": "Copy" },
                            { "id": "CopyAgain", "label": "Copy Again" },
                            { "id": "CopySVG", "label": "Copy SVG" },
                            { "id": "ViewSVG", "label": "View SVG" },
                            { "id": "ViewSource", "label": "View Source" },
                            { "id": "SaveAs", "label": "Save As" },
                            null,
                            { "id": "Help" },
                            { "id": "About", "label": "About Adobe CVG Viewer..." }
                        ]
                    }
                },
                {
                    "empty": {
                        "object": {},
                        "array": []
                    }
                },
                {
                    "really_long": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla posuere, orci quis laoreet luctus, nunc neque condimentum arcu, sed tristique sem erat non libero. Morbi et velit non justo rutrum pulvinar. Nam pellentesque laoreet lacus eget sollicitudin. Quisque maximus mattis nisl, eget tempor nisi pulvinar et. Nullam accumsan sapien sapien, non gravida turpis consectetur non. Etiam in vestibulum neque. Donec porta dui sit amet turpis efficitur laoreet. Duis eu convallis ex, vel volutpat lacus. Donec sit amet nunc a orci fermentum luctus."
                }
            ]));
</script>

</html>

How to interpolate variables in strings in JavaScript, without concatenation?

I would use the back-tick ``.

let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'

But if you don't know name1 when you create msg1.

For exemple if msg1 came from an API.

You can use :

let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'

const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
    return eval(key);
});
console.log(result); // 'Hello Geoffrey'

It will replace ${name2} with his value.

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

Bootstrap dropdown not working

For your style you need to include the css files of bootstrap, generally just before </head> element

<link href="css/bootstrap.css" rel="stylesheet">    

Next you'll need to include the js files, it's recommended to include them at the end of the document, generally before the </body> so pages load faster.

<script src="js/jquery.js"></script>        
<script src="js/bootstrap.js"></script>

Regex pattern for numeric values

"[1-9][0-9]*|0"

I'd just use "[0-9]+" to represent positive whole numbers.

Set default host and port for ng serve in config file

We have two ways to change default port number in Angular.

First way is by CLI command:

ng serve --port 2400 --open

Second way is by configuration at the location:

ProjectName\node_modules\@angular-devkit\build-angular\src\dev-server\schema.json.

Make changes in schema.json file.

{
 "title": "Dev Server Target",
  "description": "Dev Server target options for Build Facade.",
  "type": "object",
  "properties": {
    "browserTarget": {
      "type": "string",
      "description": "Target to serve."
    },
    "port": {
      "type": "number",
      "description": "Port to listen on.",
      "default": 2400
    },

Changing API level Android Studio

According to this answer, you just don't include minsdkversion in the manifest.xml, and the build system will use the values from the build.gradle file and put the information into the final apk.

Because the build system needs this information anyway, this makes sense. You should not need to define this values two times.

You just have to sync the project after changing the build.gradle file, but Android Studio 0.5.2 display a yellow status bar on top of the build.gradle editor window to help you

Also note there at least two build.gradle files: one master and one for the app/module. The one to change is in the app/module, it already includes a property minSdkVersion in a newly generated project.

How to return result of a SELECT inside a function in PostgreSQL?

Hi please check the below link

https://www.postgresql.org/docs/current/xfunc-sql.html

EX:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int, product int) AS $$
    SELECT $1 + tab.y, $1 * tab.y FROM tab;
$$ LANGUAGE SQL;

C# find biggest number

There is the Linq Max() extension method. It's available for all common number types(int, double, ...). And since it works on any class that implements IEnumerable<T> it works on all common containers such as arrays T[], List<T>,...

To use it you need to have using System.Linq in the beginning of your C# file, and need to reference the System.Core assembly. Both are done by default on new projects(C# 3 or later)

int[] numbers=new int[]{1,3,2};
int maximumNumber=numbers.Max();

You can also use Math.Max(a,b) which works only on two numbers. Or write a method yourself. That's not hard either.

Case insensitive comparison of strings in shell script

In Bash, you can use parameter expansion to modify a string to all lower-/upper-case:

var1=TesT
var2=tEst

echo ${var1,,} ${var2,,}
echo ${var1^^} ${var2^^}

Catching multiple exception types in one catch block

In PHP >= 7.1 this is possible. See this answer.


If you can modify the exceptions, use this answer.

If you can't, you could try catching all with Exception and then check which exception was thrown with instanceof.

try
{
    /* something */
}
catch( Exception $e )
{
    if ($e instanceof AError OR $e instanceof BError) {
       // It's either an A or B exception.
    } else {
        // Keep throwing it.
        throw $e;
    }
}

But it would probably be better to use multiple catch blocks as described in aforementioned answer.

try
{
    /* something */
}
catch( AError $e )
{
   handler1( $e );
}
catch ( BError $b )
{
   handler2( $e );
}

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

Is the order of elements in a JSON list preserved?

Practically speaking, if the keys were of type NaN, the browser will not change the order.

The following script will output "One", "Two", "Three":

var foo={"3":"Three", "1":"One", "2":"Two"};
for(bar in foo) {
    alert(foo[bar]);
}

Whereas the following script will output "Three", "One", "Two":

var foo={"@3":"Three", "@1":"One", "@2":"Two"};
for(bar in foo) {
    alert(foo[bar]);
}

What is an Endpoint?

Come on guys :) We could do it simpler, by examples:

/this-is-an-endpoint
/another/endpoint
/some/other/endpoint
/login
/accounts
/cart/items

and when put under a domain, it would look like:

https://example.com/this-is-an-endpoint
https://example.com/another/endpoint
https://example.com/some/other/endpoint
https://example.com/login
https://example.com/accounts
https://example.com/cart/items

Can be either http or https, we use https in the example.

Also endpoint can be different for different HTTP methods, for example:

GET /item/{id}
PUT /item/{id}

would be two different endpoints - one for retrieving (as in "cRud" abbreviation), and the other for updating (as in "crUd")

And that's all, really that simple!

How can I specify my .keystore file with Spring Boot and Tomcat?

For external keystores, prefix with "file:"

server.ssl.key-store=file:config/keystore 

How do I view Android application specific cache?

Here is the code: replace package_name by your specific package name.

Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:package_name"));
startActivity(i);

Finding all objects that have a given property inside a collection

With Java 8 lambda expression you can do something like

cats.stream()
    .filter( c -> c.getAge() == 3 && c.getFavoriteFood() == WHISKAS )
    .collect(Collectors.toList());

Conceptually the same as the Guava Predicate approach, but it looks much cleaner with lambda

Probably not a valid answer for OP but worth to note for people with similar need. :)

How to check if String is null

An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.

And yes, you should just use

if (s == null)

Note that this will still use the overloaded == operator defined in string, but that will do the right thing.

Looping each row in datagridview

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

Unable to compile class for JSP

I faced same exception in eclipse neon version exception is like below

org.apache.jasper.JasperException: Unable to compile class for JSP: 

An error occurred at line: 1 in the generated java file
The type java.io.ObjectInputStream cannot be resolved. It is indirectly referenced from required .class files

Stacktrace:
    org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
    org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
    org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
    org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
    org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:717)

I using Apache tomcat 8 of maven plugin and i tried to update that but face same issue.

After i download new external apache tomcat version 8.5.14 and run project using this its will success for me

I hope some one to useful this for resolve above exception

Selecting multiple classes with jQuery

Have you tried this?

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

What does principal end of an association means in 1:1 relationship in Entity framework

This is with reference to @Ladislav Mrnka's answer on using fluent api for configuring one-to-one relationship.

Had a situation where having FK of dependent must be it's PK was not feasible.

E.g., Foo already has one-to-many relationship with Bar.

public class Foo {
   public Guid FooId;
   public virtual ICollection<> Bars; 
}
public class Bar {
   //PK
   public Guid BarId;
   //FK to Foo
   public Guid FooId;
   public virtual Foo Foo;
}

Now, we had to add another one-to-one relationship between Foo and Bar.

public class Foo {
   public Guid FooId;
   public Guid PrimaryBarId;// needs to be removed(from entity),as we specify it in fluent api
   public virtual Bar PrimaryBar;
   public virtual ICollection<> Bars;
}
public class Bar {
   public Guid BarId;
   public Guid FooId;
   public virtual Foo PrimaryBarOfFoo;
   public virtual Foo Foo;
}

Here is how to specify one-to-one relationship using fluent api:

modelBuilder.Entity<Bar>()
            .HasOptional(p => p.PrimaryBarOfFoo)
            .WithOptionalPrincipal(o => o.PrimaryBar)
            .Map(x => x.MapKey("PrimaryBarId"));

Note that while adding PrimaryBarId needs to be removed, as we specifying it through fluent api.

Also note that method name [WithOptionalPrincipal()][1] is kind of ironic. In this case, Principal is Bar. WithOptionalDependent() description on msdn makes it more clear.

Change values of select box of "show 10 entries" of jquery datatable

enter image description here pageLength: 50,

worked for me Thanks

Versions for reference

jquery-3.3.1.js

/1.10.19/js/jquery.dataTables.min.js

/buttons/1.5.2/js/dataTables.buttons.min.js

How to output in CLI during execution of PHP Unit tests?

For some cases one could use something like that to output something to the console

class yourTests extends PHPUnit_Framework_TestCase
{
    /* Add Warnings */
    protected function addWarning($msg, Exception $previous = null)
    {
        $add_warning = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_Warning($msg, 0, $previous);
        $add_warning->addWarning($this, $msg, time());
        $this->setTestResultObject($add_warning);
    }

    /* Add errors */
    protected function addError($msg, Exception $previous = null)
    {
        $add_error = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_error->addError($this, $msg, time());
        $this->setTestResultObject($add_error);
    }

    /* Add failures */
    protected function addFailure($msg, Exception $previous = null)
    {
        $add_failure = $this->getTestResultObject();
        $msg = new PHPUnit_Framework_AssertionFailedError($msg, 0, $previous);
        $add_failure->addFailure($this, $msg, time());
        $this->setTestResultObject($add_failure);
    }

    public function test_messages()
    {
        $this->addWarning("Your warning message!");
        $this->addError("Your error message!");
        $this->addFailure("Your Failure message");
    }

    /* Or just mark test states! */
    public function test_testMarking()
    {
        $this->markTestIncomplete();
        $this->markTestSkipped();
    }
}

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

In the endpoint tag you need to include the property address=""

<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />

How do I use shell variables in an awk script?

It seems that the good-old ENVIRON built-in hash is not mentioned at all. An example of its usage:

$ X=Solaris awk 'BEGIN{print ENVIRON["X"], ENVIRON["TERM"]}'
Solaris rxvt

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

Javascript loading CSV file into an array

I highly recommend looking into this plugin:

http://github.com/evanplaice/jquery-csv/

I used this for a project handling large CSV files and it handles parsing a CSV into an array quite well. You can use this to call a local file that you specify in your code, also, so you are not dependent on a file upload.

Once you include the plugin above, you can essentially parse the CSV using the following:

$.ajax({
    url: "pathto/filename.csv",
    async: false,
    success: function (csvd) {
        data = $.csv.toArrays(csvd);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Everything will then live in the array data for you to manipulate as you need. I can provide further examples for handling the array data if you need.

There are a lot of great examples available on the plugin page to do a variety of things, too.

Javascript: 'window' is not defined

Trying to access an undefined variable will throw you a ReferenceError.

A solution to this is to use typeof:

if (typeof window === "undefined") {
  console.log("Oops, `window` is not defined")
}

or a try catch:

try { window } catch (err) {
  console.log("Oops, `window` is not defined")
}

While typeof window is probably the cleanest of the two, the try catch can still be useful in some cases.

Java swing application, close one window and open another when button is clicked

You can call dispose() on the current window and setVisible(true) on the one you want to display.

Scanning Java annotations at runtime

The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).

So, even if you could enumerate all classes, this would be very time- and memory-consuming.

The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.

Keyboard shortcut to comment lines in Sublime Text 2

For German keyboards use ctrl+shift+# to toggle a block comment and ctrl+# to toggle a line comment.

The shortcut in Preferences->Key Bindings - Default is set to Ctrl+Shift+/ and Ctrl+/, but to actually use the functions, press the keys stated above.

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Mysql - How to quit/exit from stored procedure

Why not this:

CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
     IF tablename IS NOT NULL THEN
          #proceed the code
     END IF;
     # Do nothing otherwise
END;

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Listing a public key in .ssh/authorized_keys is necessary, but not sufficient for sshd (server) to accept it. If your private key is passphrase-protected, you'll need to give ssh (client) the passphrase every time. Or you can use ssh-agent, or a GNOME equivalent.

Your updated trace is consistent with a passphrase-protected private key. See ssh-agent, or use ssh-keygen -p.

Angular.js How to change an elements css class on click and to remove all others

Create a scope property called selectedIndex, and an itemClicked function:

function MyController ($scope) {
  $scope.collection = ["Item 1", "Item 2"];

  $scope.selectedIndex = 0; // Whatever the default selected index is, use -1 for no selection

  $scope.itemClicked = function ($index) {
    $scope.selectedIndex = $index;
  };
}

Then my template would look something like this:

<div>
      <span ng-repeat="item in collection"
             ng-class="{ 'selected-class-name': $index == selectedIndex }"
             ng-click="itemClicked($index)"> {{ item }} </span>
</div>

Just for reference $index is a magic variable available within ng-repeat directives.

You can use this same sample within a directive and template as well.

Here is a working plnkr:

http://plnkr.co/edit/jOO8YdPiSJEaOcayEP1X?p=preview

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Make sure you include the = sign in addition to passing the arguments to the function. I.E.

=SUM(A1:A3) //this would give you the sum of cells A1, A2, and A3.

How to create an AVD for Android 4.0

I just did the same. If you look in the "Android SDK Manager" in the "Android 4.0 (API 14)" section you'll see a few packages. One of these is named "ARM EABI v7a System Image".

This is what you need to download in order to create an Android 4.0 virtual device:

The Android SDK download system

Set Response Status Code

Why not using Cakes Response Class? You can set the status code of the response simply by this:

$this->response->statusCode(200);

Then just render a file with the error message, which suits best with JSON.

Way to insert text having ' (apostrophe) into a SQL table

try this

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

Difference between wait and sleep

Here wait() will be in the waiting state till it notify by another Thread but where as sleep() will be having some time..after that it will automatically transfer to the Ready state...

Open Source Javascript PDF viewer

There is an open source HTML5/javascript reader available called Trapeze though its still in its early stages.

Demo site: https://brendandahl.github.io/trapeze-reader/demos/

Github page: https://github.com/brendandahl/trapeze-reader

Disclaimer: I'm the author.

I have created a table in hive, I would like to know which directory my table is created in?

To see both of the structure and location (directory) of an any (internal or external)table, we can use table's create statment-

show create table table_name;

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

Share application "link" in Android

I know this question has been answered, but I would like to share an alternate solution:

Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String shareSubText = "WhatsApp - The Great Chat App";
String shareBodyText = "https://play.google.com/store/apps/details?id=com.whatsapp&hl=en";
shareIntent.putExtra(Intent.EXTRA_SUBJECT, shareSubText);
shareIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
startActivity(Intent.createChooser(shareIntent, "Share With"));

Multiplying across in a numpy array

For those lost souls on google, using numpy.expand_dims then numpy.repeat will work, and will also work in higher dimensional cases (i.e. multiplying a shape (10, 12, 3) by a (10, 12)).

>>> import numpy
>>> a = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> b = numpy.array([0,1,2])
>>> b0 = numpy.expand_dims(b, axis = 0)
>>> b0 = numpy.repeat(b0, a.shape[0], axis = 0)
>>> b1 = numpy.expand_dims(b, axis = 1)
>>> b1 = numpy.repeat(b1, a.shape[1], axis = 1)
>>> a*b0
array([[ 0,  2,  6],
   [ 0,  5, 12],
   [ 0,  8, 18]])
>>> a*b1
array([[ 0,  0,  0],
   [ 4,  5,  6],
   [14, 16, 18]])

Which Android phones out there do have a gyroscope?

Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:

*** Phones:

  • HTC Sensation
  • HTC Sensation XL
  • HTC Evo 3D
  • HTC One S
  • HTC One X
  • Huawei Ascend P1
  • Huawei Ascend X (U9000)
  • Huawei Honor (U8860)
  • LG Nitro HD (P930)
  • LG Optimus 2x (P990)
  • LG Optimus Black (P970)
  • LG Optimus 3D (P920)
  • Samsung Galaxy S II (i9100)
  • Samsung Galaxy S III (i9300)
  • Samsung Galaxy R (i9103)
  • Samsung Google Nexus S (i9020)
  • Samsung Galaxy Nexus (i9250)
  • Samsung Galaxy J3 (2017) model
  • Samsung Galaxy Note (n7000)
  • Sony Xperia P (LT22i)
  • Sony Xperia S (LT26i)

*** Tablets:

  • Acer Iconia Tab A100 (7")
  • Acer Iconia Tab A500 (10.1")
  • Asus Eee Pad Transformer (TF101)
  • Asus Eee Pad Transformer Prime (TF201)
  • Motorola Xoom (mz604)
  • Samsung Galaxy Tab (p1000)
  • Samsung Galaxy Tab 7 plus (p6200)
  • Samsung Galaxy Tab 10.1 (p7100)
  • Sony Tablet P
  • Sony Tablet S
  • Toshiba Thrive 7"
  • Toshiba Trhive 10"

Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.

jQuery select element in parent window

I came across the same problem but, as stated above, the accepted solution did not work for me.

If you're inside a frame or iframe element, an alternative solution is to use

window.parent.$('#testdiv');

Here's a quick explanation of the differences between window.opener, window.parent and window.top:

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a frame or iframe element

What is the difference between exit and return?

In C, there's not much difference when used in the startup function of the program (which can be main(), wmain(), _tmain() or the default name used by your compiler).

If you return in main(), control goes back to the _start() function in the C library which originally started your program, which then calls exit() anyways. So it really doesn't matter which one you use.

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

How to use XMLReader in PHP?

The accepted answer gave me a good start, but brought in more classes and more processing than I would have liked; so this is my interpretation:

$xml_reader = new XMLReader;
$xml_reader->open($feed_url);

// move the pointer to the first product
while ($xml_reader->read() && $xml_reader->name != 'product');

// loop through the products
while ($xml_reader->name == 'product')
{
    // load the current xml element into simplexml and we’re off and running!
    $xml = simplexml_load_string($xml_reader->readOuterXML());

    // now you can use your simpleXML object ($xml).
    echo $xml->element_1;

    // move the pointer to the next product
    $xml_reader->next('product');
}

// don’t forget to close the file
$xml_reader->close();

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>

Convert JSONObject to Map

org.json.JSONObject#toMap() will do to work

Merging dictionaries in C#

The trivial solution would be:

using System.Collections.Generic;
...
public static Dictionary<TKey, TValue>
    Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
    var result = new Dictionary<TKey, TValue>();
    foreach (var dict in dictionaries)
        foreach (var x in dict)
            result[x.Key] = x.Value;
    return result;
}

How to plot ROC curve in Python

The previous answers assume that you indeed calculated TP/Sens yourself. It's a bad idea to do this manually, it's easy to make mistakes with the calculations, rather use a library function for all of this.

the plot_roc function in scikit_lean does exactly what you need: http://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html

The essential part of the code is:

  for i in range(n_classes):
      fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i])
      roc_auc[i] = auc(fpr[i], tpr[i])

How do I show the value of a #define at compile-time?

#define a <::BOOST_VERSION>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::106200': No such file or directory

Works even if preprocess to file is enabled, even if invalid tokens are present:

#define a <::'*/`#>
#include a
MSVC2015: fatal error C1083: Cannot open include file: '::'*/`#': No such file or directory
GCC4.x: warning: missing terminating ' character [-Winvalid-pp-token]
#define a <::'*/`#>

Check if event exists on element

$('body').click(function(){ alert('test' )})

var foo = $.data( $('body').get(0), 'events' ).click
// you can query $.data( object, 'events' ) and get an object back, then see what events are attached to it.

$.each( foo, function(i,o) {
    alert(i) // guid of the event
    alert(o) // the function definition of the event handler
});

You can inspect by feeding the object reference ( not the jQuery object though ) to $.data, and for the second argument feed 'events' and that will return an object populated with all the events such as 'click'. You can loop through that object and see what the event handler does.

Get each line from textarea

Old tread...? Well, someone may bump into this...

Please check out http://telamenta.com/techarticle/php-explode-newlines-and-you

Rather than using:

$values = explode("\n", $value_string);

Use a safer method like:

$values = preg_split('/[\n\r]+/', $value_string);

How to use radio buttons in ReactJS?

I also got confused in radio, checkbox implementation. What we need is, listen change event of the radio, and then set the state. I have made small example of gender selection.

_x000D_
_x000D_
/*_x000D_
 * A simple React component_x000D_
 */_x000D_
class App extends React.Component {_x000D_
  constructor(params) {_x000D_
     super(params) _x000D_
     // initial gender state set from props_x000D_
     this.state = {_x000D_
       gender: this.props.gender_x000D_
     }_x000D_
     this.setGender = this.setGender.bind(this)_x000D_
  }_x000D_
  _x000D_
  setGender(e) {_x000D_
    this.setState({_x000D_
      gender: e.target.value_x000D_
    })_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const {gender} = this.state_x000D_
    return  <div>_x000D_
        Gender:_x000D_
        <div>_x000D_
          <input type="radio" checked={gender == "male"} _x000D_
onClick={this.setGender} value="male" /> Male_x000D_
          <input type="radio" checked={gender == "female"} _x000D_
onClick={this.setGender} value="female"  /> Female_x000D_
        </div>_x000D_
        { "Select Gender: " } {gender}_x000D_
      </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
/*_x000D_
 * Render the above component into the div#app_x000D_
 */_x000D_
ReactDOM.render(<App gender="male" />, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

How to pass parameters or arguments into a gradle task

I think you probably want to view the minification of each set of css as a separate task

task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
     source = "src/main/webapp/css/brandA/styles.css"
     dest = "${buildDir}/brandA/styles.css"
}

etc etc

BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?

Running Tensorflow in Jupyter Notebook

I believe a short video showing all the details if you have Anaconda is the following for mac (it is very similar to windows users as well) just open Anaconda navigator and everything is just the same (almost!)

https://www.youtube.com/watch?v=gDzAm25CORk

Then go to jupyter notebook and code

!pip install tensorflow

Then

import tensorflow as tf

It work for me! :)

How to have multiple conditions for one if statement in python

I am a little late to the party but I thought I'd share a way of doing it, if you have identical types of conditions, i.e. checking if all, any or at given amount of A_1=A_2 and B_1=B_2, this can be done in the following way:

cond_list_1=["1","2","3"]
cond_list_2=["3","2","1"]
nr_conds=1

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])>=nr_conds:
    print("At least " + str(nr_conds) + " conditions are fullfilled")

if len([True for i, j in zip(cond_list_1, cond_list_2) if i == j])==len(cond_list_1):
    print("All conditions are fullfilled")

This means you can just change in the two initial lists, at least for me this makes it easier.

How to capture no file for fs.readFileSync()?

I prefer this way of handling this. You can check if the file exists synchronously:

var file = 'info.json';
var content = '';

// Check that the file exists locally
if(!fs.existsSync(file)) {
  console.log("File not found");
}

// The file *does* exist
else {
  // Read the file and do anything you want
  content = fs.readFileSync(file, 'utf-8');
}

Note: if your program also deletes files, this has a race condition as noted in the comments. If however you only write or overwrite files, without deleting them, then this is totally fine.

Get GPS location from the web browser

To give a bit more specific answer. HTML5 allows you to get the geo coordinates, and it does a pretty decent job. Overall the browser support for geolocation is pretty good, all major browsers except ie7 and ie8 (and opera mini). IE9 does the job but is the worst performer. Checkout caniuse.com:

http://caniuse.com/#search=geol

Also you need the approval of your user to access their location, so make sure you check for this and give some decent instructions in case it's turned off. Especially for Iphone turning permissions on for Safari is a bit cumbersome.

How to add an event after close the modal window?

I find answer. Thanks all but right answer next:

$("#myModal").on("hidden", function () {
  $('#result').html('yes,result');
});

Events here http://bootstrap-ru.com/javascript.php#modals

UPD

For Bootstrap 3.x need use hidden.bs.modal:

$("#myModal").on("hidden.bs.modal", function () {
  $('#result').html('yes,result');
});

JavaScript replace \n with <br />

Use a regular expression for .replace().:

messagetoSend = messagetoSend.replace(/\n/g, "<br />");

If those linebreaks were made by windows-encoding, you will also have to replace the carriage return.

messagetoSend = messagetoSend.replace(/\r\n/g, "<br />");

Download text/csv content as files from server in Angular

$http service returns a promise which has two callback methods as shown below.

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
     var anchor = angular.element('<a/>');
     anchor.attr({
         href: 'data:attachment/csv;charset=utf-8,' + encodeURI(data),
         target: '_blank',
         download: 'filename.csv'
     })[0].click();

  }).
  error(function(data, status, headers, config) {
    // handle error
  });

What is the difference between Google App Engine and Google Compute Engine?

Basic difference is that Google App Engine (GAE) is a Platform as a Service (PaaS) whereas Google Compute Engine (GCE) is an Infrastructure as a Service (IaaS).

To run your application in GAE you just need to write your code and deploy it into GAE, no other headache. Since GAE is fully scalable, it will automatically acquire more instances in case the traffic goes higher and decrease the instances when traffic decreases. You will be charged for the resources you really use, I mean, you will be billed for the Instance-Hours, Transferred Data, Storage etc your app really used. But the restriction is, you can create your application in only Python, PHP, Java, NodeJS, .NET, Ruby and **Go.

On the other hand, GCE provides you full infrastructure in the form of Virtual Machine. You have complete control over those VMs' environment and runtime as you can write or install any program there. Actually GCE is the way to use Google Data Centers virtually. In GCE you have to manually configure your infrastructure to handle scalability by using Load Balancer.

Both GAE and GCE are part of Google Cloud Platform.

Update: In March 2014 Google announced a new service under App Engine named Managed Virtual Machine. Managed VMs offers app engine applications a bit more flexibility over app platform, CPU and memory options. Like GCE you can create a custom runtime environment in these VMs for app engine application. Actually Managed VMs of App Engine blurs the frontier between IAAS and PAAS to some extent.

initialize a vector to zeros C++/C++11

Initializing a vector having struct, class or Union can be done this way

std::vector<SomeStruct> someStructVect(length);
memset(someStructVect.data(), 0, sizeof(SomeStruct)*length);

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

I also got the same issue, but I fix it by changing my key file permission to 600.

sudo chmod 600 /path/to/my/key.pem

Link : http://stackabuse.com/how-to-fix-warning-unprotected-private-key-file-on-mac-and-linux/

The smallest difference between 2 Angles

A simple method, which I use in C++ is:

double deltaOrientation = angle1 - angle2;
double delta =  remainder(deltaOrientation, 2*M_PI);

powershell is missing the terminator: "

In your script, why are you using single quotes around the variables? These will not be expanded. Use double quotes for variable expansion or just the variable names themselves.

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

to

unzipRelease –Src "$ReleaseFile" -Dst "$Destination"

How to discard uncommitted changes in SourceTree?

Ok so in Windows sourcetree that is simple, on macOS I looked as well for a while..

Click Command + Shift + R while in source tree a hidden popup will be shown that will let you discard individual files OR ALL! Why is this hidden? We will never know.. but it works!

enter image description here

Which is the preferred way to concatenate a string in Python?

You can do in different ways.

str1 = "Hello"
str2 = "World"
str_list = ['Hello', 'World']
str_dict = {'str1': 'Hello', 'str2': 'World'}

# Concatenating With the + Operator
print(str1 + ' ' + str2)  # Hello World

# String Formatting with the % Operator
print("%s %s" % (str1, str2))  # Hello World

# String Formatting with the { } Operators with str.format()
print("{}{}".format(str1, str2))  # Hello World
print("{0}{1}".format(str1, str2))  # Hello World
print("{str1} {str2}".format(str1=str_dict['str1'], str2=str_dict['str2']))  # Hello World
print("{str1} {str2}".format(**str_dict))  # Hello World

# Going From a List to a String in Python With .join()
print(' '.join(str_list))  # Hello World

# Python f'strings --> 3.6 onwards
print(f"{str1} {str2}")  # Hello World

I created this little summary through following articles.

Where is Java Installed on Mac OS X?

If you install just the JRE, it seems to be put at:

/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

Recover from git reset --hard?

I ran into same issue and I was almost going insane....initially i committed the project and merged.. later when i try running git push --set-upstream origin master i was getting this error

  fatal: refusing to merge unrelated histories

so i ran git reset --hard HEAD and it deleted a 3 weeks project but these few commands below save the day:

git reset HEAD@{1}         //this command unstage changes after reset
git fsck --lost-found      //I got the dangling commit fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b
git show <dangling commit something like-> fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b>
git rebase fc3b6bee2bca5d8a7e16b6adaca6a76e620eca4b

hope this helps

Lombok is not generating getter and setter

If you are using maven , Go to maven dependencies in your project structure then run lombok jar as java project it will install it then exit and start eclipse

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

I used the Visual Studio 2008 Uninstall tool and it worked fine for me.

You can use this tool to uninstall Visual Studio 2008 official release and Visual Studio 2008 Release candidate (Only English version).

Found here, on the MSDN Forum: MSDN forum topic.

I found this answer here

Be sure you run the tool with admin-rights.

repaint() in Java

You're doing things in the wrong order.

You need to first add all JComponents to the JFrame, and only then call pack() and then setVisible(true) on the JFrame

If you later added JComponents that could change the GUI's size you will need to call pack() again, and then repaint() on the JFrame after doing so.

Get data from fs.readFile

var path = "index.html"

const readFileAsync = fs.readFileSync(path, 'utf8');
// console.log(readFileAsync)

using simple readFileSync works for me.

How to get root access on Android emulator?

How to root android emulator (tested on Android 7.1.1/ Nougat)

Requirements:

Instructions

  1. Install the SuperSu.apk

    • Install the SuperSu app firstly, just do drag and drop (if running latest emulator version or sideload through adb i.e adb -e install supersu.apk)

    • After installing it, when you run it shows a screen as shown below indicating “There is no SU binary installed..”. This error just confirms the device is not yet rooted.

enter image description here


  1. Make emulator’ system partition writable

    • As it suggests, we need to give the emulator permission to write system files.

    • Type the following code to accomplish this: emulator -avd {emulator_name} -writable-system

If you have more than one AVD, you can get a list of avds by using the command: emulator -list-avds

Note: Navigate to the tools folder where Android SDK is installed and open command prompt there by pressing shift and right clicking.


  1. Pushing su binary in system directory

    • Extract the Recovery flashable.zip (containing the su binaries of different architectures)

Important! Only use the su binary that matches your avd architecture e.g x86, arm etc.., and note the path where you extracted these binaries.

  • Make sure you are running adb as root and also you need to remount. Just enter these codes

adb root

adb remount

Now its time to push the su binary:

This is the code I successfully used: adb -e push C:\Users\User1\Desktop\rootemu\x86\su.pie /system/bin/su

(nevermind about my specific location of su binary, any location is okay as long there is no white space)

note: To figure out bin or xbin do in console before: > adb shell, > ls /system/xbin/su

If this fails try this pushing to this directory instead /system/xbin/su. Also for emulators running android 5.1 and below use the su and not su.pie


  1. Change permissions of the su binary

    • Next let’s do a bit of modification of the permissions of su binary. We have to do this in emulator device through adb:

    adb -e shell su root cd /system/bin chmod 06755 su

Important!! Take note of su binary path (mine is /system/bin)


  1. Setting the install directive on su binary and set a daemon

Type the codes:

su --install

and for setting up daemon:

su --daemon&

Important!! Take note of spacing


  1. Setting SELinux to Permissive(i.e turning off SE Linux)

    • Finally turn off selinux through this code:

setenforce 0


  1. Open SuperSU app and it may ask to update binaries, you can use Normal method.

Note: If you're experiencing bootloops, rather don't update the binaries, just use it as it is.


That’s pretty much it!!

Open any application requiring SU permissions just to double check and indeed SuperSU ask if you wish to grant it su permissions.

enter image description here

To have the root persist update su binary (using Normal method), then copy system.img from temp directory (Users\AppData\Local\Temp\Android Emulator the file is usually randomly named e.g 1359g.tmp with a large size) and replace default system.img.

Update:

I have noted is is easier to obtain a temporary system image in Linux, than Windows. You can try using snapshot image.

Update 4 August 2018

With the emergence of emulator 27.3.x it now makes preserving root much easier through snapshot feature (if copying the system.img method isn't working):

Ideally it is more like hibernarig the virtual device with config intact, hence everything is preserved.

Snapshots

You can now save multiple AVD snapshots for a given device configuration and choose which of the saved snapshots to load when you start the emulator. Starting a virtual device by loading a snapshot is much like waking a physical from a sleep state, as opposed to booting it from a powered-off state.

This implies the only requirement to start the emulator is adding the -writable-system parameter to the normal emulator -avd [avdname] command to start the emulator. (Running the emulator just with emulator -avd [avdname] doesn't launch the rooted version/copy or may lead to some error)

Tested on API level 22

Also for bootloop issues see the other post: Android Emulator: How to avoid boot loop after rooting? and updates thereof.

Remarks

Most content in reference was for older android versions and hence the reason for different commands and paths which I modified.

Acknowledgements;

Laravel 5: Display HTML with Blade

You can try this:

{!! $text !!}

You should have a look at: http://laravel.com/docs/5.0/upgrade#upgrade-5.0

Input length must be multiple of 16 when decrypting with padded cipher

Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.

Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.

byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);

If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"

Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail. You should do URLEncoding and then pass in the token, it will work.

Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor

Required attribute on multiple checkboxes with the same name?

To provide another approach similar to the answer by @IvanCollantes. It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var requiredCheckboxes = $(':checkbox[required]');_x000D_
  requiredCheckboxes.on('change', function(e) {_x000D_
    var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
    var isChecked = checkboxGroup.is(':checked');_x000D_
    checkboxGroup.prop('required', !isChecked);_x000D_
  });_x000D_
  requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
  <p>_x000D_
    At least one checkbox from each group is required..._x000D_
  </p>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <br>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test2</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <hr>_x000D_
  <button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to place the "table" at the middle of the webpage?

The shortest and easiest answer is: you shouldn't vertically center things in webpages. HTML and CSS simply are not created with that in mind. They are text formatting languages, not user interface design languages.

That said, this is the best way I can think of. However, this will NOT WORK in Internet Explorer 7 and below!

<style>
  html, body {
    height: 100%;
  }
  #tableContainer-1 {
    height: 100%;
    width: 100%;
    display: table;
  }
  #tableContainer-2 {
    vertical-align: middle;
    display: table-cell;
    height: 100%;
  }
  #myTable {
    margin: 0 auto;
  }
</style>
<div id="tableContainer-1">
  <div id="tableContainer-2">
    <table id="myTable" border>
      <tr><td>Name</td><td>J W BUSH</td></tr>
      <tr><td>Proficiency</td><td>PHP</td></tr>
      <tr><td>Company</td><td>BLAH BLAH</td></tr>
    </table>
  </div>
</div>

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

Returning unique_ptr from functions

One thing that i didn't see in other answers is To clarify another answers that there is a difference between returning std::unique_ptr that has been created within a function, and one that has been given to that function.

The example could be like this:

class Test
{int i;};
std::unique_ptr<Test> foo1()
{
    std::unique_ptr<Test> res(new Test);
    return res;
}
std::unique_ptr<Test> foo2(std::unique_ptr<Test>&& t)
{
    // return t;  // this will produce an error!
    return std::move(t);
}

//...
auto test1=foo1();
auto test2=foo2(std::unique_ptr<Test>(new Test));

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

HTML 5 video or audio playlist

There's no way to define a playlist using just a <video> or <audio> tag, but there are ways of controlling them, so you can simulate a playlist using JavaScript. Check out sections 4.8.7, 4.8.9 (especially 4.8.9.12) of the HTML5 spec. Hopefully the majority of methods and events are implemented on modern browsers such as Chrome and Firefox (latest versions, of course).

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

include and require functions require file path, but you are giving file URI instead. The parameter should not be the one that includes http/https.

Your code should be something like:

include ("folder/file.php");

Why are primes important in cryptography?

Simple? Yup.

If you multiply two large prime numbers, you get a huge non-prime number with only two (large) prime factors.

Factoring that number is a non-trivial operation, and that fact is the source of a lot of Cryptographic algorithms. See one-way functions for more information.

Addendum: Just a bit more explanation. The product of the two prime numbers can be used as a public key, while the primes themselves as a private key. Any operation done to data that can only be undone by knowing one of the two factors will be non-trivial to unencrypt.

How to activate JMX on my JVM for access with jconsole?

Note, Java 6 in the latest incarnation allows for jconsole to attach itself to a running process even after it has been started without JMX incantations.

If that is available to you, also consider jvisualvm as it provides a wealth of information on running processes, including a profiler.

How can I get the ID of an element using jQuery?

The jQuery way:

$('#test').attr('id')

In your example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  console.log($('#test').attr('id'));_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="test"></div>
_x000D_
_x000D_
_x000D_

Or through the DOM:

$('#test').get(0).id;

or even :

$('#test')[0].id;

and reason behind usage of $('#test').get(0) in JQuery or even $('#test')[0] is that $('#test') is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is

$('#test').prop('id')

which is different from .attr() and $('#test').prop('foo') grabs the specified DOM foo property, while $('#test').attr('foo') grabs the specified HTML foo attribute and you can find more details about differences here.

how to parse xml to java object?

I find jackson fasterxml is one good choice to serializing/deserializing bean with XML.

Refer: How to use spring to marshal and unmarshal xml?

How to create a css rule for all elements except one class?

The negation pseudo-class seems to be what you are looking for.

table:not(.dojoxGrid) {color:red;}

It's not supported by = IE8 though.

String to list in Python

Or for fun:

>>> ast.literal_eval('[%s]'%','.join(map(repr,s.split())))
['QH', 'QD', 'JC', 'KD', 'JS']
>>> 

ast.literal_eval

How do I find out which DOM element has the focus?

JQuery does support the :focus pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, <!DOCTYPE... must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus:

$(":focus").each(function() {
  alert($(this).attr("id") + " has focus!");
});

Angular-Material DateTime Picker Component?

You can have a datetime picker when using matInput with type datetime-local like so:

  <mat-form-field>
    <input matInput type="datetime-local" placeholder="start date">
  </mat-form-field>

You can click on each part of the placeholder to set the day, month, year, hours,minutes and whether its AM or PM.

Create a .tar.bz2 file Linux

Try this from different folder:

sudo tar -cvjSf folder.tar.bz2 folder/*

How to install MySQLdb package? (ImportError: No module named setuptools)

For Python 2.7, one can easily install using this

apt-get install python2.7-mysqldb

Connecting to Oracle Database through C#?

Basically in this case, System.Data.OracleClient need access to some of the oracle dll which are not part of .Net. Solutions:

  • Install Oracle Client , and add bin location to Path environment varaible of windows OR
  • Copy oraociicus10.dll (Basic-Lite version) or aociei10.dll (Basic version), oci.dll, orannzsbb10.dll and oraocci10.dll from oracle client installable folder to bin folder of application so that application is able to find required dll

How do I add images in laravel view?

normaly is better image store in public folder (because it has write permission already that you can use when I upload images to it)

public
    upload_media
         photos
            image.png


$image  = public_path() . '/upload_media/photos/image.png'; // destination path

view PHP

<img src="<?= $image ?>">

View blade

<img src="{{ $image }}">

Why do I get a C malloc assertion failure?

To give you a better understanding of why this happens, I'd like to expand upon @r-samuel-klatchko's answer a bit.

When you call malloc, what is really happening is a bit more complicated than just giving you a chunk of memory to play with. Under the hood, malloc also keeps some housekeeping information about the memory it has given you (most importantly, its size), so that when you call free, it knows things like how much memory to free. This information is commonly kept right before the memory location returned to you by malloc. More exhaustive information can be found on the internet™, but the (very) basic idea is something like this:

+------+-------------------------------------------------+
+ size |                  malloc'd memory                +
+------+-------------------------------------------------+
       ^-- location in pointer returned by malloc

Building on this (and simplifying things greatly), when you call malloc, it needs to get a pointer to the next part of memory that is available. One very simple way of doing this is to look at the previous bit of memory it gave away, and move size bytes further down (or up) in memory. With this implementation, you end up with your memory looking something like this after allocating p1, p2 and p3:

+------+----------------+------+--------------------+------+----------+
+ size |                | size |                    | size |          +
+------+----------------+------+--------------------+------+----------+
       ^- p1                   ^- p2                       ^- p3

So, what is causing your error?

Well, imagine that your code erroneously writes past the amount of memory you've allocated (either because you allocated less than you needed as was your problem or because you're using the wrong boundary conditions somewhere in your code). Say your code writes so much data to p2 that it starts overwriting what is in p3's size field. When you now next call malloc, it will look at the last memory location it returned, look at its size field, move to p3 + size and then start allocating memory from there. Since your code has overwritten size, however, this memory location is no longer after the previously allocated memory.

Needless to say, this can wreck havoc! The implementors of malloc have therefore put in a number of "assertions", or checks, that try to do a bunch of sanity checking to catch this (and other issues) if they are about to happen. In your particular case, these assertions are violated, and thus malloc aborts, telling you that your code was about to do something it really shouldn't be doing.

As previously stated, this is a gross oversimplification, but it is sufficient to illustrate the point. The glibc implementation of malloc is more than 5k lines, and there have been substantial amounts of research into how to build good dynamic memory allocation mechanisms, so covering it all in a SO answer is not possible. Hopefully this has given you a bit of a view of what is really causing the problem though!

How to load external webpage in WebView

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <WebView
        android:id="@+id/webView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java:

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
    WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webView);
        webView .loadUrl("http://www.google.com");
        webView.setWebViewClient(new MyWebViewClient());
    }
}

AndroidManifest.xml: (add uses-permission and android:usesCleartextTraffic)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

How do I run a Python program in the Command Prompt in Windows 7?

First install the Python into your windows by using this url and then add path variable as

c:\python27

Static array vs. dynamic array in C++

static is a keyword in C and C++, so rather than a general descriptive term, static has very specific meaning when applied to a variable or array. To compound the confusion, it has three distinct meanings within separate contexts. Because of this, a static array may be either fixed or dynamic.

Let me explain:

The first is C++ specific:

  • A static class member is a value that is not instantiated with the constructor or deleted with the destructor. This means the member has to be initialized and maintained some other way. static member may be pointers initialized to null and then allocated the first time a constructor is called. (Yes, that would be static and dynamic)

Two are inherited from C:

  • within a function, a static variable is one whose memory location is preserved between function calls. It is static in that it is initialized only once and retains its value between function calls (use of statics makes a function non-reentrant, i.e. not threadsafe)

  • static variables declared outside of functions are global variables that can only be accessed from within the same module (source code file with any other #include's)

The question (I think) you meant to ask is what the difference between dynamic arrays and fixed or compile-time arrays. That is an easier question, compile-time arrays are determined in advance (when the program is compiled) and are part of a functions stack frame. They are allocated before the main function runs. dynamic arrays are allocated at runtime with the "new" keyword (or the malloc family from C) and their size is not known in advance. dynamic allocations are not automatically cleaned up until the program stops running.

PHP's array_map including keys

You can use map method from this array library to achieve exactly what you want as easily as:

Arr::map($test_array, function($a, $b) { return "$a loves $b"; });

also it preserves keys and returns new array, not to mention few different modes to fit your needs.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

You can configure the Javadocs with downloading jar, basically javadocs will be referred directly from internet.

Complete steps:

  1. Open the Build Path page of the project (right click, properties, Java build path).
  2. Open the Libraries tab.
  3. Expand the node of the library in question (JavaFX).
  4. Select JavaDoc location and click edit.
  5. Enter the location to the file which contains the Javadoc. Specifically for the javaFX javadoc enter http://docs.oracle.com/javafx/2.0/api/

for offline javadocs, you can download from : http://www.oracle.com/technetwork/java/javase/documentation/java-se-7-doc-download-435117.html

After clicking Accept License Agreement you can download javafx-2_2_0-apidocs.zip

ASP.NET Core Identity - get current user

I have put something like this in my Controller class and it worked:

IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);

where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).

Prevent form submission on Enter key press

A much simpler and effective way from my perspective should be :

function onPress_ENTER()
{
        var keyPressed = event.keyCode || event.which;

        //if ENTER is pressed
        if(keyPressed==13)
        {
            alert('enter pressed');
            keyPressed=null;
        }
        else
        {
            return false;
        }
}

List tables in a PostgreSQL schema

You can select the tables from information_schema

SELECT * FROM information_schema.tables 
WHERE table_schema = 'public'

Python setup.py develop vs install

Another thing that people may find useful when using the develop method is the --user option to install without sudo. Ex:

python setup.py develop --user

instead of

sudo python setup.py develop

Combine :after with :hover

Just append :after to your #alertlist li:hover selector the same way you do with your #alertlist li.selected selector:

#alertlist li.selected:after, #alertlist li:hover:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}

How to delete migration files in Rails 3

You can also run a down migration like so:

rake db:migrate:down VERSION=versionnumber

Refer to the Ruby on Rails guide on migrations for more info.

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How to copy multiple files in one layer using a Dockerfile?

COPY <all> <the> <things> <last-arg-is-destination>

But here is an important excerpt from the docs:

If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy

Identify duplicate values in a list in Python

It looks like you want the indices of the duplicates. Here is some short code that will find those in O(n) time, without using any packages:

dups = {}
[dups.setdefault(v, []).append(i) for i, v in enumerate(mylist)]
dups = {k: v for k, v in dups.items() if len(v) > 1}
# dups now has keys for all the duplicate values
# and a list of matching indices for each

# The second line produces an unused list. 
# It could be replaced with this:
for i, v in enumerate(mylist):
    dups.setdefault(v, []).append(i)

Resize a large bitmap file to scaled output file on Android

To scale the image the "correct" way, without skipping any pixels, you'd have to hook into the image decoder to perform the down-sampling row by row. Android (and the Skia library that underlies it) provides no such hooks, so you'd have to roll your own. Assuming you're talking jpeg images, your best bet would be to use libjpeg directly, in C.

Given the complexities involved, using the two-step subsample-then-rescale is probably best for image-preview type apps.

How to create a list of objects?

The Python Tutorial discusses how to use lists.

Storing a list of classes is no different than storing any other objects.

def MyClass(object):
    pass

my_types = [str, int, float, MyClass]

How can I create a copy of an Oracle table without copying the data?

Just use a where clause that won't select any rows:

create table xyz_new as select * from xyz where 1=0;

Limitations

The following things will not be copied to the new table:

  • sequences
  • triggers
  • indexes
  • some constraints may not be copied
  • materialized view logs

This also does not handle partitions


How to use Sublime over SSH

I am on MacOS, and the most convenient way for me is to using CyberDuck, which is free (also available for Windows). You can connect to your remote SSH file system and edit your file using your local editor. What CyberDuck does is download the file to a temporary place on your local OS and open it with your editor. Once you save the file, CyberDuck automatically upload it to your remote system. It seems transparent as if you are editing your remote file using your local editor. The developers of Cyberduck also make MountainDuck for mounting remote files systems.

Can't create handler inside thread which has not called Looper.prepare()

Try this

    Handler mHandler = new Handler(Looper.getMainLooper());
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
 //your code here that talks with the UI level widgets/ try to access the UI 
//elements from this block because this piece of snippet will run in the UI/MainThread.                                     
                            }
                        });

Date Comparison using Java

If for some reason you're intent on using Date objects for your solution, you'll need to do something like this:


    // Convert user input into year, month, and day integers
    Date toDate = new Date(year - 1900, month - 1, day + 1);
    Date currentDate = new Date();
    boolean runThatReport = toDate.after(currentDate);

Shifting the toDate ahead to midnight of the next day will take care of the bug I've whined about in the comments to other answers. But, note that this approach uses a deprecated constructor; any approach relying on Date will use one deprecated method or another, and depending on how you do it may lead to race conditions as well (if you base toDate off of new Date() and then fiddle around with the year, month, and day, for instance). Use Calendar, as described elsewhere.

How do I get the total number of unique pairs of a set in the database?

What you're looking for is n choose k. Basically:

enter image description here

For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).

Importing a long list of constants to a Python file

Sure, you can put your constants into a separate module. For example:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

Note that as declared above, A, B and C are variables, i.e. can be changed at run time.

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

Why is access to the path denied?

same issue for me too, I was pointing the folder instead of file.

so make sure in path, give path+filename

System.IO.File.WriteAllBytes("path", bytearray);

How to get a file directory path from file path?

HERE=$(cd $(dirname $BASH_SOURCE) && pwd)

where you get the full path with new_path=$(dirname ${BASH_SOURCE[0]}). You change current directory with cd new_path and then run pwd to get the full path to the current directory.

Syntax for if/else condition in SCSS mixin

You can assign default parameter values inline when you first create the mixin:

@mixin clearfix($width: 'auto') {

  @if $width == 'auto' {

    // if width is not passed, or empty do this

  } @else {

    display: inline-block;
    width: $width;

  }
}

How to add image to canvas

You have to use .onload

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d"); 

const drawImage = (url) => {
    const image = new Image();
    image.src = url;
    image.onload = () => {
       ctx.drawImage(image, 0, 0)
    }
}

Here's Why

If you are loading the image first after the canvas has already been created then the canvas won't be able to pass all the image data to draw the image. So you need to first load all the data that came with the image and then you can use drawImage()

Disable all dialog boxes in Excel while running VB script?

In order to get around the Enable Macro prompt I suggest

Application.AutomationSecurity = msoAutomationSecurityForceDisable

Be sure to return it to default when you are done

Application.AutomationSecurity = msoAutomationSecurityLow

A reminder that the .SaveAs function contains all optional arguments.I recommend removing CreatBackup:= False as it is not necessary.

The most interesting way I think is to create an object of the workbook and access the .SaveAs property that way. I have not tested it but you are never using Workbooks.Open rendering Application.AutomationSecurity inapplicable. Possibly saving resources and time as well.

That said I was able to execute the following without any notifications on Excel 2013 windows 10.

    Option Explicit

    Sub Convert()

    OptimizeVBA (True)  
    'function to set all the things you want to set, but hate keying in

    Application.AutomationSecurity = msoAutomationSecurityForceDisable  
    'this should stop those pesky enable prompts

    ChDir "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to 
    xlsx stop popup"

    Workbooks.Open ("Book1.xlsm")

    ActiveWorkbook.SaveAs Filename:= _
    "F:\VBA Macros\Stack Overflow Questions\When changing type xlsm to xlsx_ 
    stop popup\Book1.xlsx" _
    , FileFormat:=xlOpenXMLWorkbook

    ActiveWorkbook.Close

    Application.AutomationSecurity = msoAutomationSecurityLow 
    'make sure you set this up when done

    Kill ("F:\VBA Macros\Stack Overflow Questions\When changing type xlsm_ 
    to xlsx stop popup\Book1.xlsx") 'clean up

    OptimizeVBA (False)
    End Sub


    Function OptimizeVBA(ByRef Status As Boolean)

    If Status = True Then
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
        Application.DisplayAlerts = False
        Application.EnableEvents = False
    Else
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    End If

    End Function

"And" and "Or" troubles within an IF statement

I like assylias' answer, however I would refactor it as follows:

Sub test()

Dim origNum As String
Dim creditOrDebit As String

origNum = "30062600006"
creditOrDebit = "D"

If creditOrDebit = "D" Then
  If origNum = "006260006" Then
    MsgBox "OK"
  ElseIf origNum = "30062600006" Then
    MsgBox "OK"
  End If
End If

End Sub

This might save you some CPU cycles since if creditOrDebit is <> "D" there is no point in checking the value of origNum.

Update:

I used the following procedure to test my theory that my procedure is faster:

Public Declare Function timeGetTime Lib "winmm.dll" () As Long

Sub DoTests2()

  Dim startTime1 As Long
  Dim endTime1 As Long
  Dim startTime2 As Long
  Dim endTime2 As Long
  Dim i As Long
  Dim msg As String

  Const numberOfLoops As Long = 10000
  Const origNum As String = "006260006"
  Const creditOrDebit As String = "D"

  startTime1 = timeGetTime
  For i = 1 To numberOfLoops
    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        ' do something here
        Debug.Print "OK"
      ElseIf origNum = "30062600006" Then
        ' do something here
        Debug.Print "OK"
      End If
    End If
  Next i
  endTime1 = timeGetTime

  startTime2 = timeGetTime
  For i = 1 To numberOfLoops
    If (origNum = "006260006" Or origNum = "30062600006") And _
      creditOrDebit = "D" Then
      ' do something here
      Debug.Print "OK"
    End If
  Next i
  endTime2 = timeGetTime

  msg = "number of iterations: " & numberOfLoops & vbNewLine
  msg = msg & "JP proc: " & Format$((endTime1 - startTime1), "#,###") & _
       " ms" & vbNewLine
  msg = msg & "assylias proc: " & Format$((endTime2 - startTime2), "#,###") & _
       " ms"

  MsgBox msg

End Sub

I must have a slow computer because 1,000,000 iterations took nowhere near ~200 ms as with assylias' test. I had to limit the iterations to 10,000 -- hey, I have other things to do :)

After running the above procedure 10 times, my procedure is faster only 20% of the time. However, when it is slower it is only superficially slower. As assylias pointed out, however, when creditOrDebit is <>"D", my procedure is at least twice as fast. I was able to reasonably test it at 100 million iterations.

And that is why I refactored it - to short-circuit the logic so that origNum doesn't need to be evaluated when creditOrDebit <> "D".

At this point, the rest depends on the OP's spreadsheet. If creditOrDebit is likely to equal D, then use assylias' procedure, because it will usually run faster. But if creditOrDebit has a wide range of possible values, and D is not any more likely to be the target value, my procedure will leverage that to prevent needlessly evaluating the other variable.

How to write an inline IF statement in JavaScript?

For writing if statement inline, the code inside of it should only be one statement:

if ( a < b ) // code to be executed without curly braces;

how to do "press enter to exit" in batch

Oops... Misunderstood the question...

Pause is the way to go

Old answer:

you can pipe commands into your patch file...

try

build.bat < responsefile.txt

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

$out.='<option value="'.$key.'">'.$value["name"];

me funciono con esta

"<a  href='javascript:void(0)' onclick='cargar_datos_cliente(\"$row->DSC_EST\")' class='button micro asignar margin-none'>Editar</a>";

What difference does .AsNoTracking() make?

see this page Entity Framework and AsNoTracking

What AsNoTracking Does

Entity Framework exposes a number of performance tuning options to help you optimise the performance of your applications. One of these tuning options is .AsNoTracking(). This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query. However, it also means that you can't update these entities without reattaching them to the tracking graph.

there are significant performance gains to be had by using AsNoTracking

Adding files to java classpath at runtime

yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.

How to disable logging on the standard error stream in Python?

This will prevent all logging from a third library which it used as decribed here https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library

logging.getLogger('somelogger').addHandler(logging.NullHandler())

How to access static resources when mapping a global front controller servlet on /*

'Static' files in App Engine aren't directly accessible by your app. You either need to upload them twice, or serve the static files yourself, rather than using a static handler.

differences in application/json and application/x-www-form-urlencoded

webRequest.ContentType = "application/x-www-form-urlencoded";

  1. Where does application/x-www-form-urlencoded's name come from?

    If you send HTTP GET request, you can use query parameters as follows:

    http://example.com/path/to/page?name=ferret&color=purple

    The content of the fields is encoded as a query string. The application/x-www-form- urlencoded's name come from the previous url query parameter but the query parameters is in where the body of request instead of url.

    The whole form data is sent as a long query string.The query string contains name- value pairs separated by & character

    e.g. field1=value1&field2=value2

  2. It can be simple request called simple - don't trigger a preflight check

    Simple request must have some properties. You can look here for more info. One of them is that there are only three values allowed for Content-Type header for simple requests

    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

3.For mostly flat param trees, application/x-www-form-urlencoded is tried and tested.

request.ContentType = "application/json; charset=utf-8";

  1. The data will be json format.

axios and superagent, two of the more popular npm HTTP libraries, work with JSON bodies by default.

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}
  1. "application/json" Content-Type is one of the Preflighted requests.

Now, if the request isn't simple request, the browser automatically sends a HTTP request before the original one by OPTIONS method to check whether it is safe to send the original request. If itis ok, Then send actual request. You can look here for more info.

  1. application/json is beginner-friendly. URL encoded arrays can be a nightmare!

SSIS expression: convert date to string

If, like me, you are trying to use GETDATE() within an expression and have the seemingly unreasonable requirement (SSIS/SSDT seems very much a work in progress to me, and not a polished offering) of wanting that date to get inserted into SQL Server as a valid date (type = datetime), then I found this expression to work:

@[User::someVar] = (DT_WSTR,4)YEAR(GETDATE()) + "-"  + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-"  + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + " " + RIGHT("0" + (DT_WSTR,2)DATEPART("hh", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("mi", GETDATE()), 2) + ":" + RIGHT("0" + (DT_WSTR,2)DATEPART("ss", GETDATE()), 2)

I found this code snippet HERE

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

How to run java application by .bat file

javac Application.java

java Application

pause

The javac command will compile the java program and the java command will run the program and pause will pause the result until you cross it.

Where is the Java SDK folder in my computer? Ubuntu 12.04

$ whereis java

java: /usr/bin/java /usr/lib/java /usr/bin/X11/java /usr/share/java /usr/share/man/man1/java.1.gz

Best way to concatenate List of String objects?

Your approach is dependent on Java's ArrayList#toString() implementation.

While the implementation is documented in the Java API and very unlikely to change, there's a chance it could. It's far more reliable to implement this yourself (loops, StringBuilders, recursion whatever you like better).

Sure this approach may seem "neater" or more "too sweet" or "money" but it is, in my opinion, a worse approach.

How to check if two words are anagrams

Here's a simple fast O(n) solution without using sorting or multiple loops or hash maps. We increment the count of each character in the first array and decrement the count of each character in the second array. If the resulting counts array is full of zeros, the strings are anagrams. Can be expanded to include other characters by increasing the size of the counts array.

class AnagramsFaster{

    private static boolean compare(String a, String b){
        char[] aArr = a.toLowerCase().toCharArray(), bArr = b.toLowerCase().toCharArray();
        if (aArr.length != bArr.length)
            return false;
        int[] counts = new int[26]; // An array to hold the number of occurrences of each character
        for (int i = 0; i < aArr.length; i++){
            counts[aArr[i]-97]++;  // Increment the count of the character at i
            counts[bArr[i]-97]--;  // Decrement the count of the character at i
        }
        // If the strings are anagrams, the counts array will be full of zeros
        for (int i = 0; i<26; i++)
            if (counts[i] != 0)
                return false;
        return true;
    }

    public static void main(String[] args){
        System.out.println(compare(args[0], args[1]));
    }
}

How to reshape data from long to wide format

Using reshape function:

reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")

READ_EXTERNAL_STORAGE permission for Android

You have two solutions for your problem. The quick one is to lower targetApi to 22 (build.gradle file). Second is to use new and wonderful ask-for-permission model:

if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
    // app-defined int constant that should be quite unique

    return;
}

Sniplet found here: https://developer.android.com/training/permissions/requesting.html

Solutions 2: If it does not work try this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_PERMISSION);

return;

}

and then in callback

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Permission granted.
    } else {
        // User refused to grant permission.
    }
}
}

that is from comments. thanks

Ubuntu apt-get unable to fetch packages

As Tariq Khan suggested, I did the same thing and it worked out..

FIX UBUNTU 14.10 UNICORN APT-GET UPDATE

Backup the repo first

$ sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup 
$ sudo vi /etc/apt/sources.list

rename us.archive or archive in http://us.archive.ubuntu.com/ubuntu/ as http://old-release.ubuntu.com/ubuntu/

rename http://security.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages as http://old-releases.ubuntu.com/ubuntu/dists/saucy-security/universe/binary-i386/Packages

$ sudo apt-get update

Git error when trying to push -- pre-receive hook declined

Remove the protected branch option or allow additional roles like developers or admins to allow these users experiencing this error to do merges and push.

How to change the floating label color of TextInputLayout

This is simple but the developer gets confused due to multiple views having the same attributes in different configurations/namespaces.

In the case of the TextInputLayout we have every time a different view and with params either with TextInputEditText or directly to TextInputLayout.

I was using all the above fixes: But I found that I was using

                app:textColorHint="@color/textcolor_black"

actually i should be using

                android:textColorHint="@color/textcolor_black"

As an attribute of TextinputLayout

textcolor_black.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/black_txt" android:state_enabled="true" />
    <item android:color="@color/black_txt" android:state_selected="true" />
    <item android:color="@color/txtColorGray" android:state_selected="false" />
    <item android:color="@color/txtColorGray" android:state_enabled="false" />
</selector>

<> And Not In VB.NET

Here's the technical answer (expanding on Rowland Shaw's answer).

The Is keyword checks whether the two operands are references to the same object memory, and only returns true if this is the case. I believe it is functionally equivalent to Object.ReferenceEquals. The IsNot keyword is simply shorthand syntax for writing Not ... Is ..., nothing more.

The = (equality) operator compares values and in this case (as in many others) is equivalent to String.Equals. Now, the <> (inequality) operator does not quite have the same analogy as the Is and IsNot keywords, since it can be overriden separately from the = operator depending on the class. I believe the case should always be that it returns the logical inverse of the = operator (and certainly is in the case of String), and just allows for a more efficient comparison to made when testing for inequality rather than equality.

When dealing with strings, unless you actually mean to compare references, always use the = operator (or String.Equals I suppose). In your case, because you are testing for null (Nothing), it seems you need to use the Is or IsNot keyword (the equality operator will fail because it can't compare the values of null objects). Syntactically, the IsNot keyword is a bit nicer here, so go with that.