Programs & Examples On #Avi

This tag is for questions about playback of, creation of, and programmatic interaction with, Audio Video Interleave (*.avi) files. The AVI format was introduced by Microsoft in 1992 and has been widely adopted and modified since, but remains mostly supported on Microsoft devices

Does HTML5 <video> playback support the .avi format?

The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.

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

error : expected unqualified-id before return in c++

Just for the sake of people who landed here for the same reason I did:

Don't use reserved keywords

I named a function in my class definition delete(), which is a reserved keyword and should not be used as a function name. Renaming it to deletion() (which also made sense semantically in my case) resolved the issue.

For a list of reserved keywords: http://en.cppreference.com/w/cpp/keyword

I quote: "Since they are used by the language, these keywords are not available for re-definition or overloading. "

How to convert a currency string to a double with jQuery or Javascript?

Here's a simple function -

_x000D_
_x000D_
function getNumberFromCurrency(currency) {
  return Number(currency.replace(/[$,]/g,''))
}

console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
_x000D_
_x000D_
_x000D_

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

Move SQL data from one table to another

If the two tables use the same ID or have a common UNIQUE key:

1) Insert the selected record in table 2

INSERT INTO table2 SELECT * FROM table1 WHERE (conditions)

2) delete the selected record from table1 if presents in table2

DELETE FROM table1 as A, table2 as B WHERE (A.conditions) AND  (A.ID = B.ID)

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

When the workbook first opens, execute this code:

alertTime = Now + TimeValue("00:02:00")
Application.OnTime alertTime, "EventMacro"

Then just have a macro in the workbook called "EventMacro" that will repeat it.

Public Sub EventMacro()
    '... Execute your actions here'
    alertTime = Now + TimeValue("00:02:00")
    Application.OnTime alertTime, "EventMacro"
End Sub

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

you should not use swap to copy vectors, it would change the "original" vector.

pass the original as a parameter to the new instead.

Angular 2 Scroll to top on Route Change

You can add the AfterViewInit lifecycle hook to your component.

ngAfterViewInit() {
   window.scrollTo(0, 0);
}

Async/Await Class Constructor

The stopgap solution

You can create an async init() {... return this;} method, then instead do new MyClass().init() whenever you'd normally just say new MyClass().

This is not clean because it relies on everyone who uses your code, and yourself, to always instantiate the object like so. However if you're only using this object in a particular place or two in your code, it could maybe be fine.

A significant problem though occurs because ES has no type system, so if you forget to call it, you've just returned undefined because the constructor returns nothing. Oops. Much better would be to do something like:

The best thing to do would be:

class AsyncOnlyObject {
    constructor() {
    }
    async init() {
        this.someField = await this.calculateStuff();
    }

    async calculateStuff() {
        return 5;
    }
}

async function newAsync_AsyncOnlyObject() {
    return await new AsyncOnlyObject().init();
}

newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}

The factory method solution (slightly better)

However then you might accidentally do new AsyncOnlyObject, you should probably just create factory function that uses Object.create(AsyncOnlyObject.prototype) directly:

async function newAsync_AsyncOnlyObject() {
    return await Object.create(AsyncOnlyObject.prototype).init();
}

newAsync_AsyncOnlyObject().then(console.log);
// output: AsyncOnlyObject {someField: 5}

However say you want to use this pattern on many objects... you could abstract this as a decorator or something you (verbosely, ugh) call after defining like postProcess_makeAsyncInit(AsyncOnlyObject), but here I'm going to use extends because it sort of fits into subclass semantics (subclasses are parent class + extra, in that they should obey the design contract of the parent class, and may do additional things; an async subclass would be strange if the parent wasn't also async, because it could not be initialized the same way):


Abstracted solution (extends/subclass version)

class AsyncObject {
    constructor() {
        throw new Error('classes descended from AsyncObject must be initialized as (await) TheClassName.anew(), rather than new TheClassName()');
    }

    static async anew(...args) {
        var R = Object.create(this.prototype);
        R.init(...args);
        return R;
    }
}

class MyObject extends AsyncObject {
    async init(x, y=5) {
        this.x = x;
        this.y = y;
        // bonus: we need not return 'this'
    }
}

MyObject.anew('x').then(console.log);
// output: MyObject {x: "x", y: 5}

(do not use in production: I have not thought through complicated scenarios such as whether this is the proper way to write a wrapper for keyword arguments.)

Changing case in Vim

Visual select the text, then U for uppercase or u for lowercase. To swap all casing in a visual selection, press ~ (tilde).

Without using a visual selection, gU<motion> will make the characters in motion uppercase, or use gu<motion> for lowercase.

For more of these, see Section 3 in Vim's change.txt help file.

Using SQL LOADER in Oracle to import CSV file

Sqlldr wants to write a log file in the same directory where the control file is. But obviously it can't. It probably doesn't have the required permission.

If you're on Linux or Unix, try to run the following command the same way you run sqldr:

touch Billing.log

It will show whether you have the permissions.

Update

The proper command line is:

sqlldr myusername/mypassword control=Billing.ctl

How to use System.Net.HttpClient to post a complex type?

The generic HttpRequestMessage<T> has been removed. This :

new HttpRequestMessage<Widget>(widget)

will no longer work.

Instead, from this post, the ASP.NET team has included some new calls to support this functionality:

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

So, the new code (from dunston) becomes:

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

How to save data in an android app

In my opinion db4o is the easiest way to go. Here you can find a tutorial: http://community.versant.com/documentation/reference/db4o-7.12/java/tutorial/

And here you can download the library:

http://www.db4o.com/community/download.aspx?file=db4o-8.0-java.zip

(Just put the db4o-8.0...-all-java5.jar in the lib directory into your project's libs folder. If there is no libs folder in you project create it)

As db4o is a object oriented database system you can directly save you objects into the database and later get them back.

Cannot assign requested address using ServerSocket.socketBind

In my case, delete from /etc/hosts

  • 127.0.0.1 localhost
  • 192.168.100.20 localhost <<<<---- (delete or comment)

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

I had a struggle getting this to work i've tested it and it's working on lamp server mysql version 5.12

So, steps to success:

  1. sudo vim /etc/mysql/conf.d/mysql.cnf
  2. Scroll to the bottom of file Copy and paste

    [mysqld] sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

to the bottom of the file

  1. save and exit input mode
  2. sudo service mysql restart to restart MySQL.

Done!

Best way to incorporate Volley (or other library) into Android Studio project

For incorporate volley in android studio,

  1. paste the following command in terminal (
    git clone https://android.googlesource.com/platform/frameworks/volley ) and run it.

    Refer android developer tutorial for this.

    It will create a folder name volley in the src directory.
  2. Then go to android studio and right click on the project.
  3. choose New -> Module from the list.
  4. Then click on import existing Project from the below list.
  5. you will see a text input area namely source directory, browse the folder you downloaded (volley) and then click on finish.
  6. you will see a folder volley in your project view.
  7. the switch to android view and open the build:gradle(Module:app) file and append the following line in the dependency area:

    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

  8. Now synchronise your project and also build your project.

Sort an Array by keys based on another Array?

There you go:

function sortArrayByArray(array $array, array $orderArray) {
    $ordered = array();
    foreach ($orderArray as $key) {
        if (array_key_exists($key, $array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

APK signing error : Failed to read key from keystore

Most likely that your key alias does not exist for your keystore file.

This answer should fix your signing issue ;)

Angular2: custom pipe could not be found

This didnt worked for me. (Im with Angular 2.1.2). I had NOT to import MainPipeModule in app.module.ts and importe it instead in the module where the component Im using the pipe is imported too.

Looks like if your component is declared and imported in a different module, you need to include your PipeModule in that module too.

AngularJS - How to use $routeParams in generating the templateUrl?

//module dependent on ngRoute  
 var app=angular.module("myApp",['ngRoute']);
    //spa-Route Config file
    app.config(function($routeProvider,$locationProvider){
          $locationProvider.hashPrefix('');
          $routeProvider
            .when('/',{template:'HOME'})
            .when('/about/:paramOne/:paramTwo',{template:'ABOUT',controller:'aboutCtrl'})
            .otherwise({template:'Not Found'});
    }
   //aboutUs controller 
    app.controller('aboutCtrl',function($routeParams){
          $scope.paramOnePrint=$routeParams.paramOne;
          $scope.paramTwoPrint=$routeParams.paramTwo;
    });

in index.html

<a ng-href="#/about/firstParam/secondParam">About</a>

firstParam and secondParam can be anything according to your needs.

How to fix "Attempted relative import in non-package" even with __init__.py

Try this

import components
from components import *

What does "Content-type: application/json; charset=utf-8" really mean?

The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.

Content-type: application/json; charset=utf-8 designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.

Does this encoding limit the characters that can be in the message body?

No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.

css with background image without repeating the image

Instead of

background-repeat-x: no-repeat;
background-repeat-y: no-repeat;

which is not correct, use

background-repeat: no-repeat;

Getting URL parameter in java and extract a specific text from that URL

If you are using Jersey (which I was, my server component needs to make outbound HTTP requests) it contains the following public method:

var multiValueMap = UriComponent.decodeQuery(uri, true);

It is part of org.glassfish.jersey.uri.UriComponent, and the javadoc is here. Whilst you may not want all of Jersey, it is part of the Jersey common package which isn't too bad on dependencies...

Remove large .pack file created by git

I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/

ERROR 1064 (42000) in MySQL

Making the following changes in query solved this issue:

INSERT INTO table_name (`column1`, `column2`) values ('val1', 'val2');

Note that the column names are enclosed in ` (character above tab) and not in quotes.

jquery clone div and append it after specific div

This works great if a straight copy is in order. If the situation calls for creating new objects from templates, I usually wrap the template div in a hidden storage div and use jquery's html() in conjunction with clone() applying the following technique:

<style>
#element-storage {
    display: none;
    top: 0;
    right: 0;
    position: fixed;
    width: 0;
    height: 0;
}
</style>

<script>
$("#new-div").append($("#template").clone().html(function(index, oldHTML){ 
    // .. code to modify template, e.g. below:
    var newHTML = "";
    newHTML = oldHTML.replace("[firstname]", "Tom");
    newHTML = newHTML.replace("[lastname]", "Smith");
    // newHTML = newHTML.replace(/[Example Replace String]/g, "Replacement"); // regex for global replace
    return newHTML;
}));
</script>

<div id="element-storage">
  <div id="template">
    <p>Hello [firstname] [lastname]</p>
  </div>
</div>

<div id="new-div">

</div>

How to start MySQL server on windows xp

Start mysql server by command prompt

C:> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --console

Or alternative reach up to bin then

mysqld --console

It will start your server.

If you have mysql command line client available

click on it

it show enter your password :

Please enter your password.

Then you can access it.

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

How to use PHP with Visual Studio

I don't understand how other answers don't answer the original question about how to use PHP (not very consistent with the title).
PHP files or PHP code embedded in HTML code start always with the tag <?php and ends with ?>.

You can embed PHP code inside HTML like this (you have to save the file using .php extension to let PHP server recognize and process it, ie: index.php):

<body>
   <?php echo "<div>Hello World!</div>" ?>
</body>

or you can use a whole php file, ie: test.php:

<?php    
$mycontent = "Hello World!";
echo "<div>$mycontent</div>";
?> // is not mandatory to put this at the end of the file

there's no document.ready in PHP, the scripts are processed when they are invoked from the browser or from another PHP file.

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

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

I always like to write my own "custom enum". Than I have one class that is a little bit more complex, but I can reuse it:

public abstract class CustomEnum
{
    private readonly string _name;
    private readonly object _id;

    protected CustomEnum( string name, object id )
    {
        _name = name;
        _id = id;
    }

    public string Name
    {
        get { return _name; }
    }

    public object Id
    {
        get { return _id; }
    }

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

public abstract class CustomEnum<TEnumType, TIdType> : CustomEnum
    where TEnumType : CustomEnum<TEnumType, TIdType>
{
    protected CustomEnum( string name, TIdType id )
        : base( name, id )
    { }

    public new TIdType Id
    {
        get { return (TIdType)base.Id; }
    }

    public static TEnumType FromName( string name )
    {
        try
        {
            return FromDelegate( entry => entry.Name.Equals( name ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal name for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static TEnumType FromId( TIdType id )
    {
        try
        {
            return FromDelegate( entry => entry.Id.Equals( id ) );
        }
        catch (ArgumentException ae)
        {
            throw new ArgumentException( "Illegal id for custom enum '" + typeof( TEnumType ).Name + "'", ae );
        }
    }

    public static IEnumerable<TEnumType> GetAll()
    {
        var elements = new Collection<TEnumType>();
        var infoArray = typeof( TEnumType ).GetFields( BindingFlags.Public | BindingFlags.Static );

        foreach (var info in infoArray)
        {
            var type = info.GetValue( null ) as TEnumType;
            elements.Add( type );
        }

        return elements;
    }

    protected static TEnumType FromDelegate( Predicate<TEnumType> predicate )
    {
        if(predicate == null)
            throw new ArgumentNullException( "predicate" );

        foreach (var entry in GetAll())
        {
            if (predicate( entry ))
                return entry;
        }

        throw new ArgumentException( "Element not found while using predicate" );
    }
}

Now I just need to create my enum I want to use:

 public sealed class SampleEnum : CustomEnum<SampleEnum, int>
    {
        public static readonly SampleEnum Element1 = new SampleEnum( "Element1", 1, "foo" );
        public static readonly SampleEnum Element2 = new SampleEnum( "Element2", 2, "bar" );

        private SampleEnum( string name, int id, string additionalText )
            : base( name, id )
        {
            AdditionalText = additionalText;
        }

        public string AdditionalText { get; private set; }
    }

At last I can use it like I want:

 static void Main( string[] args )
        {
            foreach (var element in SampleEnum.GetAll())
            {
                Console.WriteLine( "{0}: {1}", element, element.AdditionalText );
                Console.WriteLine( "Is 'Element2': {0}", element == SampleEnum.Element2 );
                Console.WriteLine();
            }

            Console.ReadKey();
        }

And my output would be:

Element1: foo
Is 'Element2': False

Element2: bar
Is 'Element2': True    

Proper MIME media type for PDF files

The standard MIME type is application/pdf. The assignment is defined in RFC 3778, The application/pdf Media Type, referenced from the MIME Media Types registry.

MIME types are controlled by a standards body, The Internet Assigned Numbers Authority (IANA). This is the same organization that manages the root name servers and the IP address space.

The use of x-pdf predates the standardization of the MIME type for PDF. MIME types in the x- namespace are considered experimental, just as those in the vnd. namespace are considered vendor-specific. x-pdf might be used for compatibility with old software.

How to make HTML code inactive with comments

Reason of comments:

  1. Comment out elements temporarily rather than removing them, especially if they've been left unfinished.
  2. Write notes or reminders to yourself inside your actual HTML documents.
  3. Create notes for other scripting languages like JavaScript which requires them

HTML Comments

<!-- Everything is invisible  -->

Getting net::ERR_UNKNOWN_URL_SCHEME while calling telephone number from HTML page in Android

I had this issue occurring with mailto: and tel: links inside an iframe (in Chrome, not a webview). Clicking the links would show the grey "page not found" page and inspecting the page showed it had a ERR_UNKNOWN_URL_SCHEME error.

Adding target="_blank", as suggested by this discussion of the issue fixed the problem for me.

docker-compose up for only certain containers

Update

Starting with docker-compose 1.28.0 the new service profiles are just made for that! With profiles you can mark services to be only started in specific profiles:

services:
  client:
    # ...
  db:
    # ...
  npm:
    profiles: ["cli-only"]
    # ...
docker-compose up # start main services, no npm
docker-compose run --rm npm # run npm service
docker-compose --profile cli-only # start main and all "cli-only" services

original answer

Since docker-compose v1.5 it is possible to pass multiple docker-compose.yml files with the -f flag. This allows you to split your dev tools into a separate docker-compose.yml which you then only include on-demand:

# start and attach to all your essential services
docker-compose up

# execute a defined command in docker-compose.dev.yml
docker-compose -f docker-compose.dev.yml run npm update

# if your command depends_on a service you need to include both configs
docker-compose -f docker-compose.yml -f docker-compose.dev.yml run npm update

For an in-depth discussion on this see docker/compose#1896.

exception in thread 'main' java.lang.NoClassDefFoundError:

The Problem here is the setting the environment and the running of the class file. a. To set the environment path run the following command: set path=C:\Program Files (x86)\Java\jdk1.7.0\bin b. run the program from the package like com.test.TestJavaClass

Command: java com.test.TestJavaClass

The general issue here is we run it either from inside the package like src/package/name. We should not include src, package name is enough.

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

MySQL equivalent of DECODE function in Oracle

You can use a CASE statement...however why don't you just create a table with an integer for ages between 0 and 150, a varchar for the written out age and then you can just join on that

How to serve static files in Flask

The URL for a static file can be created using the static endpoint as following:

url_for('static', filename = 'name_of_file')
<link rel="stylesheet" href="{{url_for('static', filename='borders.css')}}" />

IN vs ANY operator in PostgreSQL

There are two obvious points, as well as the points in the other answer:

  • They are exactly equivalent when using sub queries:

    SELECT * FROM table
    WHERE column IN(subquery);
    
    SELECT * FROM table
    WHERE column = ANY(subquery);
    

On the other hand:

  • Only the IN operator allows a simple list:

    SELECT * FROM table
    WHERE column IN(… , … , …);
    

Presuming they are exactly the same has caught me out several times when forgetting that ANY doesn’t work with lists.

Can I execute a function after setState is finished updating?

setState(updater[, callback]) is an async function:

https://facebook.github.io/react/docs/react-component.html#setstate

You can execute a function after setState is finishing using the second param callback like:

this.setState({
    someState: obj
}, () => {
    this.afterSetStateFinished();
});

The same can be done with hooks in React functional component:

https://github.com/the-road-to-learn-react/use-state-with-callback#usage

Look at useStateWithCallbackLazy:

import { useStateWithCallbackLazy } from 'use-state-with-callback';

const [count, setCount] = useStateWithCallbackLazy(0);

setCount(count + 1, () => {
   afterSetCountFinished();
});

Python: access class property from string

  • getattr(x, 'y') is equivalent to x.y
  • setattr(x, 'y', v) is equivalent to x.y = v
  • delattr(x, 'y') is equivalent to del x.y

regex string replace

This should work :

str = str.replace(/[^a-z0-9-]/g, '');

Everything between the indicates what your are looking for

  1. / is here to delimit your pattern so you have one to start and one to end
  2. [] indicates the pattern your are looking for on one specific character
  3. ^ indicates that you want every character NOT corresponding to what follows
  4. a-z matches any character between 'a' and 'z' included
  5. 0-9 matches any digit between '0' and '9' included (meaning any digit)
  6. - the '-' character
  7. g at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string

Then your expression is delimited by / before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

How to set IntelliJ IDEA Project SDK

For a new project select the home directory of the jdk

eg C:\Java\jdk1.7.0_99 or C:\Program Files\Java\jdk1.7.0_99

For an existing project.

1) You need to have a jdk installed on the system.

for instance in

C:\Java\jdk1.7.0_99

2) go to project structure under File menu ctrl+alt+shift+S

3) SDKs is located under Platform Settings. Select it.

4) click the green + up the top of the window.

5) select JDK (I have to use keyboard to select it do not know why).

select the home directory for your jdk installation.

should be good to go.

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

How can I list the contents of a directory in Python?

Since Python 3.5, you can use os.scandir.

The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file to know if it's a file or not, and that saves CPU time because stat is already done when scanning dir in Windows:

example to list a directory and print files bigger than max_value bytes:

for dentry in os.scandir("/path/to/dir"):
    if dentry.stat().st_size > max_value:
       print("{} is biiiig".format(dentry.name))

(read an extensive performance-based answer of mine here)

Windows command for file size only

In a batch file, the below works for local files, but fails for files on network hard drives

for %%I in ("test.jpg") do @set filesize=%~z1

However, it's inferior code, because it doesn't work for files saved on a network drive (for example, \\Nas\test.jpg and \\192.168.2.40\test.jpg). The below code works for files in any location, and I wrote it myself.

I'm sure there are more efficient ways of doing this using VBScript, or PowerShell or whatever, but I didn't want to do any of that; good ol' batch for me!

set file=C:\Users\Admin\Documents\test.jpg
set /a filesize=
set fileExclPath=%file:*\=%

:onemoretime
set fileExclPath2=%fileExclPath:*\=%
set fileExclPath=%fileExclPath2:*\=%
if /i "%fileExclPath%" NEQ "%fileExclPath2%" goto:onemoretime

dir /s /a-d "%workingdir%">"%temp%\temp.txt"
findstr /C:"%fileExclPath%" "%temp%\temp.txt" >"%temp%\temp2.txt"

set /p filesize= <"%temp%\temp2.txt"

echo set filesize=%%filesize: %fileExclPath%%ext%=%% >"%temp%\temp.bat"
call "%temp%\temp.bat"

:RemoveTrailingSpace
if /i "%filesize:~-1%" EQU " " set filesize=%filesize:~0,-1%
if /i "%filesize:~-1%" EQU " " goto:RemoveTrailingSpace

:onemoretime2
set filesize2=%filesize:* =%
set filesize=%filesize2:* =%
if /i "%filesize%" NEQ "%filesize2%" goto:onemoretime2

set filesize=%filesize:,=%
echo %filesize% bytes

SET /a filesizeMB=%filesize%/1024/1024
echo %filesizeMB% MB

SET /a filesizeGB=%filesize%/1024/1024/1024
echo %filesizeGB% GB

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:

string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

Jquery: Find Text and replace

Try This

$("#id1 p:contains('dogsss')").replaceWith("dollsss");

Convert Rtf to HTML

If you don't mind getting your hands dirty, it isn't that difficult to write an RTF to HTML converter.

Writing a general purpose RTF->HTML converter would be somewhat complicated because you would need to deal with hundreds of RTF verbs. However, in your case you are only dealing with those verbs used specifically by Crystal Reports. I'll bet the standard RTF coding generated by Crystal doesn't vary much from report to report.

I wrote an RTF to HTML converter in C++, but it only deals with basic formatting like fonts, paragraph alignments, etc. My translator basically strips out any specialized formatting that it isn't prepared to deal with. It took about 400 lines of C++. It basically scans the text for RTF tags and replaces them with equivalent HTML tags. RTF tags that aren't in my list are simply stripped out. A regex function is really helpful when writing such a converter.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

How to set header and options in axios?

_x000D_
_x000D_
axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)
_x000D_
_x000D_
_x000D_

Convert Bitmap to File

Hope it will help u:

//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();

//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

HTML5 form validation pattern alphanumeric with spaces?

Use below code for HTML5 validation pattern alphanumeric without / with space :-

for HTML5 validation pattern alphanumeric without space :- onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90"

for HTML5 validation pattern alphanumeric with space :-

onkeypress="return event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 97 && event.charCode <= 122 || event.charCode >= 65 && event.charCode <= 90 || event.charCode == 32"

Posting a File and Associated Data to a RESTful WebService preferably as JSON

You can send the file and data over in one request using the multipart/form-data content type:

In many applications, it is possible for a user to be presented with a form. The user will fill out the form, including information that is typed, generated by user input, or included from files that the user has selected. When the form is filled out, the data from the form is sent from the user to the receiving application.

The definition of MultiPart/Form-Data is derived from one of those applications...

From http://www.faqs.org/rfcs/rfc2388.html:

"multipart/form-data" contains a series of parts. Each part is expected to contain a content-disposition header [RFC 2183] where the disposition type is "form-data", and where the disposition contains an (additional) parameter of "name", where the value of that parameter is the original field name in the form. For example, a part might contain a header:

Content-Disposition: form-data; name="user"

with the value corresponding to the entry of the "user" field.

You can include file information or field information within each section between boundaries. I've successfully implemented a RESTful service that required the user to submit both data and a form, and multipart/form-data worked perfectly. The service was built using Java/Spring, and the client was using C#, so unfortunately I don't have any Grails examples to give you concerning how to set up the service. You don't need to use JSON in this case since each "form-data" section provides you a place to specify the name of the parameter and its value.

The good thing about using multipart/form-data is that you're using HTTP-defined headers, so you're sticking with the REST philosophy of using existing HTTP tools to create your service.

How does "FOR" work in cmd batch file?

It works for me, try it.

for /f "tokens=* delims=;" %g in ('echo %PATH%') do echo %g%

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

Java HashMap: How to get a key and value by index?

You can iterate over keys by calling map.keySet(), or iterate over the entries by calling map.entrySet(). Iterating over entries will probably be faster.

for (Map.Entry<String, List<String>> entry : map.entrySet()) {
    List<String> list = entry.getValue();
    // Do things with the list
}

If you want to ensure that you iterate over the keys in the same order you inserted them then use a LinkedHashMap.

By the way, I'd recommend changing the declared type of the map to <String, List<String>>. Always best to declare types in terms of the interface rather than the implementation.

How can I disable a button in a jQuery dialog from a function?

If you create a dialog providing id's for the buttons,

$("#dialog").dialog({ buttons: [ {
 id: "dialogSave",
 text: "Save",
 click: function() { $(this).dialog("close"); }
},
{
 id: "dialogCancel",
 text: "Cancel",
 click: function() { $(this).dialog("close"); 
}
}]});       

we can disable button with the following code:

$("#dialogSave").button("option", "disabled", true);

create a white rgba / CSS3

The code you have is a white with low opacity.

If something white with a low opacity is above something black, you end up with a lighter shade of gray. Above red? Lighter red, etc. That is how opacity works.

Here is a simple demo.

If you want it to look 'more white', make it less opaque:

background:rgba(255,255,255, 0.9);

Demo

Cannot edit in read-only editor VS Code

  1. Go to File > Preference > Settings then
  2. type: run code and scroll down until you see code-runner: Run in terminal, There will be multiple options called "code-runner". In that you can find the option mentioned below.
  3. just check "Whether to run code in integrated terminal" and
  4. restart vscode.

For Mac users, it is Code > Preference > Settings.

What's the difference between integer class and numeric class in R

To quote the help page (try ?integer), bolded portion mine:

Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that (small) integer data can be represented exactly and compactly.

Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.

Like the help page says, R's integers are signed 32-bit numbers so can hold between -2147483648 and +2147483647 and take up 4 bytes.

R's numeric is identical to an 64-bit double conforming to the IEEE 754 standard. R has no single precision data type. (source: help pages of numeric and double). A double can store all integers between -2^53 and 2^53 exactly without losing precision.

We can see the data type sizes, including the overhead of a vector (source):

> object.size(1:1000)
4040 bytes
> object.size(as.numeric(1:1000))
8040 bytes

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

jQuery UI: Datepicker set year range dropdown to 100 years

Try the following:-

ChangeYear:- When set to true, indicates that the cells of the previous or next month indicated in the calendar of the current month can be selected. This option is used with options.showOtherMonths set to true.

YearRange:- Specifies the range of years in the year dropdown. (Default value: “-10:+10")

Example:-

$(document).ready(function() {
    $("#date").datepicker({
        changeYear:true,
        yearRange: "2005:2015"
    });
});

See:- set year range in jquery datepicker

Difference between static and shared libraries?

On top of all the other answers, one thing not mentionned yet is decoupling :

Let me speak about a real world production code,that I have been dealing with :

A very big software, made of >300 projects (with visual studio), mostly build as static lib and finally all link together in one huge executable , you end up with the following problems :

-Link time is extremely long. You might end up by more than 15min of link, for let's say 10s of compilation time -Some tools are on their knee with such a big executable , like memory check tools that must instrument the code. You might fall into reaching limits that had been seen as fools.

More problematic is the decoupling of your software : on this real world example, headers files of every project were reacheable from any others projects. As a consequence it was extremely easy for one developer to add dependencies; it was just about including the header, because link at the end will allwaws find symbols. It ends up by horrible cycling dependencies and complete mess.

With shared library, it's a bit of extra work because developer must edit the project build system to add the dependent library. I observed that shared library code tends to offer a cleaner code API.

ExecuteReader: Connection property has not been initialized

I like to place all my sql connections in using statements. I think they look cleaner, and they clean up after themselves when your done with them. I also recommend parameterizing every query, not only is it much safer but it is easier to maintain if you need to come back and make changes.

// create/open connection
using (SqlConnection conn = new SqlConnection("Data Source=Si-6\\SQLSERVER2005;Initial Catalog=rags;Integrated Security=SSPI")
{
    try
    {
        conn.Open();

        // initialize command
        using (SqlCommand cmd = conn.CreateCommand())
        {

            // generate query with parameters
            with cmd
            {
                .CommandType = CommandType.Text;
                .CommandText = "insert into time(project,iteration) values(@name, @iteration)";
                .Parameters.Add(new SqlParameter("@name", this.name1.SelectedValue));
                .Parameters.Add(new SqlParameter("@iteration", this.iteration.SelectedValue));
                .ExecuteNonQuery();
            }
        }
    }
    catch (Exception)
    {
        //throw;
    }
    finally
    {
        if (conn != null && conn.State == ConnectionState.Open)
        {
            conn.Close;
        }
    }
}

How do I remove a submodule?

I just found the .submodule (forgot exact name) hidden file, it has a list... you can erase them individually that way. I just had one, so I deleted it. Simple, but it might mess up Git, since I don't know if anything's attached to the submodule. Seems ok so far, aside from libetpan's usual upgrade issue, but that's (hopefully) unrelated.

Noticed nobody posted manual erasing, so added

What's the best practice to round a float to 2 decimals?

Here is a simple one-line solution

((int) ((value + 0.005f) * 100)) / 100f

Checking if a file is a directory or just a file

Use the S_ISDIRmacro:

int isDirectory(const char *path) {
   struct stat statbuf;
   if (stat(path, &statbuf) != 0)
       return 0;
   return S_ISDIR(statbuf.st_mode);
}

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Automatically run %matplotlib inline in IPython Notebook

Create any .py file in ~/.ipython/profile_default/startup/ containing

get_ipython().magic('matplotlib inline')

Where are logs located?

In Laravel 6, by default the logs are in:

storage/logs/laravel.log

Has Facebook sharer.php changed to no longer accept detailed parameters?

Facebook no longer supports custom parameters in sharer.php

The sharer will no longer accept custom parameters and facebook will pull the information that is being displayed in the preview the same way that it would appear on facebook as a post from the url OG meta tags.

Use dialog/feeds instead of sharer.php

https://www.facebook.com/dialog/feed?
  app_id=145634995501895
  &display=popup&caption=An%20example%20caption 
  &link=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2Fdialogs%2F
  &redirect_uri=https://developers.facebook.com/tools/explorer

Official answer from fb team

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

Format the date using Ruby on Rails

Here's my go at answering this,

so first you will need to convert the timestamp to an actual Ruby Date/Time. If you receive it just as a string or int from facebook, you will need to do something like this:

my_date = Time.at(timestamp_from_facebook.to_i)

OK, so now assuming you already have your date object...

to_formatted_s is a handy Ruby function that turns dates into formatted strings.

Here are some examples of its usage:

time = Time.now                     # => Thu Jan 18 06:10:17 CST 2007    

time.to_formatted_s(:time)          # => "06:10"
time.to_s(:time)                    # => "06:10"    

time.to_formatted_s(:db)            # => "2007-01-18 06:10:17"
time.to_formatted_s(:number)        # => "20070118061017"
time.to_formatted_s(:short)         # => "18 Jan 06:10"
time.to_formatted_s(:long)          # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal)  # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822)        # => "Thu, 18 Jan 2007 06:10:17 -0600"

As you can see: :db, :number, :short ... are custom date formats.

To add your own custom format, you can create this file: config/initializers/time_formats.rb and add your own formats there, for example here's one:

Date::DATE_FORMATS[:month_day_comma_year] = "%B %e, %Y" # January 28, 2015

Where :month_day_comma_year is your format's name (you can change this to anything you want), and where %B %e, %Y is unix date format.

Here's a quick cheatsheet on unix date syntax, so you can quickly setup your custom format:

From http://linux.die.net/man/3/strftime    

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %e - Day of the month without leading 0 (1..31) 
  %g - Year in YY (00-99)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character    

   t = Time.now
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM"

Hope this helped you. I've also made a github gist of this little guide, in case anyone prefers.

Form submit with AJAX passing form data to PHP without page refresh

The form is submitting after the ajax request.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'post.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input name="time" value="00:00:00.00"><br>
      <input name="date" value="0000-00-00"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

The POM for project is missing, no dependency information available

Change:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

To:

<!-- ANT4X -->
<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

The groupId of net.sourceforge was incorrect. The correct value is net.sourceforge.ant4x.

Python Dictionary Comprehension

>>> {i:i for i in range(1, 11)}
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}

Strip double quotes from a string in .NET

This worked for me

//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);

//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;

Order of execution of tests in TestNG

Use this:

public class TestNG
{
        @BeforeTest
        public void setUp() 
        {
                   /*--Initialize broowsers--*/

        }

        @Test(priority=0)
        public void Login() 
        {

        }

        @Test(priority=2)
        public void Logout() 
        {

        }

        @AfterTest
        public void tearDown() 
        {
                //--Close driver--//

        }

}

Usually TestNG provides number of annotations, We can use @BeforeSuite, @BeforeTest, @BeforeClass for initializing browsers/setup.

We can assign priority if you have written number of test cases in your script and want to execute as per assigned priority then use: @Test(priority=0) starting from 0,1,2,3....

Meanwhile we can group number of test cases and execute it by grouping. for that we will use @Test(Groups='Regression')

At the end like closing the browsers we can use @AfterTest, @AfterSuite, @AfterClass annotations.

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

PDO mysql: How to know if insert was successful

Given that most recommended error mode for PDO is ERRMODE_EXCEPTION, no direct execute() result verification will ever work. As the code execution won't even reach the condition offered in other answers.

So, there are three possible scenarios to handle the query execution result in PDO:

  1. To tell the success, no verification is needed. Just keep with your program flow.
  2. To handle the unexpected error, keep with the same - no immediate handling code is needed. An exception will be thrown in case of a database error, and it will bubble up to the site-wide error handler that eventually will result in a common 500 error page.
  3. To handle the expected error, like a duplicate primary key, and if you have a certain scenario to handle this particular error, then use a try..catch operator.

For a regular PHP user it sounds a bit alien - how's that, not to verify the direct result of the operation? - but this is exactly how exceptions work - you check the error somewhere else. Once for all. Extremely convenient.

So, in a nutshell: in a regular code you don't need any error handling at all. Just keep your code as is:

$stmt->bindParam(':field1', $field1, PDO::PARAM_STR);
$stmt->bindParam(':field2', $field2, PDO::PARAM_STR);
$stmt->execute();
echo "Success!"; // whatever

On success it will tell you so, on error it will show you the regular error page that your application is showing for such an occasion.

Only in case you have a handling scenario other than just reporting the error, put your insert statement in a try..catch operator, check whether it was the error you expected and handle it; or - if the error was any different - re-throw the exception, to make it possible to be handled by the site-wide error handler usual way. Below is the example code from my article on error handling with PDO:

try {
     $pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
    if ($e->getCode() == 1062) {
        // Take some action if there is a key constraint violation, i.e. duplicate name
    } else {
        throw $e;
    }
}
echo "Success!";

In the code above we are checking for the particular error to take some action and re-throwing the exception for the any other error (no such table for example) which will be reported to a programmer.

While again - just to tell a user something like "Your insert was successful" no condition is ever needed.

How to find the operating system version using JavaScript?

You can use this javascript function to check users' OS simply

  function getOS() {
  var userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'],
      os = null;

  if (macosPlatforms.indexOf(platform) !== -1) {
    os = 'Mac OS';
  } else if (iosPlatforms.indexOf(platform) !== -1) {
    os = 'iOS';
  } else if (windowsPlatforms.indexOf(platform) !== -1) {
    os = 'Windows';
  } else if (/Android/.test(userAgent)) {
    os = 'Android';
  } else if (!os && /Linux/.test(platform)) {
    os = 'Linux';
  }

  return os;
}

alert(getOS());

How to put a Scanner input into an array... for example a couple of numbers

**Simple solution**
public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int size;
    System.out.println("Enter the number of size of array");
    size = sc.nextInt();
    int[] a = new int[size];
    System.out.println("Enter the array element");
    //For reading the element
    for(int i=0;i<size;i++) {
        a[i] = sc.nextInt();
    }
    //For print the array element
    for(int i : a) {
        System.out.print(i+" ,");
    }
}

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

Better way to shuffle two numpy arrays in unison

Your can use NumPy's array indexing:

def unison_shuffled_copies(a, b):
    assert len(a) == len(b)
    p = numpy.random.permutation(len(a))
    return a[p], b[p]

This will result in creation of separate unison-shuffled arrays.

<div> cannot appear as a descendant of <p>

Your component might be rendered inside another component (such as a <Typography> ... </Typography>). Therefore, it will load your component inside a <p> .. </p> which is not allowed.

Fix: Remove <Typography>...</Typography> because this is only used for plain text inside a <p>...</p> or any other text element such as headings.

Vector of Vectors to create matrix

try this. m = row, n = col

vector<vector<int>> matrix(m, vector<int>(n));

for(i = 0;i < m; i++)
{
   for(j = 0; j < n; j++)
   {
      cin >> matrix[i][j];
   }
   cout << endl;
}
cout << "::matrix::" << endl;
for(i = 0; i < m; i++)
{
    for(j = 0; j < n; j++)
    {
        cout << matrix[i][j] << " ";
    }
    cout << endl;
}

Get Max value from List<myType>

Easiest way is to use System.Linq as previously described

using System.Linq;

public int GetHighestValue(List<MyTypes> list)
{
    return list.Count > 0 ? list.Max(t => t.Age) : 0; //could also return -1
}

This is also possible with a Dictionary

using System.Linq;

public int GetHighestValue(Dictionary<MyTypes, OtherType> obj)
{
    return obj.Count > 0 ? obj.Max(t => t.Key.Age) : 0; //could also return -1
}

How to set a reminder in Android?

Android complete source code for adding events and reminders with start and end time format.

/** Adds Events and Reminders in Calendar. */
private void addReminderInCalendar() {
    Calendar cal = Calendar.getInstance();
    Uri EVENTS_URI = Uri.parse(getCalendarUriBase(true) + "events");
    ContentResolver cr = getContentResolver();
    TimeZone timeZone = TimeZone.getDefault();

    /** Inserting an event in calendar. */
    ContentValues values = new ContentValues();
    values.put(CalendarContract.Events.CALENDAR_ID, 1);
    values.put(CalendarContract.Events.TITLE, "Sanjeev Reminder 01");
    values.put(CalendarContract.Events.DESCRIPTION, "A test Reminder.");
    values.put(CalendarContract.Events.ALL_DAY, 0);
    // event starts at 11 minutes from now
    values.put(CalendarContract.Events.DTSTART, cal.getTimeInMillis() + 11 * 60 * 1000);
    // ends 60 minutes from now
    values.put(CalendarContract.Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
    values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
    values.put(CalendarContract.Events.HAS_ALARM, 1);
    Uri event = cr.insert(EVENTS_URI, values);

    // Display event id
    Toast.makeText(getApplicationContext(), "Event added :: ID :: " + event.getLastPathSegment(), Toast.LENGTH_SHORT).show();

    /** Adding reminder for event added. */
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(true) + "reminders");
    values = new ContentValues();
    values.put(CalendarContract.Reminders.EVENT_ID, Long.parseLong(event.getLastPathSegment()));
    values.put(CalendarContract.Reminders.METHOD, Reminders.METHOD_ALERT);
    values.put(CalendarContract.Reminders.MINUTES, 10);
    cr.insert(REMINDERS_URI, values);
}

/** Returns Calendar Base URI, supports both new and old OS. */
private String getCalendarUriBase(boolean eventUri) {
    Uri calendarURI = null;
    try {
        if (android.os.Build.VERSION.SDK_INT <= 7) {
            calendarURI = (eventUri) ? Uri.parse("content://calendar/") : Uri.parse("content://calendar/calendars");
        } else {
            calendarURI = (eventUri) ? Uri.parse("content://com.android.calendar/") : Uri
                    .parse("content://com.android.calendar/calendars");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return calendarURI.toString();
}

Add permission to your Manifest file.

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

How do I make a newline after a twitter bootstrap element?

May be the solution could be use a padding property.

<div class="well span6" style="padding-top: 50px">
    <h3>I wish this appeared on the next line without having to 
        gratuitously use BR!
    </h3>
</div>

C# LINQ find duplicates in List

Linq query:

var query = from s2 in (from s in someList group s by new { s.Column1, s.Column2 } into sg select sg) where s2.Count() > 1 select s2;

How to create a file in a directory in java?

String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
    File f = new File(path);
    File f1 = new File(fname);

    f.mkdirs() ;
    try {
        f1.createNewFile();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

This should create a new file inside a directory

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

How to initialize log4j properly?

This is an alternative way using .yaml

Logic Structure:

Configuration:
    Properties:
    Appenders:
    Loggers:

Sample:

Configutation:
    name: Default

    Properties:
        Property:
            name: log-path
            value: "logs"

    Appenders:

        Console:
        name: Console_Appender
        target: SYSTEM_OUT
        PatternLayout:
            pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

       File:
          name: File_Appender
          fileName: ${log-path}/logfile.log
          PatternLayout:
            pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    Loggers:

        Root:
            level: debug
            AppenderRef:
              - ref: Console_Appender

        Logger:
            - name: <package>.<subpackage>.<subsubpackage>.<...>
              level: debug
              AppenderRef:
                 - ref: File_Appender
                 level: error             

Ref: LOG4J 2 CONFIGURATION: USING YAML

Horizontal Scroll Table in Bootstrap/CSS

Here is one possiblity for you if you are using Bootstrap 3

live view: http://fiddle.jshell.net/panchroma/vPH8N/10/show/

edit view: http://jsfiddle.net/panchroma/vPH8N/

I'm using the resposive table code from http://getbootstrap.com/css/#tables-responsive

ie:

<div class="table-responsive">
<table class="table">
...
</table>
</div>

Find the version of an installed npm package

Access the package.json

You can access the package.json or bower.json of the package with:

notepad ./node_modules/:packageName/package.json

This will open the package.json in notepad which has the version number of the :packageName you included in the command.

For example :

notepad ./node_modules/vue-template-compiler/package.json

Good Luck.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

git: 'credential-cache' is not a git command

We had the same issue with our Azure DevOps repositories after our domain changed, i.e. from @xy.com to @xyz.com. To fix this issue, we generated a fresh personal access token with the following permissions:

Code: read & write Packaging: read

Then we opened the Windows Credential Manager, added a new generic windows credential with the following details:

Internet or network address: "git:{projectname}@dev.azure.com/{projectname}" - alternatively you should use your git repository name here.
User name: "Personal Access Token"
Password: {The generated Personal Access Token}

Afterwards all our git operations were working again. Hope this helps someone else!

Simple proof that GUID is not unique

Here's a solution, too:

int main()
{
  QUuid uuid;
  while ( (uuid = QUuid::createUuid()) != QUuid::createUuid() ) { }
  std::cout << "Aha! I've found one! " << qPrintable( uuid.toString() ) << std::endl;
}

Note: requires Qt, but I guarantee that if you let it run long enough, it might find one.

(Note note: actually, now that I'm looking at it, there may be something about the generation algorithm that prevents two subsequently generated uuids that collide--but I kinda doubt it).

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Here is how you can trigger a block after a delay in Swift:

runThisAfterDelay(seconds: 2) { () -> () in
    print("Prints this 2 seconds later in main queue")
}

/// EZSwiftExtensions
func runThisAfterDelay(seconds seconds: Double, after: () -> ()) {
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC)))
    dispatch_after(time, dispatch_get_main_queue(), after)
}

Its included as a standard function in my repo.

Use chrome as browser in C#?

I use Awesomium, I think it is better than GeckoFX/WebKit http://awesomium.com

Entity Framework - Include Multiple Levels of Properties

I also had to use multiple includes and at 3rd level I needed multiple properties

(from e in context.JobCategorySet
                      where e.Id == id &&
                            e.AgencyId == agencyId
                      select e)
                      .Include(x => x.JobCategorySkillDetails)
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.DurationType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RuleType))
                      .Include(x => x.Shifts.Select(r => r.Rate).Select(rt => rt.RateType))
                      .FirstOrDefaultAsync();

This may help someone :)

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.

A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.

A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :

A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.

An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.

MySQL: How to reset or change the MySQL root password?

At first run this command:

sudo mysql

and then you should check which authentication method of your MySQL user accounts use.So run this command

SELECT user,authentication_string,plugin,host FROM mysql.user;

now you can see something like this already :

+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             |                                           | auth_socket           | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+

in the table that is in the above , you can see that all of your mysql users accounts status & if you have set a password for root account before you see mysql_native_password in plugin column instead auth_socket. All in all for change your root password you should run :

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Be sure to change password to a strong password of your choosing. Then for reload your server to put your new changes into effect run this;

FLUSH PRIVILEGES;

So again check the authentication methods which has employed by your mysql , by this command:

SELECT user,authentication_string,plugin,host FROM mysql.user;

and now the output is :

+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             | *3636DACC8616D997782ADD0839F92C1571D6D78F | mysql_native_password | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+

as you can see in the grant table your root account has mysql_native_password . now you can exit MYSQL shell

exit;

That's it.just you should restart mysql by sudo service mysql restart. Now you can login to mysql as a root account with your password easily.

How do I check in JavaScript if a value exists at a certain array index?

With Lodash, you can do:

if(_.has(req,'documents')){
      if (req.documents.length)
      _.forEach(req.documents, function(document){
        records.push(document);
      });
} else {
}

if(_.has(req,'documents')) is to check whether our request object has a property named documents and if it has that prop, the next if (req.documents.length) is to validate if it is not an empty array, so the other stuffs like forEach can be proceeded.

Truncate number to two decimal places without rounding

Roll your own toFixed function: for positive values Math.floor works fine.

function toFixed(num, fixed) {
    fixed = fixed || 0;
    fixed = Math.pow(10, fixed);
    return Math.floor(num * fixed) / fixed;
}

For negative values Math.floor is round of the values. So you can use Math.ceil instead.

Example,

Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.

Hibernate Criteria for Dates

Why do you use Restrictions.like(...)?

You should use Restrictions.eq(...).

Note you can also use .le, .lt, .ge, .gt on date objects as comparison operators. LIKE operator is not appropriate for this case since LIKE is useful when you want to match results according to partial content of a column. Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.

For example if you have a name column with some people's full name, you can do where name like 'robert %' so that you will return all entries with name starting with 'robert ' (% can replace any character).

In your case you know the full content of the date you're trying to match so you shouldn't use LIKE but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...).

Your date object you got with the code:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);

This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.

This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".

If you want to retrieve all entries of your database from a given day, you will have to use the following code:

    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
    String myDate = "17-04-2011";
    // Create date 17-04-2011 - 00h00
    Date minDate = formatter.parse(myDate);
    // Create date 18-04-2011 - 00h00 
    // -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
    Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
    Conjunction and = Restrictions.conjunction();
    // The order date must be >= 17-04-2011 - 00h00
    and.add( Restrictions.ge("orderDate", minDate) );
    // And the order date must be < 18-04-2011 - 00h00
    and.add( Restrictions.lt("orderDate", maxDate) ); 

How to pad zeroes to a string?

When using Python >= 3.6, the cleanest way is to use f-strings with string formatting:

>>> s = f"{1:08}"  # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}"  # inline with str
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}"  # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}"  # str variable
>>> s
'00000001'

I would prefer formatting with an int, since only then the sign is handled correctly:

>>> f"{-1:08}"
'-0000001'

>>> f"{1:+08}"
'+0000001'

>>> f"{'-1':0>8}"
'000000-1'

Converting JSONarray to ArrayList

I have fast solution. Just create a file ArrayUtil.java

import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;

public class ArrayUtil
{
    public static ArrayList<Object> convert(JSONArray jArr)
    {
        ArrayList<Object> list = new ArrayList<Object>();
        try {
            for (int i=0, l=jArr.length(); i<l; i++){
                 list.add(jArr.get(i));
            }
        } catch (JSONException e) {}

        return list;
    }

    public static JSONArray convert(Collection<Object> list)
    {
        return new JSONArray(list);
    }

}

Usage:

ArrayList<Object> list = ArrayUtil.convert(jArray);

or

JSONArray jArr = ArrayUtil.convert(list);

How to use andWhere and orWhere in Doctrine?

Here's an example for those who have more complicated conditions and using Doctrine 2.* with QueryBuilder:

$qb->where('o.foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('o.bar', 1),
      $qb->expr()->eq('o.bar', 2)
   ))
  ;

Those are expressions mentioned in Czechnology answer.

How do I rename a column in a database table using SQL?

ALTER TABLE is standard SQL. But it's not completely implemented in many database systems.

How do I export (and then import) a Subversion repository?

Basically, there are plenty of ways to accomplish the task. The topic is covered in depth in SVNBook | Migrating Repository Data Elsewhere, so I suggest reading the book's section.

Here is a brief description of your options:

  • It depends on your environment, but there is a great chance that you can simply copy the repository to the new server and it will work. You have to revise repository hook scripts after copying the repo to ensure that they are working as you expect.

  • You can use svnadmin dump and svnadmin load commands to, ehm, generate full dump and then load it to another repository on another server. You will need to svnadmin create a new clean repository to load the dump into it. Keep in mind that the approach deals with repository history only and does not move hook scripts and repository configuration files! As well, you must have read filesystem access to the original repository to dump it.

  • Since Subversion 1.7, svnrdump tool is available. Generally speaking, it mimics svnadmin dump and svnadmin load functionality, but operates remotely. You are not required to have read / write filesystem access to original and target repositories as tool operates remotely like Subversion client, e.g. over HTTPS protocol. So you need to have read access to original repository and read / write to the target one.

  • Another option is to use svnadmin hotcopy command. The command is mostly used for backup purpose, it creates full copy of the repository including configuration and hook scripts. You can move hotcopied repository to another server then.

How do I use setsockopt(SO_REUSEADDR)?

I think you should use SO_LINGER options (with timeout 0). In this case, you connection will close immediately after closing your program; and next restart will be able to bind again.

example:

linger lin;
lin.l_onoff = 0;
lin.l_linger = 0;
setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&lin, sizeof(int));

see definition: http://man7.org/linux/man-pages/man7/socket.7.html

SO_LINGER
          Sets or gets the SO_LINGER option.  The argument is a linger
          structure.

              struct linger {
                  int l_onoff;    /* linger active */
                  int l_linger;   /* how many seconds to linger for */
              };

          When enabled, a close(2) or shutdown(2) will not return until
          all queued messages for the socket have been successfully sent
          or the linger timeout has been reached.  Otherwise, the call
          returns immediately and the closing is done in the background.
          When the socket is closed as part of exit(2), it always
          lingers in the background.

More about SO_LINGER: TCP option SO_LINGER (zero) - when it's required

How to run .APK file on emulator

You need to install the APK on the emulator. You can do this with the adb command line tool that is included in the Android SDK.

adb -e install -r yourapp.apk

Once you've done that you should be able to run the app.

The -e and -r flags might not be necessary. They just specify that you are using an emulator (if you also have a device connected) and that you want to replace the app if it already exists.

Location of WSDL.exe

It is included with .NET (not sure if only in the SDK).

syntax error: unexpected token <

This usually happens when you're including or posting to a file which doesn't exist. The server will return a regular html-formatted "404 Not Found" enclosed with

'<html></html>' 

tags. That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.

What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?

EDIT (several years later)

The root cause might not always come from 404 errors. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned

{
   error: "you must be authenticated to make this request"
}

With header 401. And instead I got

<html>You must be authenticated to make this request</html>

With header 200.

Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

Python argparse command line flags without arguments

Your script is right. But by default is of None type. So it considers true of any other value other than None is assigned to args.argument_name variable.

I would suggest you to add a action="store_true". This would make the True/False type of flag. If used its True else False.

import argparse
parser = argparse.ArgumentParser('parser-name')
parser.add_argument("-f","--flag",action="store_true",help="just a flag argument")

usage

$ python3 script.py -f

After parsing when checked with args.f it returns true,

args = parser.parse_args()
print(args.f)
>>>true

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

enter image description here

Considering the particular column Amount in the above table is of integer type. The following would be a solution :

df['Amount'] = df.Amount.fillna(0).astype(int)

Similarly, you can fill it with various data types like float, str and so on.

In particular, I would consider datatype to compare various values of the same column.

How to vertically align text inside a flexbox?

It's depend on your li height just call one more thing line height

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
}

html,
body {
  height: 100%;
}

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  align-self: center;
  background: silver;
  width: 100%;
  height:50px;line-height:50px;
}
_x000D_
<ul>
  <li>This is the text</li>
</ul>
_x000D_
_x000D_
_x000D_

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

You have not accepted the license agreements of the following SDK components

For Windows users w/o using Andoid Studio:

  1. Go to the location of your sdkmanager.bat file. Per default it is at Android\sdk\tools\bin inside the %LOCALAPPDATA% folder.

  2. Open a terminal window there by typing cmd into the title bar

  3. Type

    sdkmanager.bat --licenses
    
  4. Accept all licenses with 'y'

Concatenating strings in C, which method is more efficient?

sprintf() is designed to handle far more than just strings, strcat() is specialist. But I suspect that you are sweating the small stuff. C strings are fundamentally inefficient in ways that make the differences between these two proposed methods insignificant. Read "Back to Basics" by Joel Spolsky for the gory details.

This is an instance where C++ generally performs better than C. For heavy weight string handling using std::string is likely to be more efficient and certainly safer.

[edit]

[2nd edit]Corrected code (too many iterations in C string implementation), timings, and conclusion change accordingly

I was surprised at Andrew Bainbridge's comment that std::string was slower, but he did not post complete code for this test case. I modified his (automating the timing) and added a std::string test. The test was on VC++ 2008 (native code) with default "Release" options (i.e. optimised), Athlon dual core, 2.6GHz. Results:

C string handling = 0.023000 seconds
sprintf           = 0.313000 seconds
std::string       = 0.500000 seconds

So here strcat() is faster by far (your milage may vary depending on compiler and options), despite the inherent inefficiency of the C string convention, and supports my original suggestion that sprintf() carries a lot of baggage not required for this purpose. It remains by far the least readable and safe however, so when performance is not critical, has little merit IMO.

I also tested a std::stringstream implementation, which was far slower again, but for complex string formatting still has merit.

Corrected code follows:

#include <ctime>
#include <cstdio>
#include <cstring>
#include <string>

void a(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
    {
        strcpy(both, first);
        strcat(both, " ");
        strcat(both, second);
    }
}

void b(char *first, char *second, char *both)
{
    for (int i = 0; i != 1000000; i++)
        sprintf(both, "%s %s", first, second);
}

void c(char *first, char *second, char *both)
{
    std::string first_s(first) ;
    std::string second_s(second) ;
    std::string both_s(second) ;

    for (int i = 0; i != 1000000; i++)
        both_s = first_s + " " + second_s ;
}

int main(void)
{
    char* first= "First";
    char* second = "Second";
    char* both = (char*) malloc((strlen(first) + strlen(second) + 2) * sizeof(char));
    clock_t start ;

    start = clock() ;
    a(first, second, both);
    printf( "C string handling = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    b(first, second, both);
    printf( "sprintf           = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    start = clock() ;
    c(first, second, both);
    printf( "std::string       = %f seconds\n", (float)(clock() - start)/CLOCKS_PER_SEC) ;

    return 0;
}

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

first you need to find out what the actual problem was. what you're seeing is that the C compiler failed but you don't yet know why. scroll up to where you get the original error. in my case, trying to install some packages using pip3, I found:

    Complete output from command /usr/bin/python3 -c "import setuptools, tokenize;__file__='/tmp/pip-build-4u59c_8b/cryptography/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-itjeh3va-record/install-record.txt --single-version-externally-managed --compile --user:
    c/_cffi_backend.c:15:17: fatal error: ffi.h: No such file or directory

 #include <ffi.h>

                 ^

compilation terminated.

so in my case I needed to install libffi-dev.

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

Android: Access child views from a ListView

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

Example:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

you need to add comments and associate with an artifact id with no return key at the end. for example, [artf12345] - your comments.

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

For the UPDATE

Use:

UPDATE table1 
   SET col1 = othertable.col2,
       col2 = othertable.col3 
  FROM othertable 
 WHERE othertable.col1 = 123;

For the INSERT

Use:

INSERT INTO table1 (col1, col2) 
SELECT col1, col2 
  FROM othertable

You don't need the VALUES syntax if you are using a SELECT to populate the INSERT values.

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

how to make log4j to write to the console as well

Your log4j File should look something like below read comments.

# Define the types of logger and level of logging    
log4j.rootLogger = DEBUG,console, FILE

# Define the File appender    
log4j.appender.FILE=org.apache.log4j.FileAppender    

# Define Console Appender    
log4j.appender.console=org.apache.log4j.ConsoleAppender    

# Define the layout for console appender. If you do not 
# define it, you will get an error    
log4j.appender.console.layout=org.apache.log4j.PatternLayout

# Set the name of the file    
log4j.appender.FILE.File=log.out

# Set the immediate flush to true (default)    
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode    
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite    
log4j.appender.FILE.Append=false

# Define the layout for file appender    
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout    
log4j.appender.FILE.layout.conversionPattern=%m%n

HTML5 Canvas Rotate Image

@Steve Farthing's answer is absolutely right.

But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
    if(angleInDegrees == 360){  // add this lines
        angleInDegrees = 0
    }
});

Then you will get the desired result. Thanks. Hope this will help someone :)

How to format a QString?

You can use the sprintf method, however the arg method is preferred as it supports unicode.

QString str;
str.sprintf("%s %d", "string", 213);

The smallest difference between 2 Angles

An efficient code in C++ that works for any angle and in both: radians and degrees is:

inline double getAbsoluteDiff2Angles(const double x, const double y, const double c)
{
    // c can be PI (for radians) or 180.0 (for degrees);
    return c - fabs(fmod(fabs(x - y), 2*c) - c);
}

allowing only alphabets in text box using java script

You can use HTML5 pattern attribute to do this:

<form>
    <input type='text' pattern='[A-Za-z\\s]*'/>
</form>

If the user enters an input that conflicts with the pattern, it will show an error dialogue automatically.

Conditional WHERE clause in SQL Server

Try this

SELECT 
    DateAppr,
    TimeAppr,
    TAT,
    LaserLTR,
    Permit,
    LtrPrinter,
    JobName,
    JobNumber,
    JobDesc,
    ActQty,
    (ActQty-LtrPrinted) AS L,
    (ActQty-QtyInserted) AS M,
    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM 
    [test].[dbo].[MM]
WHERE 
    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    OR 
    (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

You can read more about conditional WHERE here.

Python date string to date object

Use time module to convert data.

Code snippet:

import time 
tring='20150103040500'
var = int(time.mktime(time.strptime(tring, '%Y%m%d%H%M%S')))
print var

Docker container will automatically stop after "docker run -d"

The centos dockerfile has a default command bash.

That means, when run in background (-d), the shell exits immediately.

Update 2017

More recent versions of docker authorize to run a container both in detached mode and in foreground mode (-t, -i or -it)

In that case, you don't need any additional command and this is enough:

docker run -t -d centos

The bash will wait in the background.
That was initially reported in kalyani-chaudhari's answer and detailed in jersey bean's answer.

vonc@voncvb:~$ d ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
4a50fd9e9189        centos              "/bin/bash"         8 seconds ago       Up 2 seconds                            wonderful_wright

Note that for alpine, Marinos An reports in the comments:

docker run -t -d alpine/git does not keep the process up.
Had to do: docker run --entrypoint "/bin/sh" -it alpine/git


Original answer (2015)

As mentioned in this article:

Instead of running with docker run -i -t image your-command, using -d is recommended because you can run your container with just one command and you don’t need to detach terminal of container by hitting Ctrl + P + Q.

However, there is a problem with -d option. Your container immediately stops unless the commands keep running in foreground.
Docker requires your command to keep running in the foreground. Otherwise, it thinks that your applications stops and shutdown the container.

The problem is that some application does not run in the foreground. How can we make it easier?

In this situation, you can add tail -f /dev/null to your command.
By doing this, even if your main command runs in the background, your container doesn’t stop because tail is keep running in the foreground.

So this would work:

docker run -d centos tail -f /dev/null

A docker ps would show the centos container still running.

From there, you can attach to it or detach from it (or docker exec some commands).

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

How can I get a favicon to show up in my django app?

Now(in 2020), You could add a base tag in html file.

<head>
<base href="https://www.example.com/static/"> 
</head>

How to group by month from Date field using sql

Use the DATEPART function to extract the month from the date.

So you would do something like this:

SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)

Remove directory from remote repository after adding them to .gitignore

As per my Answer here: How to remove a directory from git repository?

To remove folder/directory only from git repository and not from the local try 3 simple steps.


Steps to remove directory

git rm -r --cached FolderName
git commit -m "Removed folder from repository"
git push origin master

Steps to ignore that folder in next commits

To ignore that folder from next commits make one file in root named .gitignore and put that folders name into it. You can put as many as you want

.gitignore file will be look like this

/FolderName

remove directory

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

Difference between frontend, backend, and middleware in web development

In terms of networking and security, the Backend is by far the most (should be) secure node.

The middle-end portion, usually being a web server, will be somewhat in the wild and cut off in many respects from a company's network. The middle-end node is usually placed in the DMZ and segmented from the network with firewall settings. Most of the server-side code parsing of web pages is handled on the middle-end web server.

Getting to the backend means going through the middle-end, which has a carefully crafted set of rules allowing/disallowing access to the vital nummies which are stored on the database (backend) server.

Calling virtual functions inside constructors

Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual . .another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.

  1. Virtual functions are used to assign value dynamically,as constructors are static,so we can not make them virtual.

Import SQL dump into PostgreSQL database

Just for funsies, if your dump is compressed you can do something like

gunzip -c filename.gz | psql dbname

As Jacob mentioned, the PostgreSQL docs describe all this quite well.

How to use protractor to check if an element is visible?

The correct way for checking the visibility of an element with Protractor is to call the isDisplayed method. You should be careful though since isDisplayed does not return a boolean, but rather a promise providing the evaluated visibility. I've seen lots of code examples that use this method wrongly and therefore don't evaluate its actual visibility.

Example for getting the visibility of an element:

element(by.className('your-class-name')).isDisplayed().then(function (isVisible) {
    if (isVisible) {
        // element is visible
    } else {
        // element is not visible
    }
});

However, you don't need this if you are just checking the visibility of the element (as opposed to getting it) because protractor patches Jasmine expect() so it always waits for promises to be resolved. See github.com/angular/jasminewd

So you can just do:

expect(element(by.className('your-class-name')).isDisplayed()).toBeTruthy();

Since you're using AngularJS to control the visibility of that element, you could also check its class attribute for ng-hide like this:

var spinner = element.by.css('i.icon-spin');
expect(spinner.getAttribute('class')).not.toMatch('ng-hide'); // expect element to be visible

What is the difference between React Native and React?

React is use for web application those work in browser. React Native is use for android and IOS application those work in mobile apps.

jQuery get values of checked checkboxes into array

DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

How to get the hours difference between two date objects?

Try using getTime (mdn doc) :

var diff = Math.abs(date1.getTime() - date2.getTime()) / 3600000;
if (diff < 18) { /* do something */ }

Using Math.abs() we don't know which date is the smallest. This code is probably more relevant :

var diff = (date1 - date2) / 3600000;
if (diff < 18) { array.push(date1); }

Concatenate two char* strings in a C program

When you use string literals, such as "this is a string" and in your case "sssss" and "kkkk", the compiler puts them in read-only memory. However, strcat attempts to write the second argument after the first. You can solve this problem by making a sufficiently sized destination buffer and write to that.

char destination[10]; // 5 times s, 4 times k, one zero-terminator
char* str1;
char* str2;
str1 = "sssss";
str2 = "kkkk";
strcpy(destination, str1);
printf("%s",strcat(destination,str2));

Note that in recent compilers, you usually get a warning for casting string literals to non-const character pointers.

Inserting an image with PHP and FPDF

$image="img_name.jpg";
$pdf =new FPDF();
$pdf-> AddPage();
$pdf-> SetFont("Arial","B",10);
$pdf-> Image('profileimage/'.$image,100,15,35,35);

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

Catch paste input

This is getting closer to what you might want.

function sanitize(s) {
  return s.replace(/\bfoo\b/g, "~"); 
};

$(function() {
 $(":text, textarea").bind("input paste", function(e) {
   try {
     clipboardData.setData("text",
       sanitize(clipboardData.getData("text"))
     );
   } catch (e) {
     $(this).val( sanitize( $(this).val() ) );
   }
 });
});

Please note that when clipboardData object is not found (on browsers other then IE) you are currently getting the element's full value + the clipboard'ed value.

You can probably do some extra steps to dif the two values, before an input & after the input, if you really are only after what data was truly pasted into the element.

Can we locate a user via user's phone number in Android?

Quick answer: No, at least not with native SMS service.

Long answer: Sure, but the receiver's phone should have the correct setup first. An app that detects incoming sms, and if a keyword matches, reports its current location to your server, which then pushes that info to the sender.

Transactions in .net

It also depends on what you need. For basic SQL transactions you could try doing TSQL transactions by using BEGIN TRANS and COMMIT TRANS in your code. That is the easiest way but it does have complexity and you have to be careful to commit properly (and rollback).

I would use something like

SQLTransaction trans = null;
using(trans = new SqlTransaction)
{
    ...
    Do SQL stuff here passing my trans into my various SQL executers
    ...
    trans.Commit  // May not be quite right
}

Any failure will pop you right out of the using and the transaction will always commit or rollback (depending on what you tell it to do). The biggest problem we faced was making sure it always committed. The using ensures the scope of the transaction is limited.

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

IIS error, Unable to start debugging on the webserver

If you can check your logs you should be able to get an error status and substatus.

Logs are usually located at %SystemDrive%\inetpub\logs\LogFiles

I just had to face a similar problem, looking at the log i've found:

2018-11-12 10:09:22 ::1 DEBUG /PPD/debugattach.aspx - 80 - ::1 - - 403 4 5 0

Here the status is 403 and substatus is 4, this table https://support.microsoft.com/en-ca/help/943891/the-http-status-code-in-iis-7-0-iis-7-5-and-iis-8-0 provided the knowledge to fix the problem! 403.4 is in fact SSL Required, once i've changed the project URL in Visual Studio from http to https (Project properties -> Web -> Server -> Project URL) the problem disappeared.

I've described my fix only to clarify the steps involved in fixing the issue, read all the answer and not just from "once i've changed the project URL..." and follow your logs!

Good luck!

How to add conditional attribute in Angular 2?

null removes it:

[attr.checked]="value ? '' : null"

or

[attr.checked]="value ? 'checked' : null"

Hint:

Attribute vs property

When the HTML element where you add this binding does not have a property with the name used in the binding (checked in this case) and also no Angular component or directive is applied to the same element that has an @Input() checked;, then [xxx]="..." can not be used.

See also What is the difference between properties and attributes in HTML?

What to bind to when there is no such property

Alternatives are [style.xxx]="...", [attr.xxx]="...", [class.xxx]="..." depending on what you try to accomplish.

Because <input> only has a checked attribute, but no checked property [attr.checked]="..." is the right way for this specific case.

Attributes can only handle string values

A common pitfall is also that for [attr.xxx]="..." bindings the value (...) is always stringified. Only properties and @Input()s can receive other value types like boolean, number, object, ...

Most properties and attributes of elements are connected and have the same name.

Property-attribute connection

When bound to the attribute the property also only receives the stringified value from the attribute.
When bound to the property the property receives the value bound to it (boolean, number, object, ...) and the attribute again the stringified value.

Two cases where attribute and property names do not match.

Angular was changed since then and knows about these special cases and handles them so that you can bind to <label [for]=" even though no such property exists (same for colspan)

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

How to Convert JSON object to Custom C# object?

To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

You'll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Angularjs ng-model doesn't work inside ng-if

You can use ngHide (or ngShow) directive. It doesn't create child scope as ngIf does.

<div ng-hide="testa">

Getting error "No such module" using Xcode, but the framework is there

The solution for me was. Inside of the targets -> Build Settings -> Framework Search Paths and adding $(inherited). However if it is a cocoapods your answer probably inside of output in terminal.

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

The backend version is not supported to design database diagrams or tables

I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:

USE [Database_Name]
GO

CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,

CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED 
(
[tableID] ASC
)
)

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

Android replace the current fragment with another fragment

Then provided your button is showing and the click event is being fired you can call the following in your click event:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.

ft.addToBackStack(null);

Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.

How to upgrade docker-compose to latest version

If you have homebrew you can also install via brew

$ brew install docker-compose

This is a good way to install on a Mac OS system

ASP.NET MVC - passing parameters to the controller

Your routing needs to be set up along the lines of {controller}/{action}/{firstItem}. If you left the routing as the default {controller}/{action}/{id} in your global.asax.cs file, then you will need to pass in id.

routes.MapRoute(
    "Inventory",
    "Inventory/{action}/{firstItem}",
    new { controller = "Inventory", action = "ListAll", firstItem = "" }
);

... or something close to that.

How to call jQuery function onclick?

JS

 $(function () {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
    $("#submit").click(function () {
        alert('button clicked');
    });
});

html

<input id="submit" type="submit" value="submit" name="submit">

Copy file(s) from one project to another using post build event...VS2010

xcopy "$(TargetDir)*$(TargetExt)" "$(SolutionDir)\Scripts\MigrationScripts\Library\" /F /R /Y /I

/F – Displays full source & target file names

/R – This will overwrite read-only files

/Y – Suppresses prompting to overwrite an existing file(s)

/I – Assumes that destination is directory (but must ends with )

A little trick – in target you must end with character \ to tell xcopy that target is directory and not file!

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Just ran into this problem. I don't know if it's the same thing that hit your code, but for me the root cause was because I forgot to put name= on the last argument of the url (or path in Django 2.0+) function call.

For instance, the following functions throw the error from the question:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), 'foo')
path('foo/{slug:bar}/', views.FooBar, 'foo')

But these actually work:

url(r'^foo/(?P<bar>[A-Za-z]+)/$', views.FooBar.as_view(), name='foo')
path('foo/{slug:bar}/', views.FooBar, name='foo')

The reason why the traceback is unhelpful is because internally, Django wants to parse the given positional argument as the keyword argument kwargs, and since a string is an iterable, an atypical code path begins to unfold. Always use name= on your urls!

How to see indexes for a database or table in MySQL?

I propose this query:

SELECT DISTINCT s.*
FROM INFORMATION_SCHEMA.STATISTICS s
LEFT OUTER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS t 
    ON t.TABLE_SCHEMA = s.TABLE_SCHEMA 
       AND t.TABLE_NAME = s.TABLE_NAME
       AND s.INDEX_NAME = t.CONSTRAINT_NAME 
WHERE 0 = 0
      AND t.CONSTRAINT_NAME IS NULL
      AND s.TABLE_SCHEMA = 'YOUR_SCHEMA_SAMPLE';

You found all Index only index.

Regard.

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

Easier way to debug a Windows service

For trouble-shooting on existing Windows Service program, use 'Debugger.Break()' as other guys suggested.

For new Windows Service program, I would suggest using James Michael Hare's method http://geekswithblogs.net/BlackRabbitCoder/archive/2011/03/01/c-toolbox-debug-able-self-installable-windows-service-template-redux.aspx

Git: How to check if a local repo is up to date?

If you use

git fetch --dry-run -v <link/to/remote/git/repo>

you'll get feedback about whether it is up-to-date. So basically, you just need to add the "verbose" option to the answer given before.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

What is the equivalent of "!=" in Excel VBA?

Just a note. If you want to compare a string with "" ,in your case, use

If LEN(str) > 0 Then

or even just

If LEN(str) Then

instead.

How to convert float value to integer in php?

What do you mean by converting?

  • casting*: (int) $float or intval($float)
  • truncating: floor($float) (down) or ceil($float) (up)
  • rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants

*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.

PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).

But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)

Undefined index error PHP

this error occurred sometime method attribute ( valid passing method ) Error option : method="get" but called by $Fname = $_POST["name"]; or

       method="post" but  called by  $Fname = $_GET["name"];

More info visit http://www.doordie.co.in/index.php

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

net::ERR_HTTP2_COMPRESSION_ERROR - WORDPRESS

Okay, I hope this will help many. I have been experiencing this for many weeks. My apology because I am using WordPress.

net::ERR_HTTP2_COMPRESSION_ERROR only occurs on Chrome:Incognito.

I have Cloudflare for my CDN and caching HTML - and W3 Total Cache - for minify js, css and Page Cache, OP-Cache, Object Cache, Browser Cache.

now, after countless of trouble shooting, I detected the issue when disabling the "Browser Cache" after that, I fixed the problem when

I modified the Browser Cache ( go to side panel )

find the ("HTTP Strict Transport Security policy") make sure its checked. under that is directive set the value to - max-age=EXPIRES_SECONDS; includeSubDomain: preload

take note that I am using sub-domain.

getCurrentPosition() and watchPosition() are deprecated on insecure origins

I know that the geoLocation API is better but for people whom can't use an SSL, you can still use some sort of services such as geopluginService.

as specified in the documentation you simply send a request with the ip to the service url http://www.geoplugin.net/php.gp?ip=xx.xx.xx.xx the output is a serialized array so you must need to unserialize it before using it.

Remember this service is not very accurate as the geoLocation is, but it is still an easy and fast solution.

CreateProcess: No such file or directory

I had a similar problem, caused by not installing the C++ compiler. In my case I was compiling .cpp files for a Python extension, but the compiler is first invoked as c:\mingw\bin\gcc.exe.

Internally, gcc.exe would notice it was asked to compile a .cpp file. It would try to call g++.exe and fail with the same error message:

gcc.exe: CreateProcess: no such file or directory

Add horizontal scrollbar to html table

First, make a display: block of your table

then, set overflow-x: to auto.

table {
    display: block;
    overflow-x: auto;
    white-space: nowrap;
}

Nice and clean. No superfluous formatting.

Here are more involved examples with scrolling table captions from a page on my website.

If an issue is taken about cells not filling the entire table, append the following additional CSS code:

table tbody {
    display: table;
    width: 100%;
}

Are arrays passed by value or passed by reference in Java?

Arrays are in fact objects, so a reference is passed (the reference itself is passed by value, confused yet?). Quick example:

// assuming you allocated the list
public void addItem(Integer[] list, int item) {
    list[1] = item;
}

You will see the changes to the list from the calling code. However you can't change the reference itself, since it's passed by value:

// assuming you allocated the list
public void changeArray(Integer[] list) {
    list = null;
}

If you pass a non-null list, it won't be null by the time the method returns.

HTTP 404 when accessing .svc file in IIS

I had to add the extension .svc to the allowed extensions in the request filtering settings (got 404.7 errors before).

enter image description here

Display a message in Visual Studio's output window when not debug mode?

This whole thread confused the h#$l out of me until I realized you have to be running the debugger to see ANY trace or debug output. I needed a debug output (outside of the debugger) because my WebApp runs fine when I debug it but not when the debugger isn't running (SqlDataSource is instantiated correctly when running through the debugger).

Just because debug output can be seen when you're running in release mode doesn't mean you'll see anything if you're not running the debugger. Careful reading of Writing to output window of Visual Studio? gave me DebugView as an alternative. Extremely useful!

Hopefully this helps anyone else confused by this.

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

Can't update: no tracked branch

Assume you have a local branch "Branch-200" (or other name) and server repository contains "origin/Branch-1". If you have local "Branch-1" not linked with "origin/Branch-1", rename it to "Branch-200".

In Android Studio checkout to "origin/Branch-1" creating a new local branch "Branch-1", then merge with you local branch "Branch-200".

Rendering HTML in a WebView with custom CSS

Is it possible to have all the content rendered in-page, in a given div? You could then reset the css based on the id, and work on from there.

Say you give your div id="ocon"

In your css, have a definition like:

#ocon *{background:none;padding:0;etc,etc,}

and you can set values to clear all css from applying to the content. After that, you can just use

#ocon ul{}

or whatever, further down the stylesheet, to apply new styles to the content.