Programs & Examples On #Htpc

receiver type *** for instance message is a forward declaration

You are using

States states;

where as you should use

States *states;

Your init method should be like this

-(id)init {
  if( (self = [super init]) ) {
      pickedGlasses = 0;
  }
  return self;
}

Now finally when you are going to create an object for States class you should do it like this.

State *states = [[States alloc] init];

I am not saying this is the best way of doing this. But it may help you understand the very basic use of initializing objects.

Cleanest way to toggle a boolean variable in Java?

Before:

boolean result = isresult();
if (result) {
    result = false;
} else {
    result = true;
}

After:

boolean result = isresult();
result ^= true;

How to use pip with python 3.4 on windows?

"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."

Have you tried it?

How to check version of python modules?

I suggest using pip in place of easy_install. With pip, you can list all installed packages and their versions with

pip freeze

In most linux systems, you can pipe this to grep(or findstr on Windows) to find the row for the particular package you're interested in:

Linux:
$ pip freeze | grep lxml
lxml==2.3

Windows:
c:\> pip freeze | findstr lxml
lxml==2.3

For an individual module, you can try the __version__ attribute, however there are modules without it:

$ python -c "import requests; print(requests.__version__)"
2.14.2
$ python -c "import lxml; print(lxml.__version__)"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'

Lastly, as the commands in your question are prefixed with sudo, it appears you're installing to the global python environment. Strongly advise to take look into python virtual environment managers, for example virtualenvwrapper

org.apache.jasper.JasperException: Unable to compile class for JSP:

include your Member Class to your jsp :

<%@ page import="pageNumber.*, java.util.*, java.io.*,yourMemberPackage.Member" %>

Comparing two java.util.Dates to see if they are in the same day

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
                  cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR);

Note that "same day" is not as simple a concept as it sounds when different time zones can be involved. The code above will for both dates compute the day relative to the time zone used by the computer it is running on. If this is not what you need, you have to pass the relevant time zone(s) to the Calendar.getInstance() calls, after you have decided what exactly you mean with "the same day".

And yes, Joda Time's LocalDate would make the whole thing much cleaner and easier (though the same difficulties involving time zones would be present).

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

Check if table exists

If using jruby, here is a code snippet to return an array of all tables in a db.

require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"

def get_database_tables(connection, db_name)
  md = connection.get_meta_data
  rs = md.get_tables(db_name, nil, '%',["TABLE"])

  tables = []
  count = 0
  while rs.next
    tables << rs.get_string(3)
  end #while
  return tables
end

Practical uses for the "internal" keyword in C#

When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.

public class DangerousClass {
    public void SafeMethod() { }
    internal void UpdateGlobalStateInSomeBizarreWay() { }
}

Style bottom Line in Android

This worked best for me:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-5dp" android:left="-5dp" android:right="-5dp" android:bottom="0dp">
        <shape android:shape="rectangle">
            <stroke android:width="4dp" android:color="#ff0000"/>
        </shape>
    </item>
</layer-list>

Shows the line on the bottom only. You can easily change with stroke width to size you like and also update the top, left, right on the accordingly.

How to scale a BufferedImage

Unfortunately the performance of getScaledInstance() is very poor if not problematic.

The alternative approach is to create a new BufferedImage and and draw a scaled version of the original on the new one.

BufferedImage resized = new BufferedImage(newWidth, newHeight, original.getType());
Graphics2D g = resized.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(original, 0, 0, newWidth, newHeight, 0, 0, original.getWidth(),
    original.getHeight(), null);
g.dispose();

newWidth,newHeight indicate the new BufferedImage size and have to be properly calculated. In case of factor scaling:

int newWidth = new Double(original.getWidth() * widthFactor).intValue();
int newHeight = new Double(original.getHeight() * heightFactor).intValue();

EDIT: Found the article illustrating the performance issue: The Perils of Image.getScaledInstance()

pyplot axes labels for subplots

# list loss and acc are your data
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)

ax1.plot(iteration1, loss)
ax2.plot(iteration2, acc)

ax1.set_title('Training Loss')
ax2.set_title('Training Accuracy')

ax1.set_xlabel('Iteration')
ax1.set_ylabel('Loss')

ax2.set_xlabel('Iteration')
ax2.set_ylabel('Accuracy')

Input from the keyboard in command line application

If you want to read space separated string, and immediately split the string into an array, you can do this:

var arr = readLine()!.characters.split(" ").map(String.init)

eg.

print("What is your full name?")

var arr = readLine()!.characters.split(" ").map(String.init)

var firstName = ""
var middleName = ""
var lastName = ""

if arr.count > 0 {
    firstName = arr[0]
}
if arr.count > 2 {
    middleName = arr[1]
    lastName = arr[2]
} else if arr.count > 1 {
    lastName = arr[1]
}

print("First Name: \(firstName)")
print("Middle Name: \(middleName)")
print("Last Name: \(lastName)")

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

Find timestamp from DateTime:

private long ConvertToTimestamp(DateTime value)
{
    TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
    TimeZone localZone = TimeZone.CurrentTimeZone;
    System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
    NyTime = NyTime.AddHours(-1);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (NyTime - epoch);
    return (long)Convert.ToDouble(span.TotalSeconds);
}

SSIS Convert Between Unicode and Non-Unicode Error

Below Steps worked for me:

1). right click on source task.

2). click on "Show Advanced editor". advanced edit option for source task in ssis

3). Go to "Input and Output Properties" tab.

4). select the output column for which you are getting the error.

5). Its data type will be "String[DT_STR]".

6). Change that data type to "Unicode String[DT_WSTR]". Changing the data type to unicode string

7). save and close. Hope this helps!

How to view the committed files you have not pushed yet?

The previous answers are all good, but they all show origin/master. These days, following the best practices, I rarely work directly on a master branch, let alone from origin repo.

So if you are like me who work in a branch, here are tips:

  1. Say you are already on a branch. If not, git checkout that branch
  2. git log # to show a list of commit such as x08d46ffb1369e603c46ae96, You need only the latest commit which comes first.
  3. git show --name-only x08d46ffb1369e603c46ae96 # to show the files commited
  4. git show x08d46ffb1369e603c46ae96 # show the detail diff of each changed file

Or more simply, just use HEAD:

  1. git show --name-only HEAD # to show a list of files committed
  2. git show HEAD # to show the detail diff.

how to know status of currently running jobs

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

check field execution_status

0 - Returns only those jobs that are not idle or suspended.
1 - Executing.
2 - Waiting for thread.
3 - Between retries.
4 - Idle.
5 - Suspended.
7 - Performing completion actions.

If you need the result of execution, check the field last_run_outcome

0 = Failed
1 = Succeeded
3 = Canceled
5 = Unknown

https://msdn.microsoft.com/en-us/library/ms186722.aspx

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

When you open the file you want to write to, open it with a specific encoding that can handle all the characters.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

List<T> or IList<T>

IList<T> is an interface so you can inherit another class and still implement IList<T> while inheriting List<T> prevents you to do so.

For example if there is a class A and your class B inherits it then you can't use List<T>

class A : B, IList<T> { ... }

jQuery Remove string from string

To add on nathan gonzalez answer, please note you need to assign the replaced object after calling replace function since it is not a mutator function:

myString = myString.replace('username1','');

How to pass datetime from c# to sql correctly?

I had many issues involving C# and SqlServer. I ended up doing the following:

  1. On SQL Server I use the DateTime column type
  2. On c# I use the .ToString("yyyy-MM-dd HH:mm:ss") method

Also make sure that all your machines run on the same timezone.

Regarding the different result sets you get, your first example is "July First" while the second is "4th of July" ...

Also, the second example can be also interpreted as "April 7th", it depends on your server localization configuration (my solution doesn't suffer from this issue).

EDIT: hh was replaced with HH, as it doesn't seem to capture the correct hour on systems with AM/PM as opposed to systems with 24h clock. See the comments below.

Is it possible to apply CSS to half of a character?

Enter image description here

I just played with @Arbel's solution:

_x000D_
_x000D_
var textToHalfStyle = $('.textToHalfStyle').text();_x000D_
var textToHalfStyleChars = textToHalfStyle.split('');_x000D_
$('.textToHalfStyle').html('');_x000D_
$.each(textToHalfStyleChars, function(i,v){_x000D_
    $('.textToHalfStyle').append('<span class="halfStyle" data-content="' + v + '">' + v + '</span>');_x000D_
});
_x000D_
body{_x000D_
    background-color: black;_x000D_
}_x000D_
.textToHalfStyle{_x000D_
    display:block;_x000D_
    margin: 200px 0 0 0;_x000D_
    text-align:center;_x000D_
}_x000D_
.halfStyle {_x000D_
    font-family: 'Libre Baskerville', serif;_x000D_
    position:relative;_x000D_
    display:inline-block;_x000D_
    width:1;_x000D_
    font-size:70px;_x000D_
    color: black;_x000D_
    overflow:hidden;_x000D_
    white-space: pre;_x000D_
    text-shadow: 1px 2px 0 white;_x000D_
}_x000D_
.halfStyle:before {_x000D_
    display:block;_x000D_
    z-index:1;_x000D_
    position:absolute;_x000D_
    top:0;_x000D_
    width: 50%;_x000D_
    content: attr(data-content); /* dynamic content for the pseudo element */_x000D_
    overflow:hidden;_x000D_
    color: white;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>_x000D_
<span class="textToHalfStyle">Dr. Jekyll and M. Hide</span>
_x000D_
_x000D_
_x000D_

What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

The difference is that if you only specify the DOCTYPE, IE’s Compatibility View Settings take precedence. By default these settings force all intranet sites into Compatibility View regardless of DOCTYPE. There’s also a checkbox to use Compatibility View for all websites, regardless of DOCTYPE.

IE Compatibility View Settings dialog

X-UA-Compatible overrides the Compatibility View Settings, so the page will render in standards mode regardless of the browser settings. This forces standards mode for:

  • intranet pages
  • external web pages when the computer administrator has chosen “Display all websites in Compatibility View” as the default—think big companies, governments, universities
  • when you unintentionally end up on the Microsoft Compatibility View List
  • cases where users have manually added your website to the list in Compatibility View Settings

DOCTYPE alone cannot do that; you will end up in one of the Compatibility View modes in these cases regardless of DOCTYPE.

If both the meta tag and the HTTP header are specified, the meta tag takes precedence.

This answer is based on examining the complete rules for deciding document mode in IE8, IE9, and IE10. Note that looking at the DOCTYPE is the very last fallback for deciding the document mode.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

How to save username and password with Mercurial?

While it may or may not work in your situation, I have found it useful to generate a public / private key using Putty's Pageant.

If you are also working with bitbucket (.org) it should give you the ability to provide a public key to your user account and then commands that reach out to the repository will be secured automatically.

If Pageant doesn't start up for you upon a reboot, you can add a shortcut to Pageant to your Windows "Start menu" and the shortcut may need to have a 'properties' populated with the location of your private (.ppk) file.

With this in place Mercurial and your local repositories will need to be set up to push/pull using the SSH format.

Here are some detailed instructions on Atlassian's site for Windows OR Mac/Linux.

You don't have to take my word for it and there are no doubt other ways to do it. Perhaps these steps described here are more for you:

  1. Start PuttyGen from Start -> PuTTY-> PuttyGen
  2. Generate a new key and save it as a .ppk file without a passphrase
  3. Use Putty to login to the server you want to connect to
  4. Append the Public Key text from PuttyGen to the text of ~/.ssh/authorized_keys
  5. Create a shortcut to your .ppk file from Start -> Putty to Start -> Startup
  6. Select the .ppk shortcut from the Startup menu (this will happen automatically at every startup)
  7. See the Pageant icon in the system tray? Right-click it and select “New session”
  8. Enter username@hostname in the “Host name” field
  9. You will now log in automatically.

Have border wrap around text

Try putting it in a span element:

_x000D_
_x000D_
<div id='page' style='width: 600px'>_x000D_
  <h1><span style='border:2px black solid; font-size:42px;'>Title</span></h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert a python 'type' object to a string

print type(someObject).__name__

If that doesn't suit you, use this:

print some_instance.__class__.__name__

Example:

class A:
    pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A

Also, it seems there are differences with type() when using new-style classes vs old-style (that is, inheritance from object). For a new-style class, type(someObject).__name__ returns the name, and for old-style classes it returns instance.

RegEx: How can I match all numbers greater than 49?

Try a conditional group matching 50-99 or any string of three or more digits:

var r = /^(?:[5-9]\d|\d{3,})$/

Format LocalDateTime with Timezone in Java8

LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd HH:mm:ss.SSSSSS Z"));

Set NA to 0 in R

You can just use the output of is.na to replace directly with subsetting:

bothbeams.data[is.na(bothbeams.data)] <- 0

Or with a reproducible example:

dfr <- data.frame(x=c(1:3,NA),y=c(NA,4:6))
dfr[is.na(dfr)] <- 0
dfr
  x y
1 1 0
2 2 4
3 3 5
4 0 6

However, be careful using this method on a data frame containing factors that also have missing values:

> d <- data.frame(x = c(NA,2,3),y = c("a",NA,"c"))
> d[is.na(d)] <- 0
Warning message:
In `[<-.factor`(`*tmp*`, thisvar, value = 0) :
  invalid factor level, NA generated

It "works":

> d
  x    y
1 0    a
2 2 <NA>
3 3    c

...but you likely will want to specifically alter only the numeric columns in this case, rather than the whole data frame. See, eg, the answer below using dplyr::mutate_if.

jQuery - disable selected options

This will disable/enable the options when you select/remove them, respectively.

$("#theSelect").change(function(){          
    var value = $(this).val();
    if (value === '') return;
    var theDiv = $(".is" + value);

    var option = $("option[value='" + value + "']", this);
    option.attr("disabled","disabled");

    theDiv.slideDown().removeClass("hidden");
    theDiv.find('a').data("option",option);
});


$("div a.remove").click(function () {     
    $(this).parent().slideUp(function() { $(this).addClass("hidden"); });
    $(this).data("option").removeAttr('disabled');
});

Demo: http://jsfiddle.net/AaXkd/

How do I redirect to another webpage?

But if someone wants to redirect back to home page then he may use the following snippet.

window.location = window.location.host

It would be helpful if you have three different environments as development, staging, and production.

You can explore this window or window.location object by just putting these words in Chrome Console or Firebug's Console.

Generate random password string with requirements in javascript

Easily generate random passwords with the help of this JavaScript code. For demo click: How to generate random passwords using JavaScript

JavaScript code:

<script>
const input = document.querySelector("input");
const button = document.querySelector("#passgen");
function GeneratePassword(length = 8) {
const cwb =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$!%^&*()_+=-";

  let password = "";
  for (let i = 0; i < length; ++i) {
    let at = Math.floor(Math.random() * (cwb.length + 1));
    password += cwb.charAt(at);
  }
  return password;
}
button.addEventListener("click", () => {
  input.value = GeneratePassword(8);
});
</script> 

Alternate background colors for list items

Try adding a pair of class attributes, say 'even' and 'odd', to alternating list elements, e.g.

<ul>
    <li class="even"><a href="link">Link 1</a></li>
    <li class="odd"><a href="link">Link 2</a></li>
    <li class="even"><a href="link">Link 3</a></li>
    <li class="odd"><a href="link">Link 4</a></li>
    <li class="even"><a href="link">Link 5</a></li>
</ul>

In a <style> section of the HTML page, or in a linked stylesheet, you would define those same classes, specifying your desired background colours:

li.even { background-color: red; }
li.odd { background-color: blue; }

You might want to use a template library as your needs evolve to provide you with greater flexibility and to cut down on the typing. Why type all those list elements by hand?

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

jquery - is not a function error

It works on my case:

import * as JQuery from "jquery";
const $ = JQuery.default;

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

<a href="javascript:void(0)" onclick="$('#myDialog').dialog();">
  Open as dialog
</a>

<div id="myDialog">
I have a dialog!
</div>

See the example I posted on jsbin.com.

What is the syntax for adding an element to a scala.collection.mutable.Map?

When you say

val map = scala.collection.mutable.Map

you are not creating a map instance, but instead aliasing the Map type.

map: collection.mutable.Map.type = scala.collection.mutable.Map$@fae93e

Try instead the following:

scala> val map = scala.collection.mutable.Map[String, Int]()
map: scala.collection.mutable.Map[String,Int] = Map()

scala> map("asdf") = 9

scala> map
res6: scala.collection.mutable.Map[String,Int] = Map((asdf,9))

grep for special characters in Unix

The one that worked for me is:

grep -e '->'

The -e means that the next argument is the pattern, and won't be interpreted as an argument.

From: http://www.linuxquestions.org/questions/programming-9/how-to-grep-for-string-769460/

Remove .php extension with .htaccess

Apache mod_rewrite

What you're looking for is mod_rewrite,

Description: Provides a rule-based rewriting engine to rewrite requested URLs on the fly.

Generally speaking, mod_rewrite works by matching the requested document against specified regular expressions, then performs URL rewrites internally (within the apache process) or externally (in the clients browser). These rewrites can be as simple as internally translating example.com/foo into a request for example.com/foo/bar.

The Apache docs include a mod_rewrite guide and I think some of the things you want to do are covered in it. Detailed mod_rewrite guide.

Force the www subdomain

I would like it to force "www" before every url, so its not domain.com but www.domain.com/page

The rewrite guide includes instructions for this under the Canonical Hostname example.

Remove trailing slashes (Part 1)

I would like to remove all trailing slashes from pages

I'm not sure why you would want to do this as the rewrite guide includes an example for the exact opposite, i.e., always including a trailing slash. The docs suggest that removing the trailing slash has great potential for causing issues:

Trailing Slash Problem

Description:

Every webmaster can sing a song about the problem of the trailing slash on URLs referencing directories. If they are missing, the server dumps an error, because if you say /~quux/foo instead of /~quux/foo/ then the server searches for a file named foo. And because this file is a directory it complains. Actually it tries to fix it itself in most of the cases, but sometimes this mechanism need to be emulated by you. For instance after you have done a lot of complicated URL rewritings to CGI scripts etc.

Perhaps you could expand on why you want to remove the trailing slash all the time?

Remove .php extension

I need it to remove the .php

The closest thing to doing this that I can think of is to internally rewrite every request document with a .php extension, i.e., example.com/somepage is instead processed as a request for example.com/somepage.php. Note that proceeding in this manner would would require that each somepage actually exists as somepage.php on the filesystem.

With the right combination of regular expressions this should be possible to some extent. However, I can foresee some possible issues with index pages not being requested correctly and not matching directories correctly.

For example, this will correctly rewrite example.com/test as a request for example.com/test.php:

RewriteEngine  on
RewriteRule ^(.*)$ $1.php

But will make example.com fail to load because there is no example.com/.php

I'm going to guess that if you're removing all trailing slashes, then picking a request for a directory index from a request for a filename in the parent directory will become almost impossible. How do you determine a request for the directory 'foobar':

example.com/foobar

from a request for a file called foobar (which is actually foobar.php)

example.com/foobar

It might be possible if you used the RewriteBase directive. But if you do that then this problem gets way more complicated as you're going to require RewriteCond directives to do filesystem level checking if the request maps to a directory or a file.

That said, if you remove your requirement of removing all trailing slashes and instead force-add trailing slashes the "no .php extension" problem becomes a bit more reasonable.

# Turn on the rewrite engine
RewriteEngine  on
# If the request doesn't end in .php (Case insensitive) continue processing rules
RewriteCond %{REQUEST_URI} !\.php$ [NC]
# If the request doesn't end in a slash continue processing the rules
RewriteCond %{REQUEST_URI} [^/]$
# Rewrite the request with a .php extension. L means this is the 'Last' rule
RewriteRule ^(.*)$ $1.php [L]

This still isn't perfect -- every request for a file still has .php appended to the request internally. A request for 'hi.txt' will put this in your error logs:

[Tue Oct 26 18:12:52 2010] [error] [client 71.61.190.56] script '/var/www/test.peopleareducks.com/rewrite/hi.txt.php' not found or unable to stat

But there is another option, set the DefaultType and DirectoryIndex directives like this:

DefaultType application/x-httpd-php
DirectoryIndex index.php index.html

Update 2013-11-14 - Fixed the above snippet to incorporate nicorellius's observation

Now requests for hi.txt (and anything else) are successful, requests to example.com/test will return the processed version of test.php, and index.php files will work again.

I must give credit where credit is due for this solution as I found it Michael J. Radwins Blog by searching Google for php no extension apache.

Remove trailing slashes

Some searching for apache remove trailing slashes brought me to some Search Engine Optimization pages. Apparently some Content Management Systems (Drupal in this case) will make content available with and without a trailing slash in URls, which in the SEO world will cause your site to incur a duplicate content penalty. Source

The solution seems fairly trivial, using mod_rewrite we rewrite on the condition that the requested resource ends in a / and rewrite the URL by sending back the 301 Permanent Redirect HTTP header.

Here's his example which assumes your domain is blamcast.net and allows the the request to optionally be prefixed with www..

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?blamcast\.net$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

Now we're getting somewhere. Lets put it all together and see what it looks like.

Mandatory www., no .php, and no trailing slashes

This assumes the domain is foobar.com and it is running on the standard port 80.

# Process all files as PHP by default
DefaultType application/x-httpd-php
# Fix sub-directory requests by allowing 'index' as a DirectoryIndex value
DirectoryIndex index index.html

# Force the domain to load with the www subdomain prefix
# If the request doesn't start with www...
RewriteCond %{HTTP_HOST}   !^www\.foobar\.com [NC]
# And the site name isn't empty
RewriteCond %{HTTP_HOST}   !^$
# Finally rewrite the request: end of rules, don't escape the output, and force a 301 redirect
RewriteRule ^/?(.*)         http://www.foobar.com/$1 [L,R,NE]

#get rid of trailing slashes
RewriteCond %{HTTP_HOST} ^(www.)?foobar\.com$ [NC]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

The 'R' flag is described in the RewriteRule directive section. Snippet:

redirect|R [=code] (force redirect) Prefix Substitution with http://thishost[:thisport]/ (which makes the new URL a URI) to force a external redirection. If no code is given, a HTTP response of 302 (MOVED TEMPORARILY) will be returned.

Final Note

I wasn't able to get the slash removal to work successfully. The redirect ended up giving me infinite redirect loops. After reading the original solution closer I get the impression that the example above works for them because of how their Drupal installation is configured. He mentions specifically:

On a normal Drupal site, with clean URLs enabled, these two addresses are basically interchangeable

In reference to URLs ending with and without a slash. Furthermore,

Drupal uses a file called .htaccess to tell your web server how to handle URLs. This is the same file that enables Drupal's clean URL magic. By adding a simple redirect command to the beginning of your .htaccess file, you can force the server to automatically remove any trailing slashes.

Function to get yesterday's date in Javascript in format DD/MM/YYYY

The problem here seems to be that you're reassigning $today by assigning a string to it:

$today = $dd+'/'+$mm+'/'+$yyyy;

Strings don't have getDate.

Also, $today.getDate()-1 just gives you the day of the month minus one; it doesn't give you the full date of 'yesterday'. Try this:

$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1); //setDate also supports negative values, which cause the month to rollover.

Then just apply the formatting code you wrote:

var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1; //January is 0!

var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+$dd} if($mm<10){$mm='0'+$mm} $yesterday = $dd+'/'+$mm+'/'+$yyyy;

Because of the last statement, $yesterday is now a String (not a Date) containing the formatted date.

What does the exclamation mark do before the function?

Its just to save a byte of data when we do javascript minification.

consider the below anonymous function

function (){}

To make the above as self invoking function we will generally change the above code as

(function (){}())

Now we added two extra characters (,) apart from adding () at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function as

!function (){}()

Still both are self invoking functions and we save a byte as well. Instead of 2 characters (,) we just used one character !

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

Get the first item from an iterable that matches a condition

You could also use the argwhere function in Numpy. For example:

i) Find the first "l" in "helloworld":

import numpy as np
l = list("helloworld") # Create list
i = np.argwhere(np.array(l)=="l") # i = array([[2],[3],[8]])
index_of_first = i.min()

ii) Find first random number > 0.1

import numpy as np
r = np.random.rand(50) # Create random numbers
i = np.argwhere(r>0.1)
index_of_first = i.min()

iii) Find the last random number > 0.1

import numpy as np
r = np.random.rand(50) # Create random numbers
i = np.argwhere(r>0.1)
index_of_last = i.max()

Running unittest with typical test directory structure

If you have multiple directories in your test directory, then you have to add to each directory an __init__.py file.

/home/johndoe/snakeoil
+-- test
    +-- __init__.py        
    +-- frontend
        +-- __init__.py
        +-- test_foo.py
    +-- backend
        +-- __init__.py
        +-- test_bar.py

Then to run every test at once, run:

python -m unittest discover -s /home/johndoe/snakeoil/test -t /home/johndoe/snakeoil

Source: python -m unittest -h

  -s START, --start-directory START
                        Directory to start discovery ('.' default)
  -t TOP, --top-level-directory TOP
                        Top level directory of project (defaults to start
                        directory)

What is AndroidX?

androidx will replace support library after 28.0.0. You should migrate your project to use it. androidx uses Semantic Versioning. Using AndroidX will not be confused by version that is presented in library name and package name. Life becomes easier

[AndroidX and support compatibility]

Unable to import a module that is definitely installed

I was able to correct this issue with a combined approach. First, I followed Chris' advice, opened a command line and typed 'pip show packagename' This provided the location of the installed package.

Next, I opened python and typed 'import sys', then 'sys.path' to show where my python searches for any packages I import. Alas, the location shown in the first step was NOT in the list.

Final step, I typed 'sys.path.append('package_location_seen_in_step_1'). You optionally can repeat step two to see the location is now in the list.

Test step, try to import the package again... it works.

The downside? It is temporary, and you need to add it to the list each time.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Often used with/as a part of OOAD and business modeling. The definition by Neil is correct, but it is basically identical to MVC, but just abstracted for the business. The "Good summary" is well done so I will not copy it here as it is not my work, more detailed but inline with Neil's bullet points.

Good summary - Conceito: Entity-Control-Boundary Pattern

OOAD

How to read the value of a private field from a different class in Java?

Use the Soot Java Optimization framework to directly modify the bytecode. http://www.sable.mcgill.ca/soot/

Soot is completely written in Java and works with new Java versions.

Immediate exit of 'while' loop in C++

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

CSS white space at bottom of page despite having both min-height and height tag

It is happening Due to:

<p><script>var _nwls=[];if(window.jQuery&&window.jQuery.find){_nwls=jQuery.find(".fw_link_newWindow");}else{if(document.getElementsByClassName){_nwls=document.getElementsByClassName("fw_link_newWindow");}else{if(document.querySelectorAll){_nwls=document.querySelectorAll(".fw_link_newWindow");}else{document.write('<scr'+'ipt src="http://static.websimages.com/static/global/js/sizzle/sizzle.min.js"><\/scr'+'ipt>');if(window.Sizzle){_nwls=Sizzle(".fw_link_newWindow");}}}}var numlinks=_nwls.length;for(var i=0;i<numlinks;i++){_nwls[i].target="_blank";}</script></p>

Remove <p></p> around the script.

How can I join elements of an array in Bash?

In case the elements you want to join is not an array just a space separated string, you can do something like this:

foo="aa bb cc dd"
bar=`for i in $foo; do printf ",'%s'" $i; done`
bar=${bar:1}
echo $bar
    'aa','bb','cc','dd'

for example, my use case is that some strings are passed in my shell script and I need to use this to run on a SQL query:

./my_script "aa bb cc dd"

In my_script, I need to do "SELECT * FROM table WHERE name IN ('aa','bb','cc','dd'). Then above command will be useful.

node.js + mysql connection pooling

i always use connection.relase(); after pool.getconnetion like

pool.getConnection(function (err, connection) {
      connection.release();
        if (!err)
        {
            console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
            //CHECKING USERNAME EXISTENCE
            email = receivedValues.email
            connection.query('SELECT * FROM users WHERE email = ?', [email],
                function (err, rows) {
                    if (!err)
                    {
                        if (rows.length == 1)
                        {
                            if (bcrypt.compareSync(req.body.password, rows[0].password))
                            {
                                var alldata = rows;
                                var userid = rows[0].id;
                                var tokendata = (receivedValues, userid);
                                var token = jwt.sign(receivedValues, config.secret, {
                                    expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                });
                                console.log("*** Authorised User");
                                res.json({
                                    "code": 200,
                                    "status": "Success",
                                    "token": token,
                                    "userData": alldata,
                                    "message": "Authorised User!"
                                });
                                logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                return;
                            }
                            else
                            {
                                console.log("*** Redirecting: Unauthorised User");
                                res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                logger.error('*** Redirecting: Unauthorised User');
                                return;
                            }
                        }
                        else
                        {
                            console.error("*** Redirecting: No User found with provided name");
                            res.json({
                                "code": 200,
                                "status": "Error",
                                "message": "No User found with provided name"
                            });
                            logger.error('url=', URL.url, 'No User found with provided name');
                            return;
                        }
                    }
                    else
                    {
                        console.log("*** Redirecting: Error for selecting user");
                        res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                        logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                        return;
                    }
                });
            connection.on('error', function (err) {
                console.log('*** Redirecting: Error Creating User...');
                res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                return;
            });
        }
        else
        {
            Errors.Connection_Error(res);
        }
    });

height: calc(100%) not working correctly in CSS

You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.

Following CSS works:

html,body {
    background: blue;
    height:100%;
    padding:0;
    margin:0;
}
header {
    background: red;
    height: 20px;
    width:100%
}
h1 {
    font-size:1.2em;
    margin:0;
    padding:0;
    height: 30px;
    font-weight: bold;
    background:yellow
}
#theCalcDiv {
    background:green;
    height: -moz-calc(100% - (20px + 30px));
    height: -webkit-calc(100% - (20px + 30px));
    height: calc(100% - (20px + 30px));
    display:block
}

I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.

Here's an updated fiddle

http://jsfiddle.net/UF3mb/10/

Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+

What is "X-Content-Type-Options=nosniff"?

Prevent content sniffing where no mimetype is sent

Configuration on Ubuntu 20.04 - apache 2.4.41:

Enable the headers module $ sudo a2enmod headers

Edit file /etc/apache2/conf-available/security.conf and add:

Header always set X-Content-Type-Options: nosniff

Restart Apache $ sudo systemctl restart apache2

$ culr -I localhost

HTTP/1.1 200 OK
Date: Fri, 23 Oct 2020 06:12:16 GMT
Server:  
X-Content-Type-Options: nosniff
Last-Modified: Thu, 22 Oct 2020 08:06:06 GMT

JQuery Redirect to URL after specified time

Use setTimeout function with either of the following

// simulates similar behavior as an HTTP redirect
window.location.replace("http://www.google.com");

// simulates similar behavior as clicking on a link
window.location.href = "http://www.google.com";

setTimeout(function(){
   window.location.replace("http://www.google.com");
}, 1000) 

source: https://www.sitepoint.com/jquery-redirect-web-page/

Normalize data in pandas

In [92]: df
Out[92]:
           a         b          c         d
A  -0.488816  0.863769   4.325608 -4.721202
B -11.937097  2.993993 -12.916784 -1.086236
C  -5.569493  4.672679  -2.168464 -9.315900
D   8.892368  0.932785   4.535396  0.598124

In [93]: df_norm = (df - df.mean()) / (df.max() - df.min())

In [94]: df_norm
Out[94]:
          a         b         c         d
A  0.085789 -0.394348  0.337016 -0.109935
B -0.463830  0.164926 -0.650963  0.256714
C -0.158129  0.605652 -0.035090 -0.573389
D  0.536170 -0.376229  0.349037  0.426611

In [95]: df_norm.mean()
Out[95]:
a   -2.081668e-17
b    4.857226e-17
c    1.734723e-17
d   -1.040834e-17

In [96]: df_norm.max() - df_norm.min()
Out[96]:
a    1
b    1
c    1
d    1

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

Can jQuery get all CSS styles associated with an element?

@marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:

for (var i = 0; i < css.length; i += 1) {
    s[css[i]] = css.getPropertyValue(css[i]);
}

Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Casting int to bool in C/C++

The following cites the C11 standard (final draft).

6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

According to 6.2.5p2:

An object declared as type _Bool is large enough to store the values 0 and 1.

AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

Disable Drag and Drop on HTML elements?

For input elements, this answer works for me.

I implemented it on a custom input component in Angular 4, but I think it could be implemented with pure JS.

HTML

<input type="text" [(ngModel)]="value" (ondragenter)="disableEvent($event)" 
(dragover)="disableEvent($event)" (ondrop)="disableEvent($event)"/>

Component definition (JS):

export class CustomInputComponent { 

  //component construction and attribute definitions

  disableEvent(event) {
    event.preventDefault();
    return false;
  }
}

How to send a html email with the bash command "sendmail"?

Found solution in http://senthilkl.blogspot.lu/2012/11/how-to-send-html-emails-using-sendemail.html

sendEmail -f "oracle@server" -t "[email protected]" -u "Alert: Backup complete" -o message-content-type=html -o message-file=$LOG_FILE  -a $LOG_FILE_ATTACH 

Find and replace string values in list

words = [w.replace('[br]', '<br />') for w in words]

These are called List Comprehensions.

What are the differences between stateless and stateful systems, and how do they impact parallelism?

A stateless system can be seen as a box [black? ;)] where at any point in time the value of the output(s) depends only on the value of the input(s) [after a certain processing time]

A stateful system instead can be seen as a box where at any point in time the value of the output(s) depends on the value of the input(s) and of an internal state, so basicaly a stateful system is like a state machine with "memory" as the same set of input(s) value can generate different output(s) depending on the previous input(s) received by the system.

From the parallel programming point of view, a stateless system, if properly implemented, can be executed by multiple threads/tasks at the same time without any concurrency issue [as an example think of a reentrant function] A stateful system will requires that multiple threads of execution access and update the internal state of the system in an exclusive way, hence there will be a need for a serialization [synchronization] point.

Django Cookies, how can I set them?

UPDATE : check Peter's answer below for a builtin solution :

This is a helper to set a persistent cookie:

import datetime

def set_cookie(response, key, value, days_expire=7):
    if days_expire is None:
        max_age = 365 * 24 * 60 * 60  # one year
    else:
        max_age = days_expire * 24 * 60 * 60
    expires = datetime.datetime.strftime(
        datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
        "%a, %d-%b-%Y %H:%M:%S GMT",
    )
    response.set_cookie(
        key,
        value,
        max_age=max_age,
        expires=expires,
        domain=settings.SESSION_COOKIE_DOMAIN,
        secure=settings.SESSION_COOKIE_SECURE or None,
    )

Use the following code before sending a response.

def view(request):
    response = HttpResponse("hello")
    set_cookie(response, 'name', 'jujule')
    return response

UPDATE : check Peter's answer below for a builtin solution :

What programming languages can one use to develop iPhone, iPod Touch and iPad (iOS) applications?

With plans to slowly retire the long-used Objective-C, Apple has introduced a new programming language, called Swift, for designing apps and applications to run on Apple iOS devices and Apple Macintosh computers.

Apple says: "Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works."

Introducing swift

enter image description here

reCAPTCHA ERROR: Invalid domain for site key

For me, I had simply forgotten to enter the actual domain name in the "Key Settings" area where it says Domains (one per line).

How do I use Join-Path to combine more than two strings into a file path?

Since PowerShell 6.0, Join-Path has a new parameter called -AdditionalChildPath and can combine multiple parts of a path out-of-the-box. Either by providing the extra parameter or by just supplying a list of elements.

Example from the documentation:

Join-Path a b c d e f g
a\b\c\d\e\f\g

So in PowerShell 6.0 and above your variant

$path = Join-Path C: "Program Files" "Microsoft Office"

works as expected!

How to export MySQL database with triggers and procedures?

I've created the following script and it worked for me just fine.

#! /bin/sh
cd $(dirname $0)
DB=$1
DBUSER=$2
DBPASSWD=$3
FILE=$DB-$(date +%F).sql
mysqldump --routines "--user=${DBUSER}"  --password=$DBPASSWD $DB > $PWD/$FILE
gzip $FILE
echo Created $PWD/$FILE*

and you call the script using command line arguments.

backupdb.sh my_db dev_user dev_password

Ways to eliminate switch in code

Everybody loves HUGE if else blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a better solution is debatable.

Language is an important factor here also, I think.

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

C# Version Of SQL LIKE

Add a VB.NET DLL encapsulating the VB.NET Like Operator

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

I had to change the js file, so to include "function()" at the beginning of it, and also "()" at the end line. That solved the problem

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

C#: calling a button event handler method without actually clicking the button

If the method isn't using either sender or e you could call:

btnTest_Click(null, null);

What you probably should consider doing is extracting the code from within that method into its own method, which you could call from both the button click event handler, and any other places in code that the functionality is required.

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

How to get current page URL in MVC 3

For me the issue was when I tried to access HTTPContext in the Controller's constructor while HTTPContext is not ready yet. When moved inside Index method it worked:

var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here

How do I enable saving of filled-in fields on a PDF form?

You can use the free foxit reader to fill in the forms, and if you pay a little you can design the forms that way you want.

You can also us iText to programmaticly create those forms.

There are free online services that allow you to upload a pdf and you can add fields also.

It depends on how you want to do the designing.

EDIT: If you use foxit reader, you can save any form that is fillable.

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

The same result can be achieved using Lodash.

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var result3 = _(result1) _x000D_
        .differenceBy(result2, 'id', 'name')_x000D_
        .map(_.partial(_.pick, _, 'id', 'name'))_x000D_
        .value();_x000D_
_x000D_
console.log(result3);
_x000D_
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

You can get the desired result applying a difference between both arrays using the properties "id" and "name" as a way to "link" elements between them. If any of those properties are different, the elements are considered different (improbably in your case because id seems to be unique).

Lastly, you have to map the result in order to "omit" the undesired properties of the object.

Hope it helps.

Reloading/refreshing Kendo Grid

In my case I had a custom url to go to each time; though the schema of the result would remain the same.
I used the following:

var searchResults = null;
$.ajax({
        url: http://myhost/context/resource,
        dataType: "json",
        success: function (result, textStatus, jqXHR) {
            //massage results and store in searchResults
            searchResults = massageData(result);
        }
    }).done(function() {
        //Kendo grid stuff
        var dataSource = new kendo.data.DataSource({ data: searchResults });
        var grid = $('#doc-list-grid').data('kendoGrid');
        dataSource.read();
        grid.setDataSource(dataSource);
    });

Python 3 ImportError: No module named 'ConfigParser'

You can instead use the mysqlclient package as a drop-in replacement for MySQL-python. It is a fork of MySQL-python with added support for Python 3.

I had luck with simply

pip install mysqlclient

in my python3.4 virtualenv after

sudo apt-get install python3-dev libmysqlclient-dev

which is obviously specific to ubuntu/debian, but I just wanted to share my success :)

Can't access Eclipse marketplace

I was facing the same issue and found here useful steps which saved my time a lot. Hope so below attached image will help you a lot-

Window-> Preferences-> General-> Network Connection

Change Active Provider Native to Manual if problem is not resolved by using the steps mentioned in snapshot. Make sure HTTP/HTTPS should be checked and if any IP is required for your proxy settings then you should provide proxy IP in host and port number as well. enter image description here

System has not been booted with systemd as init system (PID 1). Can't operate

use this command for run every service just write name service for example :

for xrdp :

sudo /etc/init.d/xrdp start

for redis :

sudo /etc/init.d/redis start

(for any other service, check the init.d folder for filenames)

jQuery, checkboxes and .is(":checked")

I'm still experiencing this behavior with jQuery 1.7.2. A simple workaround is to defer the execution of the click handler with setTimeout and let the browser do its magic in the meantime:

$("#myCheckbox").click( function() {
    var that = this;
    setTimeout(function(){
        alert($(that).is(":checked"));
    });
});

Get single row result with Doctrine NativeQuery

Both getSingleResult() and getOneOrNullResult() will throw an exception if there is more than one result. To fix this problem you could add setMaxResults(1) to your query builder.

 $firstSubscriber = $entity->createQueryBuilder()->select('sub')
        ->from("\Application\Entity\Subscriber", 'sub')
        ->where('sub.subscribe=:isSubscribe')
        ->setParameter('isSubscribe', 1)  
        ->setMaxResults(1)
        ->getQuery()
        ->getOneOrNullResult();

What does the keyword Set actually do in VBA?

Set is an Keyword and it is used to assign a reference to an Object in VBA.

For E.g., *Below example shows how to use of Set in VBA.

Dim WS As Worksheet

Set WS = ActiveWorkbook.Worksheets("Sheet1")

WS.Name = "Amit"

How to load GIF image in Swift?

it would be great if somebody told to put gif into any folder instead of assets folder

How can I get the current screen orientation?

getActivity().getResources().getConfiguration().orientation

this command returns int value 1 for Portrait and 2 for Landscape

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

How do I fix the indentation of selected lines in Visual Studio

I like Ctrl+K, Ctrl+D, which indents the whole document.

Set iframe content height to auto resize dynamically

Simple solution:

<iframe onload="this.style.height=this.contentWindow.document.body.scrollHeight + 'px';" ...></iframe>

This works when the iframe and parent window are in the same domain. It does not work when the two are in different domains.

JavaFX - create custom button with image

You just need to create your own class inherited from parent. Place an ImageView on that, and on the mousedown and mouse up events just change the images of the ImageView.

public class ImageButton extends Parent {

    private static final Image NORMAL_IMAGE = ...;
    private static final Image PRESSED_IMAGE = ...;

    private final ImageView iv;

    public ImageButton() {
        this.iv = new ImageView(NORMAL_IMAGE);
        this.getChildren().add(this.iv);

        this.iv.setOnMousePressed(new EventHandler<MouseEvent>() {

            public void handle(MouseEvent evt) {
                iv.setImage(PRESSED_IMAGE);
            }

        });

        // TODO other event handlers like mouse up

    } 

}

How to add empty spaces into MD markdown readme on GitHub?

Markdown really changes everything to html and html collapses spaces so you really can't do anything about it. You have to use the &nbsp; for it. A funny example here that I'm writing in markdown and I'll use couple of         here.

Above there are some &nbsp; without backticks

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

conda env export lists all conda and pip packages in an environment. conda-env must be installed in the conda root (conda install -c conda conda-env).

To write an environment.yml file describing the current environment:

conda env export > environment.yml

References:

Execute JavaScript using Selenium WebDriver in C#

You could also do:

public static IWebElement FindElementByJs(this IWebDriver driver, string jsCommand)
{
    return (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(jsCommand);
}

public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand, int timeoutInSeconds)
{
    if (timeoutInSeconds > 0)
    {
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
        wait.Until(d => d.FindElementByJs(jsCommand));
    }
    return driver.FindElementByJs(jsCommand);
}

public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand)
{
    return FindElementByJsWithWait(driver, jsCommand, s_PageWaitSeconds);
}

Leaflet changing Marker color

Here is the SVG of the icon.

<svg width="28" height="41" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
 <defs>
  <linearGradient id="b">
   <stop stop-color="#2e6c97" offset="0"/>
   <stop stop-color="#3883b7" offset="1"/>
  </linearGradient>
  <linearGradient id="a">
   <stop stop-color="#126fc6" offset="0"/>
   <stop stop-color="#4c9cd1" offset="1"/>
  </linearGradient>
  <linearGradient y2="-0.004651" x2="0.498125" y1="0.971494" x1="0.498125" id="c" xlink:href="#a"/>
  <linearGradient y2="-0.004651" x2="0.415917" y1="0.490437" x1="0.415917" id="d" xlink:href="#b"/>
 </defs>
 <g>
  <title>Layer 1</title>
  <rect id="svg_1" fill="#fff" width="12.625" height="14.5" x="411.279" y="508.575"/>
  <path stroke="url(#d)" id="svg_2" stroke-linecap="round" stroke-width="1.1" fill="url(#c)" d="m14.095833,1.55c-6.846875,0 -12.545833,5.691 -12.545833,11.866c0,2.778 1.629167,6.308 2.80625,8.746l9.69375,17.872l9.647916,-17.872c1.177083,-2.438 2.852083,-5.791 2.852083,-8.746c0,-6.175 -5.607291,-11.866 -12.454166,-11.866zm0,7.155c2.691667,0.017 4.873958,2.122 4.873958,4.71s-2.182292,4.663 -4.873958,4.679c-2.691667,-0.017 -4.873958,-2.09 -4.873958,-4.679c0,-2.588 2.182292,-4.693 4.873958,-4.71z"/>
  <path id="svg_3" fill="none" stroke-opacity="0.122" stroke-linecap="round" stroke-width="1.1" stroke="#fff" d="m347.488007,453.719c-5.944,0 -10.938,5.219 -10.938,10.75c0,2.359 1.443,5.832 2.563,8.25l0.031,0.031l8.313,15.969l8.25,-15.969l0.031,-0.031c1.135,-2.448 2.625,-5.706 2.625,-8.25c0,-5.538 -4.931,-10.75 -10.875,-10.75zm0,4.969c3.168,0.021 5.781,2.601 5.781,5.781c0,3.18 -2.613,5.761 -5.781,5.781c-3.168,-0.02 -5.75,-2.61 -5.75,-5.781c0,-3.172 2.582,-5.761 5.75,-5.781z"/>
 </g>
</svg>

Find files in a folder using Java

To elaborate on this response, Apache IO Utils might save you some time. Consider the following example that will recursively search for a file of a given name:

    File file = FileUtils.listFiles(new File("the/desired/root/path"), 
                new NameFileFilter("filename.ext"), 
                FileFilterUtils.trueFileFilter()
            ).iterator().next();

See:

ListView item background via custom selector

instead of:

android:drawable="@color/transparent" 

write

android:drawable="@android:color/transparent"

How to read json file into java with simple JSON library

You can use Gson for this.
GSON is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

Take a look of this Converting JSON to Java

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

If you have SELINUX enabled, it will prevent this file being created. You need to turn it off.

  1. vi /etc/selinux/config
  2. set SELINUX=disabled
  3. reboot

How do I use Linq to obtain a unique list of properties from a list of objects?

        int[] numbers = {1,2,3,4,5,3,6,4,7,8,9,1,0 };
        var nonRepeats = (from n in numbers select n).Distinct();


        foreach (var d in nonRepeats)
        {

            Response.Write(d);
        }

OUTPUT

1234567890

HTML Form: Select-Option vs Datalist-Option

There is another important difference between select and datalist. Here comes the browser support factor.

select is widely supported by browsers compared to datalist. Please take a look at this page for complete browser support of datalist--

Datalist browser support

Where as select is supported in effectively all browsers (since IE6+, Firefox 2+, Chrome 1+ etc)

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

Implementing a Custom Error page on an ASP.Net website

Try this way, almost same.. but that's what I did, and working.

<configuration>
    <system.web>
       <customErrors mode="On" defaultRedirect="apperror.aspx">
          <error statusCode="404" redirect="404.aspx" />
          <error statusCode="500" redirect="500.aspx" />
       </customErrors>
    </system.web>
</configuration> 

or try to change the 404 error page from IIS settings, if required urgently.

Connect to SQL Server through PDO using SQL Server Driver

Figured this out. Pretty simple:

 new PDO("sqlsrv:server=[sqlservername];Database=[sqlserverdbname]",  "[username]", "[password]");

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

RegEx to extract all matches from string using RegExp.exec

This isn't really going to help with your more complex issue but I'm posting this anyway because it is a simple solution for people that aren't doing a global search like you are.

I've simplified the regex in the answer to be clearer (this is not a solution to your exact problem).

var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);

// We only want the group matches in the array
function purify_regex(reResult){

  // Removes the Regex specific values and clones the array to prevent mutation
  let purifiedArray = [...reResult];

  // Removes the full match value at position 0
  purifiedArray.shift();

  // Returns a pure array without mutating the original regex result
  return purifiedArray;
}

// purifiedResult= ["description", "aoeu"]

That looks more verbose than it is because of the comments, this is what it looks like without comments

var re = /^(.+?):"(.+)"$/
var regExResult = re.exec('description:"aoeu"');
var purifiedResult = purify_regex(regExResult);

function purify_regex(reResult){
  let purifiedArray = [...reResult];
  purifiedArray.shift();
  return purifiedArray;
}

Note that any groups that do not match will be listed in the array as undefined values.

This solution uses the ES6 spread operator to purify the array of regex specific values. You will need to run your code through Babel if you want IE11 support.

python pandas dataframe columns convert to dict key and value

You can also do this if you want to play around with pandas. However, I like punchagan's way.

# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)

# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)

output: {10: 7, 20: 5, 30: 2, 40: 3}

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

I have got the solution for my query:

i have done something like this:

cell.innerHTML="<img height=40 width=40 alt='' src='<%=request.getContextPath()%>/writeImage.htm?' onerror='onImgError(this);' onLoad='setDefaultImage(this);'>"

function setDefaultImage(source){
        var badImg = new Image();
        badImg.src = "video.png";
        var cpyImg = new Image();
        cpyImg.src = source.src;

        if(!cpyImg.width)
        {
            source.src = badImg.src;
        }

    }


    function onImgError(source){
        source.src = "video.png";
        source.onerror = ""; 
        return true; 
    } 

This way it's working in all browsers.

How to navigate to a directory in C:\ with Cygwin?

you can try this

/cygdrive/c/directoryname

"Parameter" vs "Argument"

A parameter is the variable which is part of the method’s signature (method declaration). An argument is an expression used when calling the method.

Consider the following code:

void Foo(int i, float f)
{
    // Do things
}

void Bar()
{
    int anInt = 1;
    Foo(anInt, 2.0);
}

Here i and f are the parameters, and anInt and 2.0 are the arguments.

Fixed header, footer with scrollable content

As of 2013: This would be my approach. jsFiddle:


HTML

<header class="container global-header">
    <h1>Header (fixed)</h1>
</header>

<div class="container main-content">
    <div class="inner-w">
        <h1>Main Content</h1>
    </div><!-- .inner-w -->
</div> <!-- .main-content -->

<footer class="container global-footer">
    <h3>Footer (fixed)</h3>
</footer>


SCSS

// User reset

* { // creates a natural box model layout
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
    box-sizing: border-box; 
} // asume normalize.css


// structure

.container {
    position: relative;
    width: 100%;
    float: left;
    padding: 1em;
}


// type

body {
    font-family: arial;   
}

.main-content {
    h1 {
        font-size: 2em;
        font-weight: bold;
        margin-bottom: .2em;
    }
} // .main-content


// style

    // variables
    $global-header-height: 8em;
    $global-footer-height: 6em;

.global-header {
    position: fixed;
    top: 0; left: 0;
    background-color: gray;
    height: $global-header-height;
}

.main-content {
    background-color: orange;
    margin-top: $global-header-height;
    margin-bottom: $global-footer-height;
    z-index: -1; // so header will be on top
    min-height: 50em; // to make it long so you can see the scrolling
}

.global-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    height: $global-footer-height;
    background-color: gray;
}

Is a new line = \n OR \r\n?

If you are programming in PHP, it is useful to split lines by \n and then trim() each line (provided you don't care about whitespace) to give you a "clean" line regardless.

foreach($line in explode("\n", $data))
{
    $line = trim($line);
    ...
}

Python: How would you save a simple settings/config file?

ConfigParser Basic example

The file can be loaded and used like this:

#!/usr/bin/env python

import ConfigParser
import io

# Load the configuration file
with open("config.yml") as f:
    sample_config = f.read()
config = ConfigParser.RawConfigParser(allow_no_value=True)
config.readfp(io.BytesIO(sample_config))

# List all contents
print("List all contents")
for section in config.sections():
    print("Section: %s" % section)
    for options in config.options(section):
        print("x %s:::%s:::%s" % (options,
                                  config.get(section, options),
                                  str(type(options))))

# Print some contents
print("\nPrint some contents")
print(config.get('other', 'use_anonymous'))  # Just get the value
print(config.getboolean('other', 'use_anonymous'))  # You know the datatype?

which outputs

List all contents
Section: mysql
x host:::localhost:::<type 'str'>
x user:::root:::<type 'str'>
x passwd:::my secret password:::<type 'str'>
x db:::write-math:::<type 'str'>
Section: other
x preprocessing_queue:::["preprocessing.scale_and_center",
"preprocessing.dot_reduction",
"preprocessing.connect_lines"]:::<type 'str'>
x use_anonymous:::yes:::<type 'str'>

Print some contents
yes
True

As you can see, you can use a standard data format that is easy to read and write. Methods like getboolean and getint allow you to get the datatype instead of a simple string.

Writing configuration

import os
configfile_name = "config.yaml"

# Check if there is already a configurtion file
if not os.path.isfile(configfile_name):
    # Create the configuration file as it doesn't exist yet
    cfgfile = open(configfile_name, 'w')

    # Add content to the file
    Config = ConfigParser.ConfigParser()
    Config.add_section('mysql')
    Config.set('mysql', 'host', 'localhost')
    Config.set('mysql', 'user', 'root')
    Config.set('mysql', 'passwd', 'my secret password')
    Config.set('mysql', 'db', 'write-math')
    Config.add_section('other')
    Config.set('other',
               'preprocessing_queue',
               ['preprocessing.scale_and_center',
                'preprocessing.dot_reduction',
                'preprocessing.connect_lines'])
    Config.set('other', 'use_anonymous', True)
    Config.write(cfgfile)
    cfgfile.close()

results in

[mysql]
host = localhost
user = root
passwd = my secret password
db = write-math

[other]
preprocessing_queue = ['preprocessing.scale_and_center', 'preprocessing.dot_reduction', 'preprocessing.connect_lines']
use_anonymous = True

XML Basic example

Seems not to be used at all for configuration files by the Python community. However, parsing / writing XML is easy and there are plenty of possibilities to do so with Python. One is BeautifulSoup:

from BeautifulSoup import BeautifulSoup

with open("config.xml") as f:
    content = f.read()

y = BeautifulSoup(content)
print(y.mysql.host.contents[0])
for tag in y.other.preprocessing_queue:
    print(tag)

where the config.xml might look like this

<config>
    <mysql>
        <host>localhost</host>
        <user>root</user>
        <passwd>my secret password</passwd>
        <db>write-math</db>
    </mysql>
    <other>
        <preprocessing_queue>
            <li>preprocessing.scale_and_center</li>
            <li>preprocessing.dot_reduction</li>
            <li>preprocessing.connect_lines</li>
        </preprocessing_queue>
        <use_anonymous value="true" />
    </other>
</config>

How do browser cookie domains work?

The last (third to be exactly) RFC for this issue is RFC-6265 (Obsoletes RFC-2965 that in turn obsoletes RFC-2109).

According to it if the server omits the Domain attribute, the user agent will return the cookie only to the origin server (the server on which a given resource resides). But it's also warning that some existing user agents treat an absent Domain attribute as if the Domain attribute were present and contained the current host name (For example, if example.com returns a Set-Cookie header without a Domain attribute, these user agents will erroneously send the cookie to www.example.com as well).

When the Domain attribute have been specified, it will be treated as complete domain name (if there is the leading dot in attribute it will be ignored). Server should match the domain specified in attribute (have exactly the same domain name or to be a subdomain of it) to get this cookie. More accurately it specified here.

So, for example:

  • cookie attribute Domain=.example.com is equivalent to Domain=example.com
  • cookies with such Domain attributes will be available for example.com and www.example.com
  • cookies with such Domain attributes will be not available for another-example.com
  • specifying cookie attribute like Domain=www.example.com will close the way for www4.example.com

PS: trailing comma in Domain attribute will cause the user agent to ignore the attribute =(

How to append one DataTable to another DataTable

The datatype in the same columns name must be equals.

dataTable1.Merge(dataTable2);

After that the result is:

dataTable1 = dataTable1 + dataTable2

Close pre-existing figures in matplotlib when running from eclipse

See Bi Rico's answer for the general Eclipse case.

For anybody - like me - who lands here because you have lots of windows and you're struggling to close them all, just killing python can be effective, depending on your circumstances. It probably works under almost any circumstances - including with Eclipse.

I just spawned 60 plots from emacs (I prefer that to eclipse) and then I thought my script had exited. Running close('all') in my ipython window did not work for me because the plots did not come from ipython, so I resorted to looking for running python processes.

When I killed the interpreter running the script, then all 60 plots were closed - e.g.,

$ ps aux | grep python
rsage    11665  0.1  0.6 649904 109692 ?       SNl  10:54   0:03 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
rsage    12111  0.9  0.5 390956 88212 pts/30   Sl+  11:08   0:17 /usr/bin/python /usr/bin/ipython -pylab
rsage    12410 31.8  2.4 576640 406304 pts/33  Sl+  11:38   0:06 python3 ../plot_motor_data.py
rsage    12431  0.0  0.0   8860   648 pts/32   S+   11:38   0:00 grep python

$ kill 12410

Note that I did not kill my ipython/pylab, nor did I kill the update manager (killing the update manager is probably a bad idea)...

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

How to iterate over a std::map full of strings in C++

In c++11 you can use:

for ( auto iter : table ) {
     key=iter->first;
     value=iter->second;
}

Pandas create empty DataFrame with only column names

df.to_html() has a columns parameter.

Just pass the columns into the to_html() method.

df.to_html(columns=['A','B','C','D','E','F','G'])

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

call a function in success of datatable ajax call

For datatables 1.10.12.

$('#table_id').dataTable({
  ajax: function (data, callback, settings) {
    $.ajax({
      url: '/your/url',
      type: 'POST',
      data: data,
      success:function(data){
        callback(data);
        // Do whatever you want.
      }
    });
  }
});

The Import android.support.v7 cannot be resolved

I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:

[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies

I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.

How to fix 'sudo: no tty present and no askpass program specified' error?

Granting the user to use that command without prompting for password should resolve the problem. First open a shell console and type:

sudo visudo

Then edit that file to add to the very end:

username ALL = NOPASSWD: /fullpath/to/command, /fullpath/to/othercommand

eg

john ALL = NOPASSWD: /sbin/poweroff, /sbin/start, /sbin/stop

will allow user john to sudo poweroff, start and stop without being prompted for password.

Look at the bottom of the screen for the keystrokes you need to use in visudo - this is not vi by the way - and exit without saving at the first sign of any problem. Health warning: corrupting this file will have serious consequences, edit with care!

How do I correct this Illegal String Offset?

if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
    if(!isset($data[$field]))
        $data[$field]="";
}

Can I set a breakpoint on 'memory access' in GDB?

Assuming the first answer is referring to the C-like syntax (char *)(0x135700 +0xec1a04f) then the answer to do rwatch *0x135700+0xec1a04f is incorrect. The correct syntax is rwatch *(0x135700+0xec1a04f).

The lack of ()s there caused me a great deal of pain trying to use watchpoints myself.

In a Bash script, how can I exit the entire script if a certain condition occurs?

I have the same question but cannot ask it because it would be a duplicate.

The accepted answer, using exit, does not work when the script is a bit more complicated. If you use a background process to check for the condition, exit only exits that process, as it runs in a sub-shell. To kill the script, you have to explicitly kill it (at least that is the only way I know).

Here is a little script on how to do it:

#!/bin/bash

boom() {
    while true; do sleep 1.2; echo boom; done
}

f() {
    echo Hello
    N=0
    while
        ((N++ <10))
    do
        sleep 1
        echo $N
        #        ((N > 5)) && exit 4 # does not work
        ((N > 5)) && { kill -9 $$; exit 5; } # works 
    done
}

boom &
f &

while true; do sleep 0.5; echo beep; done

This is a better answer but still incomplete a I really don't know how to get rid of the boom part.

PHP multiline string with PHP

You cannot run PHP code within a string like that. It just doesn't work. As well, when you're "out" of PHP code (?>), any text outside of the PHP blocks is considered output anyway, so there's no need for the echo statement.

If you do need to do multiline output from with a chunk of PHP code, consider using a HEREDOC:

<?php

$var = 'Howdy';

echo <<<EOL
This is output
And this is a new line
blah blah blah and this following $var will actually say Howdy as well

and now the output ends
EOL;

Jackson: how to prevent field serialization

Jackson has a class named SimpleBeanPropertyFilter that helps to filter fields during serialization and deserialization; not globally. I think that's what you wanted.

@JsonFilter("custom_serializer")
class User {
    private String password;

    //setter, getter..
}

Then in your code:

String[] fieldsToSkip = new String[] { "password" };

ObjectMapper mapper = new ObjectMapper();

final SimpleFilterProvider filter = new SimpleFilterProvider();
filter.addFilter("custom_serializer",
            SimpleBeanPropertyFilter.serializeAllExcept(fieldsToSkip));

mapper.setFilters(filter);

String jsonStr = mapper.writeValueAsString(currentUser);

This will prevent password field to get serialized. Also you will be able to deserialize password fields as it is. Just make sure no filters are applied on the ObjectMapper object.

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(yourJsonStr, User.class);    // user object does have non-null password field

Dark theme in Netbeans 7 or 8

There is no more plugin in netbeans 12. In case someone comes to this page. Tools->Options->Appearance->Look and feel->Flatlaf Dark

enter image description here

Skipping every other element after the first

def skip_elements(elements):
    # code goes here
    new_list=[]
    for index,alpha in enumerate(elements):
        if index%2==0:
            new_list.append(alpha)
    return new_list


print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))  
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))  

change cursor from block or rectangle to line?

You're in replace mode. Press the Insert key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.

Maximum filename length in NTFS (Windows XP and Windows Vista)?

199 on Windows XP NTFS, I just checked.

This is not theory but from just trying on my laptop. There may be mitigating effects, but it physically won't let me make it bigger.

Is there some other setting limiting this, I wonder? Try it for yourself.

"Cannot GET /" with Connect on Node.js

Had the same issue. It was resolved as described above.

In my index.js

var port = 1338,
express = require('express'),
app = express().use(express.static(__dirname + '/')),
http = require('http').Server(app),
io = require('socket.io')(http);

app.get('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
    console.log('a user connected');
});

http.listen(port, function(){
    console.log("Node server listening on port " + port);
});

and in my index.html

<!doctype html>
<html>
    <head>
        <title>
            My page
        </title>
    </head>
    <body>
        <script src = "lib/socket.io.js"></script>
        <script src = "lib/three.js"></script>
        <script>
            var socket = io();
        </script>
    </body>
</html>

the three.js was just in there for path testing. This will set all child files to start at the root directory of your app. Also socket.io.js can be called automatically using <script src = "/socket.io/socket.io.js"> through some dark magic (since there is physically a node_modules and lib directory in between) .

What is a Python equivalent of PHP's var_dump()?

I wrote a very light-weight alternative to PHP's var_dump for using in Python and made it open source later.

GitHub: https://github.com/sha256/python-var-dump

You can simply install it using pip:

pip install var_dump

How to find Max Date in List<Object>?

Since you are asking for lambdas, you can use the following syntax with Java 8:

Date maxDate = list.stream().map(u -> u.date).max(Date::compareTo).get();

or, if you have a getter for the date:

Date maxDate = list.stream().map(User::getDate).max(Date::compareTo).get();

Finding out the name of the original repository you cloned from in Git

In the repository root, the .git/config file holds all information about remote repositories and branches. In your example, you should look for something like:

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = server:gitRepo.git

Also, the Git command git remote -v shows the remote repository name and URL. The "origin" remote repository usually corresponds to the original repository, from which the local copy was cloned.

In Node.js, how do I turn a string to a json?

use the JSON function >

JSON.parse(theString)

HashMap with multiple values under the same key

Apache Commons collection classes can implement multiple values under same key.

MultiMap multiMapDemo = new MultiValueMap();

multiMapDemo .put("fruit", "Mango");
multiMapDemo .put("fruit", "Orange");
multiMapDemo.put("fruit", "Blueberry");

System.out.println(multiMapDemo.get("fruit"));

Maven Dependency

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-collections4 -->
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-collections4</artifactId>
   <version>4.4</version>
</dependency>

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

You need the oracle client driver installed for those classes to work.

There might be 3rd party connection frameworks out there that can handle Oracle, perhaps someone else might know of some specific ones.

How to insert values in table with foreign key using MySQL?

Case 1: Insert Row and Query Foreign Key

Here is an alternate syntax I use:

INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = (
       SELECT id_teacher
         FROM tab_teacher
        WHERE name_teacher = 'Dr. Smith')

I'm doing this in Excel to import a pivot table to a dimension table and a fact table in SQL so you can import to both department and expenses tables from the following:

enter image description here

Case 2: Insert Row and Then Insert Dependant Row

Luckily, MySQL supports LAST_INSERT_ID() exactly for this purpose.

INSERT INTO tab_teacher
   SET name_teacher = 'Dr. Smith';
INSERT INTO tab_student 
   SET name_student = 'Bobby Tables',
       id_teacher_fk = LAST_INSERT_ID()

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Why do access tokens expire?

This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?

  • Many providers support bearer tokens which are very weak security-wise. By making them short-lived and requiring refresh, they limit the time an attacker can abuse a stolen token.
  • Large scale deployment don't want to perform a database lookup every API call, so instead they issue self-encoded access token which can be verified by decryption. However, this also means there is no way to revoke these tokens so they are issued for a short time and must be refreshed.
  • The refresh token requires client authentication which makes it stronger. Unlike the above access tokens, it is usually implemented with a database lookup.

Clearfix with twitter bootstrap

clearfix should contain the floating elements but in your html you have added clearfix only after floating right that is your pull-right so you should do like this:

<div class="clearfix">
  <div id="sidebar">
    <ul>
      <li>A</li>
      <li>A</li>
      <li>C</li>
      <li>D</li>
      <li>E</li>
      <li>F</li>
      <li>...</li>
      <li>Z</li>
    </ul>
  </div>
  <div id="main">
    <div>
      <div class="pull-right">
        <a>RIGHT</a>
      </div>
    </div>
  <div>MOVED BELOW Z</div>
</div>

see this demo


Happy to know you solved the problem by setting overflow properties. However this is also good idea to clear the float. Where you have floated your elements you could add overflow: hidden; as you have done in your main.

SQLite string contains other string query

While LIKE is suitable for this case, a more general purpose solution is to use instr, which doesn't require characters in the search string to be escaped. Note: instr is available starting from Sqlite 3.7.15.

SELECT *
  FROM TABLE  
 WHERE instr(column, 'cats') > 0;

Also, keep in mind that LIKE is case-insensitive, whereas instr is case-sensitive.

Java way to check if a string is palindrome

 public boolean isPalindrom(String text) {
    StringBuffer stringBuffer = new StringBuffer(text);
     return stringBuffer.reverse().toString().equals(text);
}

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

I assume that you have a .cer file containing PKCS#7-encoded certificate data and you want to convert it to PEM-encoded certificate data (typically a .crt or .pem file). For instance, a .cer file containing PKCS#7-encoded data looks like this:

-----BEGIN PKCS7-----
MIIW4gYJKoZIhvcNAQcCoIIW0zCCFs8CAQExADALBgkqhkiG9w0BBwGggha1MIIH
...
POI9n9cd2cNgQ4xYDiKWL2KjLB+6rQXvqzJ4h6BUcxm1XAX5Uj5tLUUL9wqT6u0G
+bKhADEA
-----END PKCS7-----

PEM certificate data looks like this:

-----BEGIN CERTIFICATE-----
MIIHNjCCBh6gAwIBAgIQAlBxtqKazsxUSR9QdWWxaDANBgkqhkiG9w0BAQUFADBm
...
nv72c/OV4nlyrvBLPoaS5JFUJvFUG8RfAEY=
-----END CERTIFICATE-----

There is an OpenSSL command that will convert .cer files (with PKCS#7 data) to the PEM data you may be expecting to encounter (the BEGIN CERTIFICATE block in the example above). You can coerce PKCS#7 data into PEM format by this command on a file we'll call certfile.cer:

openssl pkcs7 -text -in certfile.cer -print_certs -outform PEM -out certfile.pem

Note that a .cer or .pem file might contain one or more certificates (possibly the entire certificate chain).

How to convert string representation of list to a list?

If it's only a one dimensional list, this can be done without importing anything:

>>> x = u'[ "A","B","C" , " D"]'
>>> ls = x.strip('[]').replace('"', '').replace(' ', '').split(',')
>>> ls
['A', 'B', 'C', 'D']

Using R to download zipped data file, extract, and import data

Here is an example that works for files which cannot be read in with the read.table function. This example reads a .xls file.

url <-"https://www1.toronto.ca/City_Of_Toronto/Information_Technology/Open_Data/Data_Sets/Assets/Files/fire_stns.zip"

temp <- tempfile()
temp2 <- tempfile()

download.file(url, temp)
unzip(zipfile = temp, exdir = temp2)
data <- read_xls(file.path(temp2, "fire station x_y.xls"))

unlink(c(temp, temp2))

How to break out of nested loops?

int i = 0, j= 0;

for(i;i< 1000; i++){    
    for(j; j< 1000; j++){
        if(condition){
            i = j = 1001;
            break;
        }
    }
}

Will break both the loops.

How to get last N records with activerecord?

For Rails 5 (and likely Rails 4)

Bad:

Something.last(5)

because:

Something.last(5).class
=> Array

so:

Something.last(50000).count

will likely blow up your memory or take forever.

Good approach:

Something.limit(5).order('id desc')

because:

Something.limit(5).order('id desc').class
=> Image::ActiveRecord_Relation

Something.limit(5).order('id desc').to_sql
=> "SELECT  \"somethings\".* FROM \"somethings\" ORDER BY id desc LIMIT 5"

The latter is an unevaluated scope. You can chain it, or convert it to an array via .to_a. So:

Something.limit(50000).order('id desc').count

... takes a second.

Determine a user's timezone

Here is a robust JavaScript solution to determine the time zone the browser is in.

>>> var timezone = jstz.determine();
>>> timezone.name(); 
"Europe/London"

https://github.com/pellepim/jstimezonedetect

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

Use a JSON array with objects with javascript

Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:

if you have the JSON string as above then you'd just need to do this

var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');

then you can access these vars with something like jsonObj[0].id etc

Let me know if that's not what you were getting at and I'll try to help.

M

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

How do you specify a byte literal in Java?

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

Convert a string to a datetime

You should have to use Date.ParseExact or Date.TryParseExact with correct format string.

 Dim edate = "10/12/2009"
 Dim expenddt As Date = Date.ParseExact(edate, "dd/MM/yyyy", 
            System.Globalization.DateTimeFormatInfo.InvariantInfo)

OR

 Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
 Dim expenddt As Date = Date.ParseExact(edate, format,  
     System.Globalization.DateTimeFormatInfo.InvariantInfo, 
     Globalization.DateTimeStyles.None)

OR

Dim format() = {"dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy"}
Dim expenddt As Date
Date.TryParseExact(edate, format, 
    System.Globalization.DateTimeFormatInfo.InvariantInfo, 
    Globalization.DateTimeStyles.None, expenddt)

Get folder name from full file path

Simply use Path.GetFileName

Here - Extract folder name from the full path of a folder:

string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"

Here is some extra - Extract folder name from the full path of a file:

string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Replace

new Timestamp();

with

new java.util.Date()

because there is no default constructor for Timestamp, or you can do it with the method:

new Timestamp(System.currentTimeMillis());

How to find the cumulative sum of numbers in a list?

First, you want a running list of subsequences:

subseqs = (seq[:i] for i in range(1, len(seq)+1))

Then you just call sum on each subsequence:

sums = [sum(subseq) for subseq in subseqs]

(This isn't the most efficient way to do it, because you're adding all of the prefixes repeatedly. But that probably won't matter for most use cases, and it's easier to understand if you don't have to think of the running totals.)

If you're using Python 3.2 or newer, you can use itertools.accumulate to do it for you:

sums = itertools.accumulate(seq)

And if you're using 3.1 or earlier, you can just copy the "equivalent to" source straight out of the docs (except for changing next(it) to it.next() for 2.5 and earlier).

How to check ASP.NET Version loaded on a system?

You can see which version gets executed when you load the page with Google Chrome + developer tools (preinstalled) or Firefox + Firebug (add-on).

I use Google Chrome:

  1. Open Chrome and use Ctrl+Shift+I to open the developer tools.
  2. Go to the "Network" Tab
  3. Click on the small button at the bottom "Preserve log upon Navigation"
  4. Load any of your pages
  5. Click on the response header

It looks like this:

enter image description here

Why is it said that "HTTP is a stateless protocol"?

If protocol HTTP is given as State full protocol,browser window uses single connection to communicate with web server for multiple request given to web application.this gives chance to browser window to engage the connections between browser window and web servers for long time and to keep them in idle state for long time.This may create the situation of reaching to maximum connections of web server even though most of the connections in clients are idle.

reading from stdin in c++

You have not defined the variable input_line.

Add this:

string input_line;

And add this include.

#include <string>

Here is the full example. I also removed the semi-colon after the while loop, and you should have getline inside the while to properly detect the end of the stream.

#include <iostream>
#include <string>

int main() {
    for (std::string line; std::getline(std::cin, line);) {
        std::cout << line << std::endl;
    }
    return 0;
}

can you add HTTPS functionality to a python flask web server?

If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.

Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.

https://ngrok.com/product

It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]

It will then open up a window in terminal giving you both an http and https url to access your web app.

Multiple select in Visual Studio?

From Visual Studio 2017 Version 15.8, Ctrl + Alt + Click is now supposed to be a built-in way to manage multiple carets.

https://blogs.msdn.microsoft.com/visualstudio/2018/08/30/improving-your-productivity-in-the-visual-studio-editor/

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

Combine GET and POST request methods in Spring

@RequestMapping(value = "/books", method = { RequestMethod.GET, 
RequestMethod.POST })
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,
     HttpServletRequest request) 
    throws ParseException {

//your code 
}

This will works for both GET and POST.

For GET if your pojo(BooksFilter) have to contain the attribute which you're using in request parameter

like below

public class BooksFilter{

private String parameter1;
private String parameter2;

   //getters and setters

URl should be like below

/books?parameter1=blah

Like this way u can use it for both GET and POST

Variable name as a string in Javascript

This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

_x000D_
_x000D_
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };_x000D_
var myFirstName = 'Chuck';_x000D_
var varname = nameof(function () { return window.myFirstName; });_x000D_
console.log(varname);
_x000D_
_x000D_
_x000D_

Android Error - Open Failed ENOENT

Put the text file in the assets directory. If there isnt an assets dir create one in the root of the project. Then you can use Context.getAssets().open("BlockForTest.txt"); to open a stream to this file.

How to remove symbols from a string with Python?

One way, using regular expressions:

>>> s = "how much for the maple syrup? $20.99? That's ridiculous!!!"
>>> re.sub(r'[^\w]', ' ', s)
'how much for the maple syrup   20 99  That s ridiculous   '
  • \w will match alphanumeric characters and underscores

  • [^\w] will match anything that's not alphanumeric or underscore

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

I noticed one error in Dave Ward's answer (perhaps a recent change?): The query string paramaters are in request.query, not request.params. (See https://stackoverflow.com/a/6913287/166530 )

request.params by default is filled with the value of any "component matches" in routes, i.e.

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

and, if you have configured express to use its bodyparser (app.use(express.bodyParser());) also with POST'ed formdata. (See How to retrieve POST query parameters? )

How can change width of dropdown list?

This worked for me:

ul.dropdown-menu > li {
    max-width: 144px;
}

in Chromium and Firefox.

Can't use Swift classes inside Objective-C

I didnt have to change any settings in the build or add @obj to the class.

All I had to do was to create bridge-header which was automatically created when I created Swift classes into Objective-c project. And then I just had to do

import "Bedtime-Swift.h" <- inside objective-c file that needed to use that swift file.

How do I check if an HTML element is empty using jQuery?

Empty as in contains no text?

if (!$('#element').text().length) {
    ...
}

Removing display of row names from data frame

My answer is intended for comment though but since i havent got enough reputation, i think it will still be relevant as an answer and help some one.

I find datatable in library DT robust to handle rownames, and columnames

Library DT
datatable(df, rownames = FALSE)  # no row names 

refer to https://rstudio.github.io/DT/ for usage scenarios

How to collapse blocks of code in Eclipse?

I was using salesforce apex classes with Eclipse Neon 3.3 for Java.
I found an option "define folding region" on right click in the editor, I selected the block of code i wanted to collapse and selected this property for that code. Now I am seeing + and - symbol to expand and collapse that block of code

How can I solve ORA-00911: invalid character error?

I'm using a 3rd party program that executes Oracle SQL and I encountered this error. Prior to a SELECT statement, I had some commented notes that included special characters. Removing the comments resolved the issue.

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

json.loads will load a json string into a python dict, json.dumps will dump a python dict to a json string, for example:

>>> json_string = '{"favorited": false, "contributors": null}'
'{"favorited": false, "contributors": null}'
>>> value = json.loads(json_string)
{u'favorited': False, u'contributors': None}
>>> json_dump = json.dumps(value)
'{"favorited": false, "contributors": null}'

So that line is incorrect since you are trying to load a python dict, and json.loads is expecting a valid json string which should have <type 'str'>.

So if you are trying to load the json, you should change what you are loading to look like the json_string above, or you should be dumping it. This is just my best guess from the given information. What is it that you are trying to accomplish?

Also you don't need to specify the u before your strings, as @Cld mentioned in the comments.

Groovy executing shell commands

To add one more important information to above provided answers -

For a process

def proc = command.execute();

always try to use

def outputStream = new StringBuffer();
proc.waitForProcessOutput(outputStream, System.err)
//proc.waitForProcessOutput(System.out, System.err)

rather than

def output = proc.in.text;

to capture the outputs after executing commands in groovy as the latter is a blocking call (SO question for reason).

Combining node.js and Python

I've had a lot of success using thoonk.js along with thoonk.py. Thoonk leverages Redis (in-memory key-value store) to give you feed (think publish/subscribe), queue and job patterns for communication.

Why is this better than unix sockets or direct tcp sockets? Overall performance may be decreased a little, however Thoonk provides a really simple API that simplifies having to manually deal with a socket. Thoonk also helps make it really trivial to implement a distributed computing model that allows you to scale your python workers to increase performance, since you just spin up new instances of your python workers and connect them to the same redis server.

Palindrome check in Javascript

function palindromCheck(str) {
    var palinArr, i,
        palindrom = [],

    palinArr = str.split(/[\s!.?,;:'"-()]/ig);

    for (i = 0; i < palinArr.length; i++) {
        if (palinArr[i].toLowerCase() === palinArr[i].split('').reverse().join('').toLowerCase() &&
            palinArr[i] !== '') {
            palindrom.push(palinArr[i]);
        }
    }
        return palindrom.join(', ');
}
console.log(palindromCheck('There is a man, his name! was Bob.')); //a, Bob

Finds and upper to lower case. Split string into array, I don't know why a few white spaces remain, but I wanted to catch and single letters.

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

How do I connect to a specific Wi-Fi network in Android programmatically?

This is an activity you can subclass to force the connecting to a specific wifi: https://github.com/zoltanersek/android-wifi-activity/blob/master/app/src/main/java/com/zoltanersek/androidwifiactivity/WifiActivity.java

You will need to subclass this activity and implement its methods:

public class SampleActivity extends WifiBaseActivity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  }

  @Override
  protected int getSecondsTimeout() {
      return 10;
  }

  @Override
  protected String getWifiSSID() {
      return "WifiNetwork";
  }

  @Override
  protected String getWifiPass() {
      return "123456";
  }
}

Converting a Java Keystore into PEM Format

I kept getting errors from openssl when using StoBor's command:

MAC verified OK
Error outputting keys and certificates
139940235364168:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:evp_enc.c:535:
139940235364168:error:23077074:PKCS12 routines:PKCS12_pbe_crypt:pkcs12 cipherfinal error:p12_decr.c:97:
139940235364168:error:2306A075:PKCS12 routines:PKCS12_item_decrypt_d2i:pkcs12 pbe crypt error:p12_decr.c:123:

For some reason, only this style of command would work for my JKS file

keytool -importkeystore -srckeystore foo.jks \
   -destkeystore foo.p12 \
   -srcstoretype jks \
   -srcalias mykey \
   -deststoretype pkcs12 \
   -destkeypass DUMMY123

The key was setting destkeypass, the value of the argument did not matter.

How to get last inserted id?

If you're using executeScalar:

cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();

How to search in an array with preg_match?

$haystack = array (
   'say hello',
   'hello stackoverflow',
   'hello world',
   'foo bar bas'
);

$matches  = preg_grep('/hello/i', $haystack);

print_r($matches);

Output

Array
(
    [1] => say hello
    [2] => hello stackoverflow
    [3] => hello world
)

Subtract minute from DateTime in SQL Server 2005

Have you tried

SELECT DATEADD(mi, -15,'2000-01-01 08:30:00')

DATEDIFF is the difference between 2 dates.

How to split a long array into smaller arrays, with JavaScript

const originalArr = [1,2,3,4,5,6,7,8,9,10,11];
const splittedArray = [];
  while (originalArr.length > 0) {
    splittedArray.push(originalArr.splice(0,range));  
  }

output for range 3

splittedArray === [[1,2,3][4,5,6][7,8,9][10,11]]

output for range 4

splittedArray === [[1,2,3,4][5,6,7,8][9,10,11]]

NoClassDefFoundError - Eclipse and Android

If you change your order and export in your project build path, this error will not occur. The other way of achieving it is through .classpath in your project folder.

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

Also - please note that you may have transparency set even if you don't actually have any transparency in your images. If you're using photoshop, 'save for web' and de-select 'transparency' or just convert your image to a .jpg. iTunes Connect seems to reject transparencies as well.

How does autowiring work in Spring?

In simple words Autowiring, wiring links automatically, now comes the question who does this and which kind of wiring. Answer is: Container does this and Secondary type of wiring is supported, primitives need to be done manually.

Question: How container know what type of wiring ?

Answer: We define it as byType,byName,constructor.

Question: Is there are way we do not define type of autowiring ?

Answer: Yes, it's there by doing one annotation, @Autowired.

Question: But how system know, I need to pick this type of secondary data ?

Answer: You will provide that data in you spring.xml file or by using sterotype annotations to your class so that container can themselves create the objects for you.

ng: command not found while creating new project using angular-cli

This is how I made it worked for me :).

1 - npm link @angular/cli

It will return you the path of cli, which will look like this

/usr/local/Cellar/node/11.3.0_1/lib/node_modules/@angular/cli

For this part, /11.3.0_1 please replace this with your respective node version that can be found by typing node --version

2 - cd ~/

3 - open .bash_profile

In the bash profile create an alias for cli like this,

alias ng="/usr/local/Cellar/node/11.3.0_1/lib/node_modules/@angular/cli/bin/ng"

4 - source ~/.bash_profile

This is how your .bash_profile will look like once you add alias to it.

enter image description here

Now typing ng in the terminal will display output shown in attached snapshot.

enter image description here

I hope this answer will be helpful.

System.loadLibrary(...) couldn't find native library in my case

The reason for this error is because there is a mismatch of the ABI between your app and the native library you linked against. Another words, your app and your .so is targeting different ABI.

if you create your app using latest Android Studio templates, its probably targeting the arm64-v8a but your .so may be targeting armeabi-v7a for example.

There is 2 way to solve this problem:

  1. build your native libraries for each ABI your app support.
  2. change your app to target older ABI that your .so built against.

Choice 2 is dirty but I think you probably have more interested in:

change your app's build.gradle

android {
    defaultConfig {
        ...
        ndk {
            abiFilters 'armeabi-v7a'
        }
   }
}

How to interpolate variables in strings in JavaScript, without concatenation?

Don't see any external libraries mentioned here, but Lodash has _.template(),

https://lodash.com/docs/4.17.10#template

If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm npm install lodash.template so you can cut down overhead.

Simplest form -

var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'

There are a bunch of configuration options also -

_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'

I found custom delimiters most interesting.

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.