Programs & Examples On #Logical reads

Passing parameters from jsp to Spring Controller method

Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

Concatenating null strings in Java

You are not using the "null" and therefore you don't get the exception. If you want the NullPointer, just do

String s = null;
s = s.toString() + "hello";

And I think what you want to do is:

String s = "";
s = s + "hello";

Android RelativeLayout programmatically Set "centerInParent"

Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:

    RelativeLayout.LayoutParams layoutParams =
            (RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();

    if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
        // if true center text:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        holder.txtGuestName.setLayoutParams(layoutParams);
    } else {
        // if false remove center:
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
        holder.txtGuestName.setLayoutParams(layoutParams);
    }

how to select rows based on distinct values of A COLUMN only

use this(assume that your table name is emails):

select * from emails as a 
inner join  
(select EmailAddress, min(Id) as id from emails 
group by EmailAddress ) as b 
on a.EmailAddress = b.EmailAddress 
and a.Id = b.id

hope this help..

difference between System.out.println() and System.err.println()

System.out's main purpose is giving standard output.

System.err's main purpose is giving standard error.


Look at these

http://www.devx.com/tips/Tip/14698

http://wiki.eclipse.org/FAQ_Where_does_System.out_and_System.err_output_go%3F

C# - Substring: index and length must refer to a location within the string

The second parameter in Substring is the length of the substring, not the end index.

You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.

Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:

var prefix = "www.example.com/";
var suffix = ".jpg";
string url = "www.example.com/aaa/bbb.jpg";

if (url.StartsWith(prefix) && url.EndsWith(suffix) && url.Length >= (prefix.Length + suffix.Length))
{
    string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length);
    Console.WriteLine(newString);
}
else
    //handle invalid state

How to use a ViewBag to create a dropdownlist?

You cannot used the Helper @Html.DropdownListFor, because the first parameter was not correct, change your helper to:

@Html.DropDownList("accountid", new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

@Html.DropDownListFor receive in the first parameters a lambda expression in all overloads and is used to create strongly typed dropdowns.

Here's the documentation

If your View it's strongly typed to some Model you may change your code using a helper to created a strongly typed dropdownlist, something like

@Html.DropDownListFor(x => x.accountId, new SelectList(ViewBag.Accounts, "AccountID", "AccountName"))

SQL Server - Convert varchar to another collation (code page) to fix character encoding

I think SELECT CAST( CAST([field] AS VARBINARY(120)) AS varchar(120)) for your update

How do I move a file (or folder) from one folder to another in TortoiseSVN?

If you want to move files around and keep the csproj files up to date, the easiest way is to use a Visual Studio plugin like AnkhSVN. That will automatically commit both the move action (as an delete + add with history, because that's how Subversion works) and a change in the .csproj

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Maybe this example listed here can help you out. Statement from the author

about 24 lines of code to encrypt, 23 to decrypt

Due to the fact that the link in the original posting is dead - here the needed code parts (c&p without any change to the original source)

  /*
  Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a>
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.*/
   
  #region Usings
  using System;
  using System.IO;
  using System.Security.Cryptography;
  using System.Text;
  #endregion
   
  namespace Utilities.Encryption
  {
      /// <summary>
      /// Utility class that handles encryption
      /// </summary>
      public static class AESEncryption
      {
          #region Static Functions
   
          /// <summary>
          /// Encrypts a string
          /// </summary>
          /// <param name="PlainText">Text to be encrypted</param>
          /// <param name="Password">Password to encrypt with</param>
          /// <param name="Salt">Salt to encrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>An encrypted string</returns>
          public static string Encrypt(string PlainText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(PlainText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] PlainTextBytes = Encoding.UTF8.GetBytes(PlainText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] CipherTextBytes = null;
              using (ICryptoTransform Encryptor = SymmetricKey.CreateEncryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream())
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Encryptor, CryptoStreamMode.Write))
                      {
                          CryptoStream.Write(PlainTextBytes, 0, PlainTextBytes.Length);
                          CryptoStream.FlushFinalBlock();
                          CipherTextBytes = MemStream.ToArray();
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Convert.ToBase64String(CipherTextBytes);
          }
   
          /// <summary>
          /// Decrypts a string
          /// </summary>
          /// <param name="CipherText">Text to be decrypted</param>
          /// <param name="Password">Password to decrypt with</param>
          /// <param name="Salt">Salt to decrypt with</param>
          /// <param name="HashAlgorithm">Can be either SHA1 or MD5</param>
          /// <param name="PasswordIterations">Number of iterations to do</param>
          /// <param name="InitialVector">Needs to be 16 ASCII characters long</param>
          /// <param name="KeySize">Can be 128, 192, or 256</param>
          /// <returns>A decrypted string</returns>
          public static string Decrypt(string CipherText, string Password,
              string Salt = "Kosher", string HashAlgorithm = "SHA1",
              int PasswordIterations = 2, string InitialVector = "OFRna73m*aze01xY",
              int KeySize = 256)
          {
              if (string.IsNullOrEmpty(CipherText))
                  return "";
              byte[] InitialVectorBytes = Encoding.ASCII.GetBytes(InitialVector);
              byte[] SaltValueBytes = Encoding.ASCII.GetBytes(Salt);
              byte[] CipherTextBytes = Convert.FromBase64String(CipherText);
              PasswordDeriveBytes DerivedPassword = new PasswordDeriveBytes(Password, SaltValueBytes, HashAlgorithm, PasswordIterations);
              byte[] KeyBytes = DerivedPassword.GetBytes(KeySize / 8);
              RijndaelManaged SymmetricKey = new RijndaelManaged();
              SymmetricKey.Mode = CipherMode.CBC;
              byte[] PlainTextBytes = new byte[CipherTextBytes.Length];
              int ByteCount = 0;
              using (ICryptoTransform Decryptor = SymmetricKey.CreateDecryptor(KeyBytes, InitialVectorBytes))
              {
                  using (MemoryStream MemStream = new MemoryStream(CipherTextBytes))
                  {
                      using (CryptoStream CryptoStream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read))
                      {
   
                          ByteCount = CryptoStream.Read(PlainTextBytes, 0, PlainTextBytes.Length);
                          MemStream.Close();
                          CryptoStream.Close();
                      }
                  }
              }
              SymmetricKey.Clear();
              return Encoding.UTF8.GetString(PlainTextBytes, 0, ByteCount);
          }
   
          #endregion
      }
  }

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Cannot redeclare function php

You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:

if (!function_exists('parseDate')) {
    // ... proceed to declare your function
}

Encapsulation vs Abstraction?

NOTE: I am sharing this. It is not mean that here is not good answer but because I easily understood.

Answer:

When a class is conceptualized, what are the properties we can have in it given the context. If we are designing a class Animal in the context of a zoo, it is important that we have an attribute as animalType to describe domestic or wild. This attribute may not make sense when we design the class in a different context.

Similarly, what are the behaviors we are going to have in the class? Abstraction is also applied here. What is necessary to have here and what will be an overdose? Then we cut off some information from the class. This process is applying abstraction.

When we ask for difference between encapsulation and abstraction, I would say, encapsulation uses abstraction as a concept. So then, is it only encapsulation. No, abstraction is even a concept applied as part of inheritance and polymorphism.

Go here for more explanation about this topic.

Sorting Directory.GetFiles()

A more succinct VB.Net version, if anyone is interested

Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _
  New DirectoryInfo("c:\temp").GetFiles() _
   .OrderBy(Function(f As FileInfo) f.CreationTime)
For Each fi As IO.FileInfo In filePaths
  ' Do whatever you wish here
Next

Pass a password to ssh in pure bash

You can not specify the password from the command line but you can do either using ssh keys or using sshpass as suggested by John C. or using a expect script.

To use sshpass, you need to install it first. Then

sshpass -f <(printf '%s\n' your_password) ssh user@hostname

instead of using sshpass -p your_password. As mentioned by Charles Duffy in the comments, it is safer to supply the password from a file or from a variable instead of from command line.

BTW, a little explanation for the <(command) syntax. The shell executes the command inside the parentheses and replaces the whole thing with a file descriptor, which is connected to the command's stdout. You can find more from this answer https://unix.stackexchange.com/questions/156084/why-does-process-substitution-result-in-a-file-called-dev-fd-63-which-is-a-pipe

How to upload files in asp.net core?

you can try below code

1- model or view model

public class UploadImage 
{
  public string ImageFile { get; set; }
  public string ImageName { get; set; }
  public string ImageDescription { get; set; }
}

2- View page

<form class="form-horizontal" asp-controller="Image" asp-action="UploadImage" method="POST" enctype="multipart/form-data">

<input type="file" asp-for="ImageFile">
<input type="text" asp-for="ImageName">
<input type="text" asp-for="ImageDescription">
</form>

3- Controller

 public class Image
    {

      private IHostingEnvironment _hostingEnv;
      public Image(IHostingEnvironment hostingEnv)
      {
         _hostingEnv = hostingEnv;
      }

      [HttpPost]
      public async Task<IActionResult> UploadImage(UploadImage model, IFormFile ImageFile)
      {
        if (ModelState.IsValid)
         {
        var filename = ContentDispositionHeaderValue.Parse(ImageFile.ContentDisposition).FileName.Trim('"');
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", ImageFile.FileName);
        using (System.IO.Stream stream = new FileStream(path, FileMode.Create))
         {
            await ImageFile.CopyToAsync(stream);
         }
          model.ImageFile = filename;
         _context.Add(model);
         _context.SaveChanges();
         }        

      return RedirectToAction("Index","Home");   
    }

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Exit a Script On Error

exit 1 is all you need. The 1 is a return code, so you can change it if you want, say, 1 to mean a successful run and -1 to mean a failure or something like that.

Python [Errno 98] Address already in use

Nothing worked for me except running a subprocess with this command, before calling HTTPServer(('', 443), myHandler):

kill -9 $(lsof -ti tcp:443)

Of course this is only for linux-like OS!

Best way to create an empty map in Java

Either Collections.emptyMap(), or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()

How to remove origin from git repository

Fairly straightforward:

git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:

git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD

Using %f with strftime() in Python to get microseconds

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

What is a CSRF token? What is its importance and how does it work?

The Cloud Under blog has a good explanation of CSRF tokens. (archived)

Imagine you had a website like a simplified Twitter, hosted on a.com. Signed in users can enter some text (a tweet) into a form that’s being sent to the server as a POST request and published when they hit the submit button. On the server the user is identified by a cookie containing their unique session ID, so your server knows who posted the Tweet.

The form could be as simple as that:

 <form action="http://a.com/tweet" method="POST">
   <input type="text" name="tweet">
   <input type="submit">
 </form> 

Now imagine, a bad guy copies and pastes this form to his malicious website, let’s say b.com. The form would still work. As long

as a user is signed in to your Twitter (i.e. they’ve got a valid session cookie for a.com), the POST request would be sent to http://a.com/tweet and processed as usual when the user clicks the submit button.

So far this is not a big issue as long as the user is made aware about what the form exactly does, but what if our bad guy tweaks the form like this:

 <form action="https://example.com/tweet" method="POST">
   <input type="hidden" name="tweet" value="Buy great products at http://b.com/#iambad">
   <input type="submit" value="Click to win!">
 </form> 

Now, if one of your users ends up on the bad guy’s website and hits the “Click to win!” button, the form is submitted to

your website, the user is correctly identified by the session ID in the cookie and the hidden Tweet gets published.

If our bad guy was even worse, he would make the innocent user submit this form as soon they open his web page using JavaScript, maybe even completely hidden away in an invisible iframe. This basically is cross-site request forgery.

A form can easily be submitted from everywhere to everywhere. Generally that’s a common feature, but there are many more cases where it’s important to only allow a form being submitted from the domain where it belongs to.

Things are even worse if your web application doesn’t distinguish between POST and GET requests (e.g. in PHP by using $_REQUEST instead of $_POST). Don’t do that! Data altering requests could be submitted as easy as <img src="http://a.com/tweet?tweet=This+is+really+bad">, embedded in a malicious website or even an email.

How do I make sure a form can only be submitted from my own website? This is where the CSRF token comes in. A CSRF token is a random, hard-to-guess string. On a page with a form you want to protect, the server would generate a random string, the CSRF token, add it to the form as a hidden field and also remember it somehow, either by storing it in the session or by setting a cookie containing the value. Now the form would look like this:

    <form action="https://example.com/tweet" method="POST">
      <input type="hidden" name="csrf-token" value="nc98P987bcpncYhoadjoiydc9ajDlcn">
      <input type="text" name="tweet">
      <input type="submit">
    </form> 

When the user submits the form, the server simply has to compare the value of the posted field csrf-token (the name doesn’t

matter) with the CSRF token remembered by the server. If both strings are equal, the server may continue to process the form. Otherwise the server should immediately stop processing the form and respond with an error.

Why does this work? There are several reasons why the bad guy from our example above is unable to obtain the CSRF token:

Copying the static source code from our page to a different website would be useless, because the value of the hidden field changes with each user. Without the bad guy’s website knowing the current user’s CSRF token your server would always reject the POST request.

Because the bad guy’s malicious page is loaded by your user’s browser from a different domain (b.com instead of a.com), the bad guy has no chance to code a JavaScript, that loads the content and therefore our user’s current CSRF token from your website. That is because web browsers don’t allow cross-domain AJAX requests by default.

The bad guy is also unable to access the cookie set by your server, because the domains wouldn’t match.

When should I protect against cross-site request forgery? If you can ensure that you don’t mix up GET, POST and other request methods as described above, a good start would be to protect all POST requests by default.

You don’t have to protect PUT and DELETE requests, because as explained above, a standard HTML form cannot be submitted by a browser using those methods.

JavaScript on the other hand can indeed make other types of requests, e.g. using jQuery’s $.ajax() function, but remember, for AJAX requests to work the domains must match (as long as you don’t explicitly configure your web server otherwise).

This means, often you do not even have to add a CSRF token to AJAX requests, even if they are POST requests, but you will have to make sure that you only bypass the CSRF check in your web application if the POST request is actually an AJAX request. You can do that by looking for the presence of a header like X-Requested-With, which AJAX requests usually include. You could also set another custom header and check for its presence on the server side. That’s safe, because a browser would not add custom headers to a regular HTML form submission (see above), so no chance for Mr Bad Guy to simulate this behaviour with a form.

If you’re in doubt about AJAX requests, because for some reason you cannot check for a header like X-Requested-With, simply pass the generated CSRF token to your JavaScript and add the token to the AJAX request. There are several ways of doing this; either add it to the payload just like a regular HTML form would, or add a custom header to the AJAX request. As long as your server knows where to look for it in an incoming request and is able to compare it to the original value it remembers from the session or cookie, you’re sorted.

remove None value from a list without removing the 0 value

Iteration vs Space, usage could be an issue. In different situations profiling may show either to be "faster" and/or "less memory" intensive.

# first
>>> L = [0, 23, 234, 89, None, 0, 35, 9, ...]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9, ...]

# second
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> for i in range(L.count(None)): L.remove(None)
[0, 23, 234, 89, 0, 35, 9, ...]

The first approach (as also suggested by @jamylak, @Raymond Hettinger, and @Dipto) creates a duplicate list in memory, which could be costly of memory for a large list with few None entries.

The second approach goes through the list once, and then again each time until a None is reached. This could be less memory intensive, and the list will get smaller as it goes. The decrease in list size could have a speed up for lots of None entries in the front, but the worst case would be if lots of None entries were in the back.

The second approach would likely always be slower than the first approach. That does not make it an invalid consideration.

Parallelization and in-place techniques are other approaches, but each have their own complications in Python. Knowing the data and the runtime use-cases, as well profiling the program are where to start for intensive operations or large data.

Choosing either approach will probably not matter in common situations. It becomes more of a preference of notation. In fact, in those uncommon circumstances, numpy (example if L is numpy.array: L = L[L != numpy.array(None) (from here)) or cython may be worthwhile alternatives instead of attempting to micromanage Python optimizations.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

You must have to define no-args or default constructor if you are creating your own constructor.

You can read why default or no argument constructor is required.

why-default-or-no-argument-constructor-java-class.html

How to filter Android logcat by application?

I am working on Android Studio, there is a nice option to get the message using package name. On the "Edit Filter Configuration" you can create a new filter by adding your package name on the "by package name".

enter image description here

Test file upload using HTTP PUT method

For curl, how about using the -d switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

addClass - can add multiple classes on same div?

You can add multiple classes by separating classes names by spaces

$('.page-address-edit').addClass('test1 test2 test3');

OS X Framework Library not loaded: 'Image not found'

I experienced that problem only when running on real device (iPhone SE). On simulator project worked as expected.

I did try all fixes from this very thread and from here. None of those worked for me.

For me problem was solved after restarting iPhone (sic!).

I did:

  • clean build folder,
  • clean derived data,
  • delete app from device,
  • reboot device

And it finally works. :)

If every other solution fails don't forget to try it out.

How to add /usr/local/bin in $PATH on Mac

In MAC OS Catalina, this are the steps that worked for me, all the above solutions did help but didn't solve my problem.

  1. check node --version, still the old one in use.
  2. cd ~/
  3. atom .bash_profile
  4. Remove the $PATH pointing to old node version, in my case it was /usr/local/bin/node/@node8
  5. Add & save this to $PATH instead "export PATH=$PATH:/usr/local/git/bin:/usr/local/bin"
  6. Close all applications using node (terminal, simulator, browser expo etc)
  7. restart terminal and check node --version

How do I define the name of image built with docker-compose

As per docker-compose 1.6.0:

You can now specify both a build and an image key if you're using the new file format. docker-compose build will build the image and tag it with the name you've specified, while docker-compose pull will attempt to pull it.

So your docker-compose.yml would be

version: '2'
services:
  wildfly:
      build: /path/to/dir/Dockerfile
      image: wildfly_server
      ports:
       - 9990:9990
       - 80:8080

To update docker-compose

sudo pip install -U docker-compose==1.6.0

How to provide a mysql database connection in single file in nodejs

try this

var express = require('express');

var mysql     =    require('mysql');

var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

var con = mysql.createConnection({
  host: "localhost",
  user: "root",
  password: "admin123",
  database: "sitepoint"
});

con.connect(function(err){
  if(err){
    console.log('Error connecting to Db');
    return;
  }
  console.log('Connection established');
});



module.exports = app;

How do you add an SDK to Android Studio?

And For linux(ubuntu)

/usr/share/android-studio/data/sdk

Android canvas draw rectangle

Don't know if this is too late, but the way I solved this was to draw four thin rectangles that together made up a one big border. Drawing the border with one rectangle seems to be undoable since they're all opaque, so you should draw each edge of the border separately.

Error TF30063: You are not authorized to access ... \DefaultCollection

I had to "run as a different user" to get Visual Studio to connect using my TFS account. It seemed to be trying to use my Microsoft account instead.

Text and image from: https://www.visualstudio.com/en-us/docs/connect/connect-team-projects

To change accounts

To run Visual Studio under an account that is different from your logged on Windows account, open the context menu for devenv.exe to access your run as options.

Context menu for Visual Studio devenv.exe

You can locate the executable in the following folder: Drive:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE.

How to get AM/PM from a datetime in PHP

for flexibility with different formats, use:

$dt = DateTime::createFromFormat('m/d/Y H:i:s', '08/04/2010 22:15:00');
echo $dt->format('g:i A')

Check the php manual for additional format options.

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

I caught this error a few days ago.

IN my case it was because I was using a Transaction on a Singleton.

.Net does not work well with Singleton as stated above.

My solution was this:

public class DbHelper : DbHelperCore
{
    public DbHelper()
    {
        Connection = null;
        Transaction = null;
    }

    public static DbHelper instance
    {
        get
        {
            if (HttpContext.Current is null)
                return new DbHelper();
            else if (HttpContext.Current.Items["dbh"] == null)
                HttpContext.Current.Items["dbh"] = new DbHelper();

            return (DbHelper)HttpContext.Current.Items["dbh"];
        }
    }

    public override void BeginTransaction()
    {
        Connection = new SqlConnection(Entity.Connection.getCon);
        if (Connection.State == System.Data.ConnectionState.Closed)
            Connection.Open();
        Transaction = Connection.BeginTransaction();
    }
}

I used HttpContext.Current.Items for my instance. This class DbHelper and DbHelperCore is my own class

Get data from file input in JQuery

I created a form data object and appended the file:

var form = new FormData(); 
form.append("video", $("#fileInput")[0].files[0]);

and i got:

------WebKitFormBoundaryNczYRonipfsmaBOK
Content-Disposition: form-data; name="video"; filename="Wildlife.wmv"
Content-Type: video/x-ms-wmv

in the headers sent. I can confirm this works because my file was sent and stored in a folder on my server. If you don't know how to use the FormData object there is some documentation online, but not much. Form Data Object Explination by Mozilla

Best way to extract a subvector from a vector?

If both are not going to be modified (no adding/deleting items - modifying existing ones is fine as long as you pay heed to threading issues), you can simply pass around data.begin() + 100000 and data.begin() + 101000, and pretend that they are the begin() and end() of a smaller vector.

Or, since vector storage is guaranteed to be contiguous, you can simply pass around a 1000 item array:

T *arrayOfT = &data[0] + 100000;
size_t arrayOfTLength = 1000;

Both these techniques take constant time, but require that the length of data doesn't increase, triggering a reallocation.

Possible heap pollution via varargs parameter

When you use varargs, it can result in the creation of an Object[] to hold the arguments.

Due to escape analysis, the JIT can optimise away this array creation. (One of the few times I have found it does so) Its not guaranteed to be optimised away, but I wouldn't worry about it unless you see its an issue in your memory profiler.

AFAIK @SafeVarargs suppresses a warning by the compiler and doesn't change how the JIT behaves.

CardView background color always white

You can do it either in XML or programmatically:

In XML:

card_view:cardBackgroundColor="@android:color/red"

Programmatically:

cardView.setCardBackgroundColor(Color.RED);

How to listen to route changes in react router v4?

I just dealt with this problem, so I'll add my solution as a supplement on other answers given.

The problem here is that useEffect doesn't really work as you would want it to, since the call only gets triggered after the first render so there is an unwanted delay.
If you use some state manager like redux, chances are that you will get a flicker on the screen because of lingering state in the store.

What you really want is to use useLayoutEffect since this gets triggered immediately.

So I wrote a small utility function that I put in the same directory as my router:

export const callApis = (fn, path) => {
    useLayoutEffect(() => {
      fn();
    }, [path]);
};

Which I call from within the component HOC like this:

callApis(() => getTopicById({topicId}), path);

path is the prop that gets passed in the match object when using withRouter.

I'm not really in favour of listening / unlistening manually on history. That's just imo.

Generate C# class from XML

Yes, by using xsd.exe

D:\temp>xsd test.xml
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.xsd'.

D:\temp>xsd test.xsd /classes
Microsoft (R) Xml Schemas/DataTypes support utility
[Microsoft (R) .NET Framework, Version 4.0.30319.1]
Copyright (C) Microsoft Corporation. All rights reserved.
Writing file 'D:\temp\test.cs'.

Notes

Answer how to change directory in Developer Command Prompt to d:\temp may be useful.

If you generate classes for multi-dimensional array, there is a bug in XSD.exe generator, but there are workarounds.

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

Get class name using jQuery

if we have single or we want first div element we can use

$('div')[0].className otherwise we need an id of that element

HTML5 best practices; section/header/aside/article elements

  1. Section should be used only to wrap a section inside a document (like chapters and similar)
  2. With header tag: NO. Header tag represents a wrapper for page header and is not to be confused with H1, H2, etc.
  3. Which div? :D
  4. Yes
  5. From W3C Schools:

    The tag defines external content. The external content could be a news-article from an external provider, or a text from a web log (blog), or a text from a forum, or any other content from an external source.

  6. No, header tag has a different use. H1, H2, etc. represent document titles H1 being the most important

I didn't answer other ones because it's kind of hard to guess what you were referring to. If there are more questions, please let me know.

How to convert hex string to Java string?

Using Hex in Apache Commons:

String hexString = "fd00000aa8660b5b010006acdc0100000101000100010000";    
byte[] bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println(new String(bytes, "UTF-8"));

How to detect Safari, Chrome, IE, Firefox and Opera browser?

Here's a 2016 adjusted version of Rob's answer, including Microsoft Edge and detection of Blink:

(edit: I updated Rob's answer above with this information.)

_x000D_
_x000D_
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)_x000D_
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;_x000D_
// Firefox 1.0+_x000D_
isFirefox = typeof InstallTrigger !== 'undefined';_x000D_
// Safari 3.0+_x000D_
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);_x000D_
// Internet Explorer 6-11_x000D_
isIE = /*@cc_on!@*/false || !!document.documentMode;_x000D_
// Edge 20+_x000D_
isEdge = !isIE && !!window.StyleMedia;_x000D_
// Chrome 1+_x000D_
isChrome = !!window.chrome && !!window.chrome.webstore;_x000D_
// Blink engine detection_x000D_
isBlink = (isChrome || isOpera) && !!window.CSS;_x000D_
_x000D_
/* Results: */_x000D_
console.log("isOpera", isOpera);_x000D_
console.log("isFirefox", isFirefox);_x000D_
console.log("isSafari", isSafari);_x000D_
console.log("isIE", isIE);_x000D_
console.log("isEdge", isEdge);_x000D_
console.log("isChrome", isChrome);_x000D_
console.log("isBlink", isBlink);
_x000D_
_x000D_
_x000D_

The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.

How to update record using Entity Framework Core?

According to Microsoft docs:

the read-first approach requires an extra database read, and can result in more complex code for handling concurrency conflict

However, you should know that using Update method on DbContext will mark all the fields as modified and will include all of them in the query. If you want to update a subset of fields you should use the Attach method and then mark the desired field as modified manually.

context.Attach(person);
context.Entry(person).Property(p => p.Name).IsModified = true;
context.SaveChanges();

How to make a UILabel clickable?

Swift 3 Update

yourLabel.isUserInteractionEnabled = true

Parsing a CSV file using NodeJS

I was using csv-parse but for larger files was running into performance issues one of the better libraries I have found is Papa Parse, docs are good, good support, lightweight, no dependencies.

Install papaparse

npm install papaparse

Usage:

  • async / await
const fs = require('fs');
const Papa = require('papaparse');

const csvFilePath = 'data/test.csv'

// Function to read csv which returns a promise so you can do async / await.

const readCSV = async (filePath) => {
  const csvFile = fs.readFileSync(filePath)
  const csvData = csvFile.toString()  
  return new Promise(resolve => {
    Papa.parse(csvData, {
      header: true,
      transformHeader: header => header.trim(),
      complete: results => {
        console.log('Complete', results.data.length, 'records.'); 
        resolve(results.data);
      }
    });
  });
};

const test = async () => {
  let parsedData = await readCSV(csvFilePath); 
}

test()
  • callback
const fs = require('fs');
const Papa = require('papaparse');

const csvFilePath = 'data/test.csv'

const file = fs.createReadStream(csvFilePath);

var csvData=[];
Papa.parse(file, {
  header: true,
  transformHeader: header => header.trim(),
  step: function(result) {
    csvData.push(result.data)
  },
  complete: function(results, file) {
    console.log('Complete', csvData.length, 'records.'); 
  }
});

Note header: true is an option on the config, see docs for other options

Creating the Singleton design pattern in PHP5

You don't really need to use Singleton pattern because it's considered to be an antipattern. Basically there is a lot of reasons to not to implement this pattern at all. Read this to start with: Best practice on PHP singleton classes.

If after all you still think you need to use Singleton pattern then we could write a class that will allow us to get Singleton functionality by extending our SingletonClassVendor abstract class.

This is what I came with to solve this problem.

<?php
namespace wl;


/**
 * @author DevWL
 * @dosc allows only one instance for each extending class.
 * it acts a litle bit as registry from the SingletonClassVendor abstract class point of view
 * but it provides a valid singleton behaviour for its children classes
 * Be aware, the singleton pattern is consider to be an anti-pattern
 * mostly because it can be hard to debug and it comes with some limitations.
 * In most cases you do not need to use singleton pattern
 * so take a longer moment to think about it before you use it.
 */
abstract class SingletonClassVendor
{
    /**
     *  holds an single instance of the child class
     *
     *  @var array of objects
     */
    protected static $instance = [];

    /**
     *  @desc provides a single slot to hold an instance interchanble between all child classes.
     *  @return object
     */
    public static final function getInstance(){
        $class = get_called_class(); // or get_class(new static());
        if(!isset(self::$instance[$class]) || !self::$instance[$class] instanceof $class){
            self::$instance[$class] = new static(); // create and instance of child class which extends Singleton super class
            echo "new ". $class . PHP_EOL; // remove this line after testing
            return  self::$instance[$class]; // remove this line after testing
        }
        echo "old ". $class . PHP_EOL; // remove this line after testing
        return static::$instance[$class];
    }

    /**
     * Make constructor abstract to force protected implementation of the __constructor() method, so that nobody can call directly "new Class()".
     */
    abstract protected function __construct();

    /**
     * Make clone magic method private, so nobody can clone instance.
     */
    private function __clone() {}

    /**
     * Make sleep magic method private, so nobody can serialize instance.
     */
    private function __sleep() {}

    /**
     * Make wakeup magic method private, so nobody can unserialize instance.
     */
    private function __wakeup() {}

}

Use example:

/**
 * EXAMPLE
 */

/**
 *  @example 1 - Database class by extending SingletonClassVendor abstract class becomes fully functional singleton
 *  __constructor must be set to protected becaouse: 
 *   1 to allow instansiation from parent class 
 *   2 to prevent direct instanciation of object with "new" keword.
 *   3 to meet requierments of SingletonClassVendor abstract class
 */
class Database extends SingletonClassVendor
{
    public $type = "SomeClass";
    protected function __construct(){
        echo "DDDDDDDDD". PHP_EOL; // remove this line after testing
    }
}


/**
 *  @example 2 - Config ...
 */
class Config extends SingletonClassVendor
{
    public $name = "Config";
    protected function __construct(){
        echo "CCCCCCCCCC" . PHP_EOL; // remove this line after testing
    }
}

Just to prove that it works as expected:

/**
 *  TESTING
 */
$bd1 = Database::getInstance(); // new
$bd2 = Database::getInstance(); // old
$bd3 = Config::getInstance(); // new
$bd4 = Config::getInstance(); // old
$bd5 = Config::getInstance(); // old
$bd6 = Database::getInstance(); // old
$bd7 = Database::getInstance(); // old
$bd8 = Config::getInstance(); // old

echo PHP_EOL."COMPARE ALL DATABASE INSTANCES".PHP_EOL;
var_dump($bd1);
echo '$bd1 === $bd2' . ($bd1 === $bd2)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd2 === $bd6' . ($bd2 === $bd6)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd6 === $bd7' . ($bd6 === $bd7)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

echo PHP_EOL;

echo PHP_EOL."COMPARE ALL CONFIG INSTANCES". PHP_EOL;
var_dump($bd3);
echo '$bd3 === $bd4' . ($bd3 === $bd4)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd4 === $bd5' . ($bd4 === $bd5)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE
echo '$bd5 === $bd8' . ($bd5 === $bd8)? ' TRUE' . PHP_EOL: ' FALSE' . PHP_EOL; // TRUE

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

Yet another solution: set the timeout in the jest config file, e.g.:

{ // ... other stuff here
    "testTimeout": 90000
}

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Uncommenting the

always_populate_raw_post_data = -1 

in php.ini ( line# 703 ) and restarting APACHE services help me get rid from the message anyway

; Always populate the $HTTP_RAW_POST_DATA variable. PHP's default behavior is
; to disable this feature and it will be removed in a future version.
; If post reading is disabled through enable_post_data_reading,
; $HTTP_RAW_POST_DATA is *NOT* populated.
; http://php.net/always-populate-raw-post-data
; always_populate_raw_post_data = -1

Remove border from IFrame

I tried all of the above and if that doesn't work for you try the below CSS resolved the issue for me. Which just tells the browsers to not add any padding or margin.

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

Better way to set distance between flexbox items

I have found a solution that is based on the general sibling selector, ~, and allows infinite nesting.

See this code pen for a working example

Basically, inside of column containers, every child that is preceded by another child gets a top margin. Likewise, inside every row container, every child that is preceded by another gets a left margin.

_x000D_
_x000D_
.box {_x000D_
  display: flex;_x000D_
  flex-grow: 1;_x000D_
  flex-shrink: 1;_x000D_
}_x000D_
_x000D_
.box.columns {_x000D_
  flex-direction: row;_x000D_
}_x000D_
_x000D_
.box.columns>.box~.box {_x000D_
  margin-left: 5px;_x000D_
}_x000D_
_x000D_
.box.rows {_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
.box.rows>.box~.box {_x000D_
  margin-top: 5px;_x000D_
}
_x000D_
<div class="box columns">_x000D_
  <div class="box" style="background-color: red;"></div>_x000D_
  <div class="box rows">_x000D_
    <div class="box rows">_x000D_
      <div class="box" style="background-color: blue;"></div>_x000D_
      <div class="box" style="background-color: orange;"></div>_x000D_
      <div class="box columns">_x000D_
        <div class="box" style="background-color: yellow;"></div>_x000D_
        <div class="box" style="background-color: pink;"></div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="box" style="background-color: green;"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

What is the best way to call a script from another script?

Another way:

File test1.py:

print "test1.py"

File service.py:

import subprocess

subprocess.call("test1.py", shell=True)

The advantage to this method is that you don't have to edit an existing Python script to put all its code into a subroutine.

Documentation: Python 2, Python 3

javascript get child by id

In modern browsers (IE8, Firefox, Chrome, Opera, Safari) you can use querySelector():

function test(el){
  el.querySelector("#child").style.display = "none";
}

For older browsers (<=IE7), you would have to use some sort of library, such as Sizzle or a framework, such as jQuery, to work with selectors.

As mentioned, IDs are supposed to be unique within a document, so it's easiest to just use document.getElementById("child").

How do I get the height of a div's full content with jQuery?

You can get it with .outerHeight().

Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})

You can find a detailed post here.

OpenCV in Android Studio

For everyone who felt they want to run away with all the steps and screen shots on the (great!) above answers, this worked for me with android studio 2.2.1:

  1. Create a new project, name it as you want and take the default (minSdkVersion 15 is fine).

  2. Download the zip file from here: https://sourceforge.net/projects/opencvlibrary/files/opencv-android/ (I downloaded 3.2.0 version, but there may be a newer versions).

  3. Unzip the zip file, the best place is in your workspace folder, but it not really matter.

  4. Inside Android Studio, click File->New-> Import Module and navigate to \path_to_your_unzipped_file\OpenCV-android-sdk\sdk\java and hit Ok, then accept all default dialogs.

  5. In the gradle file of your app module, add this to the dependencies block:

     dependencies {
         compile project(':openCVLibraryXYZ')
         //rest of code
     }
    

Where XYZ is the exact version you downloaded, for example in my case:

    dependencies {
        compile project(':openCVLibrary320')
        //rest of code
    }

How to show soft-keyboard when edittext is focused

showSoftInput was not working for me at all.

I figured I needed to set the input mode: (here in the Activity component in the manifest)

android:windowSoftInputMode="stateVisible" 

How to set a Javascript object values dynamically?

myObj.name=value

or

myObj['name']=value     (Quotes are required)

Both of these are interchangeable.

Edit: I'm guessing you meant myObj[prop] = value, instead of myObj[name] = value. Second syntax works fine: http://jsfiddle.net/waitinforatrain/dNjvb/1/

What should I set JAVA_HOME environment variable on macOS X 10.6?

It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:

$ echo $SHELL
/bin/bash

If your default terminal is /bin/bash (Bash), then you should use @hygull method

If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

This method tested working in macOS Mojave Version 10.14.6.

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

How can I see the raw SQL queries Django is running?

Another option, see logging options in settings.py described by this post

http://dabapps.com/blog/logging-sql-queries-django-13/

debug_toolbar slows down each page load on your dev server, logging does not so it's faster. Outputs can be dumped to console or file, so the UI is not as nice. But for views with lots of SQLs, it can take a long time to debug and optimize the SQLs through debug_toolbar since each page load is so slow.

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

Remove duplicate rows in MySQL

As of version 8.0 (2018), MySQL finally supports window functions.

Window functions are both handy and efficient. Here is a solution that demonstrates how to use them to solve this assignment.

In a subquery, we can use ROW_NUMBER() to assign a position to each record in the table within column1/column2 groups, ordered by id. If there is no duplicates, the record will get row number 1. If duplicate exists, they will be numbered by ascending id (starting at 1).

Once records are properly numbered in the subquery, the outer query just deletes all records whose row number is not 1.

Query :

DELETE FROM tablename
WHERE id IN (
    SELECT id
    FROM (
        SELECT 
            id, 
            ROW_NUMBER() OVER(PARTITION BY column1, column2 ORDER BY id) rn
        FROM output
    ) t
    WHERE rn > 1
)

Rewrite left outer join involving multiple tables from Informix to Oracle

Write one table per join, like this:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx and tab3.desc = "XYZ"
  left join table4 tab4 on tab4.xya = tab3.xya and tab4.ss = tab3.ss
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk

Note that while my query contains actual left join, your query apparently doesn't. Since the conditions are in the where, your query should behave like inner joins. (Although I admit I don't know Informix, so maybe I'm wrong there).

The specfific Informix extension used in the question works a bit differently with regards to left joins. Apart from the exact syntax of the join itself, this is mainly in the fact that in Informix, you can specify a list of outer joined tables. These will be left outer joined, and the join conditions can be put in the where clause. Note that this is a specific extension to SQL. Informix also supports 'normal' left joins, but you can't combine the two in one query, it seems.

In Oracle this extension doesn't exist, and you can't put outer join conditions in the where clause, since the conditions will be executed regardless.

So look what happens when you move conditions to the where clause:

select tab1.a,tab2.b,tab3.c,tab4.d 
from 
  table1 tab1
  inner join table2 tab2 on tab2.fg = tab1.fg
  left join table3 tab3 on tab3.xxx = tab1.xxx
  left join table4 tab4 on tab4.xya = tab3.xya
  left join table5 tab5 on tab5.dd = tab3.dd and tab5.kk = tab4.kk
where
  tab3.desc = "XYZ" and
  tab4.ss = tab3.ss

Now, only rows will be returned for which those two conditions are true. They cannot be true when no row is found, so if there is no matching row in table3 and/or table4, or if ss is null in either of the two, one of these conditions is going to return false, and no row is returned. This effectively changed your outer join to an inner join, and as such changes the behavior significantly.

PS: left join and left outer join are the same. It means that you optionally join the second table to the first (the left one). Rows are returned if there is only data in the 'left' part of the join. In Oracle you can also right [outer] join to make not the left, but the right table the leading table. And there is and even full [outer] join to return a row if there is data in either table.

Redirecting to a new page after successful login

First of all, move all your PHP code to the top. Without it, my code below wont work.

To do the redirect, use:

header('Location: http://www.example.com/');

Also, please consider my advice. Since it's not the first question today and all your questions are related to basics, you should consider reading some good PHP book to understand how things work.

Here you can find useful links to free books: https://stackoverflow.com/tags/php/info

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

When to use IList and when to use List

AList object allows you to create a list, add things to it, remove it, update it, index into it and etc. List is used whenever you just want a generic List where you specify object type in it and that's it.

IList on the other hand is an Interface. Basically, if you want to create your own type of List, say a list class called BookList, then you can use the Interface to give you basic methods and structure to your new class. IList is for when you want to create your own, special sub-class that implements List.

Another difference is: IList is an Interface and cannot be instantiated. List is a class and can be instantiated. It means:

IList<string> MyList = new IList<string>();

List<string> MyList = new List<string>

Initialize a vector array of strings

If you are using cpp11 (enable with the -std=c++0x flag if needed), then you can simply initialize the vector like this:

// static std::vector<std::string> v;
v = {"haha", "hehe"};

How to check if a Constraint exists in Sql server?

You can use the one above with one caveat:

IF EXISTS(
    SELECT 1 FROM sys.foreign_keys 
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName') 
        AND name = 'CONSTRAINTNAME'
)
BEGIN 
    ALTER TABLE TableName DROP CONSTRAINT CONSTRAINTNAME 
END 

Need to use the name = [Constraint name] since a table may have multiple foreign keys and still not have the foreign key being checked for

Laravel Fluent Query Builder Join with subquery

I think what you looking for is "joinSub". It's supported from laravel ^5.6. If you using laravel version below 5.6 you can also register it as macro in your app service provider file. like this https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/171#issuecomment-413062522

$subquery = DB::table('catch-text')
            ->select(DB::raw("user_id,MAX(created_at) as MaxDate"))
            ->groupBy('user_id');

$query = User::joinSub($subquery,'MaxDates',function($join){
          $join->on('users.id','=','MaxDates.user_id');
})->select(['users.*','MaxDates.*']);

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
    string str;
    emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
    ~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first) 
{
    if (!skip_first)
        static emitter a("in if");
    static emitter b("in foo");
}

int main(int argc, char*[])
{
    foo(argc != 2);
    if (argc == 3)
        foo(false);
}

Output:

C:>sample.exe
Created in foo
Destroyed in foo

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

How to call getResources() from a class which has no context?

The normal solution to this is to pass an instance of the context to the class as you create it, or after it is first created but before you need to use the context.

Another solution is to create an Application object with a static method to access the application context although that couples the Droid object fairly tightly into the code.

Edit, examples added

Either modify the Droid class to be something like this

 public Droid(Context context,int x, int y) {
    this.bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.birdpic);
    this.x = x;
    this.y = y;
    }   

Or create an Application something like this:

public class App extends android.app.Application
{
    private static App mApp = null;
    /* (non-Javadoc)
     * @see android.app.Application#onCreate()
     */
    @Override
    public void onCreate()
    {
        super.onCreate();
        mApp = this;
    }
    public static Context context()
    {
        return mApp.getApplicationContext();
    }
}

And call App.context() wherever you need a context - note however that not all functions are available on an application context, some are only available on an activity context but it will certainly do with your need for getResources().

Please note that you'll need to add android:name to your application definition in your manifest, something like this:

<application
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:name=".App" >

Convert List<Object> to String[] in Java

There is a simple way available in Kotlin

var lst: List<Object> = ...
    
listOFStrings: ArrayList<String> = (lst!!.map { it.name })

Creating the checkbox dynamically using JavaScript?

You're trying to put a text node inside an input element.

Input elements are empty and can't have children.

...
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
checkbox.id = "id";

var label = document.createElement('label')
label.htmlFor = "id";
label.appendChild(document.createTextNode('text for label after checkbox'));

container.appendChild(checkbox);
container.appendChild(label);

Bash syntax error: unexpected end of file

I just cut-and-pasted your example into a file; it ran fine under bash. I don't see any problems with it.

For good measure you may want to ensure it ends with a newline, though bash shouldn't care. (It runs for me both with and without the final newline.)

You'll sometimes see strange errors if you've accidentally embedded a control character in the file. Since it's a short script, try creating a new script by pasting it from your question here on StackOverflow, or by simply re-typing it.

What version of bash are you using? (bash --version)

Good luck!

How to get Spinner selected item value to string?

I think you want the selected item of the spinner when button is clicked..

Try getSelectedItem():

spinner.getSelectedItem()

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

It could be that your default format doesn't match the file extension. You should specify the file format along with the filename, making sure the format matches the extension:

With someWorkbook
.SaveAs "C:\someDirector\Awesome.xlsm", fileformat:=xlOpenXMLWorkbookMacroEnabled
End With

OTOH, I don't see an extension on your .SaveAs filename. Maybe you need to supply one when doing this programmatically. That makes sense--not having to supply an extension from the GUI interface is convenient, but we programmers are expected to write unambiguous code. I suggest adding the extension and the matching format. See this msdn page for a list of file formats. To be honest, I don't recognize a lot o the descripions.

xlExcel8 = 56 is the .xls format

xlExcel12 = 50 is the .xlsb format

xlOpenXMLWorkbook = 51 is the .xlsx format

xlOpenXMLWorkbookMacroEnabled = 52 is the .xlsm format

xlWorkbookDefault is also listed with a value of 51, which puzzles me since I thought the default format could be changed.

Java generating non-repeating random numbers

HashSet<Integer>hashSet=new HashSet<>();
Random random = new Random();
//now add random number to this set
while(true)
{
    hashSet.add(random.nextInt(1000));
    if(hashSet.size()==1000)
        break;
}

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Xcode Simulator: how to remove older unneeded devices?

following some of the answers here, deleting some simulators from my Xcode Menu > Window > Devices > Simulators did nothing to help my dying disk space: enter image description here

however, cd ~/Library/Developer/Xcode/iOS\ DeviceSupport and running du -sh * I got all of these guys:

2.9G    10.0.1 (14A403)
1.3G    10.1.1 (14B100)
2.9G    10.3.2 (14F89)
1.3G    10.3.3 (14G60)
1.9G    11.0.1 (15A402)
1.9G    11.0.3 (15A432)
2.0G    11.1.2 (15B202)
2.0G    11.2 (15C114)
2.0G    11.2.1 (15C153)
2.0G    11.2.2 (15C202)
2.0G    11.2.6 (15D100)
2.0G    11.4 (15F79)
2.0G    11.4.1 (15G77)
2.3G    12.0 (16A366)
2.3G    12.0.1 (16A404)
2.3G    12.1 (16B92)

All together that's 33 GB!

A blood bath ensued

see more details here

WP -- Get posts by category?

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

VB.net Need Text Box to Only Accept Numbers

You must first validate if the input is actually an integer. You can do it with Integer.TryParse:

Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
    MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
    MessageBox.Show("Please Enter a Number from 1 to 10")
End If

Writing an mp4 video using python opencv

just change the codec to "DIVX". This codec works with all formats.

fourcc = cv2.VideoWriter_fourcc(*'DIVX')

i hope this works for you!

Color picker utility (color pipette) in Ubuntu

You can install the package gcolor2 for this:

sudo apt-get install gcolor2

Then:

Applications -> Graphics -> GColor2

Changing capitalization of filenames in Git

Considering larsks' answer, you can get it working with a single command with "--force":

 git mv --force myfile MyFile

get UTC timestamp in python with datetime

Simplest way:

>>> from datetime import datetime
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> dt.strftime("%s")
'1199163600'

Edit: @Daniel is correct, this would convert it to the machine's timezone. Here is a revised answer:

>>> from datetime import datetime, timezone
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0, timezone.utc)
>>> int((dt-epoch).total_seconds())
'1199145600'

In fact, its not even necessary to specify timezone.utc, because the time difference is the same so long as both datetime have the same timezone (or no timezone).

>>> from datetime import datetime
>>> epoch = datetime(1970, 1, 1, 0, 0, 0, 0)
>>> dt = datetime(2008, 1, 1, 0, 0, 0, 0)
>>> int((dt-epoch).total_seconds())
1199145600

How to add constraints programmatically using Swift

Would like to add some theoretical concept to Imanou Petit’s answer, so that one can understand how auto layout works.

To understand auto layout consider your view as rubber's object which is shrinked initially.

To place an object on screen we need 4 mandatory things :

  • X coordinate of object (horizontal position).

  • Y coordinate of object (vertical position )

  • Object’s Width

  • Object’s Height.

1 X coordinate: There are multiple ways of giving x coordinates to a view.

Such as Leading constraint, Trailing constraint , Horizontally centre etc.

2 Y coordinate: There are multiple ways of giving y coordinates to a view :

Such as Top constraint, Bottom constraint , Vertical centre etc.

3 Object's width: There are two ways of giving width constrain to a view :

a. Add fixed width constraint (consider this constraint as iron rod of fixed width and you have hooked your rubber’s object horizontally with it so rubber’s object don’t shrink or expand)

b. Do not add any width constraint but add x coordinate constraint to both end of view trailing and leading, these two constraints will expand/shrink your rubber’s object by pulling/pushing it from both end, leading and trailing.

4 Object's height: Similar to width, there are two ways of giving height constraint to a view as well :

a. Add fixed height constraint (consider this constraints as iron rod of fixed height and you have hooked your rubber’s object vertically with it so rubber’s object don’t shrink or expand)

b. Do not add any height constraint but add x coordinate constraint to both end of view top and bottom, these two constraints will expand/shrink your rubber’s object pulling/pushing it from both end, top and bottom.

Efficient way to apply multiple filters to pandas DataFrame or Series

e can also select rows based on values of a column that are not in a list or any iterable. We will create boolean variable just like before, but now we will negate the boolean variable by placing ~ in the front.

For example

list = [1, 0]
df[df.col1.isin(list)]

how to get yesterday's date in C#

DateTime dateTime = DateTime.Now ; 
string today = dateTime.DayOfWeek.ToString();
string yesterday = dateTime.AddDays(-1).DayOfWeek.ToString(); //Fetch day i.e. Mon, Tues
string result = dateTime.AddDays(-1).ToString("yyyy-MM-dd");

The above snippet will work. It is also advisable to make single instance of DateTime.Now;

Create a custom View by inflating a layout?

Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

http://developer.android.com/guide/topics/ui/custom-components.html

Removing duplicate rows in Notepad++

You may need a plugin to do this. You can try the command line cc.ddl(delete duplicate lines) of ConyEdit. It is a cross-editor plugin for the text editors, including Notepad++.

With ConyEdit running in background, follow the steps below:

  1. enter the command line cc.ddl at the end of the text.
  2. copy the text and the command line.
  3. paste, then you will see what you want.

Example
enter image description here

Bulk Insertion in Laravel using eloquent ORM

To whoever is reading this, check out createMany() method.

/**
 * Create a Collection of new instances of the related model.
 *
 * @param  array  $records
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function createMany(array $records)
{
    $instances = $this->related->newCollection();

    foreach ($records as $record) {
        $instances->push($this->create($record));
    }

    return $instances;
}

Reset local repository branch to be just like remote repository HEAD

No amount of reset and cleaning seemed to have any effect on untracked and modified files in my local git repo (I tried all the options above). My only solution to this was to rm the local repo and re-clone it from the remote.

Fortunately I didn't have any other branches I cared about.

xkcd: Git

How to load image to WPF in runtime?

In WPF an image is typically loaded from a Stream or an Uri.

BitmapImage supports both and an Uri can even be passed as constructor argument:

var uri = new Uri("http://...");
var bitmap = new BitmapImage(uri);

If the image file is located in a local folder, you would have to use a file:// Uri. You could create such a Uri from a path like this:

var path = Path.Combine(Environment.CurrentDirectory, "Bilder", "sas.png");
var uri = new Uri(path);

If the image file is an assembly resource, the Uri must follow the the Pack Uri scheme:

var uri = new Uri("pack://application:,,,/Bilder/sas.png");

In this case the Visual Studio Build Action for sas.png would have to be Resource.

Once you have created a BitmapImage and also have an Image control like in this XAML

<Image Name="image1" />

you would simply assign the BitmapImage to the Source property of that Image control:

image1.Source = bitmap;

Change Default branch in gitlab

Settings > Repository > Default Branch

enter image description here

Using find to locate files that match one of multiple patterns

I needed to remove all files in child dirs except for some files. The following worked for me (three patterns specified):

find . -depth -type f -not -name *.itp -and -not -name *ane.gro -and -not -name *.top -exec rm '{}' +

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

List file using ls command in Linux with full path

How about:

 du -a [-b] [--max-depth=N] 

That should give you a file and directory listing, relative to your current location. You will get sizes as well (add the '-b' parameter if you want the sizes in bytes). The max-depth parameter may be necessary to "encourage" du to dive deeply enough into your file structure -- or to keep it from getting carried away.

YMMV!
-101-

How to sum the values of a JavaScript object?

I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:

var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
    parskey = parseInt(array[key]);
    sum += parskey;
};
return(sum);

[Vue warn]: Property or method is not defined on the instance but referenced during render

I had two methods: in the <script>, goes to show, that you can spend hours looking for something that was such a simple mistake.

How to mock location on device?

Use this permission in manifest file

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION">

android studio will recommend that "Mock location should only be requested in a test or debug-specific manifest file (typically src/debug/AndroidManifest.xml)" just disable the inspection

Now make sure you have checked the "Allow mock locations" in developer setting of your phone

Use LocationManager

locationManager.addTestProvider(mocLocationProvider, false, false,
                false, false, true, true, true, 0, 5);
locationManager.setTestProviderEnabled(mocLocationProvider, true);

Now set the location wherever you want

Location mockLocation = new Location(mocLocationProvider); 
mockLocation.setLatitude(lat); 
mockLocation.setLongitude(lng); 
mockLocation.setAltitude(alt); 
mockLocation.setTime(System.currentTimeMillis()); 
locationManager.setTestProviderLocation( mocLocationProvider, mockLocation); 

Which tool to build a simple web front-end to my database

The most rapid option is to hand out MS Access or SQL Sever Management Studio (there's a free express edition) along with a read only account.

PHP is simple and has a well earned reputation for getting stuff done. PHP is excellent for copying and pasting code, and you can iterate insanely fast in PHP. PHP can lead to hard-to-maintain applications, and it can be difficult to set up a visual debugger.

Given that you use SQL Server, ASP.NET is also a good option. This is somewhat harder to setup; you'll need an IIS server, with a configured application. Iterations are a bit slower. ASP.NET is easier to maintain and Visual Studio is the best visual debugger around.

Python Loop: List Index Out of Range

Try reducing the range of the for loop to range(len(a)-1):

a = [0,1,2,3]
b = []

for i in range(len(a)-1):
    b.append(a[i]+a[i+1])

print(b)

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Possible to extend types in Typescript?

What you are trying to achieve is equivalent to

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent extends Event {
   UserId: string; 
}

The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.

C: What is the difference between ++i and i++?

The effective result of using either in a loop is identical. In other words, the loop will do the same exact thing in both instances.

In terms of efficiency, there could be a penalty involved with choosing i++ over ++i. In terms of the language spec, using the post-increment operator should create an extra copy of the value on which the operator is acting. This could be a source of extra operations.

However, you should consider two main problems with the preceding logic.

  1. Modern compilers are great. All good compilers are smart enough to realize that it is seeing an integer increment in a for-loop, and it will optimize both methods to the same efficient code. If using post-increment over pre-increment actually causes your program to have a slower running time, then you are using a terrible compiler.

  2. In terms of operational time-complexity, the two methods (even if a copy is actually being performed) are equivalent. The number of instructions being performed inside of the loop should dominate the number of operations in the increment operation significantly. Therefore, in any loop of significant size, the penalty of the increment method will be massively overshadowed by the execution of the loop body. In other words, you are much better off worrying about optimizing the code in the loop rather than the increment.

In my opinion, the whole issue simply boils down to a style preference. If you think pre-increment is more readable, then use it. Personally, I prefer the post-incrment, but that is probably because it was what I was taught before I knew anything about optimization.

This is a quintessential example of premature optimization, and issues like this have the potential to distract us from serious issues in design. It is still a good question to ask, however, because there is no uniformity in usage or consensus in "best practice."

Easy way to password-protect php page

Not the solution, but for your interest: HTTP authentication only works, when PHP runs as Apache module. Most hosters provide PHP as CGI version only.

Create table with jQuery - append

this is most better

html

<div id="here_table"> </div>

jQuery

$('#here_table').append( '<table>' );

for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' +  i + '</tr>' );

    for(ii=0;ii<3;ii++)
    {
    $('#here_table').append( '<td>' + 'result' +  i + '</tr>' );
    }
}

$('#here_table').append(  '</table>' );

Create component to specific module with Angular-CLI

Go to module level/we can also be in the root level and type below commands

ng g component "path to your component"/NEW_COMPONENT_NAME -m "MODULE_NAME"

Example :

ng g component common/signup/payment-processing/OnlinePayment -m pre-login.module

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Find which rows have different values for a given column in Teradata SQL

Join the table with itself and give it two different aliases (A and B in the following example). This allows to compare different rows of the same table.

SELECT DISTINCT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
    A.Address <> B.Address

The "less than" comparison < ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <> instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A alias and the B alias in turn.

The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.


The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to

SELECT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id
WHERE                     
    A.[Adress Code] = 1 AND
    B.[Adress Code] = 2 AND
    A.Address <> B.Address

I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .

Multiline for WPF TextBox

The only property corresponding in WPF to the

Winforms property: TextBox.Multiline = true

is the WPF property: TextBox.AcceptsReturn = true.

<TextBox AcceptsReturn="True" ...... />

All other settings, such as VerticalAlignement, WordWrap etc., only control how the TextBox interacts in the UI but do not affect the Multiline behaviour.

How do I find the current directory of a batch file, and then use it for the path?

You can also do

 Pushd "%~dp0"

Which also takes running from a unc path into consideration.

Cannot open output file, permission denied

In my case - I found a process called

cb_console_runner

I stopped this process and things were ok again.

Sending credentials with cross-domain posts?

Functionality is supposed to be broken in jQuery 1.5.

Since jQuery 1.5.1 you should use xhrFields param.

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true
});

Docs: http://api.jquery.com/jQuery.ajax/

Reported bug: http://bugs.jquery.com/ticket/8146

Function ereg_replace() is deprecated - How to clear this bug?

Switch to preg_replaceDocs and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) where there are differencesDocs (just as it says to do in the manual for ereg_replaceDocs).

Rounding float in Ruby

def rounding(float,precision)
    return ((float * 10**precision).round.to_f) / (10**precision)
end

Creating a list of objects in Python

You demonstrate a fundamental misunderstanding.

You never created an instance of SimpleClass at all, because you didn't call it.

for count in xrange(4):
    x = SimpleClass()
    x.attr = count
    simplelist.append(x)

Or, if you let the class take parameters, instead, you can use a list comprehension.

simplelist = [SimpleClass(count) for count in xrange(4)]

After submitting a POST form open a new window showing the result

var urlAction = 'whatever.php';
var data = {param1:'value1'};

var $form = $('<form target="_blank" method="POST" action="' + urlAction + '">');
$.each(data, function(k,v){
    $form.append('<input type="hidden" name="' + k + '" value="' + v + '">');
});
$form.submit();

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

From an array of objects, extract value of a property as array

Check out Lodash's _.pluck() function or Underscore's _.pluck() function. Both do exactly what you want in a single function call!

var result = _.pluck(objArray, 'foo');

Update: _.pluck() has been removed as of Lodash v4.0.0, in favour of _.map() in combination with something similar to Niet's answer. _.pluck() is still available in Underscore.

Update 2: As Mark points out in the comments, somewhere between Lodash v4 and 4.3, a new function has been added that provides this functionality again. _.property() is a shorthand function that returns a function for getting the value of a property in an object.

Additionally, _.map() now allows a string to be passed in as the second parameter, which is passed into _.property(). As a result, the following two lines are equivalent to the code sample above from pre-Lodash 4.

var result = _.map(objArray, 'foo');
var result = _.map(objArray, _.property('foo'));

_.property(), and hence _.map(), also allow you to provide a dot-separated string or array in order to access sub-properties:

var objArray = [
    {
        someProperty: { aNumber: 5 }
    },
    {
        someProperty: { aNumber: 2 }
    },
    {
        someProperty: { aNumber: 9 }
    }
];
var result = _.map(objArray, _.property('someProperty.aNumber'));
var result = _.map(objArray, _.property(['someProperty', 'aNumber']));

Both _.map() calls in the above example will return [5, 2, 9].

If you're a little more into functional programming, take a look at Ramda's R.pluck() function, which would look something like this:

var result = R.pluck('foo')(objArray);  // or just R.pluck('foo', objArray)

Using python's eval() vs. ast.literal_eval()?

Python's eager in its evaluation, so eval(input(...)) (Python 3) will evaluate the user's input as soon as it hits the eval, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval user input.

Use ast.literal_eval.


As an example, entering this at the prompt could be very bad for you:

__import__('os').system('rm -rf /a-path-you-really-care-about')

Why does configure say no C compiler found when GCC is installed?

Maybe gcc is not in your path? Try finding gcc using which gcc and add it to your path if it's not already there.

Getting list of lists into pandas DataFrame

Even without pop the list we can do with set_index

pd.DataFrame(table).T.set_index(0).T
Out[11]: 
0 Heading1 Heading2
1        1        2
2        3        4

Update from_records

table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]

pd.DataFrame.from_records(table[1:],columns=table[0])
Out[58]: 
   Heading1  Heading2
0         1         2
1         3         4

Test method is inconclusive: Test wasn't run. Error?

I had the same error in VS2013 and Resharper9. The problem was because i forgot to annotate test method with [Test] :) Hope this helps anyone

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

I use this for Windows (binary prefixes):

static readonly string[] BinaryPrefix = { "bytes", "KB", "MB", "GB", "TB" }; // , "PB", "EB", "ZB", "YB"
string GetMemoryString(double bytes)
{
    int counter = 0;
    double value = bytes;
    string text = "";
    do
    {
        text = value.ToString("0.0") + " " + BinaryPrefix[counter];
        value /= 1024;
        counter++;
    }
    while (Math.Floor(value) > 0 && counter < BinaryPrefix.Length);
    return text;
}

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

Spring application context external properties?

<context:property-placeholder location="classpath*:spring/*.properties" />

If you place it somewhere in the classpath in a directory named spring (change names/dirs accordingly), you can access with above

<property name="locations" value ="config/springcontext.properties" />

this will be pointing to web-inf/classes/config/springcontext.properties

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

Try Shift + Delete. Did 24.000 files in 2 minutes for me.

Splitting a string into chunks of a certain size

static IEnumerable<string> Split(string str, double chunkSize)
{
    return Enumerable.Range(0, (int) Math.Ceiling(str.Length/chunkSize))
       .Select(i => new string(str
           .Skip(i * (int)chunkSize)
           .Take((int)chunkSize)
           .ToArray()));
}

and another approach:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {

        var x = "Hello World";
        foreach(var i in x.ChunkString(2)) Console.WriteLine(i);
    }
}

public static class Ext{
    public static IEnumerable<string> ChunkString(this string val, int chunkSize){
        return val.Select((x,i) => new {Index = i, Value = x})
                  .GroupBy(x => x.Index/chunkSize, x => x.Value)
                  .Select(x => string.Join("",x));
    }
}

Does IE9 support console.log, and is it a real function?

I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js

Traverse all the Nodes of a JSON Object Tree with JavaScript

Depends on what you want to do. Here's an example of traversing a JavaScript object tree, printing keys and values as it goes:

function js_traverse(o) {
    var type = typeof o 
    if (type == "object") {
        for (var key in o) {
            print("key: ", key)
            js_traverse(o[key])
        }
    } else {
        print(o)
    }
}

js> foobar = {foo: "bar", baz: "quux", zot: [1, 2, 3, {some: "hash"}]}
[object Object]
js> js_traverse(foobar)                 
key:  foo
bar
key:  baz
quux
key:  zot
key:  0
1
key:  1
2
key:  2
3
key:  3
key:  some
hash

How can strip whitespaces in PHP's variable?

You can use trim function from php to trim both sides (left and right)

 trim($yourinputdata," ");

Or

trim($yourinputdata);

You can also use

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

Don't know if this has been solved yet but I was getting similar problems with Anaconda python 3.7.3 and Idle on Windows 10. Fixed it by adding:

<path>\Anaconda3
<path>\Anaconda3\scripts
<path>\Anaconda3\Library\bin

to the PATH variable.

Auto submit form on page load

You can submit any form automatically on page load simply by adding a snippet of javascript code to your body tag referencing the form name like this....

<body onload="document.form1.submit()">

How to update-alternatives to Python 3 without breaking apt?

Per Debian policy, python refers to Python 2 and python3 refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.

Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.

With recent Python 3, venv is part of the standard library; with older versions, you might need to install python3-venv or a similar package.

$HOME~$ python --version
Python 2.7.11

$HOME~$ python3 -m venv myenv
... stuff happens ...

$HOME~$ . ./myenv/bin/activate

(myenv) $HOME~$ type python   # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python

(myenv) $HOME~$ python --version
Python 3.5.1

A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile or similar.

Link to a section of a webpage

Simple:

Use <section>.

and use <a href="page.html#tips">Visit the Useful Tips Section</a>

w3school.com/html_links

TypeScript Objects as Dictionary types as in C#

In newer versions of typescript you can use:

type Customers = Record<string, Customer>

In older versions you can use:

var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer

You can also make an interface if you don't want to type that whole type annotation out every time:

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

Detecting when a div's height changes using jQuery

This is how I recently handled this problem:

$('#your-resizing-div').bind('getheight', function() {
    $('#your-resizing-div').height();
});

function your_function_to_load_content() {
    /*whatever your thing does*/
    $('#your-resizing-div').trigger('getheight');
}

I know I'm a few years late to the party, just think my answer may help some people in the future, without having to download any plugins.

App crashing when trying to use RecyclerView on android 5.0

I experienced this crash even though I had the RecyclerView.LayoutManager properly set. I had to move the RecyclerView initialization code into the onViewCreated(...) callback to fix this issue.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_listing, container, false);
    rootView.setTag(TAG);
    return inflater.inflate(R.layout.fragment_listing, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new ListingAdapter(mListing);
    mRecyclerView.setAdapter(mAdapter);
}

How to comment multiple lines with space or indent

One way to do it would be:

  1. Select the text, Press CTRL + K, C to comment (CTRL+E+C )
  2. Move the cursor to the first line after the delimiter // and before the Code text.
  3. Press Alt + Shift and use arrow keys to make selection. (Remember to make line selection(using down, up arrow keys), not the text selection - See Box Selection and Multi line editing)
  4. Once the selection is done, press space bar to enter a single space.

Notice the vertical blue line in the below image( that will appear once the selection is made, then you can insert any number of characters in between them)

enter image description here

I couldn't find a direct way to do that. The interesting thing is that it is mentioned in the C# Coding Conventions (C# Programming Guide) under Commenting Conventions.

Insert one space between the comment delimiter (//) and the comment text

But the default implementation of commenting in visual studio doesn't insert any space

SVN- How to commit multiple files in a single shot

You can use an svn changelist to keep track of a set of files that you want to commit together.

The linked page goes into lots of details, but here's an executive summary example:

$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist

Regular expression for validating names and surnames?

Steps:

  1. first remove all accents
  2. apply the regular expression

To strip the accents:

private static string RemoveAccents(string s)
{
    s = s.Normalize(NormalizationForm.FormD);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.Length; i++)
    {
        if (CharUnicodeInfo.GetUnicodeCategory(s[i]) != UnicodeCategory.NonSpacingMark) sb.Append(s[i]);
    }
    return sb.ToString();
}

How to "properly" print a list?

Using only print:

>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b

How can I create an executable JAR with dependencies using Maven?

The maven-assembly-plugin worked great for me. I spent hours with the maven-dependency-plugin and couldn't make it work. The main reason was that I had to define in the configuration section explicitly the artifact items which should be included as it is described in the documentation. There is an example there for the cases when you want to use it like: mvn dependency:copy, where there are not included any artifactItems but it doesn't work.

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

'python' is not recognized as an internal or external command

Another helpful but simple solution might be restarting your computer after doing the download if Python is in the PATH variable. This has been a mistake I usually make when downloading Python onto a new machine.

Loading a properties file from Java package

To add to Joachim Sauer's answer, if you ever need to do this in a static context, you can do something like the following:

static {
  Properties prop = new Properties();
  InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
  prop.load(in);
  in.close()
}

(Exception handling elided, as before.)

Fatal error: Call to a member function bind_param() on boolean

prepare return a boolean only when it fails therefore FALSE, to avoid the error you need to check if it is True first before executing:

$sql = 'SELECT value, param FROM ws_settings WHERE name = ?';
if($query = $this->db->conn->prepare($sql)){
    $query->bind_param('s', $setting);
    $query->execute();
    //rest of code here
}else{
   //error !! don't go further
   var_dump($this->db->error);
}

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I ran into this issue and the suggested fix of rvm osx-ssl-certs update all did not work despite that I am an RVM user on OSX.

The fix that worked for me was re-installing the latest version of openssl:

brew update
brew remove openssl
brew install openssl

explode string in jquery

Try This

var data = 'allow~5'; 
var result=data.split('~');

RESULT

alert(result[0]);

How do I change tab size in Vim?

:set tabstop=4
:set shiftwidth=4
:set expandtab

This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.

Correct way to write line to file?

When I need to write new lines a lot, I define a lambda that uses a print function:

out = open(file_name, 'w')
fwl = lambda *x, **y: print(*x, **y, file=out) # FileWriteLine
fwl('Hi')

This approach has the benefit that it can utilize all the features that are available with the print function.

Update: As is mentioned by Georgy in the comment section, it is possible to improve this idea further with the partial function:

from functools import partial
fwl = partial(print, file=out)

IMHO, this is a more functional and less cryptic approach.

Why do Python's math.ceil() and math.floor() operations return floats instead of integers?

As pointed out by other answers, in python they return floats probably because of historical reasons to prevent overflow problems. However, they return integers in python 3.

>>> import math
>>> type(math.floor(3.1))
<class 'int'>
>>> type(math.ceil(3.1))
<class 'int'>

You can find more information in PEP 3141.

VBA check if file exists

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

Using GregorianCalendar with SimpleDateFormat

Why such complications?

public static GregorianCalendar convertFromDMY(String dd_mm_yy) throws ParseException 
{
    SimpleDateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = fmt.parse(dd_mm_yy);
    GregorianCalendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    return cal;
}

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

public class Toggle {
public static String toggle(String s) {
    char[] ch = s.toCharArray();

    for (int i = 0; i < s.length(); i++) {
        char charat = ch[i];
        if (Character.isUpperCase(charat)) {
            charat = Character.toLowerCase(charat);
        } else
            charat = Character.toUpperCase(charat);
        System.out.print(charat);
    }
    return s;
  }

public static void main(String[] args) {
    toggle("DivYa");
   }
  }

Regular expression to match numbers with or without commas and decimals in text

This regex:

(\d{1,3},\d{3}(,\d{3})*)(\.\d*)?|\d+\.?\d*

Matched every number in the string:

1 1.0 0.1 1.001 1,000 1,000,000 1000.1 1,000.1 1,323,444,000 1,999 1,222,455,666.0 1,244

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Creating a list of pairs in java

Similar to what Mark E has proposed, but no need to recreate the wheel, if you don't mind relying on 3rd party libs.

Apache Commons has tuples already defined:

org.apache.commons.lang3.tuple.Pair<L,R>

Apache Commons is so pervasive, I typically already have it in my projects, anyway. https://mvnrepository.com/artifact/org.apache.commons/commons-lang3

https with WCF error: "Could not find base address that matches scheme https"

I had this exact same problem. Except my solution was to add an "s" to the binding value.

Old: binding="mexHttpBinding"

New: binding="mexHttpsBinding"

web.config snippet:

<services>
    <service behaviorConfiguration="ServiceBehavior" name="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService">
        <endpoint behaviorConfiguration="AspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" 
            contract="LIMS.UI.Web.WCFServices.Accessioning.QuickDataEntryService" />
        <endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange" />
    </service>

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

function convert(str) {
    var date = new Date(str),
        mnth = ("0" + (date.getMonth()+1)).slice(-2),
        day  = ("0" + date.getDate()).slice(-2);
        hours  = ("0" + date.getHours()).slice(-2);
        minutes = ("0" + date.getMinutes()).slice(-2);
    return [ date.getFullYear(), mnth, day, hours, minutes ].join("-");
}

I used this efficiently in angular because i was losing two hours on updating a $scope.STARTevent, and $scope.ENDevent, IN console.log was fine, however saving to mYsql dropped two hours.

var whatSTART = $scope.STARTevent;
whatSTART = convert(whatever);

THIS WILL ALSO work for END

Find the division remainder of a number

The remainder of a division can be discovered using the operator %:

>>> 26%7
5

In case you need both the quotient and the modulo, there's the builtin divmod function:

>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)

Real world use of JMS/message queues?

Distributed (a)synchronous computing.
A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage. So the application would act as a Producer by create a Message object, putting it on a particular Queue, and moving forward.
There would be a set of Consumers who would subscribe to the Queue in question, and would take care handling the Message sent across. Note that during the course of this transaction, the Producers are decoupled from the logic of how a given Message would be handled.
Messaging frameworks (ActiveMQ and the likes) act as a backbone to facilitate such Message transactions by providing MessageBrokers.

Changing :hover to touch/click for mobile devices

On most devices, the other answers work. For me, to ensure it worked on every device (in react) I had to wrap it in an anchor tag <a> and add the following: :hover, :focus, :active (in that order), as well as role="button" and tabIndex="0".

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

unix - count of columns in file

Unless you're using spaces in there, you should be able to use | wc -w on the first line.

wc is "Word Count", which simply counts the words in the input file. If you send only one line, it'll tell you the amount of columns.

oracle diff: how to compare two tables?

You can use a tool like AQT to create diffs between tables.

Another approach would be to dump the tables to a text file and use a diff tool like WinMerge. With this approach, you can use complex SQL to turn the tables into the same layout, first.

How to construct a WebSocket URI relative to the page URI?

Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL

Works with http(s), ports etc.

var url = new URL('/path/to/websocket', window.location.href);

url.protocol = url.protocol.replace('http', 'ws');

url.href // => ws://www.example.com:9999/path/to/websocket

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

Jquery submit form

Try this lets say your form id is formID

$(".nextbutton").click(function() { $("form#formID").submit(); });

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

How to convert an array of key-value tuples into an object

Update June 2020

ECMAScript 2021 brings Object.fromEntries which does exactly the requirement:

_x000D_
_x000D_
const array =    [ [ 'cardType', 'iDEBIT' ],
      [ 'txnAmount', '17.64' ],
      [ 'txnId', '20181' ],
      [ 'txnType', 'Purchase' ],
      [ 'txnDate', '2015/08/13 21:50:04' ],
      [ 'respCode', '0' ],
      [ 'isoCode', '0' ],
      [ 'authCode', '' ],
      [ 'acquirerInvoice', '0' ],
      [ 'message', '' ],
      [ 'isComplete', 'true' ],
      [ 'isTimeout', 'false' ] ];
      
const obj = Object.fromEntries(array);
console.log(obj);
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

This will do it:

_x000D_
_x000D_
const array =    [ [ 'cardType', 'iDEBIT' ],
      [ 'txnAmount', '17.64' ],
      [ 'txnId', '20181' ],
      [ 'txnType', 'Purchase' ],
      [ 'txnDate', '2015/08/13 21:50:04' ],
      [ 'respCode', '0' ],
      [ 'isoCode', '0' ],
      [ 'authCode', '' ],
      [ 'acquirerInvoice', '0' ],
      [ 'message', '' ],
      [ 'isComplete', 'true' ],
      [ 'isTimeout', 'false' ] ];
    
var obj = {};
array.forEach(function(data){
    obj[data[0]] = data[1]
});
console.log(obj);
_x000D_
_x000D_
_x000D_


Concatenate two JSON objects

If you'd rather copy the properties:

var json1 = { value1: '1', value2: '2' };
var json2 = { value2: '4', value3: '3' };


function jsonConcat(o1, o2) {
 for (var key in o2) {
  o1[key] = o2[key];
 }
 return o1;
}

var output = {};
output = jsonConcat(output, json1);
output = jsonConcat(output, json2);

Output of above code is{ value1: '1', value2: '4', value3: '3' }

What are examples of TCP and UDP in real life?

TCP guarantees (in-order) packet delivery. UDP doesn't.

TCP - used for traffic that you need all the data for. i.e HTML, pictures, etc. UDP - used for traffic that doesn't suffer much if a packet is dropped, i.e. video & voice streaming, some data channels of online games, etc.

Suppress command line output

You can do this instead too:

tasklist | find /I "test.exe" > nul && taskkill /f /im test.exe > nul

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

Right now the asp.mvc project template creates an account controller that gets the usermanager this way:

HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>()

The following works for me:

ApplicationUser user = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(User.Identity.GetUserId());

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

Xcode 10, Command CodeSign failed with a nonzero exit code

For me the highest rated answer didn't work.

What did work was to go to Signing and Capabilities -> Team -> add account and add the Apple ID again.

After doing this, when I built again I was asked for my login credentials and the build succeeded.

How do I delete all the duplicate records in a MySQL table without temp tables

Add Unique Index on your table:

ALTER IGNORE TABLE `TableA`   
ADD UNIQUE INDEX (`member_id`, `quiz_num`, `question_num`, `answer_num`);

Another way to do this would be:

Add primary key in your table then you can easily remove duplicates from your table using the following query:

DELETE FROM member  
WHERE id IN (SELECT * 
             FROM (SELECT id FROM member 
                   GROUP BY member_id, quiz_num, question_num, answer_num HAVING (COUNT(*) > 1)
                  ) AS A
            );

add a temporary column with a value

select field1, field2, NewField = 'example' from table1 

How to use the PI constant in C++

Pi can be calculated as atan(1)*4. You could calculate the value this way and cache it.

How to get HTTP response code for a URL in Java?

HttpURLConnection:

URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();

int code = connection.getResponseCode();

This is by no means a robust example; you'll need to handle IOExceptions and whatnot. But it should get you started.

If you need something with more capability, check out HttpClient.

cannot import name patterns

This is the code which worked for me. My django version is 1.10.4 final

from django.conf.urls import url, include

from django.contrib import admin
admin.autodiscover()

urlpatterns = [
    # Examples:
    # url(r'^$', 'blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
]

Create a dropdown component

This is the code to create dropdown in Angular 7, 8, 9

.html file code

<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
  <option value="0">--All--</option>
  <option *ngFor="let item of items" value="{{item.Id.Value}}">
    {{item.Name}}
  </option>
</select>
</div>

.ts file code

SelectItem(filterVal: any)
{
    var id=filterVal;
    //code
}

items is an array which should be initialized in .ts file.

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

Docker is in volume in use, but there aren't any Docker containers

As long as volumes are associated with a container(either running or not), they cannot be removed.

You have to run

docker inspect <container-id>/<container-name>

on each of the running/non-running containers where this volume might have been mounted onto.

If the volume is mounted onto any one of the containers, you should see it in the Mounts section of the inspect command output. Something like this :-

"Mounts": [
            {
                "Type": "volume",
                "Name": "user1",
                "Source": "/var/lib/docker/volumes/user1/_data",
                "Destination": "/opt",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],

After figuring out the responsible container(s), use :-

docker rm -f container-1 container-2 ...container-n in case of running containers

docker rm container-1 container-2 ...container-n in case of non-running containers

to completely remove the containers from the host machine.

Then try removing the volume using the command :-

docker volume remove <volume-name/volume-id>

Defining a `required` field in Bootstrap

Form validation can be enabled in markup via the data-api or via JavaScript. Automatically enable form validation by adding data-toggle="validator" to your form element.

<form role="form" data-toggle="validator">
   ...
</form>

Or activate validation via JavaScript:

$('#myForm').validator()

and you need to use required flag in input field

For more details Click Here