Programs & Examples On #Automapping

The convention-based Auto Mapping feature of Fluent NHibernate. Not to be confused with AutoMapper, the convention-based object-to-object mapper.

Regular expression for a hexadecimal number?

In case you need this within an input where the user can type 0 and 0x too but not a hex number without the 0x prefix:

^0?[xX]?[0-9a-fA-F]*$

Simplest way to read json from a URL in java

It's very easy, using jersey-client, just include this maven dependency:

<dependency>
  <groupId>org.glassfish.jersey.core</groupId>
  <artifactId>jersey-client</artifactId>
  <version>2.25.1</version>
</dependency>

Then invoke it using this example:

String json = ClientBuilder.newClient().target("http://api.coindesk.com/v1/bpi/currentprice.json").request().accept(MediaType.APPLICATION_JSON).get(String.class);

Then use Google's Gson to parse the JSON:

Gson gson = new Gson();
Type gm = new TypeToken<CoinDeskMessage>() {}.getType();
CoinDeskMessage cdm = gson.fromJson(json, gm);

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Oracle error : ORA-00905: Missing keyword

Though this is not directly related to the OP's exact question but I just found out that using a Oracle reserved word in your query (in my case the alias IN) can cause the same error.

Example:

SELECT * FROM TBL_INDEPENTS IN
JOIN TBL_VOTERS VO on IN.VOTERID = VO.VOTERID

Or if its in the query itself as a field name

 SELECT ..., ...., IN, ..., .... FROM SOMETABLE

That would also throw that error. I hope this helps someone.

Python: Converting string into decimal number

If you want the result as the nearest binary floating point number use float:

result = [float(x.strip(' "')) for x in A1]

If you want the result stored exactly use Decimal instead of float:

from decimal import Decimal
result = [Decimal(x.strip(' "')) for x in A1]

Best approach to converting Boolean object to string in java

If you're looking for a quick way to do this, for example debugging, you can simply concatenate an empty string on to the boolean:

System.out.println(b+"");

However, I strongly recommend using another method for production usage. This is a simple quick solution which is useful for debugging.

Can I replace groups in Java regex?

Add a third group by adding parens around .*, then replace the subsequence with "number" + m.group(2) + "1". e.g.:

String output = m.replaceFirst("number" + m.group(2) + "1");

Multiple conditions in a C 'for' loop

Completing Mr. Crocker's answer, be careful about ++ or -- operators or I don't know maybe other operators. They can affect the loop. for example I saw a code similar to this one in a course:

for(int i=0; i++*i<-1, i<3; printf(" %d", i));

The result would be $ 1 2$. So the first statement has affected the loop while the outcome of the following is lots of zeros.

for(int i=0; i<3; printf(" %d", i));

TypeScript: Creating an empty typed container array

Okay you got the syntax wrong here, correct way to do this is:

var arr: Criminal[] = [];

I'm assuming you are using var so that means declaring it somewhere inside the func(),my suggestion would be use let instead of var.

If declaring it as c class property usse acces modifiers like private, public, protected.

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

Text vertical alignment in WPF TextBlock

Vertically aligned single line TextBox.

To expand on the answer provided by @Orion Edwards, this is how you would do fully from code-behind (no styles set). Basically create a custom class that inherits from Border which has its Child set to a TextBox. The example below assumes that you only want a single line and that the border is a child of a Canvas. Also assumes you would need to adjust the MaxLength property of the TextBox based on the width of the Border. The example below also sets the cursor of the Border to mimic a Textbox by setting it to the type 'IBeam'. A margin of '3' is set so that the TextBox isn't absolutely aligned to the left of the border.

double __dX = 20;
double __dY = 180;
double __dW = 500;
double __dH = 40;
int __iMaxLen = 100;

this.m_Z3r0_TextBox_Description = new CZ3r0_TextBox(__dX, __dY, __dW, __dH, __iMaxLen, TextAlignment.Left);
this.Children.Add(this.m_Z3r0_TextBox_Description);

Class:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;


namespace ifn0tz3r0Exp
{
    class CZ3r0_TextBox : Border
    {
        private TextBox m_TextBox;

        private SolidColorBrush m_Brush_Green = new SolidColorBrush(Colors.MediumSpringGreen);
        private SolidColorBrush m_Brush_Black = new SolidColorBrush(Colors.Black);
        private SolidColorBrush m_Brush_Transparent = new SolidColorBrush(Colors.Transparent);

        public CZ3r0_TextBox(double _dX, double _dY, double _dW, double _dH, int _iMaxLen, TextAlignment _Align)
        {

            /////////////////////////////////////////////////////////////
            //TEXTBOX
            this.m_TextBox = new TextBox();
            this.m_TextBox.Text = "This is a vertically centered one-line textbox embedded in a border...";
            Canvas.SetLeft(this, _dX);
            Canvas.SetTop(this, _dY);
            this.m_TextBox.FontFamily = new FontFamily("Consolas");
            this.m_TextBox.FontSize = 11;
            this.m_TextBox.Background = this.m_Brush_Black;
            this.m_TextBox.Foreground = this.m_Brush_Green;
            this.m_TextBox.BorderBrush = this.m_Brush_Transparent;
            this.m_TextBox.BorderThickness = new Thickness(0.0);
            this.m_TextBox.Width = _dW;
            this.m_TextBox.MaxLength = _iMaxLen;
            this.m_TextBox.TextAlignment = _Align;
            this.m_TextBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            this.m_TextBox.FocusVisualStyle = null;
            this.m_TextBox.Margin = new Thickness(3.0);
            this.m_TextBox.CaretBrush = this.m_Brush_Green;
            this.m_TextBox.SelectionBrush = this.m_Brush_Green;
            this.m_TextBox.SelectionOpacity = 0.3;

            this.m_TextBox.GotFocus += this.CZ3r0_TextBox_GotFocus;
            this.m_TextBox.LostFocus += this.CZ3r0_TextBox_LostFocus;
            /////////////////////////////////////////////////////////////
            //BORDER

            this.BorderBrush = this.m_Brush_Transparent;
            this.BorderThickness = new Thickness(1.0);
            this.Background = this.m_Brush_Black;            
            this.Height = _dH;
            this.Child = this.m_TextBox;
            this.FocusVisualStyle = null;
            this.MouseDown += this.CZ3r0_TextBox_MouseDown;
            this.Cursor = Cursors.IBeam;
            /////////////////////////////////////////////////////////////
        }
        private void CZ3r0_TextBox_MouseDown(object _Sender, MouseEventArgs e)
        {
            this.m_TextBox.Focus();
        }
        private void CZ3r0_TextBox_GotFocus(object _Sender, RoutedEventArgs e)
        {
            this.BorderBrush = this.m_Brush_Green;
        }
        private void CZ3r0_TextBox_LostFocus(object _Sender, RoutedEventArgs e)
        {
            this.BorderBrush = this.m_Brush_Transparent;
        }
    }
}

Uninstall Node.JS using Linux command line?

If you installed node using curl + yum:

sudo curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -
sudo yum -y install nodejs

Then you can remove it using yum:

sudo yum remove nodejs

Note that using the curl script causes the wrong version of node to be installed. There is a bug that causes node v6.7 to be installed instead of v4.x intended by the path (../setup_4.x) used in the curl script.

How do I access the $scope variable in browser's console using AngularJS?

Somewhere in your controller (often the last line is a good place), put

console.log($scope);

If you want to see an inner/implicit scope, say inside an ng-repeat, something like this will work.

<li ng-repeat="item in items">
   ...
   <a ng-click="showScope($event)">show scope</a>
</li>

Then in your controller

function MyCtrl($scope) {
    ...
    $scope.showScope = function(e) {
        console.log(angular.element(e.srcElement).scope());
    }
}

Note that above we define the showScope() function in the parent scope, but that's okay... the child/inner/implicit scope can access that function, which then prints out the scope based on the event, and hence the scope associated with the element that fired the event.

@jm-'s suggestion also works, but I don't think it works inside a jsFiddle. I get this error on jsFiddle inside Chrome:

> angular.element($0).scope()
ReferenceError: angular is not defined

Iterate all files in a directory using a 'for' loop

The following code creates a file Named "AllFilesInCurrentDirectorylist.txt" in the current Directory, which contains the list of all files (Only Files) in the current Directory. Check it out

dir /b /a-d > AllFilesInCurrentDirectorylist.txt

PHP - Failed to open stream : No such file or directory

Samba Shares

If you have a Linux test server and you work from a Windows Client, the Samba share interferes with the chmod command. So, even if you use:

chmod -R 777 myfolder

on the Linux side it is fully possible that the Unix Group\www-data still doesn't have write access. One working solution if your share is set up that Windows admins are mapped to root: From Windows, open the Permissions, disable Inheritance for your folder with copy, and then grant full access for www-data.

How to "perfectly" override a dict?

All you will have to do is

class BatchCollection(dict):
    def __init__(self, *args, **kwargs):
        dict.__init__(*args, **kwargs)

OR

class BatchCollection(dict):
    def __init__(self, inpt={}):
        super(BatchCollection, self).__init__(inpt)

A sample usage for my personal use

### EXAMPLE
class BatchCollection(dict):
    def __init__(self, inpt={}):
        dict.__init__(*args, **kwargs)

    def __setitem__(self, key, item):
        if (isinstance(key, tuple) and len(key) == 2
                and isinstance(item, collections.Iterable)):
            # self.__dict__[key] = item
            super(BatchCollection, self).__setitem__(key, item)
        else:
            raise Exception(
                "Valid key should be a tuple (database_name, table_name) "
                "and value should be iterable")

Note: tested only in python3

How to output loop.counter in python jinja template?

if you are using django use forloop.counter instead of loop.counter

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{forloop.counter}}
  </li>
      {% if forloop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

Access to ES6 array element index inside for-of loop

In a for..of loop we can achieve this via array.entries(). array.entries returns a new Array iterator object. An iterator object knows how to access items from an iterable one at the time, while keeping track of its current position within that sequence.

When the next() method is called on the iterator key value pairs are generated. In these key value pairs the array index is the key and the array item is the value.

_x000D_
_x000D_
let arr = ['a', 'b', 'c'];_x000D_
let iterator = arr.entries();_x000D_
console.log(iterator.next().value); // [0, 'a']_x000D_
console.log(iterator.next().value); // [1, 'b']
_x000D_
_x000D_
_x000D_

A for..of loop is basically a construct which consumes an iterable and loops through all elements (using an iterator under the hood). We can combine this with array.entries() in the following manner:

_x000D_
_x000D_
array = ['a', 'b', 'c'];_x000D_
_x000D_
for (let indexValue of array.entries()) {_x000D_
  console.log(indexValue);_x000D_
}_x000D_
_x000D_
_x000D_
// we can use array destructuring to conveniently_x000D_
// store the index and value in variables_x000D_
for (let [index, value] of array.entries()) {_x000D_
   console.log(index, value);_x000D_
}
_x000D_
_x000D_
_x000D_

Android: show soft keyboard automatically when focus is on an EditText

try and use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

Python/Django: log to console under runserver, log to file under Apache

Text printed to stderr will show up in httpd's error log when running under mod_wsgi. You can either use print directly, or use logging instead.

print >>sys.stderr, 'Goodbye, cruel world!'

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

SQL Statement with multiple SETs and WHEREs

Use a query terminator string and set this in the options of your SQL client application. I use ; as the query terminator.

Your SQL would look like this;

UPDATE table SET ID = 111111259 WHERE ID = 2555;
UPDATE table SET ID = 111111261 WHERE ID = 2724;
UPDATE table SET ID = 111111263 WHERE ID = 2021;
UPDATE table SET ID = 111111264 WHERE ID = 2017;

This will allow you to do a Ctrl + A and run all the lines at once.

The string terminator tells the SQL client that the update statement is finished and to go to the next line and process the next statement.

Hope that helps

How can I convert uppercase letters to lowercase in Notepad++

I had to transfer texts from an Excel file to an xliff file. We had some texts that were originally in uppercase but those translators didn't use uppercase so I used notepad++ as intermediate to do the conversion.

Since I had the mouse in one hand (to mark in Excel and activate the different windows) I disliked the predefined shortcut (Ctrl+Shift+U) as "U" is too far away for my left hand. I first switched it to Ctrl+Shift+X which worked.

Then I realized, that you can create macros easily, so I recorded one doing:

  • mark all
  • paste from clipboard
  • convert to upppercase
  • copy to clipboard

That macro got assigned that very shortcut (Ctrl+Shift+X) and made my life easy :)

Finding square root without using sqrt function?

This a very simple recursive approach.

double mySqrt(double v, double test) {
    if (abs(test * test - v) < 0.0001) {
        return test;
    }

    double highOrLow = v / test;
    return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
    return mySqrt(v, v/2.0);
}

getApplication() vs. getApplicationContext()

Compare getApplication() and getApplicationContext().

getApplication returns an Application object which will allow you to manage your global application state and respond to some device situations such as onLowMemory() and onConfigurationChanged().

getApplicationContext returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.

I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.

useState set method not reflecting change immediately

Additional details to the previous answer:

While React's setState is asynchronous (both classes and hooks), and it's tempting to use that fact to explain the observed behavior, it is not the reason why it happens.

TLDR: The reason is a closure scope around an immutable const value.


Solutions:

  • read the value in render function (not inside nested functions):

      useEffect(() => { setMovies(result) }, [])
      console.log(movies)
    
  • add the variable into dependencies (and use the react-hooks/exhaustive-deps eslint rule):

      useEffect(() => { setMovies(result) }, [])
      useEffect(() => { console.log(movies) }, [movies])
    
  • use a mutable reference (when the above is not possible):

      const moviesRef = useRef(initialValue)
      useEffect(() => {
        moviesRef.current = result
        console.log(moviesRef.current)
      }, [])
    

Explanation why it happens:

If async was the only reason, it would be possible to await setState().

However, both props and state are assumed to be unchanging during 1 render.

Treat this.state as if it were immutable.

With hooks, this assumption is enhanced by using constant values with the const keyword:

const [state, setState] = useState('initial')

The value might be different between 2 renders, but remains a constant inside the render itself and inside any closures (functions that live longer even after render is finished, e.g. useEffect, event handlers, inside any Promise or setTimeout).

Consider following fake, but synchronous, React-like implementation:

_x000D_
_x000D_
// sync implementation:

let internalState
let renderAgain

const setState = (updateFn) => {
  internalState = updateFn(internalState)
  renderAgain()
}

const useState = (defaultState) => {
  if (!internalState) {
    internalState = defaultState
  }
  return [internalState, setState]
}

const render = (component, node) => {
  const {html, handleClick} = component()
  node.innerHTML = html
  renderAgain = () => render(component, node)
  return handleClick
}

// test:

const MyComponent = () => {
  const [x, setX] = useState(1)
  console.log('in render:', x) // ?
  
  const handleClick = () => {
    setX(current => current + 1)
    console.log('in handler/effect/Promise/setTimeout:', x) // ? NOT updated
  }
  
  return {
    html: `<button>${x}</button>`,
    handleClick
  }
}

const triggerClick = render(MyComponent, document.getElementById('root'))
triggerClick()
triggerClick()
triggerClick()
_x000D_
<div id="root"></div>
_x000D_
_x000D_
_x000D_

CSS content property: is it possible to insert HTML instead of Text?

Unfortunately, this is not possible. Per the spec:

Generated content does not alter the document tree. In particular, it is not fed back to the document language processor (e.g., for reparsing).

In other words, for string values this means the value is always treated literally. It is never interpreted as markup, regardless of the document language in use.

As an example, using the given CSS with the following HTML:

<h1 class="header">Title</h1>

... will result in the following output:

<a href="#top">Back</a>Title

Get Bitmap attached to ImageView

try this code:

Bitmap bitmap;
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

How to use graphics.h in codeblocks?

You don't only need the header file, you need the library that goes with it. Anyway, the include folder is not automatically loaded, you must configure your project to do so. Right-click on it : Build options > Search directories > Add. Choose your include folder, keep the path relative.

Edit For further assistance, please give details about the library you're trying to load (which provides a graphics.h file.)

Node Multer unexpected field

We have to make sure the type= file with name attribute should be same as the parameter name passed in upload.single('attr')

var multer  = require('multer');
var upload = multer({ dest: 'upload/'});
var fs = require('fs');

/** Permissible loading a single file, 
    the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('recfile');

app.post('/upload', type, function (req,res) {

  /** When using the "single"
      data come in "req.file" regardless of the attribute "name". **/
  var tmp_path = req.file.path;

  /** The original name of the uploaded file
      stored in the variable "originalname". **/
  var target_path = 'uploads/' + req.file.originalname;

  /** A better way to copy the uploaded file. **/
  var src = fs.createReadStream(tmp_path);
  var dest = fs.createWriteStream(target_path);
  src.pipe(dest);
  src.on('end', function() { res.render('complete'); });
  src.on('error', function(err) { res.render('error'); });

});

Could not reserve enough space for object heap to start JVM

I had the same problem when using a 32 bit version of java in a 64 bit environment. When using 64 java in a 64 OS it was ok.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

For port 80 (which was the original question), Daniel is exactly right. I recently moved to https and had to switch from iptables to a light nginx proxy managing the SSL certs. I found a useful answer along with a gist by gabrielhpugliese on how to handle that. Basically I

Hopefully that can save someone else some headaches. I'm sure there's a pure-node way of doing this, but nginx was quick and it worked.

SQL Server datetime LIKE select?

You can also use convert to make the date searchable using LIKE. For example,

select convert(VARCHAR(40),create_date,121) , * from sys.objects where     convert(VARCHAR(40),create_date,121) LIKE '%17:34%'

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

You want a parameter source:

Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     parameters, getRowMapper());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

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

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Check if a number has a decimal place/is a whole number

Number.isInteger(23);  // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false: 

Number.isInteger() is part of the ES6 standard and not supported in IE11.

It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.

How to get HttpClient returning status code and response body?

Don't provide the handler to execute.

Get the HttpResponse object, use the handler to get the body and get the status code from it directly

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

For quick single calls, the fluent API is useful:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

For older versions of java or httpcomponents, the code might look different.

When to Redis? When to MongoDB?

All of the answers (at the time of this writing) assume each of Redis, MongoDB, and perhaps an SQL-based relational database are essentially the same tool: "store data". They don't consider data models at all.

MongoDB: Complex Data

MongoDB is a document store. To compare with an SQL-driven relational database: relational databases simplify to indexed CSV files, each file being a table; document stores simplify to indexed JSON files, each file being a document, with multiple files grouped together.

JSON files are similar in structure to XML and YAML files, and to dictionaries as in Python, so think of your data in that sort of hierarchy. When indexing, the structure is the key: A document contains named keys, which contain either further documents, arrays, or scalar values. Consider the below document.

{
  _id:  0x194f38dc491a,
  Name:  "John Smith",
  PhoneNumber:
    Home: "555 999-1234",
    Work: "555 999-9876",
    Mobile: "555 634-5789"
  Accounts:
    - "379-1111"
    - "379-2574"
    - "414-6731"
}

The above document has a key, PhoneNumber.Mobile, which has value 555 634-5789. You can search through a collection of documents where the key, PhoneNumber.Mobile, has some value; they're indexed.

It also has an array of Accounts which hold multiple indexes. It is possible to query for a document where Accounts contains exactly some subset of values, all of some subset of values, or any of some subset of values. That means you can search for Accounts = ["379-1111", "379-2574"] and not find the above; you can search for Accounts includes ["379-1111"] and find the above document; and you can search for Accounts includes any of ["974-3785","414-6731"] and find the above and whatever document includes account "974-3785", if any.

Documents go as deep as you want. PhoneNumber.Mobile could hold an array, or even a sub-document (PhoneNumber.Mobile.Work and PhoneNumber.Mobile.Personal). If your data is highly structured, documents are a large step up from relational databases.

If your data is mostly flat, relational, and rigidly structured, you're better off with a relational database. Again, the big sign is whether your data models best to a collection of interrelated CSV files or a collection of XML/JSON/YAML files.

For most projects, you'll have to compromise, accepting a minor work-around in some small areas where either SQL or Document Stores don't fit; for some large, complex projects storing a broad spread of data (many columns; rows are irrelevant), it will make sense to store some data in one model and other data in another model. Facebook uses both SQL and a graph database (where data is put into nodes, and nodes are connected to other nodes); Craigslist used to use MySQL and MongoDB, but had been looking into moving entirely onto MongoDB. These are places where the span and relationship of the data faces significant handicaps if put under one model.

Redis: Key-Value

Redis is, most basically, a key-value store. Redis lets you give it a key and look up a single value. Redis itself can store strings, lists, hashes, and a few other things; however, it only looks up by name.

Cache invalidation is one of computer science's hard problems; the other is naming things. That means you'll use Redis when you want to avoid hundreds of excess look-ups to a back-end, but you'll have to figure out when you need a new look-up.

The most obvious case of invalidation is update on write: if you read user:Simon:lingots = NOTFOUND, you might SELECT Lingots FROM Store s INNER JOIN UserProfile u ON s.UserID = u.UserID WHERE u.Username = Simon and store the result, 100, as SET user:Simon:lingots = 100. Then when you award Simon 5 lingots, you read user:Simon:lingots = 100, SET user:Simon:lingots = 105, and UPDATE Store s INNER JOIN UserProfile u ON s.UserID = u.UserID SET s.Lingots = 105 WHERE u.Username = Simon. Now you have 105 in your database and in Redis, and can get user:Simon:lingots without querying the database.

The second case is updating dependent information. Let's say you generate chunks of a page and cache their output. The header shows the player's experience, level, and amount of money; the player's Profile page has a block that shows their statistics; and so forth. The player gains some experience. Well, now you have several templates:Header:Simon, templates:StatsBox:Simon, templates:GrowthGraph:Simon, and so forth fields where you've cached the output of a half-dozen database queries run through a template engine. Normally, when you display these pages, you say:

$t = GetStringFromRedis("templates:StatsBox:" + $playerName);
if ($t == null) {
  $t = BuildTemplate("StatsBox.tmpl",
                     GetStatsFromDatabase($playerName));
  SetStringInRedis("Templates:StatsBox:" + $playerName, $t);
}
print $t;

Because you just updated the results of GetStatsFromDatabase("Simon"), you have to drop templates:*:Simon out of your key-value cache. When you try to render any of these templates, your application will churn away fetching data from your database (PostgreSQL, MongoDB) and inserting it into your template; then it will store the result in Redis and, hopefully, not bother making database queries and rendering templates the next time it displays that block of output.

Redis also lets you do publisher-subscribe message queues and such. That's another topic entirely. Point here is Redis is a key-value cache, which differs from a relational database or a document store.

Conclusion

Pick your tools based on your needs. The largest need is usually data model, as that determines how complex and error-prone your code is. Specialized applications will lean on performance, places where you write everything in a mixture of C and Assembly; most applications will just handle the generalized case and use a caching system such as Redis or Memcached, which is a lot faster than either a high-performance SQL database or a document store.

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

What's the Use of '\r' escape sequence?

To answer the part of your question,

what is the use of \r?

Many Internet protocols, such as FTP, HTTP and SMTP, are specified in terms of lines delimited by carriage return and newline. So, for example, when sending an email, you might have code such as:

fprintf(socket, "RCPT TO: %s\r\n", recipients);

Or, when a FTP server replies with a permission-denied error:

fprintf(client, "550 Permission denied\r\n");

Using CSS to insert text

Also check out the attr() function of the CSS content attribute. It outputs a given attribute of the element as a text node. Use it like so:

<div class="Owner Joe" />

div:before {
  content: attr(class);
}

Or even with the new HTML5 custom data attributes:

<div data-employeename="Owner Joe" />

div:before {
  content: attr(data-employeename);
}

recursion versus iteration

Most of the answers seem to assume that iterative = for loop. If your for loop is unrestricted (a la C, you can do whatever you want with your loop counter), then that is correct. If it's a real for loop (say as in Python or most functional languages where you cannot manually modify the loop counter), then it is not correct.

All (computable) functions can be implemented both recursively and using while loops (or conditional jumps, which are basically the same thing). If you truly restrict yourself to for loops, you will only get a subset of those functions (the primitive recursive ones, if your elementary operations are reasonable). Granted, it's a pretty large subset which happens to contain every single function you're likely to encouter in practice.

What is much more important is that a lot of functions are very easy to implement recursively and awfully hard to implement iteratively (manually managing your call stack does not count).

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I was facing the same error while running command

pip install --upgrade pip

in a virtual venvironment (created with python -m venv venv).

using the --user flag fixed the problem for me

pip install --upgrade pip --user

If the problem not resolved use --user flag in a command prompt with admin rights.

Removing "http://" from a string

$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0); 

This would remove everything before the '//'.

EDIT

This one is tested. Using strrpos() instead or strpos().

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

DateTime fields from SQL Server display incorrectly in Excel

Although not a complete answer to your question, there are shortcut keys in Excel to change the formatting of the selected cell(s) to either Date or Time (unfortunately, I haven't found one for Date+Time).

So, if you're just looking for dates, you can perform the following:

  1. Copy range from SQL Server Management Studio
  2. Paste into Excel
  3. Select the range of cells that you need formatted as Dates
  4. Press Ctrl+Shift+3

For formatting as Times, use Ctrl+Shift+2.

You can use this in SQL SERVER

SELECT CONVERT(nvarchar(19),ColumnName,121) AS [Changed On] FROM Table

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
    var model = await response.Content.ReadAsAsync<List<Job>>();

How to Convert datetime value to yyyymmddhhmmss in SQL server?

also this works too

SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')

Add Favicon with React and Webpack

This worked for me:

Add this in index.html (inside src folder along with favicon.ico)

**<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**

webpack.config.js is like:

 plugins: [new HtmlWebpackPlugin({`enter code here`
        template: './src/index.html'
    })],

Oracle SQL - select within a select (on the same table!)

Basically, all you have to do is

select ..., (select ... from ... where ...) as ..., ..., from ... where ...

For exemple. You can insert the (select ... from ... where) wherever you want it will be replaced by the corresponding data.

I know that the others exemple (even if each of them are really great :) ) are a bit complicated to understand for the newbies (like me :p) so i hope this "simple" exemple will help some of you guys :)

Changing Placeholder Text Color with Swift

Xcode 9.2 Swift 4

extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}

How to solve SyntaxError on autogenerated manage.py?

For future readers, I too had the same issue. Turns out installing Python directly from website as well as having another version from Anaconda caused this issue. I had to uninstall Python2.7 and only keep anaconda as the sole distribution.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I have 2 targets in my project, Free and Paid. My mistake was i was looking at my free target while trying to build the paid target, a stupid mistake but possible someone out there might learn from this as well.

The static keyword and its various uses in C++

Static Object: We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member.

A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present. We can't put it in the class definition but it can be initialized outside the class as done in the following example by redeclaring the static variable, using the scope resolution operator :: to identify which class it belongs to.

Let us try the following example to understand the concept of static data members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{
   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects.
   cout << "Total objects: " << Box::objectCount << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Constructor called.
Constructor called.
Total objects: 2

Static Function Members: By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::.

A static member function can only access static data member, other static member functions and any other functions from outside the class.

Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not.

Let us try the following example to understand the concept of static function members:

#include <iostream>

using namespace std;

class Box
{
   public:
      static int objectCount;
      // Constructor definition
      Box(double l=2.0, double b=2.0, double h=2.0)
      {
         cout <<"Constructor called." << endl;
         length = l;
         breadth = b;
         height = h;
         // Increase every time object is created
         objectCount++;
      }
      double Volume()
      {
         return length * breadth * height;
      }
      static int getCount()
      {
         return objectCount;
      }
   private:
      double length;     // Length of a box
      double breadth;    // Breadth of a box
      double height;     // Height of a box
};

// Initialize static member of class Box
int Box::objectCount = 0;

int main(void)
{

   // Print total number of objects before creating object.
   cout << "Inital Stage Count: " << Box::getCount() << endl;

   Box Box1(3.3, 1.2, 1.5);    // Declare box1
   Box Box2(8.5, 6.0, 2.0);    // Declare box2

   // Print total number of objects after creating object.
   cout << "Final Stage Count: " << Box::getCount() << endl;

   return 0;
}

When the above code is compiled and executed, it produces the following result:

Inital Stage Count: 0
Constructor called.
Constructor called.
Final Stage Count: 2

Convert ASCII TO UTF-8 Encoding

If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.

But if you still want to convert, just to be sure that its UTF-8, then you can use iconv

$string = iconv('ASCII', 'UTF-8//IGNORE', $string);

The IGNORE will discard any invalid characters just in case some were not valid ASCII.

What is the purpose of the return statement?

return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.

print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.

The following code shows how to use return and print properly:

def fact(x):
    if x < 2:
        return 1
    return x * fact(x - 1)

print(fact(5))

This explanation is true for all of the programming languages not just python.

Firebase FCM notifications click_action payload

You can handle all your actions in function of your message in onMessageReceived() in your service extending FirebaseMessagingService. In order to do that, you must send a message containing exclusively data, using for example Advanced REST client in Chrome. Then you send a POST to https://fcm.googleapis.com/fcm/send using in "Raw headers":

Content-Type: application/json Authorization: key=YOUR_PERSONAL_FIREBASE_WEB_API_KEY

And a json message in the field "Raw payload".

Warning, if there is the field "notification" in your json, your message will never be received when app in background in onMessageReceived(), even if there is a data field ! For example, doing that, message work just if app in foreground:

{
    "condition": " 'Symulti' in topics || 'SymultiLite' in topics",
    "priority" : "normal",
    "time_to_live" : 0,
    "notification" : {
        "body" : "new Symulti update !",
        "title" : "new Symulti update !",
        "icon" : "ic_notif_symulti"
    },
    "data" : {
        "id" : 1,
        "text" : "new Symulti update !"
    }
}

In order to receive your message in all cases in onMessageReceived(), simply remove the "notification" field from your json !

Example:

{
    "condition": " 'Symulti' in topics || 'SymultiLite' in topics",
    "priority" : "normal",
    "time_to_live" : 0,,
    "data" : {
        "id" : 1,
        "text" : "new Symulti update !",
        "link" : "href://www.symulti.com"
    }
}

and in your FirebaseMessagingService :

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      String message = "";
      obj = remoteMessage.getData().get("text");
      if (obj != null) {
        try {
          message = obj.toString();
        } catch (Exception e) {
          message = "";
          e.printStackTrace();
        }
      }

      String link = "";
      obj = remoteMessage.getData().get("link");
      if (obj != null) {
        try {
          link = (String) obj;
        } catch (Exception e) {
          link = "";
          e.printStackTrace();
        }
      }

      Intent intent;
      PendingIntent pendingIntent;
      if (link.equals("")) { // Simply run your activity
        intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      } else { // open a link
        String url = "";
        if (!link.equals("")) {
          intent = new Intent(Intent.ACTION_VIEW);
          intent.setData(Uri.parse(link));
          intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        }
      }
      pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
          PendingIntent.FLAG_ONE_SHOT);


      NotificationCompat.Builder notificationBuilder = null;

      try {
        notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_notif_symulti)          // don't need to pass icon with your message if it's already in your app !
            .setContentTitle(URLDecoder.decode(getString(R.string.app_name), "UTF-8"))
            .setContentText(URLDecoder.decode(message, "UTF-8"))
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .setContentIntent(pendingIntent);
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }

        if (notificationBuilder != null) {
          NotificationManager notificationManager =
              (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
          notificationManager.notify(id, notificationBuilder.build());
        } else {
          Log.d(TAG, "error NotificationManager");
        }
      }
    }
}

Enjoy !

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

PHP Fatal error: Class 'PDO' not found

Ensure they are being called in the php.ini file

If the PDO is displayed in the list of currently installed php modules, you will want to check the php.ini file in the relevant folder to ensure they are being called. Somewhere in the php.ini file you should see the following:

extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so

If they are not present, simply add the lines above to the bottom of the php.ini file and save it.

Best way to "negate" an instanceof

ok just my two cents, use a is string method:

public static boolean isString(Object thing) {
    return thing instanceof String;
}

public void someMethod(Object thing){
    if (!isString(thing)) {
        return null;
    }
    log.debug("my thing is valid");
}

How do I get the APK of an installed app without root access?

Accessing /data/app is possible without root permission; the permissions on that directory are rwxrwx--x. Execute permission on a directory means you can access it, however lack of read permission means you cannot obtain a listing of its contents -- so in order to access it you must know the name of the file that you will be accessing. Android's package manager will tell you the name of the stored apk for a given package.

To do this from the command line, use adb shell pm list packages to get the list of installed packages and find the desired package.

With the package name, we can get the actual file name and location of the APK using adb shell pm path your-package-name.

And knowing the full directory, we can finally pull the adb using adb pull full/directory/of/the.apk

Credit to @tarn for pointing out that under Lollipop, the apk path will be /data/app/your-package-name-1/base.apk

What does localhost:8080 mean?

A TCP/IP connection is always made to an IP address (you can think of an IP-address as the address of a certain computer, even if that is not always the case) and a specific (logical, not physical) port on that address.

Usually one port is coupled to a specific process or "service" on the target computer. Some port numbers are standardized, like 80 for http, 25 for smtp and so on. Because of that standardization you usually don't need to put port numbers into your web adresses.

So if you say something like http://www.stackoverflow.com, the part "stackoverflow.com" resolves to an IP address (in my case 64.34.119.12) and because my browser knows the standard it tries to connect to port 80 on that address. Thus this is the same as http://www.stackoverflow.com:80.

But there is nothing that stops a process to listen for http requests on another port, like 12434, 4711 or 8080. Usually (as in your case) this is used for debugging purposes to not intermingle with another process (like IIS) already listening to port 80 on the same machine.

Why in C++ do we use DWORD rather than unsigned int?

SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

See the image for reference :- (Soruce :- Android Studio-Image Assets option and Android Office Site )

enter image description here

How to disable editing of elements in combobox for c#?

This is another method I use because changing DropDownSyle to DropDownList makes it look 3D and sometimes its just plain ugly.

You can prevent user input by handling the KeyPress event of the ComboBox like this.

private void ComboBox1_KeyPress(object sender, KeyPressEventArgs e)
{
      e.Handled = true;
}

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.

Reporting Services Remove Time from DateTime in Expression

If expected data format is MM-dd-yyyy then try below,

=CDate(Now).ToString("MM-dd-yyyy")

Similarly you can try this one,

=Format(Today(),"MM-dd-yyyy") 

Output: 02-04-2016

Note:
Now() will show you current date and time stamp

Today() will show you Date only not time part.

Also you can set any date format instead of MM-dd-yyyy in my example.

How do I escape ampersands in batch files?

From a cmd:

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % does not need to be escaped

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%20and%20percentage+in+cmd^&sourceid=opera^&ie=utf-8^&oe=utf-8

From a batch file

  • & is escaped like this: ^& (based on @Wael Dalloul's answer)
  • % is escaped like this: %% (based on the OPs update)

An example:

start http://www.google.com/search?client=opera^&rls=en^&q=escape+ampersand%%20and%%20percentage+in+batch+file^&sourceid=opera^&ie=utf-8^&oe=utf-8

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

The answer to many CSS formatting problems seems to be "add another <div>!"

So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

_x000D_
_x000D_
textarea_x000D_
{_x000D_
  width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
  border:1px solid #999999;_x000D_
  margin:5px 0;_x000D_
  padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
  <label for="rules" id="ruleslabel">Rules:</label>_x000D_
  <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

dictionary update sequence element #0 has length 3; 2 is required

This error raised up because you trying to update dict object by using a wrong sequence (list or tuple) structure.

cash_id.create(cr, uid, lines,context=None) trying to convert lines into dict object:

(0, 0, {
    'name': l.name,
    'date': l.date,
    'amount': l.amount,
    'type': l.type,
    'statement_id': exp.statement_id.id,
    'account_id': l.account_id.id,
    'account_analytic_id': l.analytic_account_id.id,
    'ref': l.ref,
    'note': l.note,
    'company_id': l.company_id.id
})

Remove the second zero from this tuple to properly convert it into a dict object.

To test it your self, try this into python shell:

>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required

>>> l=[(0,{'h':88})]
>>> a.update(l)

How do I shrink my SQL Server Database?

Late answer but might be useful useful for someone else

If neither DBCC ShrinkDatabase/ShrinkFile or SSMS (Tasks/Shrink/Database) doesn’t help, there are tools from Quest and ApexSQL that can get the job done, and even schedule periodic shrinking if you need it.

I’ve used the latter one in free trial to do this some time ago, by following short description at the end of this article:

https://solutioncenter.apexsql.com/sql-server-database-shrink-how-and-when-to-schedule-and-perform-shrinking-of-database-files/

All you need to do is install ApexSQL Backup, click "Shrink database" button in the main ribbon, select database in the window that will pop-up, and click "Finish".

Read input from console in Ruby?

There are many ways to take input from the users. I personally like using the method gets. When you use gets, it gets the string that you typed, and that includes the ENTER key that you pressed to end your input.

name = gets
"mukesh\n"

You can see this in irb; type this and you will see the \n, which is the “newline” character that the ENTER key produces: Type name = gets you will see somethings like "mukesh\n" You can get rid of pesky newline character using chomp method.

The chomp method gives you back the string, but without the terminating newline. Beautiful chomp method life saviour.

name = gets.chomp
"mukesh"

You can also use terminal to read the input. ARGV is a constant defined in the Object class. It is an instance of the Array class and has access to all the array methods. Since it’s an array, even though it’s a constant, its elements can be modified and cleared with no trouble. By default, Ruby captures all the command line arguments passed to a Ruby program (split by spaces) when the command-line binary is invoked and stores them as strings in the ARGV array.

When written inside your Ruby program, ARGV will take take a command line command that looks like this:

test.rb hi my name is mukesh

and create an array that looks like this:

["hi", "my", "name", "is", "mukesh"]

But, if I want to passed limited input then we can use something like this.

test.rb 12 23

and use those input like this in your program:

a = ARGV[0]
b = ARGV[1]

Using jQuery to compare two arrays of Javascript objects

Change array to string and compare

var arr = [1,2,3], 
arr2 = [1,2,3]; 
console.log(arr.toString() === arr2.toString());

How do I format a number with commas in T-SQL?

In SQL Server 2012 and higher, this will format a number with commas:

select format([Number], 'N0')

You can also change 0 to the number of decimal places you want.

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How to disable HTML button using JavaScript?

If you have the button object, called b: b.disabled=false;

'"SDL.h" no such file or directory found' when compiling

If the header file is /usr/include/sdl/SDL.h and your code has:

#include "SDL.h"

You need to either fix your code:

#include "sdl/SDL.h"

Or tell the preprocessor where to find include files:

CFLAGS = ... -I/usr/include/sdl ...

Fixed header, footer with scrollable content

Now we've got CSS grid. Welcome to 2019.

_x000D_
_x000D_
/* Required */_x000D_
body {_x000D_
   margin: 0;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
   height: 100vh;_x000D_
   display: grid;_x000D_
   grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
   padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
   background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
   background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
   <div id="wrapper">_x000D_
      <div id="header">Header Content</div>_x000D_
      <div id="content">_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </div>_x000D_
      <div id="footer">Footer Content</div>_x000D_
   </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Can I dispatch an action in reducer?

Dispatching and action inside of reducer seems occurs bug.

I made a simple counter example using useReducer which "INCREASE" is dispatched then "SUB" also does.

In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt to -1 and then continue "INCREASE" action to set cnt to 0, but it was -1 ("INCREASE" was ignored)

See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154

let listener = () => {
  console.log("test");
};
const middleware = (action) => {
  console.log(action);
  if (action.type === "INCREASE") {
    listener();
  }
};

const counterReducer = (state, action) => {
  middleware(action);
  switch (action.type) {
    case "INCREASE":
      return {
        ...state,
        cnt: state.cnt + action.payload
      };
    case "SUB":
      return {
        ...state,
        cnt: state.cnt - action.payload
      };
    default:
      return state;
  }
};

const Test = () => {
  const { cnt, increase, substract } = useContext(CounterContext);

  useEffect(() => {
    listener = substract;
  });

  return (
    <button
      onClick={() => {
        increase();
      }}
    >
      {cnt}
    </button>
  );
};

{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1

When use ResponseEntity<T> and @RestController for Spring RESTful applications

To complete the answer from Sotorios Delimanolis.

It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

Tomcat is not deploying my web project from Eclipse

In my case, I configured an external Maven installation, and I made sure to be using a JDK instead of a JRE (in the eclipse configuration, and in the Server Environment). You can run a Maven Build of the project from eclipse to check everything is working ok.

After that, I updated the maven projects, cleaned and built the projects, cleaned the server, and redeployed the artifacts.

jquery : focus to div is not working

a <div> can be focused if it has a tabindex attribute. (the value can be set to -1)

For example:

$("#focus_point").attr("tabindex",-1).focus();

In addition, consider setting outline: none !important; so it displayed without a focus rectangle.

var element = $("#focus_point");
element.css('outline', 'none !important')
       .attr("tabindex", -1)
       .focus();

How to generate a random number in C++?

for random every RUN file

size_t randomGenerator(size_t min, size_t max) {
    std::mt19937 rng;
    rng.seed(std::random_device()());
    //rng.seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
    std::uniform_int_distribution<std::mt19937::result_type> dist(min, max);

    return dist(rng);
}

File to byte[] in Java

As someone said, Apache Commons File Utils might have what you are looking for

public static byte[] readFileToByteArray(File file) throws IOException

Example use (Program.java):

import org.apache.commons.io.FileUtils;
public class Program {
    public static void main(String[] args) throws IOException {
        File file = new File(args[0]);  // assume args[0] is the path to file
        byte[] data = FileUtils.readFileToByteArray(file);
        ...
    }
}

Error 1046 No database Selected, how to resolve?

I faced the same error when I tried to import a database created from before. Here is what I did to fix this issue:

1- Create new database

2- Use it by use command

enter image description here

3- Try again

This works for me.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

YouTube embedded video: set different thumbnail

No. Most YouTube videos only have one pre-generated "poster" thumbnail (480x360). They usually have several other lower resolution thumbnails (120x90). So even if there were an embedding parameter to use an alternate poster image (which there isn't), it's result wouldn't be acceptable.

You can theoretically use the Player API to seek the video to whatever location you want, but this would be a major hack for a minor result.

how to write procedure to insert data in to the table in phpmyadmin?

This method work for me:

DELIMITER $$
DROP PROCEDURE IF EXISTS db.test $$
CREATE PROCEDURE db.test(IN id INT(12),IN NAME VARCHAR(255))
 BEGIN
 INSERT INTO USER VALUES(id,NAME);
 END$$
DELIMITER ;

Creating a LINQ select from multiple tables

You must create a new anonymous type:

 select new { op, pg }

Refer to the official guide.

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

WARNING: This will delete untracked files, so it's not a great answer to this question.

In my case, I didn't want to keep the files, so this worked for me:

Git 2.11 and newer:

git clean  -d  -fx .

Older Git:

git clean  -d  -fx ""

Reference: http://www.kernel.org/pub/software/scm/git/docs/git-clean.html

  • -x means ignored files are also removed as well as files unknown to git.

  • -d means remove untracked directories in addition to untracked files.

  • -f is required to force it to run.

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Adobe Reader Command Line Reference

I found this:

http://www.robvanderwoude.com/commandlineswitches.php#Acrobat

Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":

AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile

How do I make a batch file terminate upon encountering an error?

One minor update, you should change the checks for "if errorlevel 1" to the following...

IF %ERRORLEVEL% NEQ 0 

This is because on XP you can get negative numbers as errors. 0 = no problems, anything else is a problem.

And keep in mind the way that DOS handles the "IF ERRORLEVEL" tests. It will return true if the number you are checking for is that number or higher so if you are looking for specific error numbers you need to start with 255 and work down.

Select single item from a list

There are two easy ways, depending on if you want to deal with exceptions or get a default value.

You can use the First<T>() or the FirstOrDefault<T>() extension method to get the first result or default(T).

var list = new List<int> { 1, 2, 4 };
var result = list.Where(i => i == 3).First(); // throws InvalidOperationException
var result = list.Where(i => i == 3).FirstOrDefault(); // = 0

resize font to fit in a div (on one line)

I wasn't in love with the other solutions out there, so, here's another one. It requires the tag you're resizing the text inside of:

  1. Be fixed height

  2. Not be so long that it'd overrun the boundaries at 10px - the idea being, you don't want it to shoot below that and resize text to become unreadable. Not an issue in our use case, but if it's possible in yours you'd want to give some thoughts to separately truncating before running this.

It uses a binary search to find the best size so I suspect it outperforms a lot of the other solutions here and elsewhere that just step the font-size down by a pixel over and over. Most browsers today support decimals in font sizes as well, and this script has some benefits there since it will get to within .1px of the best answer, whatever that is, even if it's a relatively long decimal. You could easily change the max - fontSize < .1 to some other value than .1 to get less precision for less CPU usage.

Usage:

$('div.event').fitText();

Code:

(function() {
    function resizeLoop(testTag, checkSize) {
        var fontSize = 10;
        var min = 10;
        var max = 0;
        var exceeded = false;

        for(var i = 0; i < 30; i++) {
            testTag.css('font-size', fontSize);
            if (checkSize(testTag)) {
                max = fontSize;
                fontSize = (fontSize + min) / 2;
            } else {
                if (max == 0) {
                    // Start by growing exponentially
                    min = fontSize;
                    fontSize *= 2;
                } else {
                    // If we're within .1px of max anyway, call it a day
                    if (max - fontSize < .1)
                        break;

                    // If we've seen a max, move half way to it
                    min = fontSize;
                    fontSize = (fontSize + max) / 2;
                }
            }
        }

        return fontSize;
    }

    function sizeText(tag) {
        var width = tag.width();
        var height = tag.height();

        // Clone original tag and append to the same place so we keep its original styles, especially font
        var testTag = tag.clone(true)
        .appendTo(tag.parent())
        .css({
            position: 'absolute',
            left: 0, top: 0,
            width: 'auto', height: 'auto'
        });

        var fontSize;

        // TODO: This decision of 10 characters is arbitrary. Come up
        // with a smarter decision basis.
        if (tag.text().length < 10) {
            fontSize = resizeLoop(testTag, function(t) {
                return t.width() > width || t.height() > height;
            });
        } else {
            testTag.css('width', width);
            fontSize = resizeLoop(testTag, function(t) {
                return t.height() > height;
            });
        }

        testTag.remove();
        tag.css('font-size', fontSize);
    };

    $.fn.fitText = function() {
        this.each(function(i, tag) {
            sizeText($(tag));
        });
    };
})();

http://jsfiddle.net/b9chris/et6N6/1/

Is the LIKE operator case-sensitive with MSSQL Server?

All this talk about collation seem a bit over-complicated. Why not just use something like:

IF UPPER(@@VERSION) NOT LIKE '%AZURE%'

Then your check is case insensitive whatever the collation

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

Vue template or render function not defined yet I am using neither?

Make sure you import the .vue extension explicitly like so:

import myComponent from './my/component/my-component.vue';

If you don't add the .vue and you have a .ts file with the same name in that directory, for example, if you're separating the js/ts from the template and linking it like this inside of my-component.vue:

<script lang="ts" src="./my-component.ts"></script>

... then the import will bring in the .ts by default and so there really is no template or render function defined because it didn't import the .vue template.

When you tell it to use .vue in the import, then it finds your template right away.

How to remove element from array in forEach loop?

It looks like you are trying to do this?

Iterate and mutate an array using Array.prototype.splice

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'b', 'c', 'b', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Which works fine for simple case where you do not have 2 of the same values as adjacent array items, other wise you have this problem.

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.forEach(function(item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

So what can we do about this problem when iterating and mutating an array? Well the usual solution is to work in reverse. Using ES3 while but you could use for sugar if preferred

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a' ,'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.length - 1;

while (index >= 0) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }

  index -= 1;
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Ok, but you wanted to use ES5 iteration methods. Well and option would be to use Array.prototype.filter but this does not mutate the original array but creates a new one, so while you can get the correct answer it is not what you appear to have specified.

We could also use ES5 Array.prototype.reduceRight, not for its reducing property by rather its iteration property, i.e. iterate in reverse.

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.reduceRight(function(acc, item, index, object) {
  if (item === 'a') {
    object.splice(index, 1);
  }
}, []);

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Or we could use ES5 Array.protoype.indexOf like so.

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'],
  index = review.indexOf('a');

while (index !== -1) {
  review.splice(index, 1);
  index = review.indexOf('a');
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

But you specifically want to use ES5 Array.prototype.forEach, so what can we do? Well we need to use Array.prototype.slice to make a shallow copy of the array and Array.prototype.reverse so we can work in reverse to mutate the original array.

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

review.slice().reverse().forEach(function(item, index, object) {
  if (item === 'a') {
    review.splice(object.length - 1 - index, 1);
  }
});

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Finally ES6 offers us some further alternatives, where we do not need to make shallow copies and reverse them. Notably we can use Generators and Iterators. However support is fairly low at present.

_x000D_
_x000D_
var pre = document.getElementById('out');

function log(result) {
  pre.appendChild(document.createTextNode(result + '\n'));
}

function* reverseKeys(arr) {
  var key = arr.length - 1;

  while (key >= 0) {
    yield key;
    key -= 1;
  }
}

var review = ['a', 'a', 'b', 'c', 'b', 'a', 'a'];

for (var index of reverseKeys(review)) {
  if (review[index] === 'a') {
    review.splice(index, 1);
  }
}

log(review);
_x000D_
<pre id="out"></pre>
_x000D_
_x000D_
_x000D_

Something to note in all of the above is that, if you were stripping NaN from the array then comparing with equals is not going to work because in Javascript NaN === NaN is false. But we are going to ignore that in the solutions as it it yet another unspecified edge case.

So there we have it, a more complete answer with solutions that still have edge cases. The very first code example is still correct but as stated, it is not without issues.

Using Helvetica Neue in a Website

They are taking a 'shotgun' approach to referencing the font. The browser will attempt to match each font name with any installed fonts on the user's machine (in the order they have been listed).

In your example "HelveticaNeue-Light" will be tried first, if this font variant is unavailable the browser will try "Helvetica Neue Light" and finally "Helvetica Neue".

As far as I'm aware "Helvetica Neue" isn't considered a 'web safe font', which means you won't be able to rely on it being installed for your entire user base. It is quite common to define "serif" or "sans-serif" as a final default position.

In order to use fonts which aren't 'web safe' you'll need to use a technique known as font embedding. Embedded fonts do not need to be installed on a user's computer, instead they are downloaded as part of the page. Be aware this increases the overall payload (just like an image does) and can have an impact on page load times.

A great resource for free fonts with open-source licenses is Google Fonts. (You should still check individual licenses before using them.) Each font has a download link with instructions on how to embed them in your website.

Debugging the error "gcc: error: x86_64-linux-gnu-gcc: No such file or directory"

sudo apt-get -y install python-software-properties && \
sudo apt-get -y install software-properties-common && \
sudo apt-get -y install gcc make build-essential libssl-dev libffi-dev python-dev

You need the libssl-dev and libffi-dev if especially you are trying to install python's cryptography libraries or python libs that depend on it(eg ansible)

How to read a large file line by line?

From the python documentation for fileinput.input():

This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty

further, the definition of the function is:

fileinput.FileInput([files[, inplace[, backup[, mode[, openhook]]]]])

reading between the lines, this tells me that files can be a list so you could have something like:

for each_line in fileinput.input([input_file, input_file]):
  do_something(each_line)

See here for more information

How to submit a form when the return key is pressed?

Using the "autofocus" attribute works to give input focus to the button by default. In fact clicking on any control within the form also gives focus to the form, a requirement for the form to react to the RETURN. So, the "autofocus" does that for you in case the user never clicked on any other control within the form.

So, the "autofocus" makes the crucial difference if the user never clicked on any of the form controls before hitting RETURN.

But even then, there are still 2 conditions to be met for this to work without JS:

a) you have to specify a page to go to (if left empty it wont work). In my example it is hello.php

b) the control has to be visible. You could conceivably move it off the page to hide, but you cannot use display:none or visibility:hidden. What I did, was to use inline style to just move it off the page to the left by 200px. I made the height 0px so that it does not take up space. Because otherwise it can still disrupt other controls above and below. Or you could float the element too.

<form action="hello.php" method="get">
  Name: <input type="text" name="name"/><br/>
  Pwd: <input type="password" name="password"/><br/>
  <div class="yourCustomDiv"/>
  <input autofocus type="submit" style="position:relative; left:-200px; height:0px;" />
</form>

Copy data into another table

Insert Selected column with condition

INSERT INTO where_to_insert (col_1,col_2) SELECT col1, col2 FROM from_table WHERE condition;

Copy all data from one table to another with the same column name.

INSERT INTO where_to_insert 
SELECT * FROM from_table WHERE condition;

how to add key value pair in the JSON object already declared

Object assign copies one or more source objects to the target object. So we could use Object.assign here.

Syntax: Object.assign(target, ...sources)

_x000D_
_x000D_
var obj  = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

AngularJS - Create a directive that uses ng-model

I wouldn't set the ngmodel via an attribute, you can specify it right in the template:

template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',

plunker: http://plnkr.co/edit/9vtmnw?p=preview

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

Get list of Excel files in a folder using VBA

Ok well this might work for you, a function that takes a path and returns an array of file names in the folder. You could use an if statement to get just the excel files when looping through the array.

Function listfiles(ByVal sPath As String)

    Dim vaArray     As Variant
    Dim i           As Integer
    Dim oFile       As Object
    Dim oFSO        As Object
    Dim oFolder     As Object
    Dim oFiles      As Object

    Set oFSO = CreateObject("Scripting.FileSystemObject")
    Set oFolder = oFSO.GetFolder(sPath)
    Set oFiles = oFolder.Files

    If oFiles.Count = 0 Then Exit Function

    ReDim vaArray(1 To oFiles.Count)
    i = 1
    For Each oFile In oFiles
        vaArray(i) = oFile.Name
        i = i + 1
    Next

    listfiles = vaArray

End Function

It would be nice if we could just access the files in the files object by index number but that seems to be broken in VBA for whatever reason (bug?).

Convert seconds to Hour:Minute:Second

The following codes can display total hours plus minutes and seconds accurately

$duration_in_seconds = 86401;
if($duration_in_seconds>0)
{
    echo floor($duration_in_seconds/3600).gmdate(":i:s", $duration_in_seconds%3600);
}
else
{
    echo "00:00:00";
}

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

How do I access (read, write) Google Sheets spreadsheets with Python?

The latest google api docs document how to write to a spreadsheet with python but it's a little difficult to navigate to. Here is a link to an example of how to append.

The following code is my first successful attempt at appending to a google spreadsheet.

import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'


def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'mail_to_g_app.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def add_todo():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = 'PUT YOUR SPREADSHEET ID HERE'
    rangeName = 'A1:A'

    # https://developers.google.com/sheets/guides/values#appending_values
    values = {'values':[['Hello Saturn',],]}
    result = service.spreadsheets().values().append(
        spreadsheetId=spreadsheetId, range=rangeName,
        valueInputOption='RAW',
        body=values).execute()

if __name__ == '__main__':
    add_todo()

Replace all whitespace with a line break/paragraph mark to make a word list

All of the examples listed above for sed break on one platform or another. None of them work with the version of sed shipped on Macs.

However, Perl's regex works the same on any machine with Perl installed:

perl -pe 's/\s+/\n/g' file.txt

If you want to save the output:

perl -pe 's/\s+/\n/g' file.txt > newfile.txt

If you want only unique occurrences of words:

perl -pe 's/\s+/\n/g' file.txt | sort -u > newfile.txt

textarea's rows, and cols attribute in CSS

<textarea rows="4" cols="50"></textarea>

It is equivalent to:

textarea {
    height: 4em;
    width: 50em;
}

where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.

What does "javascript:void(0)" mean?

In addition to the technical answer, javascript:void means the author is Doing It Wrong.

There is no good reason to use a javascript: pseudo-URL(*). In practice it will cause confusion or errors should anyone try things like ‘bookmark link’, ‘open link in a new tab’, and so on. This happens quite a lot now people have got used to middle-click-for-new-tab: it looks like a link, you want to read it in a new tab, but it turns out to be not a real link at all, and gives unwanted results like a blank page or a JS error when middle-clicked.

<a href="#"> is a common alternative which might arguably be less bad. However you must remember to return false from your onclick event handler to prevent the link being followed and scrolling up to the top of the page.

In some cases there may be an actual useful place to point the link to. For example if you have a control you can click on that opens up a previously-hidden <div id="foo">, it makes some sense to use <a href="#foo"> to link to it. Or if there is a non-JavaScript way of doing the same thing (for example, ‘thispage.php?show=foo’ that sets foo visible to begin with), you can link to that.

Otherwise, if a link points only to some script, it is not really a link and should not be marked up as such. The usual approach would be to add the onclick to a <span>, <div>, or an <a> without an href and style it in some way to make it clear you can click on it. This is what StackOverflow [did at the time of writing; now it uses href="#"].

The disadvantage of this is that you lose keyboard control, since you can't tab onto a span/div/bare-a or activate it with space. Whether this is actually a disadvantage depends on what sort of action the element is intended to take. You can, with some effort, attempt to mimic the keyboard interactability by adding a tabIndex to the element, and listening for a Space keypress. But it's never going to 100% reproduce the real browser behaviour, not least because different browsers can respond to the keyboard differently (not to mention non-visual browsers).

If you really want an element that isn't a link but which can be activated as normal by mouse or keyboard, what you want is a <button type="button"> (or <input type="button"> is just as good, for simple textual contents). You can always use CSS to restyle it so it looks more like a link than a button, if you want. But since it behaves like a button, that's how really you should mark it up.

(*: in site authoring, anyway. Obviously they are useful for bookmarklets. javascript: pseudo-URLs are a conceptual bizarreness: a locator that doesn't point to a location, but instead calls active code inside the current location. They have caused massive security problems for both browsers and webapps, and should never have been invented by Netscape.)

Print specific part of webpage

Just use CSS to hide the content you do not want printed. When the user selects print - the page will look to the " media="print" CSS for instructions about the layout of the page.

The media="print" CSS has instructions to hide the content that we do not want printed.

<!-- CSS for the things we want to print (print view) -->
<style type="text/css" media="print">

#SCREEN_VIEW_CONTAINER{
        display: none;
    }
.other_print_layout{
        background-color:#FFF;
    }
</style>

<!-- CSS for the things we DO NOT want to print (web view) -->
<style type="text/css" media="screen">

   #PRINT_VIEW{
      display: none;
   }
.other_web_layout{
        background-color:#E0E0E0;
    }
</style>

<div id="SCREEN_VIEW_CONTAINER">
     the stuff I DO NOT want printed is here and will be hidden - 
     and not printed when the user selects print.
</div>

<div id="PRINT_VIEW">
     the stuff I DO want printed is here.
</div>

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Encrypt and decrypt a String in java

I had a doubt that whether the encrypted text will be same for single text when encryption done by multiple times on a same text??

This depends strongly on the crypto algorithm you use:

  • One goal of some/most (mature) algorithms is that the encrypted text is different when encryption done twice. One reason to do this is, that an attacker how known the plain and the encrypted text is not able to calculate the key.
  • Other algorithm (mainly one way crypto hashes) like MD5 or SHA based on the fact, that the hashed text is the same for each encryption/hash.

How do I read a specified line in a text file?

Read five lines each time, just put your statement in if statement , thats it

        String str1 = @"C:\Users\TEMP\Desktop\StaN.txt";   

        System.IO.StreamReader file = new System.IO.StreamReader(str1);

        line = file.ReadLine();

        Int32 ctn=0;

        try
        {

            while ((line = file.ReadLine()) != null)
            {

                    if (Counter == ctn)
                    {
                        MessageBox.Show("I am here");
                        ctn=ctn+5;
                        continue;
                    }
                    else
                    {
                        Counter++;
                        //MessageBox.Show(Counter.ToString());
                        MessageBox.Show(line.ToString());
                    } 
                }

            file.Close();
        }
        catch (Exception er)
        {

        }

Most common C# bitwise operations on enums

The idiom is to use the bitwise or-equal operator to set bits:

flags |= 0x04;

To clear a bit, the idiom is to use bitwise and with negation:

flags &= ~0x04;

Sometimes you have an offset that identifies your bit, and then the idiom is to use these combined with left-shift:

flags |= 1 << offset;
flags &= ~(1 << offset);

How to change font-size of a tag using inline css?

You should analyze your style.css file, possibly using Developer Tools in your favorite browser, to see which rule sets font size on the element in a manner that overrides the one in a style attribute. Apparently, it has to be one using the !important specifier, which generally indicates poor logic and structure in styling.

Primarily, modify the style.css file so that it does not use !important. Failing this, add !important to the rule in style attribute. But you should aim at reducing the use of !important, not increasing it.

PHP check if file is an image

Using file extension and getimagesize function to detect if uploaded file has right format is just the entry level check and it can simply bypass by uploading a file with true extension and some byte of an image header but wrong content.

for being secure and safe you may make thumbnail/resize (even with original image sizes) the uploaded picture and save this version instead the uploaded one. Also its possible to get uploaded file content and search it for special character like <?php to find the file is image or not.

Entity Framework - Include Multiple Levels of Properties

I'm going to add my solution to my particular problem. I had two collections at the same level I needed to include. The final solution looked like this.

var recipe = _bartendoContext.Recipes
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.Ingredient)
    .Include(r => r.Ingredients)
    .ThenInclude(r => r.MeasurementQuantity)
    .FirstOrDefault(r => r.Id == recipeId);
if (recipe?.Ingredients == null) return 0m;
var abv = recipe.Ingredients.Sum(ingredient => ingredient.Ingredient.AlcoholByVolume * ingredient.MeasurementQuantity.Quantity);
return abv;

This is calculating the percent alcohol by volume of a given drink recipe. As you can see I just included the ingredients collection twice then included the ingredient and quantity onto that.

ActionController::InvalidAuthenticityToken

Problem solved by downgrading to 2.3.5 from 2.3.8. (as well as infamous 'You are being redirected.' issue)

Width equal to content

Using display:inline-block; it will work only for a correct sentence with spaces like

_x000D_
_x000D_
#container {_x000D_
    width: 30%;_x000D_
    background-color: grey;_x000D_
    overflow:hidden;_x000D_
    margin:10px;_x000D_
}_x000D_
#container p{_x000D_
    display:inline-block;_x000D_
    background-color: green;_x000D_
}
_x000D_
<h5>Correct sentence with spaces </h5>_x000D_
<div id="container">_x000D_
    <p>Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1</p>_x000D_
</div>_x000D_
<h5>No specaes (not working )</h5>_x000D_
<div id="container">_x000D_
    <p>SampleSampleSampleSampleSampleSampleSampleSampleSampleSampleSamplesadasdsadasdasdsa</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why not using word-wrap: break-word;? it's made to allow long words to be able to break and wrap onto the next line.

_x000D_
_x000D_
#container {_x000D_
    width: 30%;_x000D_
    background-color: grey;_x000D_
    overflow:hidden;_x000D_
    margin:10px;_x000D_
}_x000D_
#container p{_x000D_
   word-wrap: break-word;_x000D_
    background-color: green;_x000D_
}
_x000D_
<h5> Correct sentence with spaces </h5>_x000D_
<div id="container">_x000D_
    <p>Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1 Sample Text 1</p>_x000D_
</div>_x000D_
<h5>No specaes</h5>_x000D_
<div id="container">_x000D_
    <p>SampleSampleSampleSampleSampleSampleSampleSampleSampleSampleSamplesadasdsadasdasdsa</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS Box Shadow Bottom Only

try this to get the box-shadow under your full control.

    <html>

    <head>
        <style> 
            div {
                width:300px;
                height:100px;
                background-color:yellow;
                box-shadow: 0 10px black inset,0 -10px red inset, -10px 0 blue inset, 10px 0 green inset;
           }
        </style>
    </head>
    <body>
        <div>
        </div>
    </body>

    </html>

this would apply to outer box-shadow as well.

Exception is never thrown in body of corresponding try statement

Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

Android Activity without ActionBar

If you're using AppCompat, declare your activity in AndroidManifest.xml as follows:

<activity
    android:name=".SomeActivity"
    ...
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

How to get size of mysql database?

mysqldiskusage  --server=root:MyPassword@localhost  pics

+----------+----------------+
| db_name  |         total  |
+----------+----------------+
| pics     | 1,179,131,029  |
+----------+----------------+

If not installed, this can be installed by installing the mysql-utils package which should be packaged by most major distributions.

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

Drop shadow for PNG image in CSS

If you have >100 images that you want to have drop shadows for, I would suggest using the command-line program ImageMagick. With this, you can apply shaped drop shadows to 100 images just by typing one command! For example:

for i in "*.png"; do convert $i '(' +clone -background black -shadow 80x3+3+3 ')' +swap -background none -layers merge +repage "shadow/$i"; done

The above (shell) command takes each .png file in the current directory, applies a drop shadow, and saves the result in the shadow/ directory. If you don't like the drop shadows generated, you can tweak the parameters a lot; start by looking at the documentation for shadows, and the general usage instructions have a lot of cool examples of things that can be done to images.

If you change your mind in the future about the look of the drop shadows - it's just one command to generate new images with different parameters :-)

Don't understand why UnboundLocalError occurs (closure)

To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal keyword to modify a closure variable.

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter
    return increment

increment = incrementer()

increment()   # 1
increment()   # 2

* The question origially asked about closures in Python.

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

What is sr-only in Bootstrap 3?

Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".

<div class="alert alert-danger" role="alert">
  <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
  <span class="sr-only">Error:</span>
  Enter a valid email address
</div>

Glyphicon will be displayed on all other devices, word Error: on text readers.

How to define the basic HTTP authentication using cURL correctly?

curl -u username:password http://
curl -u username http://

From the documentation page:

-u, --user <user:password>

Specify the user name and password to use for server authentication. Overrides -n, --netrc and --netrc-optional.

If you simply specify the user name, curl will prompt for a password.

The user name and passwords are split up on the first colon, which makes it impossible to use a colon in the user name with this option. The password can, still.

When using Kerberos V5 with a Windows based server you should include the Windows domain name in the user name, in order for the server to succesfully obtain a Kerberos Ticket. If you don't then the initial authentication handshake may fail.

When using NTLM, the user name can be specified simply as the user name, without the domain, if there is a single domain and forest in your setup for example.

To specify the domain name use either Down-Level Logon Name or UPN (User Principal Name) formats. For example, EXAMPLE\user and [email protected] respectively.

If you use a Windows SSPI-enabled curl binary and perform Kerberos V5, Negotiate, NTLM or Digest authentication then you can tell curl to select the user name and password from your environment by specifying a single colon with this option: "-u :".

If this option is used several times, the last one will be used.

http://curl.haxx.se/docs/manpage.html#-u

Note that you do not need --basic flag as it is the default.

How to select all records from one table that do not exist in another table?

See query:

SELECT * FROM Table1 WHERE
id NOT IN (SELECT 
        e.id
    FROM
        Table1 e
            INNER JOIN
        Table2 s ON e.id = s.id);

Conceptually would be: Fetching the matching records in subquery and then in main query fetching the records which are not in subquery.

Apply function to each column in a data frame observing each columns existing data type

If you want to learn your data summary (df) provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.

How can you export the Visual Studio Code extension list?

Windows (PowerShell) version of Benny's answer

Machine A:

In the Visual Studio Code PowerShell terminal:

code --list-extensions > extensions.list

Machine B:

  1. Copy extension.list to the machine B

  2. In the Visual Studio Code PowerShell terminal:

     cat extensions.list |% { code --install-extension $_}
    

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

Getting a timestamp for today at midnight?

$today_at_midnight = strtotime(date("Ymd"));

should give you what you're after.

explanation

What I did was use PHP's date function to get today's date without any references to time, and then pass it to the 'string to time' function which converts a date and time to a epoch timestamp. If it doesn't get a time, it assumes the first second of that day.

References: Date Function: http://php.net/manual/en/function.date.php

String To Time: http://us2.php.net/manual/en/function.strtotime.php

How to make html <select> element look like "disabled", but pass values?

Add a class .disabled and use this CSS:

?.disabled {border: 1px solid #999; color: #333; opacity: 0.5;}
.disabled option {color: #000; opacity: 1;}?

Demo: http://jsfiddle.net/ZCSRq/

Delete a closed pull request from GitHub

This is the reply I received from Github when I asked them to delete a pull request:

"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."

Set Culture in an ASP.Net MVC app

I'm using this localization method and added a route parameter that sets the culture and language whenever a user visits example.com/xx-xx/

Example:

routes.MapRoute("DefaultLocalized",
            "{language}-{culture}/{controller}/{action}/{id}",
            new
            {
                controller = "Home",
                action = "Index",
                id = "",
                language = "nl",
                culture = "NL"
            });

I have a filter that does the actual culture/language setting:

using System.Globalization;
using System.Threading;
using System.Web.Mvc;

public class InternationalizationAttribute : ActionFilterAttribute {

    public override void OnActionExecuting(ActionExecutingContext filterContext) {

        string language = (string)filterContext.RouteData.Values["language"] ?? "nl";
        string culture = (string)filterContext.RouteData.Values["culture"] ?? "NL";

        Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));
        Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(string.Format("{0}-{1}", language, culture));

    }
}

To activate the Internationalization attribute, simply add it to your class:

[Internationalization]
public class HomeController : Controller {
...

Now whenever a visitor goes to http://example.com/de-DE/Home/Index the German site is displayed.

I hope this answers points you in the right direction.

I also made a small MVC 5 example project which you can find here

Just go to http://{yourhost}:{port}/en-us/home/index to see the current date in English (US), or change it to http://{yourhost}:{port}/de-de/home/index for German etcetera.

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

Simplest way to profile a PHP script

I like to use phpDebug for profiling. http://phpdebug.sourceforge.net/www/index.html

It outputs all time / memory usage for any SQL used as well as all the included files. Obviously, it works best on code that's abstracted.

For function and class profiling I'll just use microtime() + get_memory_usage() + get_peak_memory_usage().

Resolving IP Address from hostname with PowerShell

The simplest way:

ping hostname

e.g.

ping dynlab938.meng.auth.gr

it will print: Pinging dynlab938.meng.auth.gr [155.207.29.38] with 32 bytes of data

Difference between os.getenv and os.environ.get

In addition to the answers above:

$ python3 -m timeit -s 'import os' 'os.environ.get("TERM_PROGRAM")'
200000 loops, best of 5: 1.65 usec per loop

$ python3 -m timeit -s 'import os' 'os.getenv("TERM_PROGRAM")'
200000 loops, best of 5: 1.83 usec per loop

Android Studio update -Error:Could not run build action using Gradle distribution

I have run into a similar problem on Mac.

Looking at the log under Help -> Show logs in Finder I found the following entry.

You have JVM property "https.proxyHost" set to "127.0.0.1".
This may lead to incorrect behaviour. Proxy should be set in Settings | HTTP Proxy
This JVM property is old and its usage is not recommended by Oracle.
(Note: It could have been assigned by some code dynamically.)

and it turned out I had Charles as a network proxy running. Shutting down Charles solved the problem.

Add a fragment to the URL without causing a redirect?

window.location.hash = 'something';

That is just plain JavaScript.

Your comment...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.

Try this...

window.location = '#';

Also, don't forget about the window.location.replace() method.

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

split string only on first instance of specified character

With help of destructuring assignment it can be more readable:

let [first, ...rest] = "good_luck_buddy".split('_')
rest = rest.join('_')

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.

What I did the following was:

  1. enable the 2-step verification to google HERE

  2. Create App Password to be use by your system HERE

  3. I selected Others (custom name) and clicked generate

  4. Went to my env file in laravel and edited this

    [email protected]

    MAIL_PASSWORD=thepasswordgenerated

  5. Restarted my apache server and boom! It works again.

This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

Firefox and SSL: sec_error_unknown_issuer

For nginx do this Generate a chained crt file using

$ cat www.example.com.crt bundle.crt > www.example.com.chained.crt

The resulting file should be used in the ssl_certificate directive:

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     www.example.com.chained.crt;
    ssl_certificate_key www.example.com.key;
    ...
}

Check if an object belongs to a class in Java

The usual way would be:

if (a instanceof A)

However, there are cases when you can't do this, such as when A in a generic argument.

Due to Java's type erasure, the following won't compile:

<A> boolean someMethod(Object a) {
    if (a instanceof A)
    ...
}

and the following won't work (and will produce an unchecked cast warning):

<A> void someMethod(Object a) {
    try {
        A casted = (A)a;    
    } catch (ClassCastException e) {
         ...
    }
}

You can't cast to A at runtime, because at runtime, A is essentially Object.

The solutions to such cases is to use a Class instead of the generic argument:

void someMethod(Object a, Class<A> aClass) {
    if (aClass.isInstance(a)) {
       A casted = aClass.cast(a);
       ...
    }
}

You can then call the method as:

someMethod(myInstance, MyClass.class);
someMethod(myInstance, OtherClass.class);

Convert Char to String in C

Here is a working exemple :

printf("-%s-", (char[2]){'A', 0});

This will display -A-

How could I create a list in c++?

I'm guessing this is a homework question, so you probably want to go here. It has a tutorial explaining linked lists, gives good pseudocode and also has a C++ implementation you can download.

I'd recommend reading through the explanation and understanding the pseudocode before blindly using the implementation. This is a topic that you really should understand in depth if you want to continue on in CS.

Convert Difference between 2 times into Milliseconds?

You have to convert textbox's values to DateTime (t1,t2), then:

DateTime t1,t2;
t1 = DateTime.Parse(textbox1.Text);
t2 = DateTime.Parse(textbox2.Text);
int diff = ((TimeSpan)(t2 - t1)).TotalMilliseconds;

Or use DateTime.TryParse(textbox1, out t1); Error handling is up to you.

Pythonic way to check if a file exists?

Instead of os.path.isfile, suggested by others, I suggest using os.path.exists, which checks for anything with that name, not just whether it is a regular file.

Thus:

if not os.path.exists(filename):
    file(filename, 'w').close()

Alternatively:

file(filename, 'w+').close()

The latter will create the file if it exists, but not otherwise. It will, however, fail if the file exists, but you don't have permission to write to it. That's why I prefer the first solution.

Remove portion of a string after a certain character

Use the strstr function.

<?php
$myString = "Posted On April 6th By Some Dude";
$result = strstr($myString, 'By', true);

echo $result ;

The third parameter true tells the function to return everything before first occurrence of the second parameter.

Best way to make WPF ListView/GridView sort on column-header clicking?

Just wanted to add another simple way someone can sort the the WPF ListView

void SortListView(ListView listView)
{
    IEnumerable listView_items = listView.Items.SourceCollection;
    List<MY_ITEM_CLASS> listView_items_to_list = listView_items.Cast<MY_ITEM_CLASS>().ToList();

    Comparer<MY_ITEM_CLASS> scoreComparer = Comparer<MY_ITEM_CLASS>.Create((first, second) => first.COLUMN_NAME.CompareTo(second.COLUMN_NAME));

    listView_items_to_list.Sort(scoreComparer);
    listView.ItemsSource = null;
    listView.Items.Clear();
    listView.ItemsSource = listView_items_to_list;
}

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Run below SQL query to create a view which will show all functions:

CREATE OR REPLACE VIEW show_functions AS
    SELECT routine_name FROM information_schema.routines 
        WHERE routine_type='FUNCTION' AND specific_schema='public';

Using Case/Switch and GetType to determine the object

I actually prefer the approach given as the answer here: Is there a better alternative than this to 'switch on type'?

There is however a good argument about not implementing any type comparison methids in an object oriented language like C#. You could as an alternative extend and add extra required functionality using inheritance.

This point was discussed in the comments of the authors blog here: http://blogs.msdn.com/b/jaredpar/archive/2008/05/16/switching-on-types.aspx#8553535

I found this an extremely interesting point which changed my approach in a similar situation and only hope this helps others.

Kind Regards, Wayne

What's a decent SFTP command-line client for windows?

LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.

Achtunq, it uses Cygwin, but everything is included in the bundle.

How to get the screen width and height in iOS?

The modern answer:

if your app support split view on iPad, this problem becomes a little complicated. You need window's size, not the screen's, which may contain 2 apps. Window's size may also vary while running.

Use app's main window's size:

UIApplication.shared.delegate?.window??.bounds.size ?? .zero

Note: The method above may get wrong value before window becoming key window when starting up. if you only need width, method below is very recommended:

UIApplication.shared.statusBarFrame.width

The old solution using UIScreen.main.bounds will return the device's bounds. If your app running in split view mode, it get the wrong dimensions.

self.view.window in the hottest answer may get wrong size when app contains 2 or more windows and the window have small size.

Run a JAR file from the command line and specify classpath

When you specify -jar then the -cp parameter will be ignored.

From the documentation:

When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored.

You also cannot "include" needed jar files into another jar file (you would need to extract their contents and put the .class files into your jar file)

You have two options:

  1. include all jar files from the lib directory into the manifest (you can use relative paths there)
  2. Specify everything (including your jar) on the commandline using -cp:
    java -cp MyJar.jar:lib/* com.somepackage.subpackage.Main

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Type converting slices of interfaces

Try interface{} instead. To cast back as slice, try

func foo(bar interface{}) {
    s := bar.([]string)
    // ...
}

Closing JFrame with button click

You will need a reference to the specific frame you want to close but assuming you have the reference dispose() should close the frame.

jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
       frameToClose.dispose();
    }
});

How to configure Git post commit hook

Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html

It's just a matter of using curl to trigger a Jenkins job using the git hooks provided by git.
The command

curl http://localhost:8080/job/someJob/build?delay=0sec

can run a Jenkins job, where someJob is the name of the Jenkins job.

Search for the hooks folder in your hidden .git folder. Rename the post-commit.sample file to post-commit. Open it with Notepad, remove the : Nothing line and paste the above command into it.

That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.

How to show empty data message in Datatables

Later versions of dataTables have the following language settings (taken from here):

  • "infoEmpty" - displayed when there are no records in the table
  • "zeroRecords" - displayed when there no records matching the filtering

e.g.

$('#example').DataTable( {
    "language": {
        "infoEmpty": "No records available - Got it?",
    }
});

Note: As the property names do not contain any special characters you can remove the quotes:

$('#example').DataTable( {
    language: {
        infoEmpty: "No records available - Got it?",
    }
});

IE11 Document mode defaults to IE7. How to reset?

For the website ensure that IIS HTTP response headers setting and add new key X-UA-Compatible pointing to "IE=edge"

Click here for more details

If you have access to the server, the most reliable way of doing this is to do it on the server itself, in IIS. Go in to IIS HTTP Response Headers. Add Name: X-UA-Compatible Value: IE=edge This will override your browser and your code.

BOOLEAN or TINYINT confusion

The numeric type overview for MySQL states: BOOL, BOOLEAN: These types are synonyms for TINYINT(1). A value of zero is considered false. Nonzero values are considered true.

See here: https://dev.mysql.com/doc/refman/5.7/en/numeric-type-overview.html

What's the best UML diagramming tool?

I strongly recommend BOUML. It's a free UML modelling application, which:

  • is extremely fast (fastest UML tool ever created, check out benchmarks),
  • has rock solid C++, Java, PHP and others import support,
  • is multiplatform (Linux, Windows, other OSes),
  • has a great SVG export support, which is important, because viewing large graphs in vector format, which scales fast in e.g. Firefox, is very convenient (you can quickly switch between "birds eye" view and class detail view),
  • is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
  • supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)

Believe me, there is no better tool. StarUML is a retarded turtle compared to BOUML. ArgoUML simply doesn't work. Dia is a ergonomy^-1 software.

Jquery DatePicker Set default date

Code to display current date in element input or datepicker with ID="mydate"

Don't forget add reference to jquery-ui-*.js

    $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-' + (today.getMonth() + 1);

        onlyDate = today.getDate();

        if (onlyDate.toString().length == 2) {
            dateNewFormat += '-' + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }
        $('#mydate').val(dateNewFormat);
    });

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

What is a lambda expression in C++11?

One problem it solves: Code simpler than lambda for a call in constructor that uses an output parameter function for initializing a const member

You can initialize a const member of your class, with a call to a function that sets its value by giving back its output as an output parameter.

Fixing the order of facets in ggplot

There are a couple of good solutions here.

Similar to the answer from Harpal, but within the facet, so doesn't require any change to underlying data or pre-plotting manipulation:

# Change this code:
facet_grid(.~size) + 
# To this code:
facet_grid(~factor(size, levels=c('50%','100%','150%','200%')))

This is flexible, and can be implemented for any variable as you change what element is faceted, no underlying change in the data required.

Dynamically Changing log4j log level

This answer won't help you to change the logging level dynamically, you need to restart the service, if you are fine restarting the service, please use the below solution

I did this to Change log4j log level and it worked for me, I have n't referred any document. I used this system property value to set my logfile name. I used the same technique to set logging level as well, and it worked

passed this as JVM parameter (I use Java 1.7)

Sorry this won't dynamically change the logging level, it requires a restart of the service

java -Dlogging.level=DEBUG -cp xxxxxx.jar  xxxxx.java

in the log4j.properties file, I added this entry

log4j.rootLogger=${logging.level},file,stdout

I tried

 java -Dlogging.level=DEBUG -cp xxxxxx.jar  xxxxx.java
 java -Dlogging.level=INFO-cp xxxxxx.jar  xxxxx.java
 java -Dlogging.level=OFF -cp xxxxxx.jar  xxxxx.java

It all worked. hope this helps!

I have these following dependencies in my pom.xml

<dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
</dependency>

<dependency>
    <groupId>log4j</groupId>
    <artifactId>apache-log4j-extras</artifactId>
    <version>1.2.17</version>
</dependency>

How do you style a TextInput in react native for password input

When this was asked there wasn't a way to do it natively, however this will be added on the next sync according to this pull request. Here is the last comment on the pull request - "Landed internally, will be out on the next sync"

When it is added you will be able to do something like this

<TextInput secureTextEntry={true} style={styles.default} value="abc" />

refs

AttributeError: 'tuple' object has no attribute

You're returning a tuple. Index it.

obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Display encoded html with razor

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>

How can I display an RTSP video stream in a web page?

the Microsoft Mediaplayer can do all, you need. I use the MS Mediaservices of 2003 / 2008 Server to deliver Video as Broadcast and Unicast Stream. This Service could GET the Stream from the cam and Broadcast it. Than you have "only" the Problem to "Display" that Picture in ALL Browers at all OS-Systems

My Tip :check first the OS , than load your plugin . on Windows it is easy -take WMP , on other take MS Silverligt ...

Check if Internet Connection Exists with jQuery?

I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.

http://tomriley.net/blog/archives/111

How to get the primary IP address of the local machine on Linux and OS X?

Works on Mac, Linux and inside Docker Containers:

$ hostname --ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p' | awk '{print$1; exit}')

Also works on Makefile as:

LOCAL_HOST := ${shell hostname --ip-address 2> /dev/null || (ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p' | awk '{print $1; exit}')}