Programs & Examples On #Supervisor mode

MySQL count occurrences greater than 2

To get a list of the words that appear more than once together with how often they occur, use a combination of GROUP BY and HAVING:

SELECT word, COUNT(*) AS cnt
FROM words
GROUP BY word
HAVING cnt > 1

To find the number of words in the above result set, use that as a subquery and count the rows in an outer query:

SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    GROUP BY word
    HAVING COUNT(*) > 1
) T1

Struct memory layout in C

You can start by reading the data structure alignment wikipedia article to get a better understanding of data alignment.

From the wikipedia article:

Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory. To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.

From 6.54.8 Structure-Packing Pragmas of the GCC documentation:

For compatibility with Microsoft Windows compilers, GCC supports a set of #pragma directives which change the maximum alignment of members of structures (other than zero-width bitfields), unions, and classes subsequently defined. The n value below always is required to be a small power of two and specifies the new alignment in bytes.

  1. #pragma pack(n) simply sets the new alignment.
  2. #pragma pack() sets the alignment to the one that was in effect when compilation started (see also command line option -fpack-struct[=] see Code Gen Options).
  3. #pragma pack(push[,n]) pushes the current alignment setting on an internal stack and then optionally sets the new alignment.
  4. #pragma pack(pop) restores the alignment setting to the one saved at the top of the internal stack (and removes that stack entry). Note that #pragma pack([n]) does not influence this internal stack; thus it is possible to have #pragma pack(push) followed by multiple #pragma pack(n) instances and finalized by a single #pragma pack(pop).

Some targets, e.g. i386 and powerpc, support the ms_struct #pragma which lays out a structure as the documented __attribute__ ((ms_struct)).

  1. #pragma ms_struct on turns on the layout for structures declared.
  2. #pragma ms_struct off turns off the layout for structures declared.
  3. #pragma ms_struct reset goes back to the default layout.

SQL: how to select a single id ("row") that meets multiple criteria from a single column

I was having a similar issue like yours, except that I wanted a specific subset of 'ancestry'. Hong Ning's query was a good start, except it will return combined records containing duplicates and/or extra ancestries (e.g. it would also return someone with ancestries ('England', 'France', 'Germany', 'Netherlands') and ('England', 'France', 'England'). Supposing you'd want just the three and only the three, you'd need the following query:

SELECT Src.user_id
FROM yourtable Src
WHERE ancestry in ('England', 'France', 'Germany')
    AND EXISTS (
        SELECT user_id
        FROM dbo.yourtable
        WHERE user_id = Src.user_id
        GROUP BY user_id
        HAVING COUNT(DISTINCT ancestry) = 3
        )
GROUP BY user_id
HAVING COUNT(DISTINCT ancestry) = 3

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

How to apply color in Markdown?

When you want to use pure Markdown (without nested HTML), you can use Emojis to draw attention to some fragment of the file, i.e. ??WARNING??, IMPORTANT? or NEW.

How do you round a number to two decimal places in C#?

This is for rounding to 2 decimal places in C#:

label8.Text = valor_cuota .ToString("N2") ;

In VB.NET:

 Imports System.Math
 round(label8.text,2)

Passing Arrays to Function in C++

firstarray and secondarray are converted to a pointer to int, when passed to printarray().

printarray(int arg[], ...) is equivalent to printarray(int *arg, ...)

However, this is not specific to C++. C has the same rules for passing array names to a function.

Getting permission denied (public key) on gitlab

Go to the terminal and regenerate the ssh key again. Type ssh-keygen. It will ask you where you want to save it, type the path.

Then copy the public key to gitlabs platform. It usually starts with ssh-rsa.

How do I insert values into a Map<K, V>?

The syntax is

data.put("John","Taxi driver");

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

If strings starts with in PowerShell

$Group is an object, but you will actually need to check if $Group.samaccountname.StartsWith("string").

Change $Group.StartsWith("S_G_") to $Group.samaccountname.StartsWith("S_G_").

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

script to map network drive

Why not map the network drive but deselect "Reconnect at logon"? The drive will only connect when you try to access it. Note that some applications will fail if they point to it, but if you're accessing files directly through Windows Explorer this works great.

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Have you seen this? Sending email using Smtp.mail.microsoftonline.com

Setting the UseDefaultCredentials after setting the Credentials would be resetting your Credentials property.

Modifying Objects within stream in Java8 while iterating

To get rid from ConcurrentModificationException Use CopyOnWriteArrayList

convert string to date in sql server

Write a function

CREATE FUNCTION dbo.SAP_TO_DATETIME(@input VARCHAR(14))
RETURNS datetime
AS BEGIN
    DECLARE @ret datetime
    DECLARE @dtStr varchar(19)

    SET @dtStr = substring(@input,1,4) + '-' +  substring(@input,5,2) + '-' + substring(@input,7,2)
                + ' ' + substring(@input,9,2) + ':' + substring(@input,11,2) + ':' + substring(@input,13,2);        

    SET @ret = COALESCE(convert(DATETIME, @dtStr, 20),null);
    RETURN @ret
END

Best way to encode Degree Celsius symbol into web page?

I'm not sure why this hasn't come up yet but why don't you use &#8451; (?) or &#8457; (?) for Celsius and Fahrenheit respectively!

Check if an array contains duplicate values

An easy solution, if you've got ES6, uses Set:

_x000D_
_x000D_
function checkIfArrayIsUnique(myArray) {_x000D_
  return myArray.length === new Set(myArray).size;_x000D_
}_x000D_
_x000D_
let uniqueArray = [1, 2, 3, 4, 5];_x000D_
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);_x000D_
_x000D_
let nonUniqueArray = [1, 1, 2, 3, 4, 5];_x000D_
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
_x000D_
_x000D_
_x000D_

How to disable Google Chrome auto update?

I have tried all of these options and none seem to work. Sometimes I actually got a message "GoogleUpdate is disabled" when I checked the "About" page, but somehow a week later it was still updated.

Now I just add GoogleUpdate to the firewall and block internet access. If I check the "About" page I get a message it is updating and after a few seconds that it can't update and I should check my firewall.

Question mark characters displaying within text, why is this?

Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.

Curl Command to Repeat URL Request

You can use any bash looping constructs like FOR, with is compatible to Linux and Mac.

https://tiswww.case.edu/php/chet/bash/bashref.html#Looping-Constructs

In your specific case you can define N iterations, with N is a number defining how many curl executions you want.

for n in {1..N}; do curl <arguments>; done

ex:

for n in {1..20}; do curl -d @notification.json -H 'Content-Type: application/json' localhost:3000/dispatcher/notify; done

Removing first x characters from string?

>>> x = 'lipsum'
>>> x.replace(x[:3], '')
'sum'

Variable is accessed within inner class. Needs to be declared final

If you don't want to make it final, you can always just make it a global variable.

how to implement Pagination in reactJs

I've implemented pagination in pure React JS recently. Here is a working demo: http://codepen.io/PiotrBerebecki/pen/pEYPbY

You would of course have to adjust the logic and the way page numbers are displayed so that it meets your requirements.

Full code:

class TodoApp extends React.Component {
  constructor() {
    super();
    this.state = {
      todos: ['a','b','c','d','e','f','g','h','i','j','k'],
      currentPage: 1,
      todosPerPage: 3
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    this.setState({
      currentPage: Number(event.target.id)
    });
  }

  render() {
    const { todos, currentPage, todosPerPage } = this.state;

    // Logic for displaying todos
    const indexOfLastTodo = currentPage * todosPerPage;
    const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
    const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

    const renderTodos = currentTodos.map((todo, index) => {
      return <li key={index}>{todo}</li>;
    });

    // Logic for displaying page numbers
    const pageNumbers = [];
    for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
      pageNumbers.push(i);
    }

    const renderPageNumbers = pageNumbers.map(number => {
      return (
        <li
          key={number}
          id={number}
          onClick={this.handleClick}
        >
          {number}
        </li>
      );
    });

    return (
      <div>
        <ul>
          {renderTodos}
        </ul>
        <ul id="page-numbers">
          {renderPageNumbers}
        </ul>
      </div>
    );
  }
}


ReactDOM.render(
  <TodoApp />,
  document.getElementById('app')
);

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

MySQL/SQL: Group by date only on a Datetime column

Or:

SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;

More efficient (I think.) Because you don't have to cast mydate twice per row.

How to get logged-in user's name in Access vba?

Public Declare Function GetUserName Lib "advapi32.dll" 
    Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long

....

Dim strLen As Long
Dim strtmp As String * 256
Dim strUserName As String

strLen = 255
GetUserName strtmp, strLen
strUserName = Trim$(TrimNull(strtmp))

Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

C/C++ check if one bit is set in, i.e. int variable

What the selected answer is doing is actually wrong. The below function will return the bit position or 0 depending on if the bit is actually enabled. This is not what the poster was asking for.

#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))

Here is what the poster was originally looking for. The below function will return either a 1 or 0 if the bit is enabled and not the position.

#define CHECK_BIT(var,pos) (((var)>>(pos)) & 1)

passing JSON data to a Spring MVC controller

Add the following dependencies

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.7</version>
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-core-asl</artifactId>
    <version>1.9.7</version>
</dependency>

Modify request as follows

$.ajax({ 
    url:urlName,    
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser          
    processData:false, //To avoid making query String instead of JSON
    success: function(resposeJsonObject){
        // Success Message Handler
    }
});

Controller side

@RequestMapping(value = urlPattern , method = RequestMethod.POST)
public @ResponseBody Person save(@RequestBody Person jsonString) {

   Person person=personService.savedata(jsonString);
   return person;
}

@RequestBody - Covert Json object to java
@ResponseBody- convert Java object to json

How to save an activity state using save instance state?

When an activity is created it's onCreate() method is called.

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

savedInstanceState is an object of Bundle class which is null for the first time, but it contains values when it is recreated. To save Activity's state you have to override onSaveInstanceState().

   @Override
    protected void onSaveInstanceState(Bundle outState) {
      outState.putString("key","Welcome Back")
        super.onSaveInstanceState(outState);       //save state
    }

put your values in "outState" Bundle object like outState.putString("key","Welcome Back") and save by calling super. When activity will be destroyed it's state get saved in Bundle object and can be restored after recreation in onCreate() or onRestoreInstanceState(). Bundle received in onCreate() and onRestoreInstanceState() are same.

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          //restore activity's state
         if(savedInstanceState!=null){
          String reStoredString=savedInstanceState.getString("key");
            }
    }

or

  //restores activity's saved state
 @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
      String restoredMessage=savedInstanceState.getString("key");
    }

Angular - Set headers for every request

HTTP interceptors are now available via the new HttpClient from @angular/common/http, as of Angular 4.3.x versions and beyond.

It's pretty simple to add a header for every request now:

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
 
export class AddHeaderInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Clone the request to add the new header
    const clonedRequest = req.clone({ headers: req.headers.append('Authorization', 'Bearer 123') });

    // Pass the cloned request instead of the original request to the next handle
    return next.handle(clonedRequest);
  }
}

There's a principle of immutability, that's the reason the request needs to be cloned before setting something new on it.

As editing headers is a very common task, there's actually a shortcut for it (while cloning the request):

const clonedRequest = req.clone({ setHeaders: { Authorization: 'Bearer 123' } });

After creating the interceptor, you should register it using the HTTP_INTERCEPTORS provide.

import { HTTP_INTERCEPTORS } from '@angular/common/http';

@NgModule({
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: AddHeaderInterceptor,
    multi: true,
  }],
})
export class AppModule {}

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

The answer may sound silly, but after wasting hours of time, this is how I got it to work

mysql -u root -p

I got the error message

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Even though I was typing the correct password(the temporary password you get when you first install mysql)

I got it right when I typed in the password when the password prompt was blinking

How to change webservice url endpoint?

IMO, the provider is telling you to change the service endpoint (i.e. where to reach the web service), not the client endpoint (I don't understand what this could be). To change the service endpoint, you basically have two options.

Use the Binding Provider to set the endpoint URL

The first option is to change the BindingProvider.ENDPOINT_ADDRESS_PROPERTY property value of the BindingProvider (every proxy implements javax.xml.ws.BindingProvider interface):

...
EchoService service = new EchoService();
Echo port = service.getEchoPort();

/* Set NEW Endpoint Location */
String endpointURL = "http://NEW_ENDPOINT_URL";
BindingProvider bp = (BindingProvider)port;
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointURL);

System.out.println("Server said: " + echo.echo(args[0]));
...

The drawback is that this only works when the original WSDL is still accessible. Not recommended.

Use the WSDL to get the endpoint URL

The second option is to get the endpoint URL from the WSDL.

...
URL newEndpoint = new URL("NEW_ENDPOINT_URL");
QName qname = new QName("http://ws.mycompany.tld","EchoService"); 

EchoService service = new EchoService(newEndpoint, qname);
Echo port = service.getEchoPort();

System.out.println("Server said: " + echo.echo(args[0]));
...

What is causing this error - "Fatal error: Unable to find local grunt"

Install Grunt in node_modules rather than globally

Unable to find local Grunt likely means that you have installed Grunt globally.

The Grunt CLI insists that you install grunt in your local node_modules directory, so Grunt is local to your project.

This will fail:

npm install -g grunt

Do this instead:

npm install grunt --save-dev

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

How to use QueryPerformanceCounter?

Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks() method to it, in particular, to do exactly what you require).

On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).

How to reset form body in bootstrap modal box?

Just find your form and clear before it opens!

    $modal = $('#modal');
    $modal.find('form')[0].reset();

I lose my data when the container exits

the similar problem (and no way Dockerfile alone could fix it) brought me to this page.

stage 0: for all, hoping Dockerfile could fix it: until --dns and --dns-search will appear in Dockerfile support - there is no way to integrate intranet based resources into.

stage 1: after building image using Dockerfile (by the way it's a serious glitch Dockerfile must be in the current folder), having an image to deploy what's intranet based, by running docker run script. example: docker run -d \ --dns=${DNSLOCAL} \ --dns=${DNSGLOBAL} \ --dns-search=intranet \ -t pack/bsp \ --name packbsp-cont \ bash -c " \ wget -r --no-parent http://intranet/intranet-content.tar.gz \ tar -xvf intranet-content.tar.gz \ sudo -u ${USERNAME} bash --norc"

stage 2: applying docker run script in daemon mode providing local dns records to have ability to download and deploy local stuff.

important point: run script should be ending with something like /usr/bin/sudo -u ${USERNAME} bash --norc to keep container running even after the installation scripts finishes.

no, it's not possible to run container in interactive mode for the full automation matter as it will remain inside internal shall command prompt until CTRL-p CTRL-q being pressed.

no, if interacting bash will not be executed at the end of the installation script, the container will terminate immediately after finishes script execution, loosing all installation results.

stage 3: container is still running in background but it's unclear whether container has ended installation procedure or not yet. using following block to determine execution procedure finishes: while ! docker container top ${CONTNAME} | grep "00[[:space:]]\{12\}bash \--norc" - do echo "." sleep 5 done the script will proceed further only after completed installation. and this is the right moment to call: commit, providing current container id as well as destination image name (it may be the same as on the build/run procedure but appended with the local installation purposes tag. example: docker commit containerID pack/bsp:toolchained. see this link on how to get proper containerID

stage 4: container has been updated with the local installs as well as it has been committed into newly assigned image (the one having purposes tag added). it's safe now to stop container running. example: docker stop packbsp-cont

stage5: any moment the container with local installs require to run, start it with the image previously saved. example: docker run -d -t pack/bsp:toolchained

JavaScript Number Split into individual digits

Without converting to string:

function toDigits(number) {
    var left;
    var results = [];

    while (true) {
        left = number % 10;
        results.unshift(left);
        number = (number - left) / 10;
        if (number === 0) {
            break;
        }
    }

    return results;
}

Node.js + Nginx - What now?

answering your question 2:

I would use option b simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

But be ware that if you have multiple cores you should tweak node.js to use all of them.

Convert a timedelta to days, hours and minutes

If you have a datetime.timedelta value td, td.days already gives you the "days" you want. timedelta values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60

MongoDb shuts down with Code 100

For windows i've got same issue.

The fix was - i need to run command line as administrator.

Android: adbd cannot run as root in production builds

For those who rooted the Android device with Magisk, you can install adb_root from https://github.com/evdenis/adb_root. Then adb root can run smoothly.

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

How to pause a YouTube player when hiding the iframe?

This is working fine to me with YT player

 createPlayer(): void {
  return new window['YT'].Player(this.youtube.playerId, {
  height: this.youtube.playerHeight,
  width: this.youtube.playerWidth,
  playerVars: {
    rel: 0,
    showinfo: 0
  }
});
}

this.youtube.player.pauseVideo();

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Here is a simple example for others visiting this old post, but is confused by the example in the question and the other answer:

Delivery -> Package (One -> Many)

CREATE TABLE Delivery(
    Id INT IDENTITY PRIMARY KEY,
    NoteNumber NVARCHAR(255) NOT NULL
)

CREATE TABLE Package(
    Id INT IDENTITY PRIMARY KEY,
    Status INT NOT NULL DEFAULT 0,
    Delivery_Id INT NOT NULL,
    CONSTRAINT FK_Package_Delivery_Id FOREIGN KEY (Delivery_Id) REFERENCES Delivery (Id) ON DELETE CASCADE
)

The entry with the foreign key Delivery_Id (Package) is deleted with the referenced entity in the FK relationship (Delivery).

So when a Delivery is deleted the Packages referencing it will also be deleted. If a Package is deleted nothing happens to any deliveries.

Input and Output binary streams using JERSEY?

I have been composing my Jersey 1.17 services the following way:

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

    public FileStreamingOutput(File file) {
        this.file = file;
    }

    @Override
    public void write(OutputStream output)
            throws IOException, WebApplicationException {
        FileInputStream input = new FileInputStream(file);
        try {
            int bytes;
            while ((bytes = input.read()) != -1) {
                output.write(bytes);
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
            if (output != null) output.close();
            if (input != null) input.close();
        }
    }

}

GET

@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
    if (pdfFileName == null)
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";

    File pdf = new File(Settings.basePath, pdfFileName);
    if (!pdf.exists())
        throw new WebApplicationException(Response.Status.NOT_FOUND);

    return new FileStreamingOutput(pdf);
}

And the client, if you need it:

Client

private WebResource resource;

public InputStream getPDFStream(String filename) throws IOException {
    ClientResponse response = resource.path("pdf").queryParam("name", filename)
        .type("application/pdf").get(ClientResponse.class);
    return response.getEntityInputStream();
}

Load image from url

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.Toast;

public class imageDownload {

    Bitmap bmImg;
    void downloadfile(String fileurl,ImageView img)
    {
        URL myfileurl =null;
        try
        {
            myfileurl= new URL(fileurl);

        }
        catch (MalformedURLException e)
        {

            e.printStackTrace();
        }

        try
        {
            HttpURLConnection conn= (HttpURLConnection)myfileurl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            int length = conn.getContentLength();
            int[] bitmapData =new int[length];
            byte[] bitmapData2 =new byte[length];
            InputStream is = conn.getInputStream();
            BitmapFactory.Options options = new BitmapFactory.Options();

            bmImg = BitmapFactory.decodeStream(is,null,options);

            img.setImageBitmap(bmImg);

            //dialog.dismiss();
            } 
        catch(IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
//          Toast.makeText(PhotoRating.this, "Connection Problem. Try Again.", Toast.LENGTH_SHORT).show();
        }


    }


}

in your activity take imageview & set resource imageDownload(url,yourImageview);

Calculate time difference in Windows batch file

Using a single function with the possibility of custom unit of measure or formatted. Each time the function is called without parameters we restarted the initial time.

@ECHO OFF

ECHO.
ECHO DEMO timer function
ECHO --------------------

SET DELAY=4

:: First we call the function without any parameters to set the starting time
CALL:timer

:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.

ping -n %DELAY% -w 1 127.0.0.1 >NUL

:: Now we call the function again with the desired parameters

CALL:timer elapsed_time

ECHO by Default : %elapsed_time%

CALL:timer elapsed_time "s"

ECHO in Seconds : %elapsed_time%

CALL:timer elapsed_time "anything"

ECHO Formatted  : %elapsed_time%  (HH:MM:SS.CS)

ECHO.
PAUSE


:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters 
:: to be in another unit of measure or with formatted
::
::  Parameters:
::             <return>     the returned value
::             [formatted]  s (for seconds), m (for minutes), h (for hours)
::                          anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
    SetLocal EnableExtensions EnableDelayedExpansion

    SET _t=%time%
    SET _t=%_t::0=: %
    SET _t=%_t:,0=, %
    SET _t=%_t:.0=. %
    SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
    SET /A _t=%_t%

    :: If we call the function without parameters is defined initial time
    SET _r=%~1
    IF NOT DEFINED _r (
        EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
    )

    SET /A _t=%_t% - %TIMER_START_TIME%

    :: In the case of wanting a formatted output
    SET _f=%~2
    IF DEFINED _f (

        IF "%_f%" == "s" (

            SET /A "_t=%_t% / 100"

        ) ELSE (
            IF "%_f%" == "m" (

                SET /A "_t=%_t% / 6000"

            ) ELSE (

                IF "%_f%" == "h" (

                    SET /A "_t=%_t% / 360000"

                ) ELSE (

                    SET /A "_h=%_t% / 360000"
                    SET /A "_m=(%_t% - !_h! * 360000) / 6000"
                    SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
                    SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"

                    IF !_h! LSS 10 SET "_h=0!_h!"
                    IF !_m! LSS 10 SET "_m=0!_m!"
                    IF !_s! LSS 10 SET "_s=0!_s!"
                    IF !_cs! LSS 10 SET "_cs=0!_cs!"
                    SET "_t=!_h!:!_m!:!_s!.!_cs!"
                    SET "_t=!_t:00:=!"

                )
            )
        )
    )

    EndLocal & SET %~1=%_t%
goto :EOF

A test with a delay of 94 sec

DEMO timer function
--------------------

Making some delay, please wait...

by Default : 9404
in Seconds : 94
Formatted  : 01:34.05  (HH:MM:SS.CS)

Presione una tecla para continuar . . .

HTML entity for check mark

Something like this?

if so, type the HTML &#10004;

And &#10003; gives a lighter one:

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Good to see someone's chimed in about Lucene - because I've no idea about that.

Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.

  • Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
  • Indexing speed is super-fast, because it talks directly to the database. Any slowness will come from complex SQL queries and un-indexed foreign keys and other such problems. I've never noticed any slowness in searching either.
  • I'm a Rails guy, so I've no idea how easy it is to implement with Django. There is a Python API that comes with the Sphinx source though.
  • The search service daemon (searchd) is pretty low on memory usage - and you can set limits on how much memory the indexer process uses too.
  • Scalability is where my knowledge is more sketchy - but it's easy enough to copy index files to multiple machines and run several searchd daemons. The general impression I get from others though is that it's pretty damn good under high load, so scaling it out across multiple machines isn't something that needs to be dealt with.
  • There's no support for 'did-you-mean', etc - although these can be done with other tools easily enough. Sphinx does stem words though using dictionaries, so 'driving' and 'drive' (for example) would be considered the same in searches.
  • Sphinx doesn't allow partial index updates for field data though. The common approach to this is to maintain a delta index with all the recent changes, and re-index this after every change (and those new results appear within a second or two). Because of the small amount of data, this can take a matter of seconds. You will still need to re-index the main dataset regularly though (although how regularly depends on the volatility of your data - every day? every hour?). The fast indexing speeds keep this all pretty painless though.

I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.

I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.

Remove characters after specific character in string, then remove substring?

Request.QueryString helps you to get the parameters and values included within the URL

example

string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();

so the customername variable should be equal to dave

regards

Pull all images from a specified directory and then display them

Strict Standards: Only variables should be passed by reference in /home/aadarshi/public_html/----------/upload/view.php on line 32

and the code is:

<?php

echo scanDirectoryImages("uploads");

/**
* Recursively search through directory for images and display them
* 
* @param  array  $exts
* @param  string $directory
* @return string
*/
function scanDirectoryImages($directory, array $exts = array('jpeg', 'jpg', 'gif', 'png'))
{
if (substr($directory, -1) == '/') {
    $directory = substr($directory, 0, -1);
}
$html = '';
if (
    is_readable($directory)
    && (file_exists($directory) || is_dir($directory))
) {
    $directoryList = opendir($directory);
    while($file = readdir($directoryList)) {
        if ($file != '.' && $file != '..') {
            $path = $directory . '/' . $file;
            if (is_readable($path)) {
                if (is_dir($path)) {
                    return scanDirectoryImages($path, $exts);
                }
                if (
                    is_file($path)
                    && in_array(end(explode('.', end(explode('/', $path)))),   $exts)
                ) {
                    $html .= '<a href="' . $path . '"><img src="' . $path
                        . '" style="max-height:100px;max-width:100px" />  </a>';
                }
            }
        }
    }
    closedir($directoryList);
}
return $html;
}

Writing html form data to a txt file without the use of a webserver

i made a little change to this code to save entry of a radio button but unable to save the text which appears in text box after selecting the radio button.

the code is below:-

    <!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 

encodeURIComponent(text));
  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>

<form onsubmit="download(this['name'].value, this['text'].value)">
  <input type="text" name="name" value="test.txt">
  <textarea rows=3 cols=50 name="text">PLEASE WRITE ANSWER HERE. </textarea>
<input type="radio" name="radio" value="Option 1" onclick="getElementById('problem').value=this.value;"> Option 1<br>
<input type="radio" name="radio" value="Option 2" onclick="getElementById('problem').value=this.value;"> Option 2<br>
<form onsubmit="download(this['name'].value, this['text'].value)">
<input type="text" name="problem" id="problem">
  <input type="submit" value="SAVE">
</form>
</body>
</html>

Unfortunately MyApp has stopped. How can I solve this?

This popup shows only when you get a fatal exception in your code which stops the execution of the app. It could be any exception NullPointerException, OutOfMemoryException etc.

Best way to check is through Logcat if you are still developing the app in Android studio which is quick way to read stack trace and check the cause of the app.

If your app is already live, then you can not use logcat. So, for that you can implement Crashlytics to provide you bug reports of any exception that occurs.

Check if string is neither empty nor space in shell script

In case you need to check against any amount of whitespace, not just single space, you can do this:

To strip string of extra white space (also condences whitespace in the middle to one space):

trimmed=`echo -- $original`

The -- ensures that if $original contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put "" around $original, or the spaces will not get removed.

After that you can just check if $trimmed is empty.

[ -z "$trimmed" ] && echo "empty!"

How to upgrade scikit-learn package in anaconda

So to upgrade scikit-learn package, you have to follow below process

Step-1: Open your terminal(Ctrl+Alt+t)

Step-2: Now for checking currently installed packages along with the versions installed on your conda environment by typing conda list

Step-3: Now for upgrade type below command

conda update scikit-learn

Hope it helps!!

Get querystring from URL using jQuery

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

ImportError: No module named Crypto.Cipher

It could be a problem of loading python modules installed via pip. Refer to this answer Can't load Python modules installed via pip from site-packages directory and try something like

python -m pip install pycrypto

How to view hierarchical package structure in Eclipse package explorer

For Eclipse in Macbook it is just 2 click process:

  • Click on view menu (3 dot symbol) in package explorer -> hover over package presentation -> Click on Hierarchical

enter image description here

Best practice for partial updates in a RESTful service

Check out http://www.odata.org/

It defines the MERGE method, so in your case it would be something like this:

MERGE /customer/123

<customer>
   <status>DISABLED</status>
</customer>

Only the status property is updated and the other values are preserved.

Remove the last line from a file in Bash

You can try this method also : example of removing last n number of lines.

a=0 ; while [ $a -lt 4 ];do sed -i '$ d' output.txt; a=expr $a + 1;done

Removing last 4 lines from file(output.txt).

Link a photo with the cell in excel

Hold down the Alt key and drag the pictures to snap to the upper left corner of the cell.

Format the picture and in the Properties tab select "Move but don't size with cells"

Now you can sort the data table by any column and the pictures will stay with the respective data.

This post at SuperUser has a bit more background and screenshots: https://superuser.com/questions/712622/put-an-equation-object-in-an-excel-cell/712627#712627

Why is visible="false" not working for a plain html table?

Use display: none instead. Besides, this is probably what you need, because this also truncates the page by removing the space the table occupies, whereas visibility: hidden leaves the white space left by the table.

How to access parameters in a Parameterized Build?

When you add a build parameter, foo, it gets converted to something which acts like a "bare variable", so in your script you would do:

node {
   echo foo
}

If you look at the implementation of the workflow script, you will see that when a script is executed, a class called WorkflowScript is dynamically generated. All statements in the script are executed in the context of this class. All build parameters passed down to this script are converted to properties which are accessible from this class.

For example, you can do:

node {
    getProperty("foo")
}

If you are curious, here is a workflow script I wrote which attempts to print out the build parameters, environment variables, and methods on the WorkflowScript class.

node {
   echo "I am a "+getClass().getName()

   echo "PARAMETERS"
   echo "=========="
   echo getBinding().getVariables().getClass().getName()
   def myvariables = getBinding().getVariables()
   for (v in myvariables) {
       echo "${v} " + myvariables.get(v)
   }
   echo STRING_PARAM1.getClass().getName()

   echo "METHODS"
   echo "======="
   def methods = getMetaClass().getMethods()

   for (method in methods) {
       echo method.getName()    
   } 

   echo "PROPERTIES"
   echo "=========="
   properties.each{ k, v -> 
       println "${k} ${v}" 
   }
   echo properties
   echo properties["class"].getName()

   echo "ENVIRONMENT VARIABLES"
   echo "======================"
   echo "env is " + env.getClass().getName()
   def envvars = env.getEnvironment()
   envvars.each{ k, v ->
        println "${k} ${v}"
   }
}

Here is another code example I tried, where I wanted to test to see if a build parameter was set or not.

node {
   groovy.lang.Binding myBinding = getBinding()
   boolean mybool = myBinding.hasVariable("STRING_PARAM1")
   echo mybool.toString()
   if (mybool) {
       echo STRING_PARAM1
       echo getProperty("STRING_PARAM1")
   } else {
       echo "STRING_PARAM1 is not defined"
   }

   mybool = myBinding.hasVariable("DID_NOT_DEFINE_THIS")
   if (mybool) {
       echo DID_NOT_DEFINE_THIS
       echo getProperty("DID_NOT_DEFINE_THIS")
   } else {
       echo "DID_NOT_DEFINE_THIS is not defined"
   }
}

Warning: Failed propType: Invalid prop `component` supplied to `Route`

it is solved in react-router-dom 4.4.0 see: Route's proptypes fail

now it is beta, or just wait for final release.

npm install [email protected] --save

How to extract a substring using regex

There's a simple one-liner for this:

String target = myData.replaceAll("[^']*(?:'(.*?)')?.*", "$1");

By making the matching group optional, this also caters for quotes not being found by returning a blank in that case.

See live demo.

How to change link color (Bootstrap)

using bootstrap 4 and SCSS check out this link here for full details

https://getbootstrap.com/docs/4.0/getting-started/theming/

in a nutshell...

open up lib/bootstrap/scss/_navbar.scss and find the statements that create these variables

  .navbar-nav {
    .nav-link {
      color: $navbar-light-color;

      @include hover-focus() {
        color: $navbar-light-hover-color;
      }

      &.disabled {
        color: $navbar-light-disabled-color;
      }
    }

so now you need to override

$navbar-light-color
$navbar-light-hover-color
$navbar-light-disabled-color

create a new scss file _localVariables.scss and add the following (with your colors)

$navbar-light-color : #520b71
$navbar-light-hover-color: #F3EFE6;
$navbar-light-disabled-color: #F3EFE6;

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

and on your other scss pages just add

@import "_localVariables";

instead of

@import "../lib/bootstrap/scss/functions";
@import "../lib/bootstrap/scss/variables";
@import "../lib/bootstrap/scss/mixins/_breakpoints";

CSS Font Border?

There seems to be a 'text-stroke' property, but (at least for me) it only works in Safari.

http://webkit.org/blog/85/introducing-text-stroke/

Can't find how to use HttpContent

I'm pretty sure the code is not using the System.Net.Http.HttpContent class, but instead Microsoft.Http.HttpContent. Microsoft.Http was the WCF REST Starter Kit, which never made it out preview before being placed in the .NET Framework. You can still find it here: http://aspnet.codeplex.com/releases/view/24644

I would not recommend basing new code on it.

How to display custom view in ActionBar?

For example, you can define a layout file which contains a EditText element.

<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/searchfield"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:inputType="textFilter" >

</EditText> 

you can do

public class MainActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ActionBar actionBar = getActionBar();
    // add the custom view to the action bar
    actionBar.setCustomView(R.layout.actionbar_view);
    EditText search = (EditText) actionBar.getCustomView().findViewById(R.id.searchfield);
    search.setOnEditorActionListener(new OnEditorActionListener() {

      @Override
      public boolean onEditorAction(TextView v, int actionId,
          KeyEvent event) {
        Toast.makeText(MainActivity.this, "Search triggered",
            Toast.LENGTH_LONG).show();
        return false;
      }
    });
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
        | ActionBar.DISPLAY_SHOW_HOME);


    }

Error in Eclipse: "The project cannot be built until build path errors are resolved"

In Eclipse, go to Build Path, click "Add Library", select JRE System Library, click "Next", select option "Workspace default JRE(i)", and click "Finish".

This worked for me.

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

Matlab: Running an m-file from command-line

I run this command within a bash script, in particular to submit SGE jobs and batch process things:

/Path_to_matlab -nodisplay -nosplash -nodesktop < m_file.m

JQuery post JSON object to a server

It is also possible to use FormData(). But you need to set contentType as false:

var data = new FormData();
data.append('name', 'Bob'); 

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: false,
        data: data,
        dataType: 'json'
    });
}

What's the purpose of git-mv?

git mv moves the file, updating the index to record the replaced file path, as well as updating any affected git submodules. Unlike a manual move, it also detects case-only renames that would not otherwise be detected as a change by git.

It is similar (though not identical) in behavior to moving the file externally to git, removing the old path from the index using git rm, and adding the new one to the index using git add.

Answer Motivation

This question has a lot of great partial answers. This answer is an attempt to combine them into a single cohesive answer. Additionally, one thing not called out by any of the other answers is the fact that the man page actually does mostly answer the question, but it's perhaps less obvious than it could be.

Detailed Explanation

Three different effects are called out in the man page:

  1. The file, directory, or symlink is moved in the filesystem:

    git-mv - Move or rename a file, a directory, or a symlink

  2. The index is updated, adding the new path and removing the previous one:

    The index is updated after successful completion, but the change must still be committed.

  3. Moved submodules are updated to work at the new location:

    Moving a submodule using a gitfile (which means they were cloned with a Git version 1.7.8 or newer) will update the gitfile and core.worktree setting to make the submodule work in the new location. It also will attempt to update the submodule.<name>.path setting in the gitmodules(5) file and stage that file (unless -n is used).

As mentioned in this answer, git mv is very similar to moving the file, adding the new path to the index, and removing the previous path from the index:

mv oldname newname
git add newname
git rm oldname

However, as this answer points out, git mv is not strictly identical to this in behavior. Moving the file via git mv adds the new path to the index, but not any modified content in the file. Using the three individual commands, on the other hand, adds the entire file to the index, including any modified content. This could be relevant when using a workflow which patches the index, rather than adding all changes in the file.

Additionally, as mentioned in this answer and this comment, git mv has the added benefit of handling case-only renames on file systems that are case-insensitive but case-preserving, as is often the case in current macOS and Windows file systems. For example, in such systems, git would not detect that the file name has changed after moving a file via mv Mytest.txt MyTest.txt, whereas using git mv Mytest.txt MyTest.txt would successfully update its name.

Opacity of background-color, but not the text

Relaxing your requirement to work on IE6 and legacy browsers you can use ::before and display: inline-block

div
{
  display: inline-block;
  position: relative;    
}
div::before
{
  content: "";
  display: block;
  position: absolute;
  z-index: -1;
  width: 100%;
  height: 100%;
  background:red;
  opacity: .2;
}

Demo at http://jsfiddle.net/KVyFH/172/ ?

It will work on any modern browser

How to create a library project in Android Studio and an application project that uses the library project

Check out this link about multi project setups.

Some things to point out, make sure you have your settings.gradle updated to reference both the app and library modules.

settings.gradle: include ':app', ':libraries:lib1', ':libraries:lib2'

Also make sure that the app's build.gradle has the followng:

dependencies {
     compile project(':libraries:lib1')
}

You should have the following structure:

 MyProject/
  | settings.gradle
  + app/
    | build.gradle
  + libraries/
    + lib1/
       | build.gradle
    + lib2/
       | build.gradle

The app's build.gradle should use the com.android.application plugin while any libraries' build.gradle should use the com.android.library plugin.

The Android Studio IDE should update if you're able to build from the command line with this setup.

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

LaTeX source code listing like in professional books

And please, whatever you do, configure the listings package to use fixed-width font (as in your example; you'll find the option in the documentation). Default setting uses proportional font typeset on a grid, which is, IMHO, incredibly ugly and unreadable, as can be seen from the other answers with pictures. I am personally very irritated when I must read some code typeset in a proportional font.

Try setting fixed-width font with this:

\lstset{basicstyle=\ttfamily}

How to test Spring Data repositories?

With JUnit5 and @DataJpaTest test will look like (kotlin code):

@DataJpaTest
@ExtendWith(value = [SpringExtension::class])
class ActivityJpaTest {

    @Autowired
    lateinit var entityManager: TestEntityManager

    @Autowired
    lateinit var myEntityRepository: MyEntityRepository

    @Test
    fun shouldSaveEntity() {
        // when
        val savedEntity = myEntityRepository.save(MyEntity(1, "test")

        // then 
        Assertions.assertNotNull(entityManager.find(MyEntity::class.java, savedEntity.id))
    }
}

You could use TestEntityManager from org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager package in order to validate entity state.

How to solve "Kernel panic - not syncing - Attempted to kill init" -- without erasing any user data

Mount remount the /
Eg.

  1. mount -o remount,rw /dev/xyz /
  2. sed -i 's/1 1/0 0/' /etc/fstab
  3. sed -i 's/1 2/0 0/' /etc/fstab
  4. reboot

How to check if a service is running via batch file and start it, if it is not running?

@echo off

color 1F


@sc query >%COMPUTERNAME%_START.TXT


find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul

IF ERRORLEVEL 0 EXIT

IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"

ALTER TABLE add constraint

alter table User 
    add constraint userProperties
    foreign key (properties)
    references Properties(ID)

Dynamically allocating an array of objects

For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.

If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).

  • Constructor
  • Destructor
  • Copy Constructor
  • Assignment Operator
  • Move Constructor (C++11)
  • Move Assignment (C++11)

This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.

The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.

See below for full details on the absolute minimum for a class containing a pointer to an array of integers.

Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.

class A
{ 
    std::vector<int>   mArray;
    public:
        A(){}
        A(size_t s) :mArray(s)  {}
};

Looking at your problem:

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    // As you surmised the problem is on this line.
    arrayOfAs[i] = A(3);

    // What is happening:
    // 1) A(3) Build your A object (fine)
    // 2) A::operator=(A const&) is called to assign the value
    //    onto the result of the array access. Because you did
    //    not define this operator the compiler generated one is
    //    used.
}

The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.

The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

So the minimum for a class that contains a pointer:

class A
{
    size_t     mSize;
    int*       mArray;
    public:
         // Simple constructor/destructor are obvious.
         A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
        ~A()             {delete [] mArray;}

         // Copy constructor needs more work
         A(A const& copy)
         {
             mSize  = copy.mSize;
             mArray = new int[copy.mSize];

             // Don't need to worry about copying integers.
             // But if the object has a copy constructor then
             // it would also need to worry about throws from the copy constructor.
             std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);

         }

         // Define assignment operator in terms of the copy constructor
         // Modified: There is a slight twist to the copy swap idiom, that you can
         //           Remove the manual copy made by passing the rhs by value thus
         //           providing an implicit copy generated by the compiler.
         A& operator=(A rhs) // Pass by value (thus generating a copy)
         {
             rhs.swap(*this); // Now swap data with the copy.
                              // The rhs parameter will delete the array when it
                              // goes out of scope at the end of the function
             return *this;
         }
         void swap(A& s) noexcept
         {
             using std::swap;
             swap(this.mArray,s.mArray);
             swap(this.mSize ,s.mSize);
         }

         // C++11
         A(A&& src) noexcept
             : mSize(0)
             , mArray(NULL)
         {
             src.swap(*this);
         }
         A& operator=(A&& src) noexcept
         {
             src.swap(*this);     // You are moving the state of the src object
                                  // into this one. The state of the src object
                                  // after the move must be valid but indeterminate.
                                  //
                                  // The easiest way to do this is to swap the states
                                  // of the two objects.
                                  //
                                  // Note: Doing any operation on src after a move 
                                  // is risky (apart from destroy) until you put it 
                                  // into a specific state. Your object should have
                                  // appropriate methods for this.
                                  // 
                                  // Example: Assignment (operator = should work).
                                  //          std::vector() has clear() which sets
                                  //          a specific state without needing to
                                  //          know the current state.
             return *this;
         }   
 }

Array.size() vs Array.length

array.length isn't necessarily the number of items in the array:

var a = ['car1', 'car2', 'car3'];
a[100] = 'car100';
a.length; // 101

The length of the array is one more than the highest index.

As stated before Array.size() is not a valid method.

More information

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.

< original link no longer active >

http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"

http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"

How to obtain the number of CPUs/cores in Linux from the command line?

You can use one of the following methods to determine the number of physical CPU cores.

  • Count the number of unique core ids (roughly equivalent to grep -P '^core id\t' /proc/cpuinfo | sort -u | wc -l).

    awk '/^core id\t/ {cores[$NF]++} END {print length(cores)}' /proc/cpuinfo

  • Multiply the number of 'cores per socket' by the number of sockets.

    lscpu | awk '/^Core\(s\) per socket:/ {cores=$NF}; /^Socket\(s\):/ {sockets=$NF}; END{print cores*sockets}'

  • Count the number of unique logical CPU's as used by the Linux kernel. The -p option generates output for easy parsing and is compatible with earlier versions of lscpu.

    lscpu -p | awk -F, '$0 !~ /^#/ {cores[$1]++} END {print length(cores)}'


Just to reiterate what others have said, there are a number of related properties.

To determine the number of processors available:

getconf _NPROCESSORS_ONLN
grep -cP '^processor\t' /proc/cpuinfo

To determine the number of processing units available (not necessarily the same as the number of cores). This is hyperthreading-aware.

nproc

I don't want to go too far down the rabbit-hole, but you can also determine the number of configured processors (as opposed to simply available/online processors) via getconf _NPROCESSORS_CONF. To determine total number of CPU's (offline and online) you'd want to parse the output of lscpu -ap.

How to schedule a function to run every hour on Flask?

You can use BackgroundScheduler() from APScheduler package (v3.5.3):

import time
import atexit

from apscheduler.schedulers.background import BackgroundScheduler


def print_date_time():
    print(time.strftime("%A, %d. %B %Y %I:%M:%S %p"))


scheduler = BackgroundScheduler()
scheduler.add_job(func=print_date_time, trigger="interval", seconds=3)
scheduler.start()

# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())

Note that two of these schedulers will be launched when Flask is in debug mode. For more information, check out this question.

javascript Unable to get property 'value' of undefined or null reference

you have many HTML and java script mistakes includes: tag, using non UTF-8 encoding for form submission, no need,... You must use document.forms.FORMNAME or document.forms[0] for first appear form in page Corrected:

_x000D_
_x000D_
 function validate_frm_new_user_request()_x000D_
{_x000D_
    alert('test');_x000D_
    var valid = true;_x000D_
_x000D_
    if ( document.forms.frm_new_user_request.u_userid.value == "" )_x000D_
    {_x000D_
        alert ( "Please enter your valid ISID Information." );_x000D_
        document.forms.frm_new_user_request.u_userid.focus();_x000D_
        valid = false;_x000D_
  console.log("FALSE::Empty Value ");_x000D_
    }_x000D_
return valid;_x000D_
}
_x000D_
<html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta content="text/html;charset=UTF-8" http-equiv="content-type" />_x000D_
_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<form method="post" action="" name="frm_new_user_request" id="frm_new_user_request" onsubmit="return validate_frm_new_user_request();">_x000D_
<center>_x000D_
<table>_x000D_
_x000D_
        <tr align="left">_x000D_
            <td><Label>ISID<em>*:</Label><input maxlength="15" id="u_userid" name="u_userid" size="20" type="text"/></td>_x000D_
            </tr>_x000D_
_x000D_
<tr>_x000D_
            <td align="center" colspan="4">_x000D_
                <input type="image" src="btn.png" border="0" ALT="Create New Request">_x000D_
_x000D_
                </td>_x000D_
        </tr>_x000D_
    </table>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to hide a button programmatically?

For "Xamarin Android":

FindViewById<Button>(Resource.Id.Button1).Visibility = ViewStates.Gone;

GridView - Show headers on empty data source

Add this property to your grid-view : ShowHeaderWhenEmpty="True" it might help just check

For div to extend full height

This might be of some help: http://www.webmasterworld.com/forum83/200.htm

A relevant quote:

Most attempts to accomplish this were made by assigning the property and value: div{height:100%} - this alone will not work. The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.

The solution to the problem is found by assigning a height value to the parent container, in this case, the body element. Writing your body stlye to include height 100% supplies the needed value.

html, body { 
  margin:0; 
  padding:0; 
  height:100%; 
}

`require': no such file to load -- mkmf (LoadError)

I think is a little late but

sudo yum install -y gcc ruby-devel libxml2 libxml2-devel libxslt libxslt-devel

worked for me on fedora.

http://nokogiri.org/tutorials/installing_nokogiri.html

Virtualenv Command Not Found

Figure out the problem

Try installing with the --verbose flag

pip install virtualenv --verbose

Output will look something like this

  ..
  Using cached virtualenv-15.1.0-py2.py3-none-any.whl
  Downloading from URL https://pypi.python.org/packages/6f/86/3dc328ee7b1a6419ebfac7896d882fba83c48e3561d22ddddf38294d3e83/virtualenv-15.1.0-py2.py3-none-any.whl#md5=aa7e5b86cc8cdb99794c4b99e8d670f3 (from https://pypi.python.org/simple/virtualenv/)
Installing collected packages: virtualenv

  changing mode of /home/manos/.local/bin/virtualenv to 755
Successfully installed virtualenv-15.1.0
Cleaning up...

From the output we can see that it's installed at /home/manos/.local/bin/virtualenv so let's ensure PATH includes that.

echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

In my case we can clearly see that /home/manos/.local/bin is totally missing and that's why the shell can't find the program.

Solutions

We can solve this in many ways:

  1. We can install directly to a specific directory by fiddling with pip options (not recomended).
  2. Create appropriate symlinks at /usr/local/bin or similar.
  3. Append /home/manos/.local/bin to PATH.
  4. Install as sudo to install directly to /usr/local/bin

The two last options are probably the most sensible. The last solution is the simplest so therefore I will just show solution 3.

Add this to ~/.profile:

PATH="$PATH:$HOME/.local/bin"

Logout out and in again and it should work.

How to make a submit out of a <a href...>...</a> link?

Something like this page ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>BSO Communication</title>

<style type="text/css">
.submit {
    border : 0;
    background : url(ok.gif) left top no-repeat;
    height : 24px;
    width : 24px;
    cursor : pointer;
    text-indent : -9999px;
}
html:first-child .submit {
    padding-left : 1000px;
}
</style>
<!--[if IE]>
<style type="text/css">
.submit {
    text-indent : 0;
    color : expression(this.value = '');
}
</style>
<![endif]-->
</head>

<body>
    <h1>Display input submit as image with CSS</h1>

    <p>Take a look at <a href="/2007/07/26/afficher-un-input-submit-comme-une-image/">the related article</a> (in french).</p>
    <form action="" method="get">
        <fieldset>
            <legend>Some form</legend>
            <p class="field">
                <label for="input">Some value</label>

                <input type="text" id="input" name="value" />
                <input type="submit" class="submit" />
            </p>
        </fieldset>
    </form>

    <hr />
    <p>This page is part of the <a href="http://www.bsohq.fr">BSO Communication blog</a>.</p>

</body>
</html>

What data is stored in Ephemeral Storage of Amazon EC2 instance?

According to AWS documentation [https://aws.amazon.com/premiumsupport/knowledge-center/instance-store-vs-ebs/] instance store volumes is not persistent through instance stops, terminations, or hardware failures. Any AMI created from instance stored disk doesn't contain data present in instance store so all instances launched by this AMI will not have data stored in instance store. Instance store can be used as cache for applications running on instance, for all persistent data you should use EBS.

How to clear the entire array?

It is as simple as :

Erase aFirstArray

Java 8 method references: provide a Supplier capable of supplying a parameterized result

optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));

How to loop and render elements in React-native?

You would usually use map for that kind of thing.

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);

(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)

As a side, I would use an object instead of an array. I find it looks nicer:

initialArr = [
  {
    id: 1,
    color: "blue",
    text: "text1"
  },
  {
    id: 2,
    color: "red",
    text: "text2"
  },
];

buttonsListArr = initialArr.map(buttonInfo => (
  <Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);

How to remove old Docker containers

You can stop the docker container and once it is stopped you can remove the container.

Stop the container:

$ docker stop "containerID" - you can also mention the first two letters of the container ID, and it works.

Remove the container

$ docker rm "containerID" - again you can also mention the first two letters of the container

If these command do not let you stop/remove the containers, m,ake sure you have sudo access to docker host.

How to display length of filtered ng-repeat data

The easiest way if you have

<div ng-repeat="person in data | filter: query"></div>

Filtered data length

<div>{{ (data | filter: query).length }}</div>

SELECT FOR UPDATE with SQL Server

How about trying to do a simple update on this row first (without really changing any data)? After that you can proceed with the row like in was selected for update.

UPDATE dbo.Customer SET FieldForLock = FieldForLock WHERE CustomerID = @CustomerID
/* do whatever you want */

Edit: you should wrap it in a transaction of course

Edit 2: another solution is to use SERIALIZABLE isolation level

How might I force a floating DIV to match the height of another floating DIV?

You should wrap them in a div with no float.

<div style="float:none;background:#FDD017;" class="clearfix">
    <div id="response" style="float:left; width:65%;">Response with two lines</div>
    <div id="note" style="float:left; width:35%;">single line note</div>
</div>

I also use the clearfix patch on here http://www.webtoolkit.info/css-clearfix.html

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

Unable to specify the compiler with CMake

I had similar problem as Pietro,

I am on Window 10 and using "Git Bash". I tried to execute >>cmake -G "MinGW Makefiles", but I got the same error as Pietro.

Then, I tried >>cmake -G "MSYS Makefiles", but realized that I need to set my environment correctly.

Make sure set a path to C:\MinGW\msys\1.0\bin and check if you have gcc.exe there. If gcc.exe is not there then you have to run C:/MinGW/bin/mingw-get.exe and install gcc from MSYS.

After that it works fine for me

Http Post request with content type application/x-www-form-urlencoded not working in Spring

You have to tell Spring what input content-type is supported by your service. You can do this with the "consumes" Annotation Element that corresponds to your request's "Content-Type" header.

@RequestMapping(value = "/", method = RequestMethod.POST, consumes = {"application/x-www-form-urlencoded"})

It would be helpful if you posted your code.

How can I use UIColorFromRGB in Swift?

That can be simply done by using this initialization

view.backgroundColor = UIColor(hex: "067AB5")

Notify ObservableCollection when Item changes

All the solutions here are correct,but they are missing an important scenario in which the method Clear() is used, which doesn't provide OldItems in the NotifyCollectionChangedEventArgs object.

this is the perfect ObservableCollection .

public delegate void ListedItemPropertyChangedEventHandler(IList SourceList, object Item, PropertyChangedEventArgs e);
public class ObservableCollectionEX<T> : ObservableCollection<T>
{
    #region Constructors
    public ObservableCollectionEX() : base()
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(IEnumerable<T> c) : base(c)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }
    public ObservableCollectionEX(List<T> l) : base(l)
    {
        CollectionChanged += ObservableCollection_CollectionChanged;
    }

    #endregion



    public new void Clear()
    {
        foreach (var item in this)            
            if (item is INotifyPropertyChanged i)                
                i.PropertyChanged -= Element_PropertyChanged;            
        base.Clear();
    }
    private void ObservableCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.OldItems != null)
            foreach (var item in e.OldItems)                
                if (item != null && item is INotifyPropertyChanged i)                    
                    i.PropertyChanged -= Element_PropertyChanged;


        if (e.NewItems != null)
            foreach (var item in e.NewItems)                
                if (item != null && item is INotifyPropertyChanged i)
                {
                    i.PropertyChanged -= Element_PropertyChanged;
                    i.PropertyChanged += Element_PropertyChanged;
                }
            }
    }
    private void Element_PropertyChanged(object sender, PropertyChangedEventArgs e) => ItemPropertyChanged?.Invoke(this, sender, e);


    public ListedItemPropertyChangedEventHandler ItemPropertyChanged;

}

How to use 'hover' in CSS

The href is a required attribute of an anchor element, so without it, you cannot expect all browsers to handle it equally. Anyway, I read somewhere in a comment that you only want the link to be underlined when hovering, and not otherwise. You can use the following to achieve this, and it will only apply to links with the hover-class:

<a class="hover" href="">click</a>

a.hover {
    text-decoration: none;
}

a.hover:hover {
    text-decoration:underline;
}

Padding characters in printf

This one is even simpler and execs no external commands.

$ PROC_NAME="JBoss"
$ PROC_STATUS="UP"
$ printf "%-.20s [%s]\n" "${PROC_NAME}................................" "$PROC_STATUS"

JBoss............... [UP]

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

Android: How to enable/disable option menu item on button click?

You could save the item as a variable when creating the option menu and then change its properties at will.

private MenuItem securedConnection;
private MenuItem insecuredConnection;

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.connect_menu, menu);
    securedConnection = menu.getItem(0);
    insecuredConnection =  menu.getItem(1);
    return true;
}

public void foo(){
       securedConnection.setEnabled(true);
}    

How to remove listview all items

You can only use

 lv.setAdapter(null);

How do I pass a string into subprocess.Popen (using the stdin argument)?

On Python 3.7+ do this:

my_data = "whatever you want\nshould match this f"
subprocess.run(["grep", "f"], text=True, input=my_data)

and you'll probably want to add capture_output=True to get the output of running the command as a string.

On older versions of Python, replace text=True with universal_newlines=True:

subprocess.run(["grep", "f"], universal_newlines=True, input=my_data)

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How to make a PHP SOAP call using the SoapClient class

You can use SOAP services this way too:

<?php 
//Create the client object
$soapclient = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');

//Use the functions of the client, the params of the function are in 
//the associative array
$params = array('CountryName' => 'Spain', 'CityName' => 'Alicante');
$response = $soapclient->getWeather($params);

var_dump($response);

// Get the Cities By Country
$param = array('CountryName' => 'Spain');
$response = $soapclient->getCitiesByCountry($param);

var_dump($response);

This is an example with a real service, and it works when the url is up.

Just in case the http://www.webservicex.net is down.

Here is another example using the example web service from W3C XML Web Services example, you can find more information on the link.

<?php
//Create the client object
$soapclient = new SoapClient('https://www.w3schools.com/xml/tempconvert.asmx?WSDL');

//Use the functions of the client, the params of the function are in
//the associative array
$params = array('Celsius' => '25');
$response = $soapclient->CelsiusToFahrenheit($params);

var_dump($response);

// Get the Celsius degrees from the Farenheit
$param = array('Fahrenheit' => '25');
$response = $soapclient->FahrenheitToCelsius($param);

var_dump($response);

This is working and returning the converted temperature values.

Hope this helps.

HTML Table cell background image alignment

use like this your inline css

<td width="178" rowspan="3" valign="top" 
align="right" background="images/left.jpg" 
style="background-repeat:background-position: right top;">
</td>

MySQL Workbench not opening on Windows

I have uninstalled 8.0.19 (64) and installed 8.0.18 (64 bit) and now it Opens.

How to bring an activity to foreground (top of stack)?

If you want to bring an activity to the top of the stack when clicking on a Notification then you may need to do the following to make the FLAG_ACTIVITY_REORDER_TO_FRONT work:

The solution for me for this was to make a broadcast receiver that listens to broadcast actions that the notification triggers. So basically:

  1. Notification triggers a broadcast action with an extra the name of the activity to launch.

  2. Broadcast receiver catches this when the notification is clicked, then creates an intent to launch that activity using the FLAG_ACTIVITY_REORDER_TO_FRONT flag

  3. Activity is brought to the top of activity stack, no duplicates.

Blue and Purple Default links, how to remove?

REMOVE DEFAULT LINK SOLVED that :visited thing is css.... you just go to your HTML and add a simple

< a href="" style="text-decoration: none" > < /a>

... thats the way html pages used to be

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

symfony 2 No route found for "GET /"

i could have been only one who made this mistake but maybe not so i'll post.

the format for annotations in the comments before a route has to start with a slash and two asterisks. i was making the mistake of a slash and only one asterisk, which PHPStorm autocompleted.

my route looked like this:

/*
 * @Route("/",name="homepage")
 */
public function indexAction(Request $request) {
    return $this->render('default/index.html.twig');
}

when it should have been this

/**
 * @Route("/",name="homepage")
 */
public function indexAction(Request $request) {
    return $this->render('default/base.html.twig');
}

How to left align a fixed width string?

A slightly more readable alternative solution:
sys.stdout.write(code.ljust(5) + name.ljust(20) + industry)

Note that ljust(#ofchars) uses fixed width characters and doesn't dynamically adjust like the other solutions.

PHP foreach change original array values

Try this

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }

How to make a great R reproducible example

Basically a minimal reproducible example (MWE) should enable others to exactly reproduce your issue on their machines.

A MWE consists of the following items:

  • a minimal dataset, necessary to demonstrate the problem
  • the minimal runnable code necessary to reproduce the error, which can be run on the given dataset
  • all necessary information on the used packages, the R version, and the OS it is run on.
  • in the case of random processes, a seed (set by set.seed()) for reproducibility

For examples of good MWEs, see section "Examples" at the bottom of help files on the function you are using. Simply type e.g. help(mean), or short ?mean into your R console.

Providing a minimal dataset

Usually, sharing huge data sets is not necessary and may rather discourage others from reading your question. Therefore, it is better to use built-in datasets or create a small "toy" example that resembles your original data, which is actually what is meant by minimal. If for some reason you really need to share your original data, you should use a method, such as dput(), that allows others to get an exact copy of your data.

Built-in datasets

You can use one of the built-in datasets. A comprehensive list of built-in datasets can be seen with data(). There is a short description of every data set, and more information can be obtained, e.g. with ?iris, for the 'iris' data set that comes with R. Installed packages might contain additional datasets.

Creating example data sets

Preliminary note: Sometimes you may need special formats (i.e. classes), such as factors, dates, or time series. For these, make use of functions like: as.factor, as.Date, as.xts, ... Example:

d <- as.Date("2020-12-30")

where

class(d)
# [1] "Date"

Vectors

x <- rnorm(10)  ## random vector normal distributed
x <- runif(10)  ## random vector uniformly distributed    
x <- sample(1:100, 10)  ## 10 random draws out of 1, 2, ..., 100    
x <- sample(LETTERS, 10)  ## 10 random draws out of built-in latin alphabet

Matrices

m <- matrix(1:12, 3, 4, dimnames=list(LETTERS[1:3], LETTERS[1:4]))
m
#   A B C  D
# A 1 4 7 10
# B 2 5 8 11
# C 3 6 9 12

Data frames

set.seed(42)  ## for sake of reproducibility
n <- 6
dat <- data.frame(id=1:n, 
                  date=seq.Date(as.Date("2020-12-26"), as.Date("2020-12-31"), "day"),
                  group=rep(LETTERS[1:2], n/2),
                  age=sample(18:30, n, replace=TRUE),
                  type=factor(paste("type", 1:n)),
                  x=rnorm(n))
dat
#   id       date group age   type         x
# 1  1 2020-12-26     A  27 type 1 0.0356312
# 2  2 2020-12-27     B  19 type 2 1.3149588
# 3  3 2020-12-28     A  20 type 3 0.9781675
# 4  4 2020-12-29     B  26 type 4 0.8817912
# 5  5 2020-12-30     A  26 type 5 0.4822047
# 6  6 2020-12-31     B  28 type 6 0.9657529

Note: Although it is widely used, better do not name your data frame df, because df() is an R function for the density (i.e. height of the curve at point x) of the F distribution and you might get a clash with it.

Copying original data

If you have a specific reason, or data that would be too difficult to construct an example from, you could provide a small subset of your original data, best by using dput.

Why use dput()?

dput throws all information needed to exactly reproduce your data on your console. You may simply copy the output and paste it into your question.

Calling dat (from above) produces output that still lacks information about variable classes and other features if you share it in your question. Furthermore the spaces in the type column make it difficult to do anything with it. Even when we set out to use the data, we won't manage to get important features of your data right.

  id       date group age   type         x
1  1 2020-12-26     A  27 type 1 0.0356312
2  2 2020-12-27     B  19 type 2 1.3149588
3  3 2020-12-28     A  20 type 3 0.9781675

Subset your data

Tho share a subset, use head(), subset() or the indices iris[1:4, ]. Then wrap it into dput() to give others something that can be put in R immediately. Example

dput(iris[1:4, ]) # first four rows of the iris data set

Console output to share in your question:

structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6), Sepal.Width = c(3.5, 
3, 3.2, 3.1), Petal.Length = c(1.4, 1.4, 1.3, 1.5), Petal.Width = c(0.2, 
0.2, 0.2, 0.2), Species = structure(c(1L, 1L, 1L, 1L), .Label = c("setosa", 
"versicolor", "virginica"), class = "factor")), row.names = c(NA, 
4L), class = "data.frame")

When using dput, you may also want to include only relevant columns, e.g. dput(mtcars[1:3, c(2, 5, 6)])

Note: If your data frame has a factor with many levels, the dput output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the the subset of your data. To solve this issue, you can use the droplevels() function. Notice below how species is a factor with only one level, e.g. dput(droplevels(iris[1:4, ])). One other caveat for dput is that it will not work for keyed data.table objects or for grouped tbl_df (class grouped_df) from the tidyverse. In these cases you can convert back to a regular data frame before sharing, dput(as.data.frame(my_data)).

Producing minimal code

Combined with the minimal data (see above), your code should exactly reproduce the problem on another machine by simply copying and pasting it.

This should be the easy part but often isn't. What you should not do:

  • showing all kinds of data conversions; make sure the provided data is already in the correct format (unless that is the problem, of course)
  • copy-paste a whole script that gives an error somewhere. Try to locate which lines exactly result in the error. More often than not, you'll find out what the problem is yourself.

What you should do:

  • add which packages you use if you use any (using library())
  • test run your code in a fresh R session to ensure the code is runnable. People should be able to copy-paste your data and your code in the console and get the same as you have.
  • if you open connections or create files, add some code to close them or delete the files (using unlink())
  • if you change options, make sure the code contains a statement to revert them back to the original ones. (eg op <- par(mfrow=c(1,2)) ...some code... par(op) )

Providing necessary information

In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of sessionInfo() can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible, also the necessary information on the setup.

If you are running R in R Studio, using rstudioapi::versionInfo() can help report your RStudio version.

If you have a problem with a specific package, you may want to provide the package version by giving the output of packageVersion("name of the package").

Seed

Using set.seed() you may specify a seed1, i.e. the specific state, R's random number generator is fixed. This makes it possible for random functions, such as sample(), rnorm(), runif() and lots of others, to always return the same result, Example:

set.seed(42)
rnorm(3)
# [1]  1.3709584 -0.5646982  0.3631284

set.seed(42)
rnorm(3)
# [1]  1.3709584 -0.5646982  0.3631284

1 Note: The output of set.seed() differs between R >3.6.0 and previous versions. Specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use the RNGversion()-function before set.seed() (e.g.: RNGversion("3.5.2")).

How can I delete Docker's images?

The image could be currently used by a running container, so you first have to stop and remove the container(s).

docker stop <container-name>
docker rm <container-id>

Then you could try deleting the image:

docker rmi <image-id>

You must be sure that this image doesn't depend on other images (otherwise you must delete them first).

I had a strange case in which I had no more containers still alive (docker ps -a returned nothing) but I couldn't manage to delete the image and its image-dependency.

To solve these special cases you could force the image removal with this:

docker rmi -f <image-id>

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

we can use this two line of code to generate unique string have tested around 10000000 times of iteration

  $sffledStr= str_shuffle('abscdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_-+');
    $uniqueString = md5(time().$sffledStr);

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Change Placeholder Text using jQuery

simply you can use

$("#yourtextboxid").attr("placeholder", "variable");

where, if variable is string then you can use like above, if it is variable replace it with the name like "variable" with out double quotes.

eg: $("#youtextboxid").attr("placeholder", variable); it will work.

How to clear browser cache with php?

With recent browser support of "Clear-Site-Data" headers, you can clear different types of data: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Clear-Site-Data

header('Clear-Site-Data: "cache", "cookies", "storage", "executionContexts"');

Align two inline-blocks left and right on same line

If you don't want to use floats, you're going to have to wrap your nav:

<header>
<h1>Title</h1>
<div id="navWrap">
<nav>
    <a>A Link</a>
    <a>Another Link</a>
    <a>A Third Link</a>
</nav>
</div>
</header>

...and add some more specific css:

header {
//text-align: center; // will set in js when the nav overflows (i think)
width:960px;/*Change as needed*/
height:75px;/*Change as needed*/
}

h1 {
display: inline-block;
margin-top: 0.321em;
}

#navWrap{
position:absolute;
top:50px; /*Change as needed*/
right:0;
}

nav {
display: inline-block;
vertical-align: baseline;
}

You may need to do a little more, but that's a start.

A regular expression to exclude a word/string

Here's yet another way (using a negative look-ahead):

^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$ 

Note: There's only one capturing expression: ([a-z0-9]+).

rbind error: "names do not match previous names"

The names of the first dataframe do not match the names of the second one. Just as the error message says.

> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE

If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:

> names(xd.small[[1]]) <- names(xd.small[[2]]) 
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE

Then things should proceed happily.

Prompt Dialog in Windows Forms

There is no such thing natively in Windows Forms.

You have to create your own form for that or:

use the Microsoft.VisualBasic reference.

Inputbox is legacy code brought into .Net for VB6 compatibility - so i advise to not do this.

Python+OpenCV: cv2.imwrite

This following code should extract face in images and save faces on disk

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

Update my gradle dependencies in eclipse

First, please check you have include eclipse gradle plugin. apply plugin : 'eclipse' Then go to your project directory in Terminal. Type gradle clean and then gradle eclipse. Then go to project in eclipse and refresh the project.

How do I delete specific lines in Notepad++?

Notepad++ v6.5

  1. Search menu -> Find... -> Mark tab -> Find what: your search text, check Bookmark Line, then Mark All. This will bookmark all the lines with the search term, you'll see the blue circles in the margin.

  2. Then Search menu -> Bookmark -> Remove Bookmarked Lines. This will delete all the bookmarked lines.

You can also use a regex to search. This method won't result in a blank line like John's and will actually delete the line.

Older Versions

  1. Search menu -> Find... -> Find what: your search text, check Bookmark Line and click Find All.
  2. Then Search -> Bookmark -> Remove Bookmarked Lines

How should I call 3 functions in order to execute them one after the other?

asec=1000; 

setTimeout('some_3secs_function("somevalue")',asec*3);
setTimeout('some_5secs_function("somevalue")',asec*5);
setTimeout('some_8secs_function("somevalue")',asec*8);

I won't go into a deep discussion of setTimeout here, but:

  • in this case I've added the code to execute as a string. this is the simplest way to pass a var into your setTimeout-ed function, but purists will complain.
  • you can also pass a function name without quotes, but no variable can be passed.
  • your code does not wait for setTimeout to trigger.
  • This one can be hard to get your head around at first: because of the previous point, if you pass a variable from your calling function, that variable will not exist anymore by the time the timeout triggers - the calling function will have executed and it's vars gone.
  • I have been known to use anonymous functions to get around all this, but there could well be a better way,

How to create an executable .exe file from a .m file

The "StandAlone" method to compile .m file (or files) requires a set of Matlab published library (.dll) files on a target (non-Matlab) platform to allow execution of the compiler generated .exe.

Check MATLAB main site for their compiler products and their limitations.

Using atan2 to find angle between two vectors

I think a better formula was posted here: http://www.mathworks.com/matlabcentral/answers/16243-angle-between-two-vectors-in-3d

angle = atan2(norm(cross(a,b)), dot(a,b))

So this formula works in 2 or 3 dimensions. For 2 dimensions this formula simplifies to the one stated above.

Escape double quotes in Java

Yes you will have to escape all double quotes by a backslash.

Why should I use a pointer rather than the object itself?

There are many benefits of using pointers to object -

  1. Efficiency (as you already pointed out). Passing objects to functions mean creating new copies of object.
  2. Working with objects from third party libraries. If your object belongs to a third party code and the authors intend the usage of their objects through pointers only (no copy constructors etc) the only way you can pass around this object is using pointers. Passing by value may cause issues. (Deep copy / shallow copy issues).
  3. if the object owns a resource and you want that the ownership should not be sahred with other objects.

How to use systemctl in Ubuntu 14.04

So you want to remove dangling images? Am I correct?

systemctl enable docker-container-cleanup.timer
systemctl start docker-container-cleanup.timer
systemctl enable docker-image-cleanup.timer 
systemctl start docker-image-cleanup.timer

https://github.com/larsks/docker-tools/tree/master/docker-maintenance-units

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

How Do I 'git fetch' and 'git merge' from a Remote Tracking Branch (like 'git pull')

these are the commands:

git fetch origin
git merge origin/somebranch somebranch

if you do this on the second line:

git merge origin somebranch

it will try to merge the local master into your current branch.

The question, as I've understood it, was you fetched already locally and want to now merge your branch to the latest of the same branch.

How do you align left / right a div without using float?

No need to add extra elements. While flexbox uses very non-intuitive property names if you know what it can do you'll find yourself using it quite often.

<div style="display: flex; justify-content: space-between;">
<span>Item Left</span>
<span>Item Right</span>
</div>

Plan on needing this often?

.align_between {display: flex; justify-content: space-between;}

I see other people using secondary words in the primary position which makes a mess of information hierarchy. If align is the primary task and right, left, and/or between are the secondary the class should be .align_outer, not .outer_align as it will make sense as you vertically scan your code:

.align_between {}
.align_left {}
.align_outer {}
.align_right {}

Good habits over time will allow you to get to bed sooner than later.

Angular 2: Get Values of Multiple Checked Checkboxes

I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:

<div class="form-group">
            <label for="options">Options :</label>
            <div *ngFor="#option of options; #i = index">
                <label>
                    <input type="checkbox"
                           name="options"
                           value="{{option}}"
                           [checked]="options.indexOf(option) >= 0"
                           (change)="updateCheckedOptions(option, $event)"/>
                    {{option}}
                </label>
            </div>
        </div>

Here are the 3 objects I'm using:

options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
        OptionA: false,
        OptionB: false,
        OptionC: false,
};
optionsChecked = [];

And there are 3 useful methods:

1. To initiate optionsMap:

initOptionsMap() {
    for (var x = 0; x<this.order.options.length; x++) {
        this.optionsMap[this.options[x]] = true;
    }
}

2. to update the optionsMap:

updateCheckedOptions(option, event) {
   this.optionsMap[option] = event.target.checked;
}

3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:

updateOptions() {
    for(var x in this.optionsMap) {
        if(this.optionsMap[x]) {
            this.optionsChecked.push(x);
        }
    }
    this.options = this.optionsChecked;
    this.optionsChecked = [];
}

How do I render a shadow?

Use elevation to implement shadows on RN Android. Added elevation prop #27

<View elevation={5}> </View>

Oracle listener not running and won't start

I had the same problem on 11.201 on Windows. After: additional install 11.203 64bit server and client in new folders. PATH environment variable was changed right after install. Error in listener appeared after listener service restart. In my case there was a night time and number of windows updates, so windows server restart helped us. Also I cleaned listener.log file according to http://pavandba.com/tag/tns-12560-tns-protocol-adapter-error/, it was surprisingly big.

What's the fastest way to delete a large folder in Windows?

use the command prompt, as suggested. I figured out why explorer is so slow a while ago, it gives you an estimate of how long it will take to delete the files/folders. To do this, it has to scan the number of items and the size. This takes ages, hence the ridiculous wait with large folders.

Also, explorer will stop if there is a particular problem with a file,

CryptographicException 'Keyset does not exist', but only through WCF

If you use ApplicationPoolIdentity for your application pool, you may have problem with specifying permission for that "virtual" user in registry editor (there is not such user in system).

So, use subinacl - command-line tool that enables set registry ACL's, or something like this.

Check if a string is a palindrome

static void Main(string[] args)
{
    string str, rev="";

    Console.Write("Enter string");

    str = Console.ReadLine();

    for (int i = str.Length - 1; i >= 0; i--)
    {
        rev = rev + str[i];
    }

    if (rev == str)
        Console.Write("Entered string is pallindrome");
    else
        Console.Write("Entered string is not pallindrome");

    Console.ReadKey();
}

Errno 13 Permission denied Python

For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

Error Code: 2013. Lost connection to MySQL server during query

I had the same problem - but for me the solution was a DB user with too strict permissions. I had to allow the Execute ability on the mysql table. After allowing that I had no dropping connections anymore

An attempt was made to access a socket in a way forbidden by its access permissions

My situation and solution: I had created and enabled a HyperV ethernet adapter. For some reason, my main windows machine was using the "virtual" ethernet adapter instead of the 'hardware' adapter.

I disabled the virtual ethernet and my network settings to change the network public/privacy settings were revealed.

Set date input field's max date to today

I am using Laravel 7.x with blade templating and I use:

<input ... max="{{ now()->toDateString('Y-m-d') }}">

Prevent direct access to a php include file

<?php       
$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
  if (false !== strpos($url,'.php')) {
      die ("Direct access not premitted");
  }
?>

How to check if a value exists in an array in Ruby

There is an in? method in ActiveSupport (part of Rails) since v3.1, as pointed out by @campaterson. So within Rails, or if you require 'active_support', you can write:

'Unicorn'.in?(['Cat', 'Dog', 'Bird']) # => false

OTOH, there is no in operator or #in? method in Ruby itself, even though it has been proposed before, in particular by Yusuke Endoh a top notch member of ruby-core.

As pointed out by others, the reverse method include? exists, for all Enumerables including Array, Hash, Set, Range:

['Cat', 'Dog', 'Bird'].include?('Unicorn') # => false

Note that if you have many values in your array, they will all be checked one after the other (i.e. O(n)), while that lookup for a hash will be constant time (i.e O(1)). So if you array is constant, for example, it is a good idea to use a Set instead. E.g:

require 'set'
ALLOWED_METHODS = Set[:to_s, :to_i, :upcase, :downcase
                       # etc
                     ]

def foo(what)
  raise "Not allowed" unless ALLOWED_METHODS.include?(what.to_sym)
  bar.send(what)
end

A quick test reveals that calling include? on a 10 element Set is about 3.5x faster than calling it on the equivalent Array (if the element is not found).

A final closing note: be wary when using include? on a Range, there are subtleties, so refer to the doc and compare with cover?...

How to get max value of a column using Entity Framework?

If the list is empty I get an exception. This solution will take into account this issue:

int maxAge = context.Persons.Select(p => p.Age).DefaultIfEmpty(0).Max();

Adding a regression line on a ggplot

I found this function on a blog

 ggplotRegression <- function (fit) {

    `require(ggplot2)

    ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) + 
      geom_point() +
      stat_smooth(method = "lm", col = "red") +
      labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                         "Intercept =",signif(fit$coef[[1]],5 ),
                         " Slope =",signif(fit$coef[[2]], 5),
                         " P =",signif(summary(fit)$coef[2,4], 5)))
    }`

once you loaded the function you could simply

ggplotRegression(fit)

you can also go for ggplotregression( y ~ x + z + Q, data)

Hope this helps.

write() versus writelines() and concatenated strings

  • writelines expects an iterable of strings
  • write expects a single string.

line1 + "\n" + line2 merges those strings together into a single string before passing it to write.

Note that if you have many lines, you may want to use "\n".join(list_of_lines).

Python one-line "for" expression

Even array2.extend(array1) will work.

When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?

That heavily depends on the structure of the search tree and the number and location of solutions (aka searched-for items).

  • If you know a solution is not far from the root of the tree, a breadth first search (BFS) might be better.

  • If the tree is very deep and solutions are rare, depth first search (DFS) might take an extremely long time, but BFS could be faster.

  • If the tree is very wide, a BFS might need too much memory, so it might be completely impractical.

  • If solutions are frequent but located deep in the tree, BFS could be impractical.

  • If the search tree is very deep you will need to restrict the search depth for depth first search (DFS), anyway (for example with iterative deepening).

But these are just rules of thumb; you'll probably need to experiment.

Another issue is parallelism: if you want to parallelize BFS you would need a shared datastructure between threads, which is a bad thing. DFS might be easier to distribute even between connected machines if you don't insist on the exact order of visiting the nodes.

How can I debug git/git-shell related problems?

If its over SSH, you can use the following:

For a higher debug level for type -vv or -vvv for debug level 2 and 3 respectively:

# Debug level 1
GIT_SSH_COMMAND="ssh -v" git clone <repositoryurl>

# Debug level 2
GIT_SSH_COMMAND="ssh -vv" git clone <repositoryurl>

# Debug level 3
GIT_SSH_COMMAND="ssh -vvv" git clone <repositoryurl>

This is mainly useful to handle public and private key problems with the server. You can use this command for any git command, not only 'git clone'.

How do I size a UITextView to its content?

The simplest solution that worked for me was to put a height constraint on the textView in the Storyboard, then connect the textView and height constraint to the code:

@IBOutlet var myAwesomeTextView: UITextView!
@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!

Then after setting the text and paragraph styles, add this in viewDidAppear:

self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height

Some notes:

  1. In contrast to other solutions, isScrollEnabled must to be set to true in order for this to work.
  2. In my case, I was setting custom attributes to the font inside the code, therefore I had to set the height in viewDidAppear (it wouldn't work properly before that). If you aren't changing any text attributes in code, you should be able to set the height in viewDidLoad or anywhere after setting the text.

How to get the element clicked (for the whole document)?

Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.

jQuery('div').on('click', function(){
    var node = jQuery(this).get(0);
    var range = document.createRange();
    range.selectNodeContents( node );
    window.getSelection().removeAllRanges();
    window.getSelection().addRange( range );
});

Choosing a file in Python with simple Dialog

Python 3.x version of Etaoin's answer for completeness:

from tkinter.filedialog import askopenfilename
filename = askopenfilename()

Remove CSS class from element with JavaScript (no jQuery)

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

How to force child div to be 100% of parent div's height without specifying parent's height?

This is a frustrating issue that's dealt with designers all the time. The trick is that you need to set the height to 100% on BODY and HTML in your CSS.

html,body {
    height:100%;
}

This seemingly pointless code is to define to the browser what 100% means. Frustrating, yes, but is the simplest way.

Get Mouse Position

In my scenario, I was supposed to open a dialog box in the mouse position based on a GUI operation done with the mouse. The following code worked for me:

    public Object open() {
    //create the contents of the dialog
    createContents();
    //setting the shell location based on the curent position
    //of the mouse
    PointerInfo a = MouseInfo.getPointerInfo();
    Point pt = a.getLocation();
    shellEO.setLocation (pt.x, pt.y);

    //once the contents are created and location is set-
    //open the dialog
    shellEO.open();
    shellEO.layout();
    Display display = getParent().getDisplay();
    while (!shellEO.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    return result;
}

Change CSS class properties with jQuery

Here's a bit of an improvement on the excellent answer provided by Mathew Wolf. This one appends the main container as a style tag to the head element and appends each new class to that style tag. a little more concise and I find it works well.

function changeCss(className, classValue) {
    var cssMainContainer = $('#css-modifier-container');

    if (cssMainContainer.length == 0) {
        var cssMainContainer = $('<style id="css-modifier-container"></style>');
        cssMainContainer.appendTo($('head'));
    }

    cssMainContainer.append(className + " {" + classValue + "}\n");
}

How to set layout_weight attribute dynamically from code?

If you have already defined your view in layout(xml) file and only want to change the weight pro grammatically, then then creating new LayoutParams overwrites other params defined in you xml file.

So first you should use "getLayoutParams" and then setLayoutParams

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mButton.getLayoutParams(); params.weight = 4f; mButton.setLayoutParams(params);

How do I simulate a low bandwidth, high latency environment?

You can try this: CovenantSQL/GNTE just write YAML like this:

group:
  - 
    name: china
    nodes:
      - 
        ip: 10.250.1.2
        cmd: "cd /scripts && ./YourBin args"
      - 
        ip: 10.250.1.3
        cmd: "cd /scripts && ./YourBin args"
    delay: "100ms 10ms 30%"
    loss: "1% 10%"
  - 
    name: us
    nodes:
      - 
        ip: 10.250.2.2
        cmd: "cd /scripts && ./YourBin args"
      - 
        ip: 10.250.2.3
        cmd: "cd /scripts && ./YourBin args"
    delay: "1000ms 10ms 30%"
    loss: "1% 10%"

network:
  -
    groups:
      - china
      - us
    delay: "200ms 10ms 1%"
    corrupt: "0.2%"
    rate: "10mbit"

run ./generate scripts/your.yaml

How to Maximize window in chrome using webDriver (python)

I do the following:

from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()

Search an array for matching attribute

@Chap - you can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:

var data = [
   { "restaurant": { "name": "McDonald's", "food": "burger" } },
   { "restaurant": { "name": "KFC",        "food": "chicken" } },
   { "restaurant": { "name": "Pizza Hut",  "food": "pizza" } }
].
res = JSON.search( data, '//*[food="pizza"]' );

console.log( res[0].name );
// Pizza Hut

DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:

http://www.defiantjs.com/#xpath_evaluator

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

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

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

Python integer incrementing with ++

Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python

However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.

In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.

How to develop a soft keyboard for Android?

A good place to start is the sample application provided on the developer docs.

  • Guidelines would be to just make it as usable as possible. Take a look at the others available on the market to see what you should be aiming for
  • Yes, services can do most things, including internet; provided you have asked for those permissions
  • You can open activities and do anything you like n those if you run into a problem with doing some things in the keyboard. For example HTC's keyboard has a button to open the settings activity, and another to open a dialog to change languages.

Take a look at other IME's to see what you should be aiming for. Some (like the official one) are open source.

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

Checkout CefSharp .Net bindings, a project I started a while back that thankfully got picked up by the community and turned into something wonderful.

The project wraps the Chromium Embedded Framework and has been used in a number of major projects including Rdio's Windows client, Facebook Messenger for Windows and Github for Windows.

It features browser controls for WPF and Winforms and has tons of features and extension points. Being based on Chromium it's blisteringly fast too.

Grab it from NuGet: Install-Package CefSharp.Wpf or Install-Package CefSharp.WinForms

Check out examples and give your thoughts/feedback/pull-requests: https://github.com/cefsharp/CefSharp

BSD Licensed

How set background drawable programmatically in Android

setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

"Could not find a valid gem in any repository" (rubygame and others)

are you behind any proxy?

check your browser for proxy that you might use:

execute the command: gem install xxx --http-proxy=http://user:password@server and you should be good to go.

Count the number of items in my array list

You can get the number of elements in the list by calling list.size(), however some of the elements may be duplicates or null (if your list implementation allows null).

If you want the number of unique items and your items implement equals and hashCode correctly you can put them all in a set and call size on that, like this:

new HashSet<>(list).size()

If you want the number of items with a distinct itemId you can do this:

list.stream().map(i -> i.itemId).distinct().count()

Assuming that the type of itemId correctly implements equals and hashCode (which String in the question does, unless you want to do something like ignore case, in which case you could do map(i -> i.itemId.toLowerCase())).

You may need to handle null elements by either filtering them before the call to map: filter(Objects::nonNull) or by providing a default itemId for them in the map call: map(i -> i == null ? null : i.itemId).

How do you check whether a number is divisible by another number (Python)?

You can use % operator to check divisiblity of a given number

The code to check whether given no. is divisible by 3 or 5 when no. less than 1000 is given below:

n=0
while n<1000:
    if n%3==0 or n%5==0:
        print n,'is multiple of 3 or 5'
    n=n+1

Nullable type as a generic parameter possible?

Just had to do something incredible similar to this. My code:

public T IsNull<T>(this object value, T nullAlterative)
{
    if(value != DBNull.Value)
    {
        Type type = typeof(T);
        if (type.IsGenericType && 
            type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
        {
            type = Nullable.GetUnderlyingType(type);
        }

        return (T)(type.IsEnum ? Enum.ToObject(type, Convert.ToInt32(value)) :
            Convert.ChangeType(value, type));
    }
    else 
        return nullAlternative;
}

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

I just had this problem, it turns it was just because I was using x64 version of the opencv file. Tried the x86 and it worked.

Laravel - Pass more than one variable to view

Its simple :)

<link rel="icon" href="{{ asset('favicon.ico')}}" type="image/x-icon" />

How to read values from properties file?

Another way is using a ResourceBundle. Basically you get the bundle using its name without the '.properties'

private static final ResourceBundle resource = ResourceBundle.getBundle("config");

And you recover any value using this:

private final String prop = resource.getString("propName");

How to create the most compact mapping n ? isprime(n) up to a limit N?

bool isPrime(int n)
{
    // Corner cases
    if (n <= 1)  return false;
    if (n <= 3)  return true;

    // This is checked so that we can skip 
    // middle five numbers in below loop
    if (n%2 == 0 || n%3 == 0) return false;

    for (int i=5; i*i<=n; i=i+6)
        if (n%i == 0 || n%(i+2) == 0)
           return false;

    return true;
}

this is just c++ implementation of above AKS algorithm

How to use external ".js" files

Note :- Do not use script tag in external JavaScript file.

<html>
<head>

</head>
<body>
    <p id="cn"> Click on the button to change the light button</p>
    <button type="button" onclick="changefont()">Click</button>

     <script src="external.js"></script>
</body>

External Java Script file:-

        function changefont()
            {

                var x = document.getElementById("cn");
                x.style.fontSize = "25px";           
                x.style.color = "red"; 
            }

Command not found when using sudo

It seems that linux will say "command not found" even if you explicitly give the path to the file.

[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
sudo: /tmp/uid.sh: command not found
1
[veeam@jsandbox ~]$ chmod +x /tmp/uid.sh
[veeam@jsandbox ~]$ sudo /tmp/uid.sh;echo $?
0

It's a somewhat misleading error, however it's probably technically correct. A file is not a command until its executable, and so cannot be found.

Python function to convert seconds into minutes, hours, and days

Patching as well Ralph Bolton's answer. Moving to a class and moving tulp of tulp (intervals) to dictionary. Adding an optional rounded function depending of granularity (enable by default). Ready to translation using gettext (default is disable). This is intend to be load from an module. This is for python3 (tested 3.6 - 3.8)

import gettext
import locale
from itertools import chain

mylocale = locale.getdefaultlocale()
# see --> https://stackoverflow.com/a/10174657/11869956 thx 
#localedir = os.path.join(os.path.dirname(__file__), 'locales')
# or python > 3.4:
try:
    localedir = pathlib.Path(__file__).parent/'locales'
    lang_translations = gettext.translation('utils', localedir, 
                                            languages=[mylocale[0]])
    lang_translations.install()
    _ = lang_translations.gettext
except Exception as exc:
    print('Error: unexcept error while initializing translation:', file=sys.stderr)
    print(f'Error: {exc}', file=sys.stderr)
    print(f'Error: localedir={localedir}, languages={mylocale[0]}', file=sys.stderr)
    print('Error: translation has been disabled.', file=sys.stderr)
    _ = gettext.gettext

Here is the class:

class FormatTimestamp:
    """Convert seconds to, optional rounded, time depending of granularity's degrees.
        inspired by https://stackoverflow.com/a/24542445/11869956"""
    def __init__(self):
        # For now i haven't found a way to do it better
        # TODO: optimize ?!? ;)
        self.intervals = {
            # 'years'     :   31556952,  # https://www.calculateme.com/time/years/to-seconds/
            # https://www.calculateme.com/time/months/to-seconds/ -> 2629746 seconds
            # But it's outputing some strange result :
            # So 3 seconds less (2629743) : 4 weeks, 2 days, 10 hours, 29 minutes and 3 seconds
            # than after 3 more seconds : 1 month ?!?
            # Google give me 2628000 seconds
            # So 3 seconds less (2627997): 4 weeks, 2 days, 9 hours, 59 minutes and 57 seconds
            # Strange as well 
            # So for the moment latest is week ...
            #'months'    :   2419200, # 60 * 60 * 24 * 7 * 4 
            'weeks'     :   604800,  # 60 * 60 * 24 * 7
            'days'      :   86400,    # 60 * 60 * 24
            'hours'     :   3600,    # 60 * 60
            'minutes'   :   60,
            'seconds'  :   1
            }
        self.nextkey = {
            'seconds'   :   'minutes',
            'minutes'   :   'hours',
            'hours'     :   'days',
            'days'      :   'weeks',
            'weeks'     :   'weeks',
            #'months'    :   'months',
            #'years'     :   'years' # stop here
            }
        self.translate = {
            'weeks'     :   _('weeks'),
            'days'      :   _('days'),
            'hours'     :   _('hours'),
            'minutes'   :   _('minutes'),
            'seconds'   :   _('seconds'),
            ## Single
            'week'      :   _('week'),
            'day'       :   _('day'),
            'hour'      :   _('hour'),
            'minute'    :   _('minute'),
            'second'    :   _('second'),
            ' and'      :   _('and'),
            ','         :   _(','),     # This is for compatibility
            ''          :   '\0'        # same here BUT we CANNOT pass empty string to gettext 
                                        # or we get : warning: Empty msgid.  It is reserved by GNU gettext:
                                        # gettext("") returns the header entry with
                                        # meta information, not the empty string.
                                        # Thx to --> https://stackoverflow.com/a/30852705/11869956 - saved my day
            }

    def convert(self, seconds, granularity=2, rounded=True, translate=False):
        """Proceed the conversion"""

        def _format(result):
            """Return the formatted result
            TODO : numpy / google docstrings"""
            start = 1 
            length = len(result)
            none = 0
            next_item = False
            for item in reversed(result[:]):
                if item['value']:
                    # if we have more than one item
                    if length - none > 1:
                        # This is the first 'real' item 
                        if start == 1:
                            item['punctuation'] = ''
                            next_item = True
                        elif next_item:
                            # This is the second 'real' item
                            # Happened 'and' to key name
                            item['punctuation'] = ' and'
                            next_item = False
                        # If there is more than two 'real' item
                        # than happened ','
                        elif 2 < start:
                            item['punctuation'] = ','
                        else:
                            item['punctuation'] = ''
                    else:
                        item['punctuation'] = ''
                    start += 1
                else:
                    none += 1
            return [ { 'value'        :   mydict['value'], 
                       'name'         :   mydict['name_strip'],
                       'punctuation'  :   mydict['punctuation'] } for mydict in result \
                                                                  if mydict['value'] is not None ]


        def _rstrip(value, name):
            """Rstrip 's' name depending of value"""
            if value == 1:
                name = name.rstrip('s')
            return name


        # Make sure granularity is an integer
        if not isinstance(granularity, int):
            raise ValueError(f'Granularity should be an integer: {granularity}')

        # For seconds only don't need to compute
        if seconds < 0:
            return 'any time now.'
        elif seconds < 60:
            return 'less than a minute.'

        result = []
        for name, count in self.intervals.items():
            value = seconds // count
            if value:
                seconds -= value * count
                name_strip = _rstrip(value, name)
                # save as dict: value, name_strip (eventually strip), name (for reference), value in seconds
                # and count (for reference)
                result.append({ 
                        'value'        :   value,
                        'name_strip'   :   name_strip,
                        'name'         :   name, 
                        'seconds'      :   value * count,
                        'count'        :   count
                                 })
            else:
                if len(result) > 0:
                    # We strip the name as second == 0
                    name_strip = name.rstrip('s')
                    # adding None to key 'value' but keep other value
                    # in case when need to add seconds when we will 
                    # recompute every thing
                    result.append({ 
                        'value'        :   None,
                        'name_strip'   :   name_strip,
                        'name'         :   name, 
                        'seconds'      :   0,
                        'count'        :   count
                                 })

        # Get the length of the list
        length = len(result)
        # Don't need to compute everything / every time
        if length < granularity or not rounded:
            if translate:
                return ' '.join('{0} {1}{2}'.format(item['value'], _(self.translate[item['name']]), 
                                                _(self.translate[item['punctuation']])) \
                                                for item in _format(result))
            else:
                return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
                                                for item in _format(result))

        start = length - 1
        # Reverse list so the firsts elements 
        # could be not selected depending on granularity.
        # And we can delete item after we had his seconds to next
        # item in the current list (result)
        for item in reversed(result[:]):
            if granularity <= start <= length - 1:
                # So we have to round
                current_index = result.index(item)
                next_index = current_index - 1
                # skip item value == None
                # if the seconds of current item is superior
                # to the half seconds of the next item: round
                if item['value'] and item['seconds'] > result[next_index]['count'] // 2:
                    # +1 to the next item (in seconds: depending on item count)
                    result[next_index]['seconds'] += result[next_index]['count']
                # Remove item which is not selected
                del result[current_index]
            start -= 1
        # Ok now recalculate everything
        # Reverse as well 
        for item in reversed(result[:]):
            # Check if seconds is superior or equal to the next item 
            # but not from 'result' list but from 'self.intervals' dict
            # Make sure it's not None
            if item['value']:
                next_item_name = self.nextkey[item['name']]
                # This mean we are at weeks
                if item['name'] == next_item_name:
                    # Just recalcul
                    item['value'] = item['seconds'] // item['count']
                    item['name_strip'] = _rstrip(item['value'], item['name'])
                # Stop to weeks to stay 'right' 
                elif item['seconds'] >= self.intervals[next_item_name]:
                    # First make sure we have the 'next item'
                    # found via --> https://stackoverflow.com/q/26447309/11869956
                    # maybe there is a faster way to do it ? - TODO
                    if any(search_item['name'] == next_item_name for search_item in result):
                        next_item_index = result.index(item) - 1
                        # Append to
                        result[next_item_index]['seconds'] += item['seconds']
                        # recalculate value
                        result[next_item_index]['value'] = result[next_item_index]['seconds'] // \
                                                           result[next_item_index]['count']
                        # strip or not
                        result[next_item_index]['name_strip'] = _rstrip(result[next_item_index]['value'],
                                                                       result[next_item_index]['name'])
                    else:
                        # Creating 
                        next_item_index = result.index(item) - 1
                        # get count
                        next_item_count = self.intervals[next_item_name]
                        # convert seconds
                        next_item_value = item['seconds'] // next_item_count
                        # strip 's' or not
                        next_item_name_strip = _rstrip(next_item_value, next_item_name)
                        # added to dict
                        next_item = {
                                       'value'      :   next_item_value,
                                       'name_strip' :   next_item_name_strip,
                                       'name'       :   next_item_name,
                                       'seconds'    :   item['seconds'],
                                       'count'      :   next_item_count
                                       }
                        # insert to the list
                        result.insert(next_item_index, next_item)
                    # Remove current item
                    del result[result.index(item)]
                else:
                    # for current item recalculate
                    # keys 'value' and 'name_strip'
                    item['value'] = item['seconds'] // item['count']
                    item['name_strip'] = _rstrip(item['value'], item['name'])
        if translate:
            return ' '.join('{0} {1}{2}'.format(item['value'], 
                                                _(self.translate[item['name']]), 
                                                _(self.translate[item['punctuation']])) \
                                                for item in _format(result))
        else:
            return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
                                                for item in _format(result))

To use it:

myformater = FormatTimestamp()
myconverter = myformater.convert(seconds) 

granularity = 1 - 5, rounded = True / False, translate = True / False

Some test to show difference:

myformater = FormatTimestamp()
for firstrange in [131440, 563440, 604780, 2419180, 113478160]:
    print(f'#### Seconds : {firstrange} ####')
    print('\tFull - function: {0}'.format(display_time(firstrange, granularity=5)))
    print('\tFull -    class: {0}'.format(myformater.convert(firstrange, granularity=5))) 
    for secondrange in range(1, 6, 1):
        print('\tGranularity   this   answer ({0}): {1}'.format(secondrange, 
                                                             myformater.convert(firstrange,
                                                                                granularity=secondrange, translate=False)))
        print('\tGranularity Bolton\'s answer ({0}): {1}'.format(secondrange, display_time(firstrange,
                                                                                granularity=secondrange)))
    print()
Seconds : 131440
    Full - function: 1 day, 12 hours, 30 minutes, 40 seconds
    Full -    class: 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity   this   answer (1): 2 days
    Granularity Bolton's answer (1): 1 day
    Granularity   this   answer (2): 1 day and 13 hours
    Granularity Bolton's answer (2): 1 day, 12 hours
    Granularity   this   answer (3): 1 day, 12 hours and 31 minutes
    Granularity Bolton's answer (3): 1 day, 12 hours, 30 minutes
    Granularity   this   answer (4): 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (4): 1 day, 12 hours, 30 minutes, 40 seconds
    Granularity   this   answer (5): 1 day, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (5): 1 day, 12 hours, 30 minutes, 40 seconds
Seconds : 563440
    Full - function: 6 days, 12 hours, 30 minutes, 40 seconds
    Full -    class: 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity   this   answer (1): 1 week
    Granularity Bolton's answer (1): 6 days
    Granularity   this   answer (2): 6 days and 13 hours
    Granularity Bolton's answer (2): 6 days, 12 hours
    Granularity   this   answer (3): 6 days, 12 hours and 31 minutes
    Granularity Bolton's answer (3): 6 days, 12 hours, 30 minutes
    Granularity   this   answer (4): 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (4): 6 days, 12 hours, 30 minutes, 40 seconds
    Granularity   this   answer (5): 6 days, 12 hours, 30 minutes and 40 seconds
    Granularity Bolton's answer (5): 6 days, 12 hours, 30 minutes, 40 seconds
Seconds : 604780
    Full - function: 6 days, 23 hours, 59 minutes, 40 seconds
    Full -    class: 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity   this   answer (1): 1 week
    Granularity Bolton's answer (1): 6 days
    Granularity   this   answer (2): 1 week
    Granularity Bolton's answer (2): 6 days, 23 hours
    Granularity   this   answer (3): 1 week
    Granularity Bolton's answer (3): 6 days, 23 hours, 59 minutes
    Granularity   this   answer (4): 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (4): 6 days, 23 hours, 59 minutes, 40 seconds
    Granularity   this   answer (5): 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (5): 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 2419180
    Full - function: 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
    Full -    class: 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity   this   answer (1): 4 weeks
    Granularity Bolton's answer (1): 3 weeks
    Granularity   this   answer (2): 4 weeks
    Granularity Bolton's answer (2): 3 weeks, 6 days
    Granularity   this   answer (3): 4 weeks
    Granularity Bolton's answer (3): 3 weeks, 6 days, 23 hours
    Granularity   this   answer (4): 4 weeks
    Granularity Bolton's answer (4): 3 weeks, 6 days, 23 hours, 59 minutes
    Granularity   this   answer (5): 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
    Granularity Bolton's answer (5): 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 113478160
    Full - function: 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds
    Full -    class: 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
    Granularity   this   answer (1): 188 weeks
    Granularity Bolton's answer (1): 187 weeks
    Granularity   this   answer (2): 187 weeks and 4 days
    Granularity Bolton's answer (2): 187 weeks, 4 days
    Granularity   this   answer (3): 187 weeks, 4 days and 10 hours
    Granularity Bolton's answer (3): 187 weeks, 4 days, 9 hours
    Granularity   this   answer (4): 187 weeks, 4 days, 9 hours and 43 minutes
    Granularity Bolton's answer (4): 187 weeks, 4 days, 9 hours, 42 minutes
    Granularity   this   answer (5): 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
    Granularity Bolton's answer (5): 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds

I have a french translation ready. But it's fast to do the translation ... just few words. Hope this could help as the other answer help me a lot.

mysql datetime comparison

...this is obviously performing a 'string' comparison

No - if the date/time format matches the supported format, MySQL performs implicit conversion to convert the value to a DATETIME, based on the column it is being compared to. Same thing happens with:

WHERE int_column = '1'

...where the string value of "1" is converted to an INTeger because int_column's data type is INT, not CHAR/VARCHAR/TEXT.

If you want to explicitly convert the string to a DATETIME, the STR_TO_DATE function would be the best choice:

WHERE expires_at <= STR_TO_DATE('2010-10-15 10:00:00', '%Y-%m-%d %H:%i:%s')

Replace Div Content onclick

EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


Here is an example of how it could work:

Working jsFiddle Demo

HTML:

<div id="someDiv">
    Once upon a midnight dreary
    <br>While I pondered weak and weary
    <br>Over many a quaint and curious
    <br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />

<input type="hidden" id="vault" />

javascript/jQuery:

//Declare persistent vars outside function
var savText, newText, myState = 0;

$('#mybutt').click(function(){
    if (myState==0){
        savText = $('#someDiv').html(); //save poem data from DIV
        newText = $('#replacementtext').val(); //save data from input field
        $('#replacementtext').val(''); //clear input field
        $('#someDiv').html( newText ); //replace poem with insert field data
        myState = 1; //remember swap has been done once
    } else {
        $('#someDiv').html(savText);
        $('#replacementtext').val(newText); //replace contents
        myState = 0;
    }
});

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.