Programs & Examples On #Html formatting

Remove all multiple spaces in Javascript and replace with single space

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

How to get .app file of a xcode application

The application will appear in your projects Build directory. In the source pane on the left of the Xcode window you should see a section called 'Products'. Listed under there will be your application name. If you right-click on this you can select 'Reveal in Finder' to be taken to the application in the Finder. You can send this to your friend directly and he can just copy it into his Applications folder. Most applications do not require an installer package on Mac OS X.

CMake does not find Visual C++ compiler

I had this issue with CMake GUI and the VS 21019 Community Edition. I think I may have installed CMake before Visual Studio - certainly after I updated CMake 3.15.2 to 3.15.3 the problem went away.

What's the difference between VARCHAR and CHAR?

CHAR is fixed length and VARCHAR is variable length. CHAR always uses the same amount of storage space per entry, while VARCHAR only uses the amount necessary to store the actual text.

React / JSX Dynamic Component Name

Suspose we wish to access various views with dynamic component loading.The following code gives a working example of how to accomplish this by using a string parsed from the search string of a url.

Lets assume we want to access a page 'snozberrys' with two unique views using these url paths:

'http://localhost:3000/snozberrys?aComponent'

and

'http://localhost:3000/snozberrys?bComponent'

we define our view's controller like this:

import React, { Component } from 'react';
import ReactDOM from 'react-dom'
import {
  BrowserRouter as Router,
  Route
} from 'react-router-dom'
import AComponent from './AComponent.js';
import CoBComponent sole from './BComponent.js';

const views = {
  aComponent: <AComponent />,
  console: <BComponent />
}

const View = (props) => {
  let name = props.location.search.substr(1);
  let view = views[name];
  if(view == null) throw "View '" + name + "' is undefined";
  return view;
}

class ViewManager extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path='/' component={View}/>
        </div>
      </Router>
    );
  }
}

export default ViewManager

ReactDOM.render(<ViewManager />, document.getElementById('root'));

Why does Firebug say toFixed() is not a function?

That is because Low is a string.

.toFixed() only works with a number.


Try doing:

Low = parseFloat(Low).toFixed(..);

How can I solve the error LNK2019: unresolved external symbol - function?

In Visual Studio 2017 if you want to test public members, simply put your real project and test project in the same solution, and add a reference to your real project in the test project.

See C++ Unit Testing in Visual Studio from the MSDN blog for more details. You can also check Write unit tests for C/C++ in Visual Studio as well as Use the Microsoft Unit Testing Framework for C++ in Visual Studio, the latter being if you need to test non public members and need to put the tests in the same project as your real code.

Note that things you want to test will need to be exported using __declspec(dllexport). See Exporting from a DLL Using __declspec(dllexport) for more details.

TransactionRequiredException Executing an update/delete query

Using @PersistenceContext with @Modifying as below fixes error while using createNativeQuery

    import org.springframework.data.jpa.repository.Modifying;
    import org.springframework.transaction.annotation.Transactional;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    @Modifying
    public <S extends T> S save(S entity) {
         Query q = entityManager.createNativeQuery(...);
         q.setParameter...
         q.executeUpdate();
         return entity;
    }

How to get a div to resize its height to fit container?

I had the same issue, I resolved it using some javascript.

<script type="text/javascript">
 var theHeight = $("#PrimaryContent").height() + 100;
 $('#SecondaryContent').height(theHeight);
</script>

What's a "static method" in C#?

From another point of view: Consider that you want to make some changes on a single String. for example you want to make the letters Uppercase and so on. you make another class named "Tools" for these actions. there is no meaning of making instance of "Tools" class because there is not any kind of entity available inside that class (compare to "Person" or "Teacher" class). So we use static keyword in order to use "Tools" class without making any instance of that, and when you press dot after class name ("Tools") you can have access to the methods you want.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Tools.ToUpperCase("Behnoud Sherafati"));
        Console.ReadKey();
    }
}

public static class Tools
{
    public static string ToUpperCase(string str)
    {
        return str.ToUpper();

    }
}
}

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

Oracle query to fetch column names

in oracle you can use

desc users

to display all columns containing in users table

Vba macro to copy row from table if value in table meets condition

you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.

You should always consider a non-vba solution first.

Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):

http://www.youtube.com/watch?v=RCLUM0UMLXo

http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx


If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.

If it has to be the latter, then there is need for more details on your specification, regarding performance questions.

You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.

This would look something like that:

Public Sub CopyFilter()

  Dim wks As Worksheet
  Dim avarTemp() As Variant
  'go through each worksheet
  For Each wks In ThisWorkbook.Worksheets
        avarTemp = wks.UsedRange
        For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
          'check in the first column in each row
          If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
            'copy cell
             targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
          End If
        Next i
  Next wks
End Sub

Ok, now i have something nice which could come in handy for myself:

Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
  Dim avarTemp() As Variant
  Dim avarResult() As Variant
  Dim i As Long
  avarTemp = rng

  ReDim avarResult(0)

  For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
      If avarTemp(i, 1) = "active" Then
        avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
        'expand our result array
        ReDim Preserve avarResult(UBound(avarResult) + 1)
      End If
  Next i

  FILTER = avarResult
End Function

You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)

Effective method to hide email from spam bots

One of my favorite methods is to obfuscate the email address using php, a classic example is to convert the characters to HEX values like so:

function myobfiscate($emailaddress){
 $email= $emailaddress;                
 $length = strlen($email);                         
 for ($i = 0; $i < $length; $i++){                
 $obfuscatedEmail .= "&#" . ord($email[$i]).";";
 }
 echo $obfuscatedEmail;
}

And then in my markup I'll simply call it as follows:

  <a href="mailto:<?php echo myobfiscate('[email protected]'); ?>"
title="Email me!"><?php echo myobfiscate('[email protected]');?> </a>

Then examine your source, you'll be pleasantly surprised!

Send mail via Gmail with PowerShell V2's Send-MailMessage

I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

## Send-Gmail.ps1 - Send a gmail message
## By Rodney Fisk - [email protected]
## 2 / 13 / 2011

# Get command line arguments to fill in the fields
# Must be the first statement in the script
param(
    [Parameter(Mandatory = $true,
               Position = 0,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('From')] # This is the name of the parameter e.g. -From [email protected]
    [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]

    [Parameter(Mandatory = $true,
               Position = 1,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('To')]
    [String[]]$Arry_EmailTo,

    [Parameter(Mandatory = $true,
               Position = 2,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Subj')]
    [String]$EmailSubj,

    [Parameter(Mandatory = $true,
               Position = 3,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Body')]
    [String]$EmailBody,

    [Parameter(Mandatory = $false,
               Position = 4,
               ValueFromPipelineByPropertyName = $true)]
    [Alias('Attachment')]
    [String[]]$Arry_EmailAttachments
)

# From Christian @ stackoverflow.com
$SMTPServer = "smtp.gmail.com"
$SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
$SMTPClient.EnableSSL = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");

# From Core @ stackoverflow.com
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
foreach ($recipient in $Arry_EmailTo)
{
    $emailMessage.To.Add($recipient)
}
$emailMessage.Subject = $EmailSubj
$emailMessage.Body = $EmailBody
# Do we have any attachments?
# If yes, then add them, if not, do nothing
if ($Arry_EmailAttachments.Count -ne $NULL)
{
    $emailMessage.Attachments.Add()
}
$SMTPClient.Send($emailMessage)

Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

How to place the ~/.composer/vendor/bin directory in your PATH?

add environment variable into bashrc file

For Ubuntu 17.04 and 17.10:

echo 'export PATH="~/.config/composer/vendor/bin"' >> ~/.bashrc

For Ubuntu 18.04

echo 'export PATH="$PATH:$HOME/.composer/vendor/bin"' >> ~/.bashrc

to Check environment variable working or not first reload the bashrc file

source ~/.bashrc

if not working any method then First Check Where is install Composer to Check Run This Command :

locate composer -l 1

then Copy Output add output into this line and run again command.

 echo 'export PATH="OUTPUTHERE/vendor/bin"' >> ~/.bashrc

After Successfully Laravel Command Work Give a Permission To Parent Folder (for example u are using apache server than give permission to apache web listing directory like that)

sudo chown $USER:$USER -R /var/www/html/

Setting default value in select drop-down using Angularjs

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

This would get you desired result Dude :) Cheers

How do I switch between command and insert mode in Vim?

This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.

Add a prefix string to beginning of each line

You can use Vim in Ex mode:

ex -sc '%s/^/prefix/|x' file
  1. % select all lines

  2. s replace

  3. x save and close

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

Git error: "Host Key Verification Failed" when connecting to remote repository

The solutions mentioned here are great, the only missing point is, what if your public and private key file names are different than the default ones?

Create a file called "config" under ~/.ssh and add the following contents

Host github.com
    IdentityFile ~/.ssh/github_id_rsa

Replace github_id_rsa with your private key file.

Disable Logback in SpringBoot

It might help if you say what your preferred logger is exactly, and what you did to try and install it. Anyway, Spring Boot tries to work with whatever is in the classpath, so if you don't want logback, take it off the classpath. There are instructions for log4j in the docs, but the same thing would apply to other supported logging systems (anything slf4j, log4j or java util).

Remove Primary Key in MySQL

First backup the database. Then drop any foreign key associated with the table. truncate the foreign key table.Truncate the current table. Remove the required primary keys. Use sqlyog or workbench or heidisql or dbeaver or phpmyadmin.

How do I resolve `The following packages have unmet dependencies`

The command to have Ubuntu fix unmet dependencies and broken packages is

sudo apt-get install -f

from the man page:

-f, --fix-broken Fix; attempt to correct a system with broken dependencies in place. This option, when used with install/remove, can omit any packages to permit APT to deduce a likely solution. If packages are specified, these have to completely correct the problem. The option is sometimes necessary when running APT for the first time; APT itself does not allow broken package dependencies to exist on a system. It is possible that a system's dependency structure can be so corrupt as to require manual intervention (which usually means using dselect(1) or dpkg --remove to eliminate some of the offending packages)

Ubuntu will try to fix itself when you run the command. When it completes, you can test if it worked by running the command again, and you should receive output similar to:

Reading package lists... Done Building dependency tree Reading state information... Done 0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.

Oracle Age calculation from Date of birth and Today

Suppose that you want to have the age (number of years only, a fixed number) of someone born on June 4, 1996, execute this command :

SELECT TRUNC(TO_NUMBER(SYSDATE - TO_DATE('04-06-1996')) / 365.25) AS AGE FROM DUAL;

Result : (Executed May 28, 2019)

       AGE
----------
        22

Explanation :

  • SYSDATE : Get system's (OS) actual date.
  • TO_DATE('04-06-1996') : Convert VARCHAR (string) birthdate into DATE (SQL type).
  • TO_NUMBER(...) : Convert a date to NUMBER (SQL type)
  • Devide per 365.25 : To have a bissextile year every four years (4 * 0.25 = 1 more day).
  • Trunc(...) : Retrieve the entire part only from a number.

Maven error "Failure to transfer..."

settings.xml for proxy? and in eclipse there are maven global\local profile, add the settings.xml

Get Android Device Name

@hbhakhra's answer will do.

If you're interested in detailed explanation, it is useful to look into Android Compatibility Definition Document. (3.2.2 Build Parameters)

You will find:

DEVICE - A value chosen by the device implementer containing the development name or code name identifying the configuration of the hardware features and industrial design of the device. The value of this field MUST be encodable as 7-bit ASCII and match the regular expression “^[a-zA-Z0-9_-]+$”.

MODEL - A value chosen by the device implementer containing the name of the device as known to the end user. This SHOULD be the same name under which the device is marketed and sold to end users. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

MANUFACTURER - The trade name of the Original Equipment Manufacturer (OEM) of the product. There are no requirements on the specific format of this field, except that it MUST NOT be null or the empty string ("").

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.

Example:

<div class="editor-field">
    <%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
    <%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>

Here's a more specific example:

I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).

I made the following model:

namespace DeleteMeQuestion.Models
{
    public class QuizModel
    {
        public int ParentQuestionId { get; set; }
        public int QuestionId { get; set; }
        public string QuestionDisplayText { get; set; }
        public List<Response> Responses { get; set; }

        [Range(1,999, ErrorMessage = "Please choose a response.")]
        public int SelectedResponse { get; set; }
    }

    public class Response
    {
        public int ResponseId { get; set; }
        public int ChildQuestionId { get; set; }
        public string ResponseDisplayText { get; set; }
    }
}

There's a simple range validator in the model, just for fun. Next up, I made the following controller:

namespace DeleteMeQuestion.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index(int? id)
        {
            // TODO: get question to show based on method parameter 
            var model = GetModel(id);
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(int? id, QuizModel model)
        {
            if (!ModelState.IsValid)
            {
                var freshModel = GetModel(id);
                return View(freshModel);
            }

            // TODO: save selected answer in database
            // TODO: get next question based on selected answer (hard coded to 999 for now)

            var nextQuestionId = 999;
            return RedirectToAction("Index", "Home", new {id = nextQuestionId});
        }

        private QuizModel GetModel(int? questionId)
        {
            // just a stub, in lieu of a database

            var model = new QuizModel
            {
                QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
                QuestionId = 1,
                Responses = new List<Response>
                                                {
                                                    new Response
                                                        {
                                                            ChildQuestionId = 2,
                                                            ResponseId = 1,
                                                            ResponseDisplayText = "Red"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 3,
                                                            ResponseId = 2,
                                                            ResponseDisplayText = "Blue"
                                                        },
                                                    new Response
                                                        {
                                                            ChildQuestionId = 4,
                                                            ResponseId = 3,
                                                            ResponseDisplayText = "Green"
                                                        },
                                                }
            };

            return model;
        }
    }
}

Finally, I made the following view that makes use of the model:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>

<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ContentPlaceHolderID="MainContent" runat="server">

    <% using (Html.BeginForm()) { %>

        <div>

            <h1><%: Model.QuestionDisplayText %></h1>

            <div>
            <ul>
            <% foreach (var item in Model.Responses) { %>
                <li>
                    <%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
                    <label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
                </li>
            <% } %>
            </ul>

            <%= Html.ValidationMessageFor(m => m.SelectedResponse) %>

        </div>

        <input type="submit" value="Submit" />

    <% } %>

</asp:Content>

As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.

This gives you the radio buttons with the same name attribute, but different ID attributes.

the MySQL service on local computer started and then stopped

mysqld --initialize

Run the above after the install command. Then try to start the service - that should work.

Better way to shuffle two numpy arrays in unison

There is a well-known function that can handle this:

from sklearn.model_selection import train_test_split
X, _, Y, _ = train_test_split(X,Y, test_size=0.0)

Just setting test_size to 0 will avoid splitting and give you shuffled data. Though it is usually used to split train and test data, it does shuffle them too.
From documentation

Split arrays or matrices into random train and test subsets

Quick utility that wraps input validation and next(ShuffleSplit().split(X, y)) and application to input data into a single call for splitting (and optionally subsampling) data in a oneliner.

Installing tkinter on ubuntu 14.04

First, make sure you have Tkinter module installed.

sudo apt-get install python-tk

In python 2 the package name is Tkinter not tkinter.

from Tkinter import *

ref: http://www.techinfected.net/2015/09/how-to-install-and-use-tkinter-in-ubuntu-debian-linux-mint.html

How to convert a byte array to its numeric value (Java)?

Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:

    long content = 212000607777l;
    byte[] numberByte = Longs.toByteArray(content);
    logger.info(Longs.fromByteArray(numberByte));

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

Shell script to set environment variables

You need to run the script as source or the shorthand .

source ./myscript.sh

or

. ./myscript.sh

This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.

Running the script just using the filename will execute the script in a separate subshell.

Convert java.util.Date to java.time.LocalDate

Date input = new Date();
LocalDateTime  conv=LocalDateTime.ofInstant(input.toInstant(), ZoneId.systemDefault());
LocalDate convDate=conv.toLocalDate();

The Date instance does contain time too along with the date while LocalDate doesn't. So you can firstly convert it into LocalDateTime using its method ofInstant() then if you want it without time then convert the instance into LocalDate.

React Native TextInput that only accepts numeric characters

That is the correct way to do it till such a component (or attribute on the TextInput) is specifically developed.

The web has the ‘number’ type for the input element, but that is web based and react-native does not use a web view.

You could consider to create that input as a react component on it’s own (maybe call NumberInput): that’ll enable you to reuse it or maybe even open source it since you can create many TextInputs that has different value filters/checkers.

The downside to immediate correction is to ensure correct feedback is given to the user as to prevent confusion as to what happened to his value

Listview Scroll to the end of the list after updating the list

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL.

Proper way to handle multiple forms on one page in Django

This is a bit late, but this is the best solution I found. You make a look-up dictionary for the form name and its class, you also have to add an attribute to identify the form, and in your views you have to add it as a hidden field, with the form.formlabel.

# form holder
form_holder = {
    'majeur': {
        'class': FormClass1,
    },
    'majsoft': {
        'class': FormClass2,
    },
    'tiers1': {
        'class': FormClass3,
    },
    'tiers2': {
        'class': FormClass4,
    },
    'tiers3': {
        'class': FormClass5,
    },
    'tiers4': {
        'class': FormClass6,
    },
}

for key in form_holder.keys():
    # If the key is the same as the formlabel, we should use the posted data
    if request.POST.get('formlabel', None) == key:
        # Get the form and initate it with the sent data
        form = form_holder.get(key).get('class')(
            data=request.POST
        )

        # Validate the form
        if form.is_valid():
            # Correct data entries
            messages.info(request, _(u"Configuration validée."))

            if form.save():
                # Save succeeded
                messages.success(
                    request,
                    _(u"Données enregistrées avec succès.")
                )
            else:
                # Save failed
                messages.warning(
                    request,
                    _(u"Un problème est survenu pendant l'enregistrement "
                      u"des données, merci de réessayer plus tard.")
                )
        else:
            # Form is not valid, show feedback to the user
            messages.error(
                request,
                _(u"Merci de corriger les erreurs suivantes.")
            )
    else:
        # Just initiate the form without data
        form = form_holder.get(key).get('class')(key)()

    # Add the attribute for the name
    setattr(form, 'formlabel', key)

    # Append it to the tempalte variable that will hold all the forms
    forms.append(form)

I hope this will help in the future.

App.Config file in console application C#

use this

System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")

How do I remove a submodule?

I've created a bash script to ease the removal process. It also checks whether there are changes in the repo left unsaved and asks for confirmation. It has been tested on os x would be interesting to know if it works as is on common linux distros as well:

https://gist.github.com/fabifrank/cdc7e67fd194333760b060835ac0172f

MySQL: How to add one day to datetime field in query

How about this: 

select * from fab_scheduler where custid = 1334666058 and eventdate = eventdate + INTERVAL 1 DAY

What is the error "Every derived table must have its own alias" in MySQL?

I think it's asking you to do this:

SELECT ID
FROM (SELECT ID,
             msisdn 
      FROM (SELECT * FROM TT2) as myalias
     ) as anotheralias;

But why would you write this query in the first place?

What's the difference between unit, functional, acceptance, and integration tests?

http://martinfowler.com/articles/microservice-testing/

Martin Fowler's blog post speaks about strategies to test code (Especially in a micro-services architecture) but most of it applies to any application.

I'll quote from his summary slide:

  • Unit tests - exercise the smallest pieces of testable software in the application to determine whether they behave as expected.
  • Integration tests - verify the communication paths and interactions between components to detect interface defects.
  • Component tests - limit the scope of the exercised software to a portion of the system under test, manipulating the system through internal code interfaces and using test doubles to isolate the code under test from other components.
  • Contract tests - verify interactions at the boundary of an external service asserting that it meets the contract expected by a consuming service.
  • End-To-End tests - verify that a system meets external requirements and achieves its goals, testing the entire system, from end to end.

Makefile to compile multiple C programs?

A simple program's compilation workflow is simple, I can draw it as a small graph: source -> [compilation] -> object [linking] -> executable. There are files (source, object, executable) in this graph, and rules (make's terminology). That graph is definied in the Makefile.

When you launch make, it reads Makefile, and checks for changed files. If there's any, it triggers the rule, which depends on it. The rule may produce/update further files, which may trigger other rules and so on. If you create a good makefile, only the necessary rules (compiler/link commands) will run, which stands "to next" from the modified file in the dependency path.

Pick an example Makefile, read the manual for syntax (anyway, it's clear for first sight, w/o manual), and draw the graph. You have to understand compiler options in order to find out the names of the result files.

The make graph should be as complex just as you want. You can even do infinite loops (don't do)! You can tell make, which rule is your target, so only the left-standing files will be used as triggers.

Again: draw the graph!.

RecyclerView vs. ListView

The RecyclerView is a new ViewGroup that is prepared to render any adapter-based view in a similar way. It is supossed to be the successor of ListView and GridView, and it can be found in the latest support-v7 version. The RecyclerView has been developed with extensibility in mind, so it is possible to create any kind of layout you can think of, but not without a little pain-in-the-ass dose.

Answer taken from Antonio leiva

 compile 'com.android.support:recyclerview-v7:27.0.0'

RecyclerView is indeed a powerful view than ListView . For more details you can visit This page.

How to check for an undefined or null variable in JavaScript?

You have to differentiate between cases:

  1. Variables can be undefined or undeclared. You'll get an error if you access an undeclared variable in any context other than typeof.
if(typeof someUndeclaredVar == whatever) // works
if(someUndeclaredVar) // throws error

A variable that has been declared but not initialized is undefined.

let foo;
if (foo) //evaluates to false because foo === undefined
  1. Undefined properties , like someExistingObj.someUndefProperty. An undefined property doesn't yield an error and simply returns undefined, which, when converted to a boolean, evaluates to false. So, if you don't care about 0 and false, using if(obj.undefProp) is ok. There's a common idiom based on this fact:

    value = obj.prop || defaultValue
    

    which means "if obj has the property prop, assign it to value, otherwise assign the default value defautValue".

    Some people consider this behavior confusing, arguing that it leads to hard-to-find errors and recommend using the in operator instead

    value = ('prop' in obj) ? obj.prop : defaultValue
    

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

What are "res" and "req" parameters in Express functions?

req is an object containing information about the HTTP request that raised the event. In response to req, you use res to send back the desired HTTP response.

Those parameters can be named anything. You could change that code to this if it's more clear:

app.get('/user/:id', function(request, response){
  response.send('user ' + request.params.id);
});

Edit:

Say you have this method:

app.get('/people.json', function(request, response) { });

The request will be an object with properties like these (just to name a few):

  • request.url, which will be "/people.json" when this particular action is triggered
  • request.method, which will be "GET" in this case, hence the app.get() call.
  • An array of HTTP headers in request.headers, containing items like request.headers.accept, which you can use to determine what kind of browser made the request, what sort of responses it can handle, whether or not it's able to understand HTTP compression, etc.
  • An array of query string parameters if there were any, in request.query (e.g. /people.json?foo=bar would result in request.query.foo containing the string "bar").

To respond to that request, you use the response object to build your response. To expand on the people.json example:

app.get('/people.json', function(request, response) {
  // We want to set the content-type header so that the browser understands
  //  the content of the response.
  response.contentType('application/json');

  // Normally, the data is fetched from a database, but we can cheat:
  var people = [
    { name: 'Dave', location: 'Atlanta' },
    { name: 'Santa Claus', location: 'North Pole' },
    { name: 'Man in the Moon', location: 'The Moon' }
  ];

  // Since the request is for a JSON representation of the people, we
  //  should JSON serialize them. The built-in JSON.stringify() function
  //  does that.
  var peopleJSON = JSON.stringify(people);

  // Now, we can use the response object's send method to push that string
  //  of people JSON back to the browser in response to this request:
  response.send(peopleJSON);
});

Check if a value exists in pandas dataframe index

This should do the trick

'g' in df.index

How can I initialise a static Map?

Map.of in Java 9+

private static final Map<Integer, String> MY_MAP = Map.of(1, "one", 2, "two");

See JEP 269 for details. JDK 9 reached general availability in September 2017.

Check if Cookie Exists

public static class CookieHelper
{
    /// <summary>
    /// Checks whether a cookie exists.
    /// </summary>
    /// <param name="cookieCollection">A CookieCollection, such as Response.Cookies.</param>
    /// <param name="name">The cookie name to delete.</param>
    /// <returns>A bool indicating whether a cookie exists.</returns>
    public static bool Exists(this HttpCookieCollection cookieCollection, string name)
    {
        if (cookieCollection == null)
        {
            throw new ArgumentNullException("cookieCollection");
        }

        return cookieCollection[name] != null;
    }
}

Usage:

Request.Cookies.Exists("MyCookie")

Can overridden methods differ in return type?

Java supports* covariant return types for overridden methods. This means an overridden method may have a more specific return type. That is, as long as the new return type is assignable to the return type of the method you are overriding, it's allowed.

For example:

class ShapeBuilder {
    ...
    public Shape build() {
    ....
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public Circle build() {
    ....
}

This is specified in section 8.4.5 of the Java Language Specification:

Return types may vary among methods that override each other if the return types are reference types. The notion of return-type-substitutability supports covariant returns, that is, the specialization of the return type to a subtype.

A method declaration d1 with return type R1 is return-type-substitutable for another method d2 with return type R2, if and only if the following conditions hold:

  • If R1 is void then R2 is void.

  • If R1 is a primitive type, then R2 is identical to R1.

  • If R1 is a reference type then:

    • R1 is either a subtype of R2 or R1 can be converted to a subtype of R2 by unchecked conversion (§5.1.9), or

    • R1 = |R2|

("|R2|" refers to the erasure of R2, as defined in §4.6 of the JLS.)


* Prior to Java 5, Java had invariant return types, which meant the return type of a method override needed to exactly match the method being overridden.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

How to create JNDI context in Spring Boot with Embedded Tomcat Container

In SpringBoot 2.1, I found another solution. Extend standard factory class method getTomcatWebServer. And then return it as a bean from anywhere.

public class CustomTomcatServletWebServerFactory extends TomcatServletWebServerFactory {

    @Override
    protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
        System.setProperty("catalina.useNaming", "true");
        tomcat.enableNaming();
        return new TomcatWebServer(tomcat, getPort() >= 0);
    }
}

@Component
public class TomcatConfiguration {
    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new CustomTomcatServletWebServerFactory();

        return factory;
    }

Loading resources from context.xml doesn't work though. Will try to find out.

Google Script to see if text contains a value

Update 2020:

You can now use Modern ECMAScript syntax thanks to V8 Runtime.

You can use includes():

var grade = itemResponse.getResponse();
if(grade.includes("9th")){do something}

OperationalError, no such column. Django

If the error persists after doing what @Burhan Khalid said

Try this line: python manage.py migrate --run-syncdb

Block direct access to a file over http but allow php script access

If you have access to you httpd.conf file (in ubuntu it is in the /etc/apache2 directory), you should add the same lines that you would to the .htaccess file in the specific directory. That is (for example):

ServerName YOURSERVERNAMEHERE
<Directory /var/www/>
AllowOverride None
order deny,allow
Options -Indexes FollowSymLinks
</Directory>

Do this for every directory that you want to control the information, and you will have one file in one spot to manage all access. It the example above, I did it for the root directory, /var/www.

This option may not be available with outsourced hosting, especially shared hosting. But it is a better option than adding many .htaccess files.

What design patterns are used in Spring framework?

Spring is a collection of best-practise API patterns, you can write up a shopping list of them as long as your arm. The way that the API is designed encourages you (but doesn't force you) to follow these patterns, and half the time you follow them without knowing you are doing so.

pass array to method Java

There is an important point of arrays that is often not taught or missed in java classes. When arrays are passed to a function, then another pointer is created to the same array ( the same pointer is never passed ). You can manipulate the array using both the pointers, but once you assign the second pointer to a new array in the called method and return back by void to calling function, then the original pointer still remains unchanged.

You can directly run the code here : https://www.compilejava.net/

import java.util.Arrays;

public class HelloWorld
{
    public static void main(String[] args)
    {
        int Main_Array[] = {20,19,18,4,16,15,14,4,12,11,9};
        Demo1.Demo1(Main_Array);
        // THE POINTER Main_Array IS NOT PASSED TO Demo1
        // A DIFFERENT POINTER TO THE SAME LOCATION OF Main_Array IS PASSED TO Demo1

        System.out.println("Main_Array = "+Arrays.toString(Main_Array));
        // outputs : Main_Array = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]
        // Since Main_Array points to the original location,
        // I cannot access the results of Demo1 , Demo2 when they are void.
        // I can use array clone method in Demo1 to get the required result,
        // but it would be faster if Demo1 returned the result to main
    }
}

public class Demo1
{
    public static void Demo1(int A[])
    {
        int B[] = new int[A.length];
        System.out.println("B = "+Arrays.toString(B)); // output : B = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        Demo2.Demo2(A,B);
        System.out.println("B = "+Arrays.toString(B)); // output : B = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        System.out.println("A = "+Arrays.toString(A)); // output : A = [20, 19, 18, 4, 16, 15, 14, 4, 12, 11, 9]

        A = B;
        // A was pointing to location of Main_Array, now it points to location of B
        // Main_Array pointer still keeps pointing to the original location in void main

        System.out.println("A = "+Arrays.toString(A)); // output : A = [9999, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        // Hence to access this result from main, I have to return it to main
    }
}
public class Demo2
{
    public static void Demo2(int AAA[],int BBB[])
    {
        BBB[0] = 9999;
        // BBB points to the same location as B in Demo1, so whatever I do
        // with BBB, I am manipulating the location. Since B points to the
        // same location, I can access the results from B
    }
}

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

Difference between ApiController and Controller in ASP.NET MVC

Every method in Web API will return data (JSON) without serialization.

However, in order to return JSON Data in MVC controllers, we will set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.

Username and password in https url

When you put the username and password in front of the host, this data is not sent that way to the server. It is instead transformed to a request header depending on the authentication schema used. Most of the time this is going to be Basic Auth which I describe below. A similar (but significantly less often used) authentication scheme is Digest Auth which nowadays provides comparable security features.

With Basic Auth, the HTTP request from the question will look something like this:

GET / HTTP/1.1
Host: example.com
Authorization: Basic Zm9vOnBhc3N3b3Jk

The hash like string you see there is created by the browser like this: base64_encode(username + ":" + password).

To outsiders of the HTTPS transfer, this information is hidden (as everything else on the HTTP level). You should take care of logging on the client and all intermediate servers though. The username will normally be shown in server logs, but the password won't. This is not guaranteed though. When you call that URL on the client with e.g. curl, the username and password will be clearly visible on the process list and might turn up in the bash history file.

When you send passwords in a GET request as e.g. http://example.com/login.php?username=me&password=secure the username and password will always turn up in server logs of your webserver, application server, caches, ... unless you specifically configure your servers to not log it. This only applies to servers being able to read the unencrypted http data, like your application server or any middleboxes such as loadbalancers, CDNs, proxies, etc. though.

Basic auth is standardized and implemented by browsers by showing this little username/password popup you might have seen already. When you put the username/password into an HTML form sent via GET or POST, you have to implement all the login/logout logic yourself (which might be an advantage and allows you to more control over the login/logout flow for the added "cost" of having to implement this securely again). But you should never transfer usernames and passwords by GET parameters. If you have to, use POST instead. The prevents the logging of this data by default.

When implementing an authentication mechanism with a user/password entry form and a subsequent cookie-based session as it is commonly used today, you have to make sure that the password is either transported with POST requests or one of the standardized authentication schemes above only.

Concluding I could say, that transfering data that way over HTTPS is likely safe, as long as you take care that the password does not turn up in unexpected places. But that advice applies to every transfer of any password in any way.

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Adding a regression line on a ggplot

If you want to fit other type of models, like a dose-response curve using logistic models you would also need to create more data points with the function predict if you want to have a smoother regression line:

fit: your fit of a logistic regression curve

#Create a range of doses:
mm <- data.frame(DOSE = seq(0, max(data$DOSE), length.out = 100))
#Create a new data frame for ggplot using predict and your range of new 
#doses:
fit.ggplot=data.frame(y=predict(fit, newdata=mm),x=mm$DOSE)

ggplot(data=data,aes(x=log10(DOSE),y=log(viability)))+geom_point()+
geom_line(data=fit.ggplot,aes(x=log10(x),y=log(y)))

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Checking for Undefined In React

What you can do is check whether you props is defined initially or not by checking if nextProps.blog.content is undefined or not since your body is nested inside it like

componentWillReceiveProps(nextProps) {

    if(nextProps.blog.content !== undefined && nextProps.blog.title !== undefined) {
       console.log("new title is", nextProps.blog.title);
       console.log("new body content is", nextProps.blog.content["body"]);
       this.setState({
           title: nextProps.blog.title,
           body: nextProps.blog.content["body"]
       })
    }
}

You need not use type to check for undefined, just the strict operator !== which compares the value by their type as well as value

In order to check for undefined, you can also use the typeof operator like

typeof nextProps.blog.content != "undefined"

Get generic type of java.util.List

Short answer: no.

This is probably a duplicate, can't find an appropriate one right now.

Java uses something called type erasure, which means at runtime both objects are equivalent. The compiler knows the lists contain integers or strings, and as such can maintain a type safe environment. This information is lost (on an object instance basis) at runtime, and the list only contain 'Objects'.

You CAN find out a little about the class, what types it might be parametrized by, but normally this is just anything that extends "Object", i.e. anything. If you define a type as

class <A extends MyClass> AClass {....}

AClass.class will only contain the fact that the parameter A is bounded by MyClass, but more than that, there's no way to tell.

Fastest way to determine if an integer's square root is an integer

It ought to be possible to pack the 'cannot be a perfect square if the last X digits are N' much more efficiently than that! I'll use java 32 bit ints, and produce enough data to check the last 16 bits of the number - that's 2048 hexadecimal int values.

...

Ok. Either I have run into some number theory that is a little beyond me, or there is a bug in my code. In any case, here is the code:

public static void main(String[] args) {
    final int BITS = 16;

    BitSet foo = new BitSet();

    for(int i = 0; i< (1<<BITS); i++) {
        int sq = (i*i);
        sq = sq & ((1<<BITS)-1);
        foo.set(sq);
    }

    System.out.println("int[] mayBeASquare = {");

    for(int i = 0; i< 1<<(BITS-5); i++) {
        int kk = 0;
        for(int j = 0; j<32; j++) {
            if(foo.get((i << 5) | j)) {
                kk |= 1<<j;
            }
        }
        System.out.print("0x" + Integer.toHexString(kk) + ", ");
        if(i%8 == 7) System.out.println();
    }
    System.out.println("};");
}

and here are the results:

(ed: elided for poor performance in prettify.js; view revision history to see.)

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?

I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).

However the refused message is likely a server side problem, (usually port closed).

Access a URL and read Data with R

base

read.csv without the url function just works fine. Probably I am missing something if Dirk Eddelbuettel included it in his answer:

ad <- read.csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

  X    TV radio newspaper sales
1 1 230.1  37.8      69.2  22.1
2 2  44.5  39.3      45.1  10.4
3 3  17.2  45.9      69.3   9.3
4 4 151.5  41.3      58.5  18.5
5 5 180.8  10.8      58.4  12.9
6 6   8.7  48.9      75.0   7.2

Another options using two popular packages:

data.table

library(data.table)
ad <- fread("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

V1    TV radio newspaper sales
1:  1 230.1  37.8      69.2  22.1
2:  2  44.5  39.3      45.1  10.4
3:  3  17.2  45.9      69.3   9.3
4:  4 151.5  41.3      58.5  18.5
5:  5 180.8  10.8      58.4  12.9
6:  6   8.7  48.9      75.0   7.2

readr

library(readr)
ad <- read_csv("http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv")
head(ad)

# A tibble: 6 x 5
     X1    TV radio newspaper sales
  <int> <dbl> <dbl>     <dbl> <dbl>
1     1 230.1  37.8      69.2  22.1
2     2  44.5  39.3      45.1  10.4
3     3  17.2  45.9      69.3   9.3
4     4 151.5  41.3      58.5  18.5
5     5 180.8  10.8      58.4  12.9
6     6   8.7  48.9      75.0   7.2

Replace line break characters with <br /> in ASP.NET MVC Razor view

Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!

<span style="white-space: pre-line">@Model.CommentText</span>

How to return a file using Web API?

I made the follow action:

[HttpGet]
[Route("api/DownloadPdfFile/{id}")]
public HttpResponseMessage DownloadPdfFile(long id)
{
    HttpResponseMessage result = null;
    try
    {
        SQL.File file = db.Files.Where(b => b.ID == id).SingleOrDefault();

        if (file == null)
        {
            result = Request.CreateResponse(HttpStatusCode.Gone);
        }
        else
        {
            // sendo file to client
            byte[] bytes = Convert.FromBase64String(file.pdfBase64);


            result = Request.CreateResponse(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(bytes);
            result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = file.name + ".pdf";
        }

        return result;
    }
    catch (Exception ex)
    {
        return Request.CreateResponse(HttpStatusCode.Gone);
    }
}

Windows batch - concatenate multiple text files into one

Try this:

@echo off
set yyyy=%date:~6,4%
set mm=%date:~3,2%
set dd=%date:~0,2%

set /p temp= "Enter the name of text file: "
FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%temp%.txt

This code ask you to set the name of the file after "day_" where you can input the date. If you want to name your file like the actual date you can do this:

FOR /F "tokens=* delims=" %%x in (texto1.txt, texto2.txt, texto3.txt) DO echo %%x >> day_%yyyy%-%mm%-%dd%.txt

C# SQL Server - Passing a list to a stored procedure

CREATE TYPE [dbo].[StringList1] AS TABLE(
[Item] [NVARCHAR](MAX) NULL,
[counts][nvarchar](20) NULL);

create a TYPE as table and name it as"StringList1"

create PROCEDURE [dbo].[sp_UseStringList1]
@list StringList1 READONLY
AS
BEGIN
    -- Just return the items we passed in
    SELECT l.item,l.counts FROM @list l;
    SELECT l.item,l.counts into tempTable FROM @list l;
 End

The create a procedure as above and name it as "UserStringList1" s

String strConnection = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString.ToString();
            SqlConnection con = new SqlConnection(strConnection);
            con.Open();
            var table = new DataTable();

            table.Columns.Add("Item", typeof(string));
            table.Columns.Add("count", typeof(string));

            for (int i = 0; i < 10; i++)
            {
                table.Rows.Add(i.ToString(), (i+i).ToString());

            }
                SqlCommand cmd = new SqlCommand("exec sp_UseStringList1 @list", con);


                    var pList = new SqlParameter("@list", SqlDbType.Structured);
                    pList.TypeName = "dbo.StringList1";
                    pList.Value = table;

                    cmd.Parameters.Add(pList);
                    string result = string.Empty;
                    string counts = string.Empty;
                    var dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        result += dr["Item"].ToString();
                        counts += dr["counts"].ToString();
                    }

in the c#,Try this

Append text using StreamWriter

using(StreamWriter writer = new StreamWriter("debug.txt", true))
{
  writer.WriteLine("whatever you text is");
}

The second "true" parameter tells it to append.

http://msdn.microsoft.com/en-us/library/36b035cb.aspx

Android: how to refresh ListView contents?

Another easy way:

//In your ListViewActivity:
public void refreshListView() {
    listAdapter = new ListAdapter(this);
    setListAdapter(listAdapter);
}

Any tools to generate an XSD schema from an XML instance document?

the Microsoft XSD inference tool is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.

edit: I just discovered the .net XmlSchemaInference class, so if you're using .net you should consider that

Unable to specify the compiler with CMake

Using with FILEPATH option might work:

set(CMAKE_CXX_COMPILER:FILEPATH C:/MinGW/bin/gcc.exe)

How to get the index of an item in a list in a single step?

If you don't want to use LINQ, then:

int index;
for (int i = 0; i < myList.Count; i++)
{
    if (myList[i].Prop == oProp)
    {
       index = i;
       break;
    }
}

this way you are iterating list only once.

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Neither one of the solutions worked form me. The only one that worked for me in Spring form is:

action="./upload?${_csrf.parameterName}=${_csrf.token}"

REPLACED WITH:

action="./upload?_csrf=${_csrf.token}"

(Spring 5 with enabled csrf in java configuration)

Alternate output format for psql

pspg is a simple tool that offers advanced table formatting, horizontal scrolling, search and many more features.

git clone https://github.com/okbob/pspg.git
cd pspg
./configure
make
make install

then make sure to update PAGER variable e.g. in your ~/.bashrc

export PAGER="pspg -s 6" 

where -s stands for color scheme (1-14). If you're using pgdg repositories simply install a package (on Debian-like distribution):

sudo apt install pspg

pspg example

How to display div after click the button in Javascript?

<div  style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" onclick="document.getElementsByClassName('answer_list')[0].style.display = 'auto';">

What SOAP client libraries exist for Python, and where is the documentation for them?

Update (2016):

If you only need SOAP client, there is well maintained library called zeep. It supports both Python 2 and 3 :)


Update:

Additionally to what is mentioned above, I will refer to Python WebServices page which is always up-to-date with all actively maintained and recommended modules to SOAP and all other webservice types.


Unfortunately, at the moment, I don't think there is a "best" Python SOAP library. Each of the mainstream ones available has its own pros and cons.

Older libraries:

  • SOAPy: Was the "best," but no longer maintained. Does not work on Python 2.5+

  • ZSI: Very painful to use, and development is slow. Has a module called "SOAPpy", which is different than SOAPy (above).

"Newer" libraries:

  • SUDS: Very Pythonic, and easy to create WSDL-consuming SOAP clients. Creating SOAP servers is a little bit more difficult. (This package does not work with Python3. For Python3 see SUDS-py3)

  • SUDS-py3: The Python3 version of SUDS

  • spyne: Creating servers is easy, creating clients a little bit more challenging. Documentation is somewhat lacking.

  • ladon: Creating servers is much like in soaplib (using a decorator). Ladon exposes more interfaces than SOAP at the same time without extra user code needed.

  • pysimplesoap: very lightweight but useful for both client and server - includes a web2py server integration that ships with web2py.

  • SOAPpy: Distinct from the abandoned SOAPpy that's hosted at the ZSI link above, this version was actually maintained until 2011, now it seems to be abandoned too.
  • soaplib: Easy to use python library for writing and calling soap web services. Webservices written with soaplib are simple, lightweight, work well with other SOAP implementations, and can be deployed as WSGI applications.
  • osa: A fast/slim easy to use SOAP python client library.

Of the above, I've only used SUDS personally, and I liked it a lot.

How do I auto-resize an image to fit a 'div' container?

A beautiful hack.

You have two ways of making the image responsive.

  1. When an image is a background image.
#container{
    width: 300px;
    height: 300px;
    background-image: url(http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

<div id="container"><div>

Run it here


But one should use img tag to put images as it is better than background-image in terms of SEO as you can write keyword in the alt of the img tag. So here is you can make the image responsive.

  1. When image is in img tag.
#container{
    max-width: 400px;
    overflow: hidden;
}
img{
    width: 100%;
    object-fit: contain;
}

<div id="container">
   <img src="http://images.fonearena.com/blog/wp-content/uploads/2013/11/Lenovo-p780-camera-sample-10.jpg" alt="your_keyword"/>
<div>

Run it here

How do I include a JavaScript file in another JavaScript file?

If you find there are two or more scripts occupying the same function when they are called, and we cannot be include them at the same time, we need to do it dynamically by user selection.

Including another file in jQuery using $.getScript works since the script will not be cached by default. So we are safe to call other scripts. The calls can be arranged like this:

HTML

<select class="choice">
  <option value="script1" selected>Script-1</option>
  <option value="script2">Script-2</option>
</select>

JavaScript

  $(".choice").change(on_change);

    var url = "https://example.com";
    $.url1 = url + "/script1.js";
    $.url2 = url + "/script2.js";

  function on_change() {
    if ($(".choice").val()=="script1") {
        script1();
    } else {
         script2();
    }

    // script1
    function script1() {
      $.getScript($.url1, function( data, textStatus, jqxhr ) {
          // Execute here
      });
    }

    // script2
    function script2() {
       $.getScript($.url2, function( data, textStatus, jqxhr ) {
          // Execute here
      });
    }

Python script to do something at the same time every day

You can do that like this:

from datetime import datetime
from threading import Timer

x=datetime.today()
y=x.replace(day=x.day+1, hour=1, minute=0, second=0, microsecond=0)
delta_t=y-x

secs=delta_t.seconds+1

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

This will execute a function (eg. hello_world) in the next day at 1a.m.

EDIT:

As suggested by @PaulMag, more generally, in order to detect if the day of the month must be reset due to the reaching of the end of the month, the definition of y in this context shall be the following:

y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)

With this fix, it is also needed to add timedelta to the imports. The other code lines maintain the same. The full solution, using also the total_seconds() function, is therefore:

from datetime import datetime, timedelta
from threading import Timer

x=datetime.today()
y = x.replace(day=x.day, hour=1, minute=0, second=0, microsecond=0) + timedelta(days=1)
delta_t=y-x

secs=delta_t.total_seconds()

def hello_world():
    print "hello world"
    #...

t = Timer(secs, hello_world)
t.start()

dplyr mutate with conditional values

With dplyr 0.7.2, you can use the very useful case_when function :

x=read.table(
 text="V1 V2 V3 V4
 1  1  2  3  5
 2  2  4  4  1
 3  1  4  1  1
 4  4  5  1  3
 5  5  5  5  4")
x$V5 = case_when(x$V1==1 & x$V2!=4 ~ 1,
                 x$V2==4 & x$V3!=1 ~ 2,
                 TRUE ~ 0)

Expressed with dplyr::mutate, it gives:

x = x %>% mutate(
     V5 = case_when(
         V1==1 & V2!=4 ~ 1,
         V2==4 & V3!=1 ~ 2,
         TRUE ~ 0
     )
)

Please note that NA are not treated specially, as it can be misleading. The function will return NA only when no condition is matched. If you put a line with TRUE ~ ..., like I did in my example, the return value will then never be NA.

Therefore, you have to expressively tell case_when to put NA where it belongs by adding a statement like is.na(x$V1) | is.na(x$V3) ~ NA_integer_. Hint: the dplyr::coalesce() function can be really useful here sometimes!

Moreover, please note that NA alone will usually not work, you have to put special NA values : NA_integer_, NA_character_ or NA_real_.

Correct use of transactions in SQL Server

Easy approach:

CREATE TABLE T
(
    C [nvarchar](100) NOT NULL UNIQUE,
);

SET XACT_ABORT ON -- Turns on rollback if T-SQL statement raises a run-time error.
SELECT * FROM T; -- Check before.
BEGIN TRAN
    INSERT INTO T VALUES ('A');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('B');
    INSERT INTO T VALUES ('C');
COMMIT TRAN
SELECT * FROM T; -- Check after.
DELETE T;

Visual Studio Post Build Event - Copy to Relative Directory Location

If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.

ie. Use $(SolutionDir)\..\.. to get your base directory.


For list of all macros, see here:

http://msdn.microsoft.com/en-us/library/c02as0cs.aspx

Auto code completion on Eclipse

Steps:

  • In Eclipse, open the code auto completion box from first letter
  • Go to >> Window >> preference >> [ Java c++ php ... ] >> Editor >> Auto activation triggers for...
  • Add the character SPACE by just putting your cursor inside and box and push the space key..

All the commands and variables which begin with that letter are now going to appear

How to return more than one value from a function in Python?

Here is also the code to handle the result:

def foo (a):
    x=a
    y=a*2
    return (x,y)

(x,y) = foo(50)

Simulating Button click in javascript

The reason your code isn't working the way you would expect is because this line:

<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>

should be changed to:

<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>

There are two things to notice here:

1: The "s around datepicker have been changed to 's so that they do not interfere with the quotes surrounding the onclick event.

2: The click() has been changed to focus() to activate the datepicker calendar. When the button is pressed.

Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>, this should not be a problem.

Inline events are not recommended.

Extract month and year from a zoo::yearmon object

You can use format:

library(zoo)
x <- as.yearmon(Sys.time())
format(x,"%b")
[1] "Mar"
format(x,"%Y")
[1] "2012"

Best tool for inspecting PDF files?

Adobe Acrobat has a very cool but rather well hidden mode allowing you to inspect PDF files. I wrote a blog article explaining it at https://blog.idrsolutions.com/2009/04/viewing-pdf-objects/

Why doesn't "System.out.println" work in Android?

System.out.println("...") is displayed on the Android Monitor in Android Studio

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Get file name from URI string in C#

I think this will do what you need:

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();

SQLAlchemy: print the actual query

So building on @zzzeek's comments on @bukzor's code I came up with this to easily get a "pretty-printable" query:

def prettyprintable(statement, dialect=None, reindent=True):
    """Generate an SQL expression string with bound parameters rendered inline
    for the given SQLAlchemy statement. The function can also receive a
    `sqlalchemy.orm.Query` object instead of statement.
    can 

    WARNING: Should only be used for debugging. Inlining parameters is not
             safe when handling user created data.
    """
    import sqlparse
    import sqlalchemy.orm
    if isinstance(statement, sqlalchemy.orm.Query):
        if dialect is None:
            dialect = statement.session.get_bind().dialect
        statement = statement.statement
    compiled = statement.compile(dialect=dialect,
                                 compile_kwargs={'literal_binds': True})
    return sqlparse.format(str(compiled), reindent=reindent)

I personally have a hard time reading code which is not indented so I've used sqlparse to reindent the SQL. It can be installed with pip install sqlparse.

How do I split a string with multiple separators in JavaScript?

Starting from @stephen-sweriduk solution (that was the more interesting to me!), I have slightly modified it to make more generic and reusable:

/**
 * Adapted from: http://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript
*/
var StringUtils = {

  /**
   * Flatten a list of strings
   * http://rosettacode.org/wiki/Flatten_a_list
   */
  flatten : function(arr) {
    var self=this;
    return arr.reduce(function(acc, val) {
        return acc.concat(val.constructor === Array ? self.flatten(val) : val);
    },[]);
  },

  /**
   * Recursively Traverse a list and apply a function to each item
   * @param list array
   * @param expression Expression to use in func
   * @param func function of (item,expression) to apply expression to item
   *
   */
  traverseListFunc : function(list, expression, index, func) {
    var self=this;
    if(list[index]) {
        if((list.constructor !== String) && (list[index].constructor === String))
            (list[index] != func(list[index], expression)) ? list[index] = func(list[index], expression) : null;
        (list[index].constructor === Array) ? self.traverseListFunc(list[index], expression, 0, func) : null;
        (list.constructor === Array) ? self.traverseListFunc(list, expression, index+1, func) : null;
    }
  },

  /**
   * Recursively map function to string
   * @param string
   * @param expression Expression to apply to func
   * @param function of (item, expressions[i])
   */
  mapFuncToString : function(string, expressions, func) {
    var self=this;
    var list = [string];
    for(var i=0, len=expressions.length; i<len; i++) {
        self.traverseListFunc(list, expressions[i], 0, func);
    }
    return self.flatten(list);
  },

  /**
   * Split a string
   * @param splitters Array of characters to apply the split
   */
  splitString : function(string, splitters) {
    return this.mapFuncToString(string, splitters, function(item, expression) {
      return item.split(expression);
    })
  },

}

and then

var stringToSplit = "people and_other/things";
var splitList = [" ", "_", "/"];
var splittedString=StringUtils.splitString(stringToSplit, splitList);
console.log(splitList, stringToSplit, splittedString);

that gives back as the original:

[ ' ', '_', '/' ] 'people and_other/things' [ 'people', 'and', 'other', 'things' ]

Should I use int or Int32

Once upon a time, the int datatype was pegged to the register size of the machine targeted by the compiler. So, for example, a compiler for a 16-bit system would use a 16-bit integer.

However, we thankfully don't see much 16-bit any more, and when 64-bit started to get popular people were more concerned with making it compatible with older software and 32-bit had been around so long that for most compilers an int is just assumed to be 32 bits.

Can a CSV file have a comment?

If you need something like:

  ¦ A                              ¦ B
--+--------------------------------+---
1 ¦ #My comment, something else    ¦
2 ¦ 1                              ¦ 2

Your CSV may contain the following lines:

"#My comment, something else"
1,2

Pay close attention at the 'quotes' in the first line.

When converting your text to columns using the Excel wizard, remember checking the 'Treat consecutive delimiters as one', setting it to use 'quotes' as delimiter.

Thus, Excel will split the text at the commas, keeping the 'comment' line as a single column value (and it will remove the quotes).

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

Currency format for display

If you just have the currency symbol and the number of decimal places, you can use the following helper function, which respects the symbol/amount order, separators etc, only changing the currency symbol itself and the number of decimal places to display to.

public static string FormatCurrency(string currencySymbol, Decimal currency, int decPlaces)
{
    NumberFormatInfo localFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
    localFormat.CurrencySymbol = currencySymbol;
    localFormat.CurrencyDecimalDigits = decPlaces;
    return currency.ToString("c", localFormat);
}

What are the complexity guarantees of the standard containers?

I found the nice resource Standard C++ Containers. Probably this is what you all looking for.

VECTOR

Constructors

vector<T> v;              Make an empty vector.                                     O(1)
vector<T> v(n);           Make a vector with N elements.                            O(n)
vector<T> v(n, value);    Make a vector with N elements, initialized to value.      O(n)
vector<T> v(begin, end);  Make a vector and copy the elements from begin to end.    O(n)

Accessors

v[i]          Return (or set) the I'th element.                        O(1)
v.at(i)       Return (or set) the I'th element, with bounds checking.  O(1)
v.size()      Return current number of elements.                       O(1)
v.empty()     Return true if vector is empty.                          O(1)
v.begin()     Return random access iterator to start.                  O(1)
v.end()       Return random access iterator to end.                    O(1)
v.front()     Return the first element.                                O(1)
v.back()      Return the last element.                                 O(1)
v.capacity()  Return maximum number of elements.                       O(1)

Modifiers

v.push_back(value)         Add value to end.                                                O(1) (amortized)
v.insert(iterator, value)  Insert value at the position indexed by iterator.                O(n)
v.pop_back()               Remove value from end.                                           O(1)
v.assign(begin, end)       Clear the container and copy in the elements from begin to end.  O(n)
v.erase(iterator)          Erase value indexed by iterator.                                 O(n)
v.erase(begin, end)        Erase the elements from begin to end.                            O(n)

For other containers, refer to the page.

How to convert datetime format to date format in crystal report using C#?

There are many ways you can do this. You can just use what is described here or you can do myDate.ToString("dd-MMM-yyyy"); There are plenty of help for this topic in the MSDN documentation.

You could also write you own DateExtension class which will allow you to go something like myDate.ToMyDateFormat();

    public static class DateTimeExtensions
    {
        public static DateTime ToMyDateFormat(this DateTime d)
        {
            return d.ToString("dd-MMM-yyyy");
        }
    }

How to get the focused element with jQuery?

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

How to call a PHP function on the click of a button

You should make the button call the same page and in a PHP section check if the button was pressed:

HTML:

<form action="theSamePage.php" method="post">
    <input type="submit" name="someAction" value="GO" />
</form>

PHP:

<?php
    if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
    {
        func();
    }
    function func()
    {
        // do stuff     
    }
?>

Quick Sort Vs Merge Sort

quicksort is named so for a reason ,

highlights : both are stable sorts,(simply an implementation nuisance ) , so lets just move on to complexities

its very confusing with just the big-oh notations being spilled and "abused" , both have average case complexity of 0(nlogn) ,

but merge sort is always 0(nlogn) , whereas quicksort for bad partitions, ie skewed partitions like 1 element-10 element (which can happen due to sorted or reverse sorted list ) can lead to a 0(n^2)..

.. and so we have randomized quicksort , where we pick the pivot randomly and avoid such skewed partitioning , thereby nullifying the whole n^2 scenario anyway even for moderately skewed partitioning like 3-4 , we have a nlog(7/4)n, ideally we want 1-1 partion , thus the whole 2 of O(nlog(2)n).

so it is O(nlogn) , almost always and unlike merge sort the constants hidden under the "big-oh" notation are better for quicksort than for mergesort ..and it doesnt use up extra space like merge sort.

but getting quicksort run perfectly requires tweaking ,rephrase , quicksort provides you opportunities to tweak ....

Lumen: get URL parameter in a Blade view

As per official 5.8 docs:

The request() function returns the current request instance or obtains an input item:

$request = request();

$value = request('key', $default);

Docs

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

Call a function with argument list in python

You can use *args and **kwargs syntax for variable length arguments.

What do *args and **kwargs mean?

And from the official python tutorial

http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions

How to prevent "The play() request was interrupted by a call to pause()" error?

I have hit this issue, and have a case where I needed to hit pause() then play() but when using pause().then() I get undefined.

I found that if I started play 150ms after pause it resolved the issue. (Hopefully Google fixes soon)

playerMP3.volume = 0;
playerMP3.pause();

//Avoid the Promise Error
setTimeout(function () {      
   playerMP3.play();
}, 150);

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

check this image link for all steps https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms

STEP1: I created a field of type varbinary in table

STEP2: I created a stored procedure to accept a parameter of type sql_variant

STEP3: In my front end asp.net page, I created a sql data source parameter of object type

        <tr>
        <td>
            UPLOAD DOCUMENT</td>
        <td>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <asp:SqlDataSource ID="sqldsFileUploadConn" runat="server" 
                ConnectionString="<%$ ConnectionStrings: %>" 
                InsertCommand="ph_SaveDocument"     
               InsertCommandType="StoredProcedure">
                <InsertParameters>
                    <asp:Parameter Name="DocBinaryForm" Type="Object" />
                </InsertParameters>

             </asp:SqlDataSource>
        </td>
        <td>
            &nbsp;</td>
    </tr>

STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control

      Dim filebytes As Object
      filebytes = FileUpload1.FileBytes()
      sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
      Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()

               ' ... code continues ... '

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?
});
Response.Write(json);

SQL Server - copy stored procedures from one db to another

This code copies all stored procedures in the Master database to the target database, you can copy just the procedures you like by filtering the query on procedure name.

@sql is defined as nvarchar(max), @Name is the target database

DECLARE c CURSOR FOR 
   SELECT Definition
   FROM [ResiDazeMaster].[sys].[procedures] p
   INNER JOIN [ResiDazeMaster].sys.sql_modules m ON p.object_id = m.object_id

OPEN c

FETCH NEXT FROM c INTO @sql

WHILE @@FETCH_STATUS = 0 
BEGIN
   SET @sql = REPLACE(@sql,'''','''''')
   SET @sql = 'USE [' + @Name + ']; EXEC(''' + @sql + ''')'

   EXEC(@sql)

   FETCH NEXT FROM c INTO @sql
END             

CLOSE c
DEALLOCATE c

How to mark-up phone numbers?

As one would expect, WebKit's support of tel: extends to the Android mobile browser as well - FYI

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

How to clear or stop timeInterval in angularjs?

var interval = $interval(function() {
  console.log('say hello');
}, 1000);

$interval.cancel(interval);

Is it possible to change the package name of an Android app on Google Play?

Never, you can't do it since package name is the unique name Identifier for your app.....

MySQL Query to select data from last week?

Here is a way to get last week, month, and year records in MySQL.

Last Week

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE WEEK(InsertTime) = WEEK(NOW()) - 1;

Last Month

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE MONTH(InsertTime) = MONTH(NOW()) - 1;

Last YEAR

SELECT UserName, InsertTime 
FROM tblaccounts
WHERE YEAR(InsertTime) = YEAR(NOW()) - 1;

JavaScript Loading Screen while page loads

You can wait until the body is ready:

_x000D_
_x000D_
function onReady(callback) {_x000D_
  var intervalId = window.setInterval(function() {_x000D_
    if (document.getElementsByTagName('body')[0] !== undefined) {_x000D_
      window.clearInterval(intervalId);_x000D_
      callback.call(this);_x000D_
    }_x000D_
  }, 1000);_x000D_
}_x000D_
_x000D_
function setVisible(selector, visible) {_x000D_
  document.querySelector(selector).style.display = visible ? 'block' : 'none';_x000D_
}_x000D_
_x000D_
onReady(function() {_x000D_
  setVisible('.page', true);_x000D_
  setVisible('#loading', false);_x000D_
});
_x000D_
body {_x000D_
  background: #FFF url("https://i.imgur.com/KheAuef.png") top left repeat-x;_x000D_
  font-family: 'Alex Brush', cursive !important;_x000D_
}_x000D_
_x000D_
.page    { display: none; padding: 0 0.5em; }_x000D_
.page h1 { font-size: 2em; line-height: 1em; margin-top: 1.1em; font-weight: bold; }_x000D_
.page p  { font-size: 1.5em; line-height: 1.275em; margin-top: 0.15em; }_x000D_
_x000D_
#loading {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 100;_x000D_
  width: 100vw;_x000D_
  height: 100vh;_x000D_
  background-color: rgba(192, 192, 192, 0.5);_x000D_
  background-image: url("https://i.stack.imgur.com/MnyxU.gif");_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: center;_x000D_
}
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" rel="stylesheet"/>_x000D_
<link href="https://fonts.googleapis.com/css?family=Alex+Brush" rel="stylesheet">_x000D_
<div class="page">_x000D_
  <h1>The standard Lorem Ipsum passage</h1>_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure_x000D_
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
</div>_x000D_
<div id="loading"></div>
_x000D_
_x000D_
_x000D_

Here is a JSFiddle that demonstrates this technique.

Add spaces between the characters of a string in Java?

  • Create a char array from your string
  • Loop through the array, adding a space +" " after each item in the array(except the last one, maybe)
  • BOOM...done!!

Adding local .aar files to Gradle build using "flatDirs" is not working

Building upon Josiah's answer, here's how I got it to work.

Following his instructions (under edit) (File -> New-> New Module -> Import .JAR/.AAR) and import your .AAR.

Then in your project build.gradle (not the top level one, the one under 'app') add the following (in the dependencies section):

dependencies {
    compile project(':Name-Of-Your-Project')
}

Note Name-Of-Your-Project should match the name of the folder that was added after you imported the AAR file (at the same level as app/.idea under the top most level folder). Or to put it another way...

MyApplication
  .idea
  app
  build.gradle (here's where to add compile project(':ProjectName') to dependency section)
  ProjectName (added automatically after importing, matching the name of your aar file)
  build
  gradle
  etc

This worked for me running Android Studio 0.8.0. Don't forget to synchronize gradle (using toolbar button or in File->Synchronize) after you do this.

(Thanks to Josiah for getting me going in the right direction)

(Note: prior to this I tried adding it to the libs folder, trying to manipulate the top level build.gradle and the app level build.gradle, but none of that worked for my aars files--jar's will work fine, but not the aar files)

C++ - Hold the console window open?

I use std::getwchar() in my environment which is with mingw32 - gcc-4.6.2 compiler, Here is a sample code.

#include <iostream>
#include "Arithmetics.h"

using namespace std;

int main() {
    ARITHMETICS_H::testPriorities();

    cout << "Press any key to exit." << endl;
    getwchar();
    return 0;
}

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

adding to window.onload event?

You can use attachEvent(ie8) and addEventListener instead

addEvent(window, 'load', function(){ some_methods_1() });
addEvent(window, 'load', function(){ some_methods_2() });

function addEvent(element, eventName, fn) {
    if (element.addEventListener)
        element.addEventListener(eventName, fn, false);
    else if (element.attachEvent)
        element.attachEvent('on' + eventName, fn);
}

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

Echoing the last command run in Bash?

I was able to achieve this by using set -x in the main script (which makes the script print out every command that is executed) and writing a wrapper script which just shows the last line of output generated by set -x.

This is the main script:

#!/bin/bash
set -x
echo some command here
echo last command

And this is the wrapper script:

#!/bin/sh
./test.sh 2>&1 | grep '^\+' | tail -n 1 | sed -e 's/^\+ //'

Running the wrapper script produces this as output:

echo last command

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

Loading custom configuration files

The config file is just an XML file, you can open it by:

private static XmlDocument loadConfigDocument()
{
    XmlDocument doc = null;
    try
    {
        doc = new XmlDocument();
        doc.Load(getConfigFilePath());
        return doc;
    }
    catch (System.IO.FileNotFoundException e)
    {
        throw new Exception("No configuration file found.", e);
    }
    catch (Exception ex)
    {
        return null;
    }
}

and later retrieving values by:

    // retrieve appSettings node

    XmlNode node =  doc.SelectSingleNode("//appSettings");

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

Parsing a JSON string in Ruby

Just to extend the answers a bit with what to do with the parsed object:

# JSON Parsing example
require "rubygems" # don't need this if you're Ruby v1.9.3 or higher
require "json"

string = '{"desc":{"someKey":"someValue","anotherKey":"value"},"main_item":{"stats":{"a":8,"b":12,"c":10}}}'
parsed = JSON.parse(string) # returns a hash

p parsed["desc"]["someKey"]
p parsed["main_item"]["stats"]["a"]

# Read JSON from a file, iterate over objects
file = open("shops.json")
json = file.read

parsed = JSON.parse(json)

parsed["shop"].each do |shop|
  p shop["id"]
end

How to print to console in pytest?

Short Answer

Use the -s option:

pytest -s

Detailed answer

From the docs:

During test execution any output sent to stdout and stderr is captured. If a test or a setup method fails its according captured output will usually be shown along with the failure traceback.

pytest has the option --capture=method in which method is per-test capturing method, and could be one of the following: fd, sys or no. pytest also has the option -s which is a shortcut for --capture=no, and this is the option that will allow you to see your print statements in the console.

pytest --capture=no     # show print statements in console
pytest -s               # equivalent to previous command

Setting capturing methods or disabling capturing

There are two ways in which pytest can perform capturing:

  1. file descriptor (FD) level capturing (default): All writes going to the operating system file descriptors 1 and 2 will be captured.

  2. sys level capturing: Only writes to Python files sys.stdout and sys.stderr will be captured. No capturing of writes to filedescriptors is performed.

pytest -s            # disable all capturing
pytest --capture=sys # replace sys.stdout/stderr with in-mem files
pytest --capture=fd  # also point filedescriptors 1 and 2 to temp file

Read a javascript cookie by name

One of the shortest ways is this, however as mentioned previously it can return the wrong cookie if there's similar names (MyCookie vs AnotherMyCookie):

var regex = /MyCookie=(.[^;]*)/ig;
var match = regex.exec(document.cookie);
var value = match[1];

I use this in a chrome extension so I know the name I'm setting, and I can make sure there won't be a duplicate, more or less.

php is null or empty?

No it's not a bug. Have a look at the Loose comparisons with == table (second table), which shows the result of comparing each value in the first column with the values in the other columns:

    TRUE    FALSE   1       0       -1      "1"     "0"     "-1"    NULL    array() "php"   ""

    [...]    

""  FALSE   TRUE    FALSE   TRUE    FALSE   FALSE   FALSE   FALSE   TRUE    FALSE   FALSE   TRUE

There you can see that an empty string "" compared with false, 0, NULL or "" will yield true.

You might want to use is_null [docs] instead, or strict comparison (third table).

ThreeJS: Remove object from scene

THIS WORKS GREAT - I tested it so, please SET NAME for every object

give the name to the object upon creation

    mesh.name = 'nameMeshObject';

and use this if you have to delete an object

    delete3DOBJ('nameMeshObject');



    function delete3DOBJ(objName){
        var selectedObject = scene.getObjectByName(objName);
        scene.remove( selectedObject );
        animate();
    }

open a new scene , add object open new scene , add object

delete an object and create new delete object and create new

Getting Exception(org.apache.poi.openxml4j.exception - no content type [M1.13]) when reading xlsx file using Apache POI?

Try saving the file as Excel Workbook ONLY. NOT any other format. It worked for me. I was getting the same error.

Whitespace Matching Regex - Java

Seems to work for me:

String s = "  a   b      c";
System.out.println("\""  + s.replaceAll("\\s\\s", " ") + "\"");

will print:

" a  b   c"

I think you intended to do this instead of your code:

Pattern whitespace = Pattern.compile("\\s\\s");
Matcher matcher = whitespace.matcher(s);
String result = "";
if (matcher.find()) {
    result = matcher.replaceAll(" ");
}

System.out.println(result);

php - insert a variable in an echo string

Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.

$var = 'my variable';
echo "I love ${var}";

or

$var = 'my variable';
echo "I love {$var}";

Above would return the following: I love my variable

What's the strangest corner case you've seen in C# or .NET?

Consider this weird case:

public interface MyInterface {
  void Method();
}
public class Base {
  public void Method() { }
}
public class Derived : Base, MyInterface { }

If Base and Derived are declared in the same assembly, the compiler will make Base::Method virtual and sealed (in the CIL), even though Base doesn't implement the interface.

If Base and Derived are in different assemblies, when compiling the Derived assembly, the compiler won't change the other assembly, so it will introduce a member in Derived that will be an explicit implementation for MyInterface::Method that will just delegate the call to Base::Method.

The compiler has to do this in order to support polymorphic dispatch with regards to the interface, i.e. it has to make that method virtual.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

Assign NOW() to a variable then update the datetime with variable:

update_date_time=now()

now update like this

UPDATE table SET datetime =update_date_time;

correct the syntax, as per your requirement

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

In my case I mistakely imported Action into my combineEpics, rather than Epic...

Verify all the functions within combine Epics are epic funcitons

Heroku deployment error H10 (App crashed)

I had this problem when trying to run Rails in a subdirectory, and not in /. For example, I had Angular/Node/Gulp app running in /client and a Rails app running in /server, but both of them were in the same git repo, so I could track changes across the front end and back end. I got this error when trying to deploy them to Heroku. For anyone else having this issue, here is a custom buildpack that will allow running Rails in a subdirectory.

https://github.com/aarongray/heroku-buildpack-ruby

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

HTML inside Twitter Bootstrap popover

I used a pop over inside a list, Im giving an example via HTML

<a type="button" data-container="body" data-toggle="popover" data-html="true" data-placement="right" data-content='<ul class="nav"><li><a href="#">hola</li><li><a href="#">hola2</li></ul>'>

How can I catch a ctrl-c event?

Yeah, this is a platform dependent question.

If you are writing a console program on POSIX, use the signal API (#include <signal.h>).

In a WIN32 GUI application you should handle the WM_KEYDOWN message.

How can I include all JavaScript files in a directory via JavaScript file?

You can't do that in JavaScript, since JS is executed in the browser, not in the server, so it didn't know anything about directories or other server resources.

The best option is using a server side script like the one posted by jellyfishtree.

Group By Multiple Columns

For Group By Multiple Columns, Try this instead...

GroupBy(x=> new { x.Column1, x.Column2 }, (key, group) => new 
{ 
  Key1 = key.Column1,
  Key2 = key.Column2,
  Result = group.ToList() 
});

Same way you can add Column3, Column4 etc.

Jenkins could not run git

Like Darksaint2014 said, you need to configure two parts if you installed Jenkins in Windows.

If you installed your Jenkins in windows, you need to install Git in both local and your linux server, then configure below in both locations:


Global tool configuration:

global tool configuration


For server side:

For server side


What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

Full width image with fixed height

Set the image's width to 100%, and the image's height will adjust itself:

<img style="width:100%;" id="image" src="...">

If you have a custom CSS, then:

HTML:

<img id="image" src="...">

CSS:

#image
{
    width: 100%;
}

Also, you could do File -> View Source next time, or maybe Google.

How to set Spinner default value to null?

This is a complete implementation of Paul Bourdeaux's idea, namely returning a special initial view (or an empty view) in getView() for position 0.

It works for me and is relatively straightforward. You might consider this approach especially if you already have a custom adapter for your Spinner. (In my case, I was using custom adapter in order to easily customise the layout of the items, each item having a couple of TextViews.)

The adapter would be something along these lines:

public class MySpinnerAdapter extends ArrayAdapter<MyModel> {

    public MySpinnerAdapter(Context context, List<MyModel> items) {
        super(context, R.layout.my_spinner_row, items);
    }

    @Override
    public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
        if (position == 0) {
            return initialSelection(true);
        }
        return getCustomView(position, convertView, parent);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, @NonNull ViewGroup parent) {
        if (position == 0) {
            return initialSelection(false);
        }
        return getCustomView(position, convertView, parent);
    }


    @Override
    public int getCount() {
        return super.getCount() + 1; // Adjust for initial selection item
    }

    private View initialSelection(boolean dropdown) {
        // Just an example using a simple TextView. Create whatever default view 
        // to suit your needs, inflating a separate layout if it's cleaner.
        TextView view = new TextView(getContext());
        view.setText(R.string.select_one);
        int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
        view.setPadding(0, spacing, 0, spacing);

        if (dropdown) { // Hidden when the dropdown is opened
            view.setHeight(0);
        }

        return view;
    }

    private View getCustomView(int position, View convertView, ViewGroup parent) {
        // Distinguish "real" spinner items (that can be reused) from initial selection item
        View row = convertView != null && !(convertView instanceof TextView) 
        ? convertView :
        LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);

        position = position - 1; // Adjust for initial selection item
        MyModel item = getItem(position);

        // ... Resolve views & populate with data ...

        return row;
    }

}

That's it. Note that if you use a OnItemSelectedListener with your Spinner, in onItemSelected() you'd also have to adjust position to take the default item into account, for example:

if (position == 0) {
    return;
} else {
    position = position - 1;
}
MyModel selected = items.get(position);

Can I set a TTL for @Cacheable

Here is a full example of setting up Guava Cache in Spring. I used Guava over Ehcache because it's a bit lighter weight and the config seemed more straight forward to me.

Import Maven Dependencies

Add these dependencies to your maven pom file and run clean and packages. These files are the Guava dep and Spring helper methods for use in the CacheBuilder.

    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>18.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.1.7.RELEASE</version>
    </dependency>

Configure the Cache

You need to create a CacheConfig file to configure the cache using Java config.

@Configuration
@EnableCaching
public class CacheConfig {

   public final static String CACHE_ONE = "cacheOne";
   public final static String CACHE_TWO = "cacheTwo";

   @Bean
   public Cache cacheOne() {
      return new GuavaCache(CACHE_ONE, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.MINUTES)
            .build());
   }

   @Bean
   public Cache cacheTwo() {
      return new GuavaCache(CACHE_TWO, CacheBuilder.newBuilder()
            .expireAfterWrite(60, TimeUnit.SECONDS)
            .build());
   }
}

Annotate the method to be cached

Add the @Cacheable annotation and pass in the cache name.

@Service
public class CachedService extends WebServiceGatewaySupport implements CachedService {

    @Inject
    private RestTemplate restTemplate;


    @Cacheable(CacheConfig.CACHE_ONE)
    public String getCached() {

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

        HttpEntity<String> reqEntity = new HttpEntity<>("url", headers);

        ResponseEntity<String> response;

        String url = "url";
        response = restTemplate.exchange(
                url,
                HttpMethod.GET, reqEntity, String.class);

        return response.getBody();
    }
}

You can see a more complete example here with annotated screenshots: Guava Cache in Spring

How can I extract a good quality JPEG image from a video file with ffmpeg?

Use -qscale:v to control quality

Use -qscale:v (or the alias -q:v) as an output option.

  • Normal range for JPEG is 2-31 with 31 being the worst quality.
  • The scale is linear with double the qscale being roughly half the bitrate.
  • Recommend trying values of 2-5.
  • You can use a value of 1 but you must add the -qmin 1 output option (because the default is -qmin 2).

To output a series of images:

ffmpeg -i input.mp4 -qscale:v 2 output_%03d.jpg

See the image muxer documentation for more options involving image outputs.

To output a single image at ~60 seconds duration:

ffmpeg -ss 60 -i input.mp4 -qscale:v 4 -frames:v 1 output.jpg

Also see

Where can I set path to make.exe on Windows?

here I'm providing solution to setup terraform enviroment variable in windows to beginners.

  1. Download the terraform package from portal either 32/64 bit version.
  2. make a folder in C drive in program files if its 32 bit package you have to create folder inside on programs(x86) folder or else inside programs(64 bit) folder.
  3. Extract a downloaded file in this location or copy terraform.exe file into this folder. copy this path location like C:\Programfile\terraform\
  4. Then got to Control Panel -> System -> System settings -> Environment Variables

Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\

and Save it.

  1. Open new terminal and now check the terraform.

How to get all properties values of a JavaScript Object (without knowing the keys)?

For those early adapting people on the CofeeScript era, here's another equivalent for it.

val for key,val of objects

Which may be better than this because the objects can be reduced to be typed again and decreased readability.

objects[key] for key of objects

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How to implement "select all" check box in HTML?

Demo http://jsfiddle.net/H37cb/

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>

<script type="text/javascript">
$(document).ready(function(){

$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).attr('checked', status);
});

});
</script>




<div id="wrapper">
 <li style="margin-top: 20px">
  <input type="checkbox" name="all" id="all" /> <label for='all'>All</label>
  <ul>
   <li><input type="checkbox" name="title" id="title_1" /> <label for="title_1"><strong>Title 01</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_1" value="1" /> <label for="box_1">Sub Title 01</label></li>
     <li><input type="checkbox" name="selected[]" id="box_2" value="2" /> <label for="box_2">Sub Title 02</label></li>
     <li><input type="checkbox" name="selected[]" id="box_3" value="3" /> <label for="box_3">Sub Title 03</label></li>
     <li><input type="checkbox" name="selected[]" id="box_4" value="4" /> <label for="box_4">Sub Title 04</label></li>
    </ul>
   </li>
  </ul>
  <ul>
   <li><input type="checkbox" name="title" id="title_2" /> <label for="title_2"><strong>Title 02</strong></label>
    <ul>
     <li><input type="checkbox" name="selected[]" id="box_5" value="5" /> <label for="box_5">Sub Title 05</label></li>
     <li><input type="checkbox" name="selected[]" id="box_6" value="6" /> <label for="box_6">Sub Title 06</label></li>
     <li><input type="checkbox" name="selected[]" id="box_7" value="7" /> <label for="box_7">Sub Title 07</label></li>
    </ul>
   </li>
  </ul>
 </li>
</div>

Dynamic Web Module 3.0 -- 3.1

I had the same problem and fixed this by editing org.eclipse.wst.common.project.facet.core.xml.

In this file, I was able to change the following line

<installed facet="jst.web" version="3.1"/>

back to

<installed facet="jst.web" version="3.0"/>

That seemed to fix the problem for me.

Insert string at specified position

str_replace($sub_str, $insert_str.$sub_str, $org_str);

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Determine if char is a num or letter

<ctype.h> includes a range of functions for determining if a char represents a letter or a number, such as isalpha, isdigit and isalnum.

The reason why int a = (int)theChar won't do what you want is because a will simply hold the integer value that represents a specific character. For example the ASCII number for '9' is 57, and for 'a' it's 97.

Also for ASCII:

  • Numeric - if (theChar >= '0' && theChar <= '9')
  • Alphabetic -
    if (theChar >= 'A' && theChar <= 'Z' || theChar >= 'a' && theChar <= 'z')

Take a look at an ASCII table to see for yourself.

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

1) Put =Left(E1,5) in F1

2) Copy F1, then select entire F column and paste.

How can I read large text files in Python, line by line, without loading it into memory?

f=open('filename','r').read()
f1=f.split('\n')
for i in range (len(f1)):
    do_something_with(f1[i])

hope this helps.

How to convert a file into a dictionary?

Here's another option...

events = {}
for line in csv.reader(open(os.path.join(path, 'events.txt'), "rb")):
    if line[0][0] == "#":
        continue
    events[line[0]] = line[1] if len(line) == 2 else line[1:]

SQL UPDATE with sub-query that references the same table in MySQL

UPDATE user_account student, (
   SELECT teacher.education_facility_id as teacherid
   FROM user_account teacher
   WHERE teacher.user_account_id = student.teacher_id AND teacher.user_type = 'ROLE_TEACHER'
) teach SET student.student_education_facility_id= teach.teacherid WHERE student.user_type = 'ROLE_STUDENT';

How to position a div scrollbar on the left hand side?

I have the same problem. but when i add direction: rtl; in tabs and accordion combo but it crashes my structure.

The way to do it is add div with direction: rtl; as parent element, and for child div set direction: ltr;.

I use this first https://api.jquery.com/wrap/

$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );

then just simply work with css :)

In children div add to css

 .your_class {
            direction: ltr;    
        }

And to parent div added by jQuery with class .scroll

.scroll {
            unicode-bidi:bidi-override;
            direction: rtl;
            overflow: scroll;
            overflow-x: hidden!important;
        }

Works prefect for me

http://jsfiddle.net/jw3jsz08/1/

ImportError: No module named pythoncom

$ pip3 install pypiwin32

Sometimes using pip3 also works if just pip by itself is not working.

Unix command to check the filesize

I hope ls -lah will do the job. Also if you are new to unix environment please go to http://www.tutorialspoint.com/unix/unix-useful-commands.htm

How to SUM two fields within an SQL query

If you want to add two columns together, all you have to do is add them. Then you will get the sum of those two columns for each row returned by the query.

What your code is doing is adding the two columns together and then getting a sum of the sums. That will work, but it might not be what you are attempting to accomplish.

How to configure Visual Studio to use Beyond Compare

In Visual Studio, go to the Tools menu, select Options, expand Source Control, (In a TFS environment, click Visual Studio Team Foundation Server), and click on the Configure User Tools button.

image to show location of the Configure User Tools button

Click the Add button.

Enter/select the following options for Compare:

  • Extension: .*
  • Operation: Compare
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 /title1=%6 /title2=%7

If using Beyond Compare Professional (3-way Merge):

  • Extension: .*
  • Operation: Merge
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 %3 %4 /title1=%6 /title2=%7 /title3=%8 /title4=%9

If using Beyond Compare v3/v4 Standard or Beyond Compare v2 (2-way Merge):

  • Extension: .*
  • Operation: Merge
  • Command: C:\Program Files\Beyond Compare 3\BComp.exe (replace with the proper path for your machine, including version number)
  • Arguments: %1 %2 /savetarget=%4 /title1=%6 /title2=%7

If you use tabs in Beyond Compare

If you run Beyond Compare in tabbed mode, it can get confused when you diff or merge more than one set of files at a time from Visual Studio. To fix this, you can add the argument /solo to the end of the arguments; this ensures each comparison opens in a new window, working around the issue with tabs.

What is the difference between Cygwin and MinGW?

Cygwin is designed to provide a more-or-less complete POSIX environment for Windows, including an extensive set of tools designed to provide a full-fledged Linux-like platform. In comparison, MinGW and MSYS provide a lightweight, minimalist POSIX-like layer, with only the more essential tools like gcc and bash available. Because of MinGW's more minimalist approach, it does not provide the degree of POSIX API coverage Cygwin offers, and therefore cannot build certain programs which can otherwise be compiled on Cygwin.

In terms of the code generated by the two, the Cygwin toolchain relies on dynamic linking to a large runtime library, cygwin1.dll, while the MinGW toolchain compiles code to binaries that link dynamically to the Windows native C library msvcrt.dll as well as statically to parts of glibc. Cygwin executables are therefore more compact but require a separate redistributable DLL, while MinGW binaries can be shipped standalone but tend to be larger.

The fact that Cygwin-based programs require a separate DLL to run also leads to licensing restrictions. The Cygwin runtime library is licensed under GPLv3 with a linking exception for applications with OSI-compliant licenses, so developers wishing to build a closed-source application around Cygwin must acquire a commercial license from Red Hat. On the other hand, MinGW code can be used in both open-source and closed-source applications, as the headers and libraries are permissively licensed.

Load text file as strings using numpy.loadtxt()

There is also read_csv in Pandas, which is fast and supports non-comma column separators and automatic typing by column:

import pandas as pd
df = pd.read_csv('your_file',sep='\t')

It can be converted to a NumPy array if you prefer that type with:

import numpy as np
arr = np.array(df)

This is by far the easiest and most mature text import approach I've come across.

How to revert uncommitted changes including files and folders?

git clean -fd

didn't help, new files remained. What I did is totally deleting all the working tree and then

git reset --hard

See "How do I clear my local working directory in git?" for advice to add the -x option to clean:

git clean -fdx

Note -x flag will remove all files ignored by Git so be careful (see discussion in the answer I refer to).

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

Postgres: clear entire database before re-creating / re-populating from bash script

If you don't actually need a backup of the database dumped onto disk in a plain-text .sql script file format, you could connect pg_dump and pg_restore directly together over a pipe.

To drop and recreate tables, you could use the --clean command-line option for pg_dump to emit SQL commands to clean (drop) database objects prior to (the commands for) creating them. (This will not drop the whole database, just each table/sequence/index/etc. before recreating them.)

The above two would look something like this:

pg_dump -U username --clean | pg_restore -U username

Show special characters in Unix while using 'less' Command

All special, nonprintable characters are displayed using ^ notation in less. However, line feed is actually printable (just make a new line), so not considered special, so you'll have problems replacing it. If you just want to see line endings, the easiest way might be

sed -e 's/$/$/' | less

Why powershell does not run Angular commands?

Remove ng.ps1 from the directory C:\Users\%username%\AppData\Roaming\npm\ then try clearing the npm cache at C:\Users\%username%\AppData\Roaming\npm-cache\

Recursively list all files in a directory including files in symlink directories

in case you would like to print all file contents: find . -type f -exec cat {} +

How to automatically generate a stacktrace when my program crashes

ulimit -c <value> sets the core file size limit on unix. By default, the core file size limit is 0. You can see your ulimit values with ulimit -a.

also, if you run your program from within gdb, it will halt your program on "segmentation violations" (SIGSEGV, generally when you accessed a piece of memory that you hadn't allocated) or you can set breakpoints.

ddd and nemiver are front-ends for gdb which make working with it much easier for the novice.

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

How can I uninstall npm modules in Node.js?

To uninstall the Node.js module:

npm uninstall <module_name>

This will remove the module from folder node_modules, but not from file package.json.

Remove the module from package.json use by using this command:

npm uninstall <module_name> --save

This also deletes it from package.json.

How to reload the current route with the angular 2 router

just use native javascript reload method:

reloadPage() {
    window.location.reload();
}

log4net vs. Nlog

I was recently tasked to "prototype up some loggin'" for an upcoming project. I didn't have any logging framework experience. I researched, ran through tutorials, made toy apps, etc. on Log4Net, NLog, and Enterprise Library for a few days. Came back 3-4 weeks later and put them together into a cohesive demo. Hopefully some of this is useful to you.

My recommendation for our project is this:

  1. Use a logging facade (e.g. Common.Logging, SimpleLoggingFacade) to avoid direct dependencies.
  2. If we end up using Enterprise Library for other facilities, then use it for Logging, too.
  3. If we end up using something with a dependency on Log4Net, use Log4Net.
  4. If none of the above, use NLog. Which I'd prefer.

That's based on these findings (opinions!):

  • All 3 frameworks are capable and can do some sophisticated things. We want a quality solution, but frankly don't need ultra high performance or 60 types of event sinks.
  • All 3 have very similar basic concepts.
  • Each has its own cool tricks, like really advanced routing, or dynamic log filenames, file truncating, etc.
  • All 3 are pretty well documented in their own way.
  • For a complete newb like me, they were all a little awkward initially. No drastic differences here for the basics. I got over it.
  • When revisiting things a few weeks later, NLog was clearly the easiest to resume. I needed very little brush up on it. With Log4Net, I had to revisit a few online examples to get going. With EntLib, I gave up and did the tutorials all over again from scratch - I was totally lost.
  • I couldn't figure out how to get EntLib to do some things like log to the database. It might be easy, but it was beyond my time limit.
  • Log4Net and NLog have a small in-code footprint. EntLib is spammy, but I'd use a facade over it anyway.
  • I accidentally mis-configured EntLib and it told me at run time. Log4Net didn't. I didn't have an accidental mis-config with NLog.
  • EntLib comes with a nice looking app.config editor, which you 100% need. NLog has a config file schema so you get "intellisense". Log4Net comes with nada.

So obviously I like NLog so far. Not enough to use it in spite of having another solution available, though.

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

How can I check which version of Angular I'm using?

On your project folder, open the command terminal and type

ng -v

it will give you a list of items, in that you will be able to see the angular version. See the screenshot.

version details

How to get a Color from hexadecimal Color String

I use this and it works great for me for setting any color I want.

public static final int MY_COLOR = Color.rgb(255, 102, 153);

Set the colors using 0-255 for each red, green and blue then anywhere you want that color used just put MY_COLOR instead of Color.BLUE or Color.RED or any of the other static colors the Color class offers.

Just do a Google search for color chart and it you can find a chart with the correct RGB codes using 0-255.

Console.log(); How to & Debugging javascript

console.log() just takes whatever you pass to it and writes it to a console's log window. If you pass in an array, you'll be able to inspect the array's contents. Pass in an object, you can examine the object's attributes/methods. pass in a string, it'll log the string. Basically it's "document.write" but can intelligently take apart its arguments and write them out elsewhere.

It's useful to outputting occasional debugging information, but not particularly useful if you have a massive amount of debugging output.

To watch as a script's executing, you'd use a debugger instead, which allows you step through the code line-by-line. console.log's used when you need to display what some variable's contents were for later inspection, but do not want to interrupt execution.

Select a Dictionary<T1, T2> with LINQ

A more explicit option is to project collection to an IEnumerable of KeyValuePair and then convert it to a Dictionary.

Dictionary<int, string> dictionary = objects
    .Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
    .ToDictionary(x=>x.Key, x=>x.Value);

RegExp in TypeScript

I think you want to test your RegExp in TypeScript, so you have to do like this:

var trigger = "2",
    regexp = new RegExp('^[1-9]\d{0,2}$'),
    test = regexp.test(trigger);
alert(test + ""); // will display true

You should read MDN Reference - RegExp, the RegExp object accepts two parameters pattern and flags which is nullable(can be omitted/undefined). To test your regex you have to use the .test() method, not passing the string you want to test inside the declaration of your RegExp!

Why test + ""? Because alert() in TS accepts a string as argument, it is better to write it this way. You can try the full code here.

Keep values selected after form submission

Try this solution for keep selected value in dropdown:

<form action="<?php echo get_page_link(); ?>" method="post">
    <select name="<?php echo $field_key['key']; ?>" onchange="javascript: 
       submit()">
    <option value="">All Category</option>
    <?php 
    foreach( $field['choices'] as $key => $value ){ 
       if($post_key==$key){ ?>
          <option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
   }else{?>
  <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
 <?php }
  }?>
 </select>
</form>

Java String.split() Regex

Can you invert your regex so split by the non operation characters?

String ops[] = string.split("[a-z]")
// ops == [+, -, *, /, <, >, >=, <=, == ]   

This obviously doesn't return the variables in the array. Maybe you can interleave two splits (one by the operators, one by the variables)

SVN Repository on Google Drive or DropBox

I would try fossil scm and the Chisel hosting service

simple, self contained and easily interchangeable with git should you desire in future

How to compile for Windows on Linux with gcc/g++?

For Fedora:

# Fedora 18 or greater
sudo dnf group install "MinGW cross-compiler"

# Or (not recommended, because of its deprecation)
sudo yum groupinstall -y "MinGW cross-compiler"

Google Maps API 3 - Custom marker color for default (dot) marker

Sometimes something really simple, can be answered complex. I am not saying that any of the above answers are incorrect, but I would just apply, that it can be done as simple as this:

I know this question is old, but if anyone just wants to change to pin or marker color, then check out the documentation: https://developers.google.com/maps/documentation/android-sdk/marker

when you add your marker simply set the icon-property:

GoogleMap gMap;
LatLng latLng;
....
// write your code...
....
gMap.addMarker(new MarkerOptions()
    .position(latLng)
    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

There are 10 default colors to choose from. If that isn't enough (the simple solution) then I would probably go for the more complex given in the other answers, fulfilling a more complex need.

ps: I've written something similar in another answer and therefore I should refer to that answer, but the last time I did that, I was asked to post the answer since it was so short (as this one)..