Programs & Examples On #Drupal permissions

User permissions refers to the permissions defined by modules to allow users to do specific actions defined from modules. It is different from "file permissions," which are the access permissions users have for files in a file system.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

I encountered the same problem with Android devices but not iOS devices. Managed to resolve by specifying position:relative in the outer div of the absolutely positioned elements (with overflow:hidden for outer div)

Open existing file, append a single line

//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
   stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
   stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
   stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
   stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

if you use Bootstrap 2.2.1 then maybe is this what you are looking for.

Sample file index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title></title>_x000D_
    <link href="Content/bootstrap.min.css" rel="stylesheet" />_x000D_
    <link href="Content/Site.css" rel="stylesheet" />_x000D_
</head>_x000D_
<body>_x000D_
    <menu>_x000D_
        <div class="navbar navbar-default navbar-fixed-top">_x000D_
            <div class="container">_x000D_
                <div class="navbar-header">_x000D_
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
                    <a class="navbar-brand" href="/">Application name</a>_x000D_
                </div>_x000D_
                <div class="navbar-collapse collapse">_x000D_
                    <ul class="nav navbar-nav">_x000D_
                        <li><a href="/">Home</a></li>_x000D_
                        <li><a href="/Home/About">About</a></li>_x000D_
                        <li><a href="/Home/Contact">Contact</a></li>_x000D_
                    </ul>_x000D_
                    <ul class="nav navbar-nav navbar-right">_x000D_
                        <li><a href="/Account/Register" id="registerLink">Register</a></li>_x000D_
                        <li><a href="/Account/Login" id="loginLink">Log in</a></li>_x000D_
                    </ul>_x000D_
_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </menu>_x000D_
_x000D_
    <nav>_x000D_
        <div class="col-md-2">_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
            <a href="#" class="btn btn-block btn-info">Some Menu</a>_x000D_
        </div>_x000D_
_x000D_
    </nav>_x000D_
    <content>_x000D_
       <div class="col-md-10">_x000D_
_x000D_
               <h2>About.</h2>_x000D_
               <h3>Your application description page.</h3>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <p>Use this area to provide additional information.</p>_x000D_
               <hr />_x000D_
       </div>_x000D_
    </content>_x000D_
_x000D_
    <footer>_x000D_
        <div class="navbar navbar-default navbar-fixed-bottom">_x000D_
            <div class="container" style="font-size: .8em">_x000D_
                <p class="navbar-text">_x000D_
                    &copy; Some info_x000D_
                </p>_x000D_
            </div>_x000D_
        </div>_x000D_
    </footer>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_ File Content/Site.css
_x000D_
_x000D_
body {_x000D_
    padding-bottom: 70px;_x000D_
    padding-top: 70px;_x000D_
}
_x000D_
_x000D_
_x000D_

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

How to test if JSON object is empty in Java

I would do the following to check for an empty object

obj.similar(new JSONObject())

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

If you want to compare file in your project/directory with an external file (which is by the way the most common way I used to compare files) you can easily drag and drop the external file into the editor's tab and just use the command: "Compare Active File With..." on one of them selecting the other one in the newly popped up choice window. That seems to be the fastest way.

How does facebook, gmail send the real time notification?

One important issue with long polling is error handling. There are two types of errors:

  1. The request might timeout in which case the client should reestablish the connection immediately. This is a normal event in long polling when no messages have arrived.

  2. A network error or an execution error. This is an actual error which the client should gracefully accept and wait for the server to come back on-line.

The main issue is that if your error handler reestablishes the connection immediately also for a type 2 error, the clients would DOS the server.

Both answers with code sample miss this.

function longPoll() { 
        var shouldDelay = false;

        $.ajax({
            url: 'poll.php',
            async: true,            // by default, it's async, but...
            dataType: 'json',       // or the dataType you are working with
            timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
            cache: false

        }).done(function (data, textStatus, jqXHR) {
             // do something with data...

        }).fail(function (jqXHR, textStatus, errorThrown ) {
            shouldDelay = textStatus !== "timeout";

        }).always(function() {
            // in case of network error. throttle otherwise we DOS ourselves. If it was a timeout, its normal operation. go again.
            var delay = shouldDelay ? 10000: 0;
            window.setTimeout(longPoll, delay);
        });
}
longPoll(); //fire first handler

Subversion ignoring "--password" and "--username" options

Look to your local svn repo and look into directory .svn . there is file: entries look into them and you'll see lines begins with: svn+ssh://

this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'

if you want to change this, te best way is completly refresh this repository. update/commit what you should for save work. then remove completly directory and last step is create this by svn co/checkout 'URI-for-main-repo' [optionally local directory for store]

you should select connection method to repo file:// svn+ssh:// http:// https:// or other described in documentation.

after that you use svn update/commit as usual.

this topic looks like out of topic. better you go to superuser pages.

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

Apply these two things.

  1. You need to set the character set of your database to be utf8.

  2. You need to call the mysql_set_charset('utf8') in the file where you made the connection with the database and right after the selection of database like mysql_select_db use the mysql_set_charset. That will allow you to add and retrieve data properly in whatever the language.

ValueError: setting an array element with a sequence

In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:

print([i for i,x in enumerate(list) if len(x) != 560])

In my case, the length reference was 560.

Django set default form values

I hope this can help you:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id

The current .NET SDK does not support targeting .NET Standard 2.0 error in Visual Studio 2017 update 15.3

I had this issue while trying to build my solution in TFS. We were using "dot net publish" task. Using msbuild broke the ice for us.

Cannot start MongoDB as a service

I ran this command:

C:\MongoDB\Server\3.4\bin>net start MongoDB

And got this message:

The service is not responding to the control function. More help is available by typing NET HELPMSG 2186.

After some trials and errors, I noticed when following the tutorial it asked me to name my file mongod.conf but the command was trying to refer to mongod.cfg.

As soon as I corrected that name and re-run the commands,

C:\MongoDB\Server\3.4\bin>sc.exe delete MongoDB
[SC] DeleteService SUCCESS

C:\MongoDB\Server\3.4\bin>sc.exe create MongoDB binPath= "\"C:\MongoDB\Server\3.4\bin\mongod.exe\" --service --config=\"C:\MongoDB\Server\3.4\mongod.cfg\"" DisplayName= "MongoDB" start= "auto"
[SC] CreateService SUCCESS

C:\MongoDB\Server\3.4\bin>net start MongoDB
The MongoDB service is starting....
The MongoDB service was started successfully.

The service started running fine.

Is it correct to use alt tag for an anchor link?

I'm surprised to see all answers stating the use of alt attribute in a tag is not valid. This is absolutely wrong.

Html does not block you using any attributes:

<a your-custom-attribute="value">Any attribute can be used</a>

If you ask if it is semantically correct to use alt attribute in a then I will say:

NO. It is used to set image description <img alt="image description" />.

It is a matter of what you'd do with the attributes. Here's an example:

_x000D_
_x000D_
a::after {_x000D_
  content: attr(color); /* attr can be used as content */_x000D_
  display: block;_x000D_
  color: white;_x000D_
  background-color: blue;_x000D_
  background-color: attr(color); /* This won't work */_x000D_
  display: none;_x000D_
}_x000D_
a:hover::after {_x000D_
  display: block;_x000D_
}_x000D_
[hidden] {_x000D_
  display: none;_x000D_
}
_x000D_
<a href="#" color="red">Hover me!</a>_x000D_
<a href="#" color="red" hidden>In some cases, it can be used to hide it!</a>
_x000D_
_x000D_
_x000D_

Again, if you ask if it is semantically correct to use custom attribute then I will say:

No. Use data-* attributes for its semantic use.


Oops, question was asked in 2013.

Truncate a string straight JavaScript

in case you want to truncate by word.

_x000D_
_x000D_
function limit(str, limit, end) {_x000D_
_x000D_
      limit = (limit)? limit : 100;_x000D_
      end = (end)? end : '...';_x000D_
      str = str.split(' ');_x000D_
      _x000D_
      if (str.length > limit) {_x000D_
        var cutTolimit = str.slice(0, limit);_x000D_
        return cutTolimit.join(' ') + ' ' + end;_x000D_
      }_x000D_
_x000D_
      return str.join(' ');_x000D_
    }_x000D_
_x000D_
    var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);_x000D_
_x000D_
    console.log(limit);
_x000D_
_x000D_
_x000D_

Vue.js : How to set a unique ID for each component instance?

To Nihat's point (above): Evan You has advised against using _uid: "The vm _uid is reserved for internal use and it's important to keep it private (and not rely on it in user code) so that we keep the flexibility to change its behavior for potential future use cases. ... I'd suggest generating UIDs yourself [using a module, a global mixin, etc.]"

Using the suggested mixin in this GitHub issue to generate the UID seems like a better approach:

let uuid = 0;

export default {
  beforeCreate() {
    this.uuid = uuid.toString();
    uuid += 1;
  },
};

How can I create an Asynchronous function in Javascript?

Function.prototype.applyAsync = function(params, cb){
      var function_context = this;
      setTimeout(function(){
          var val = function_context.apply(undefined, params); 
          if(cb) cb(val);
      }, 0);
}

// usage
var double = function(n){return 2*n;};
var display = function(){console.log(arguments); return undefined;};
double.applyAsync([3], display);

Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:

  • it allows for parameters to the functions
  • it passes the output of the function to the callback
  • it is added to Function.prototype allowing a nicer way to call it

Also, the similarity to the built-in function Function.prototype.apply seems appropriate to me.

Why does foo = filter(...) return a <filter object>, not a list?

Please see this sample implementation of filter to understand how it works in Python 3:

def my_filter(function, iterable):
    """my_filter(function or None, iterable) --> filter object

    Return an iterator yielding those items of iterable for which function(item)
    is true. If function is None, return the items that are true."""
    if function is None:
        return (item for item in iterable if item)
    return (item for item in iterable if function(item))

The following is an example of how you might use filter or my_filter generators:

>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello

Soft hyphen in HTML (<wbr> vs. &shy;)

The zero-width space entity can be used in place of <wbr> tag reliably on virtually every platform.

&#8203;

Also useful is the word joiner entity, that can be used to prohibit a break. (Insert between each character of a word, except where you want the break.)

&#8288;

With the two of these, you can do anything.

What is a provisioning profile used for when developing iPhone applications?

A Quote from : iPhone Developer Program (~8MB PDF)

A provisioning profile is a collection of digital entities that uniquely ties developers and devices to an authorized iPhone Development Team and enables a device to be used for testing. A Development Provisioning Profile must be installed on each device on which you wish to run your application code. Each Development Provisioning Profile will contain a set of iPhone Development Certificates, Unique Device Identifiers and an App ID. Devices specified within the provisioning profile can be used for testing only by those individuals whose iPhone Development Certificates are included in the profile. A single device can contain multiple provisioning profiles.

How to do an array of hashmaps?

What gives? It works. Just ignore it:

@SuppressWarnings("unchecked")

No, you cannot parameterize it. I'd however rather use a List<Map<K, V>> instead.

List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();

To learn more about collections and maps, have a look at this tutorial.

How to Round to the nearest whole number in C#

Use Math.Round:

double roundedValue = Math.Round(value, 0)

Can you display HTML5 <video> as a full screen background?

I might be a bit late to answer this but this will be useful for new people looking for this answer.

The answers above are good, but to have a perfect video background you have to check at the aspect ratio as the video might cut or the canvas around get deformed when resizing the screen or using it on different screen sizes.

I got into this issue not long ago and I found the solution using media queries.

Here is a tutorial that I wrote on how to create a Fullscreen Video Background with only CSS

I will add the code here as well:

HTML:

<div class="videoBgWrapper">
    <video loop muted autoplay poster="img/videoframe.jpg" class="videoBg">
        <source src="videosfolder/video.webm" type="video/webm">
        <source src="videosfolder/video.mp4" type="video/mp4">
        <source src="videosfolder/video.ogv" type="video/ogg">
    </video>
</div>

CSS:

.videoBgWrapper {
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    overflow: hidden;
    z-index: -100;
}
.videoBg{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

@media (min-aspect-ratio: 16/9) {
  .videoBg{
    width: 100%;
    height: auto;
  }
}
@media (max-aspect-ratio: 16/9) {
  .videoBg {
    width: auto;
    height: 100%;
  }
}

I hope you find it useful.

What is the difference between 'SAME' and 'VALID' padding in tf.nn.max_pool of tensorflow?

Based on the explanation here and following up on Tristan's answer, I usually use these quick functions for sanity checks.

# a function to help us stay clean
def getPaddings(pad_along_height,pad_along_width):
    # if even.. easy..
    if pad_along_height%2 == 0:
        pad_top = pad_along_height / 2
        pad_bottom = pad_top
    # if odd
    else:
        pad_top = np.floor( pad_along_height / 2 )
        pad_bottom = np.floor( pad_along_height / 2 ) +1
    # check if width padding is odd or even
    # if even.. easy..
    if pad_along_width%2 == 0:
        pad_left = pad_along_width / 2
        pad_right= pad_left
    # if odd
    else:
        pad_left = np.floor( pad_along_width / 2 )
        pad_right = np.floor( pad_along_width / 2 ) +1
        #
    return pad_top,pad_bottom,pad_left,pad_right

# strides [image index, y, x, depth]
# padding 'SAME' or 'VALID'
# bottom and right sides always get the one additional padded pixel (if padding is odd)
def getOutputDim (inputWidth,inputHeight,filterWidth,filterHeight,strides,padding):
    if padding == 'SAME':
        out_height = np.ceil(float(inputHeight) / float(strides[1]))
        out_width  = np.ceil(float(inputWidth) / float(strides[2]))
        #
        pad_along_height = ((out_height - 1) * strides[1] + filterHeight - inputHeight)
        pad_along_width = ((out_width - 1) * strides[2] + filterWidth - inputWidth)
        #
        # now get padding
        pad_top,pad_bottom,pad_left,pad_right = getPaddings(pad_along_height,pad_along_width)
        #
        print 'output height', out_height
        print 'output width' , out_width
        print 'total pad along height' , pad_along_height
        print 'total pad along width' , pad_along_width
        print 'pad at top' , pad_top
        print 'pad at bottom' ,pad_bottom
        print 'pad at left' , pad_left
        print 'pad at right' ,pad_right

    elif padding == 'VALID':
        out_height = np.ceil(float(inputHeight - filterHeight + 1) / float(strides[1]))
        out_width  = np.ceil(float(inputWidth - filterWidth + 1) / float(strides[2]))
        #
        print 'output height', out_height
        print 'output width' , out_width
        print 'no padding'


# use like so
getOutputDim (80,80,4,4,[1,1,1,1],'SAME')

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

Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.

The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.

int maxAge = _dbContext.Persons
  .OrderByDescending(p => p.Age)
  .Select(p => p.Age)
  .FirstOrDefault();

Add single element to array in numpy

If you want to add an element use append()

a = numpy.append(a, 1) in this case add the 1 at the end of the array

If you want to insert an element use insert()

a = numpy.insert(a, index, 1) in this case you can put the 1 where you desire, using index to set the position in the array.

How do I get the file name from a String containing the Absolute file path?

just use File.getName()

File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");
System.out.println(f.getName());

using String methods:

  File f = new File("C:\\Hello\\AnotherFolder\\The File Name.PDF");  
System.out.println(f.getAbsolutePath().substring(f.getAbsolutePath().lastIndexOf("\\")+1));

How to change Bootstrap's global default font size?

There are several ways but since you are using just the CSS version and not the SASS or LESS versions, your best bet to use Bootstraps own customization tool:

http://getbootstrap.com/customize/

Customize whatever you want on this page and then you can download a custom build with your own font sizes and anything else you want to change.

Altering the CSS file directly (or simply adding new CSS styles that override the Bootstrap CSS) is not recommended because other Bootstrap styles' values are derived from the base font size. For example:

https://github.com/twbs/bootstrap-sass/blob/master/assets/stylesheets/bootstrap/_variables.scss#L52

You can see that the base font size is used to calculate the sizes of the h1, h2, h3 etc. If you just changed the font size in the CSS (or added your own overriding font-size) all the other values that used the font size in calculations would no longer be proportionally accurate according to Bootstrap's design.

As I said, your best bet is to just use their own Customize tool. That is exactly what it's for.

If you are using SASS or LESS, you would change the font size in the variables file before compiling.

ImportError: No module named PIL

This worked for me on Ubuntu 16.04:

sudo apt-get install python-imaging

I found this on Wikibooks after searching for about half an hour.

How much does it cost to develop an iPhone application?

I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)

Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)

One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)

We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)

With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.

Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.

There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.

Take another hit, dude.

Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.

mssql convert varchar to float

You can convert varchars to floats, and you can do it in the manner you have expressed. Your varchar must not be a numeric value. There must be something else in it. You can use IsNumeric to test it. See this:

declare @thing varchar(100)

select @thing = '122.332'

--This returns 1 since it is numeric.
select isnumeric(@thing)

--This converts just fine.
select convert(float,@thing)

select @thing = '122.332.'

--This returns 0 since it is not numeric.
select isnumeric(@thing)

--This convert throws.
select convert(float,@thing)

Redirect to an external URL from controller action in Spring MVC

For external url you have to use "http://www.yahoo.com" as the redirect url.

This is explained in the redirect: prefix of Spring reference documentation.

redirect:/myapp/some/resource

will redirect relative to the current Servlet context, while a name such as

redirect:http://myhost.com/some/arbitrary/path

will redirect to an absolute URL

Catching exceptions from Guzzle

If the Exception is being thrown in that try block then at worst case scenario Exception should be catching anything uncaught.

Consider that the first part of the test is throwing the Exception and wrap that in the try block as well.

How to check if MySQL returns null/empty?

Use empty() and/or is_null()

http://www.php.net/empty http://www.php.net/is_null

Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.

What are the differences between NP, NP-Complete and NP-Hard?

This is a very informal answer to the question asked.

Can 3233 be written as the product of two other numbers bigger than 1? Is there any way to walk a path around all of the Seven Bridges of Königsberg without taking any bridge twice? These are examples of questions that share a common trait. It may not be obvious how to efficiently determine the answer, but if the answer is 'yes', then there's a short and quick to check proof. In the first case a non-trivial factorization of 51; in the second, a route for walking the bridges (fitting the constraints).

A decision problem is a collection of questions with yes or no answers that vary only in one parameter. Say the problem COMPOSITE={"Is n composite": n is an integer} or EULERPATH={"Does the graph G have an Euler path?": G is a finite graph}.

Now, some decision problems lend themselves to efficient, if not obvious algorithms. Euler discovered an efficient algorithm for problems like the "Seven Bridges of Königsberg" over 250 years ago.

On the other hand, for many decision problems, it's not obvious how to get the answer -- but if you know some additional piece of information, it's obvious how to go about proving you've got the answer right. COMPOSITE is like this: Trial division is the obvious algorithm, and it's slow: to factor a 10 digit number, you have to try something like 100,000 possible divisors. But if, for example, somebody told you that 61 is a divisor of 3233, simple long division is a efficient way to see that they're correct.

The complexity class NP is the class of decision problems where the 'yes' answers have short to state, quick to check proofs. Like COMPOSITE. One important point is that this definition doesn't say anything about how hard the problem is. If you have a correct, efficient way to solve a decision problem, just writing down the steps in the solution is proof enough.

Algorithms research continues, and new clever algorithms are created all the time. A problem you might not know how to solve efficiently today may turn out to have an efficient (if not obvious) solution tomorrow. In fact, it took researchers until 2002 to find an efficient solution to COMPOSITE! With all these advances, one really has to wonder: Is this bit about having short proofs just an illusion? Maybe every decision problem that lends itself to efficient proofs has an efficient solution? Nobody knows.

Perhaps the biggest contribution to this field came with the discovery a peculiar class of NP problems. By playing around with circuit models for computation, Stephen Cook found a decision problem of the NP variety that was provably as hard or harder than every other NP problem. An efficient solution for the boolean satisfiability problem could be used to create an efficient solution to any other problem in NP. Soon after, Richard Karp showed that a number of other decision problems could serve the same purpose. These problems, in a sense the "hardest" problems in NP, became known as NP-complete problems.

Of course, NP is only a class of decision problems. Many problems aren't naturally stated in this manner: "find the factors of N", "find the shortest path in the graph G that visits every vertex", "give a set of variable assignments that makes the following boolean expression true". Though one may informally talk about some such problems being "in NP", technically that doesn't make much sense -- they're not decision problems. Some of these problems might even have the same sort of power as an NP-complete problem: an efficient solution to these (non-decision) problems would lead directly to an efficient solution to any NP problem. A problem like this is called NP-hard.

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • Reset/remove CSS styles for element only

    The CSS3 keyword initial sets the CSS3 property to the initial value as defined in the spec. The initial keyword has broad browser support except for the IE and Opera Mini families.

    Since IE's lack of support may cause issue here are some of the ways you can reset some CSS properties to their initial values:

    .reset-this {
        animation : none;
        animation-delay : 0;
        animation-direction : normal;
        animation-duration : 0;
        animation-fill-mode : none;
        animation-iteration-count : 1;
        animation-name : none;
        animation-play-state : running;
        animation-timing-function : ease;
        backface-visibility : visible;
        background : 0;
        background-attachment : scroll;
        background-clip : border-box;
        background-color : transparent;
        background-image : none;
        background-origin : padding-box;
        background-position : 0 0;
        background-position-x : 0;
        background-position-y : 0;
        background-repeat : repeat;
        background-size : auto auto;
        border : 0;
        border-style : none;
        border-width : medium;
        border-color : inherit;
        border-bottom : 0;
        border-bottom-color : inherit;
        border-bottom-left-radius : 0;
        border-bottom-right-radius : 0;
        border-bottom-style : none;
        border-bottom-width : medium;
        border-collapse : separate;
        border-image : none;
        border-left : 0;
        border-left-color : inherit;
        border-left-style : none;
        border-left-width : medium;
        border-radius : 0;
        border-right : 0;
        border-right-color : inherit;
        border-right-style : none;
        border-right-width : medium;
        border-spacing : 0;
        border-top : 0;
        border-top-color : inherit;
        border-top-left-radius : 0;
        border-top-right-radius : 0;
        border-top-style : none;
        border-top-width : medium;
        bottom : auto;
        box-shadow : none;
        box-sizing : content-box;
        caption-side : top;
        clear : none;
        clip : auto;
        color : inherit;
        columns : auto;
        column-count : auto;
        column-fill : balance;
        column-gap : normal;
        column-rule : medium none currentColor;
        column-rule-color : currentColor;
        column-rule-style : none;
        column-rule-width : none;
        column-span : 1;
        column-width : auto;
        content : normal;
        counter-increment : none;
        counter-reset : none;
        cursor : auto;
        direction : ltr;
        display : inline;
        empty-cells : show;
        float : none;
        font : normal;
        font-family : inherit;
        font-size : medium;
        font-style : normal;
        font-variant : normal;
        font-weight : normal;
        height : auto;
        hyphens : none;
        left : auto;
        letter-spacing : normal;
        line-height : normal;
        list-style : none;
        list-style-image : none;
        list-style-position : outside;
        list-style-type : disc;
        margin : 0;
        margin-bottom : 0;
        margin-left : 0;
        margin-right : 0;
        margin-top : 0;
        max-height : none;
        max-width : none;
        min-height : 0;
        min-width : 0;
        opacity : 1;
        orphans : 0;
        outline : 0;
        outline-color : invert;
        outline-style : none;
        outline-width : medium;
        overflow : visible;
        overflow-x : visible;
        overflow-y : visible;
        padding : 0;
        padding-bottom : 0;
        padding-left : 0;
        padding-right : 0;
        padding-top : 0;
        page-break-after : auto;
        page-break-before : auto;
        page-break-inside : auto;
        perspective : none;
        perspective-origin : 50% 50%;
        position : static;
        /* May need to alter quotes for different locales (e.g fr) */
        quotes : '\201C' '\201D' '\2018' '\2019';
        right : auto;
        tab-size : 8;
        table-layout : auto;
        text-align : inherit;
        text-align-last : auto;
        text-decoration : none;
        text-decoration-color : inherit;
        text-decoration-line : none;
        text-decoration-style : solid;
        text-indent : 0;
        text-shadow : none;
        text-transform : none;
        top : auto;
        transform : none;
        transform-style : flat;
        transition : none;
        transition-delay : 0s;
        transition-duration : 0s;
        transition-property : none;
        transition-timing-function : ease;
        unicode-bidi : normal;
        vertical-align : baseline;
        visibility : visible;
        white-space : normal;
        widows : 0;
        width : auto;
        word-spacing : normal;
        z-index : auto;
        /* basic modern patch */
        all: initial;
        all: unset;
    }
    
    /* basic modern patch */
    
    #reset-this-root {
        all: initial;
        * {
            all: unset;
        }
    }
    

    As mentioned in a comment by @user566245 :

    this is correct in principle, but individual mileage may vary. For example certain elements like textarea by default have a border, applying this reset will render those textarea's border less.


    JAVASCRIPT ?

    Nobody thought about other than css to reset css? Yes?

    There is that snip fully relevant : https://stackoverflow.com/a/14791113/845310

    getElementsByTagName("*") will return all elements from DOM. Then you may set styles for each element in the collection:

    answered Feb 9 '13 at 20:15 by VisioN

    var allElements = document.getElementsByTagName("*");
    for (var i = 0, len = allElements.length; i < len; i++) {
        var element = allElements[i];
        // element.style.border = ...
    }
    

    With all this said; i don't think a css reset is something feasable unless we end up with only one web browser .. if the 'default' is set by browser in the end.

    For comparison, here is Firefox 40.0 values list for a <blockquote style="all: unset;font-style: oblique"> where font-style: oblique triggers DOM operation.

    align-content: unset;
    align-items: unset;
    align-self: unset;
    animation: unset;
    appearance: unset;
    backface-visibility: unset;
    background-blend-mode: unset;
    background: unset;
    binding: unset;
    block-size: unset;
    border-block-end: unset;
    border-block-start: unset;
    border-collapse: unset;
    border-inline-end: unset;
    border-inline-start: unset;
    border-radius: unset;
    border-spacing: unset;
    border: unset;
    bottom: unset;
    box-align: unset;
    box-decoration-break: unset;
    box-direction: unset;
    box-flex: unset;
    box-ordinal-group: unset;
    box-orient: unset;
    box-pack: unset;
    box-shadow: unset;
    box-sizing: unset;
    caption-side: unset;
    clear: unset;
    clip-path: unset;
    clip-rule: unset;
    clip: unset;
    color-adjust: unset;
    color-interpolation-filters: unset;
    color-interpolation: unset;
    color: unset;
    column-fill: unset;
    column-gap: unset;
    column-rule: unset;
    columns: unset;
    content: unset;
    control-character-visibility: unset;
    counter-increment: unset;
    counter-reset: unset;
    cursor: unset;
    display: unset;
    dominant-baseline: unset;
    empty-cells: unset;
    fill-opacity: unset;
    fill-rule: unset;
    fill: unset;
    filter: unset;
    flex-flow: unset;
    flex: unset;
    float-edge: unset;
    float: unset;
    flood-color: unset;
    flood-opacity: unset;
    font-family: unset;
    font-feature-settings: unset;
    font-kerning: unset;
    font-language-override: unset;
    font-size-adjust: unset;
    font-size: unset;
    font-stretch: unset;
    font-style: oblique;
    font-synthesis: unset;
    font-variant: unset;
    font-weight: unset;
    font: ;
    force-broken-image-icon: unset;
    height: unset;
    hyphens: unset;
    image-orientation: unset;
    image-region: unset;
    image-rendering: unset;
    ime-mode: unset;
    inline-size: unset;
    isolation: unset;
    justify-content: unset;
    justify-items: unset;
    justify-self: unset;
    left: unset;
    letter-spacing: unset;
    lighting-color: unset;
    line-height: unset;
    list-style: unset;
    margin-block-end: unset;
    margin-block-start: unset;
    margin-inline-end: unset;
    margin-inline-start: unset;
    margin: unset;
    marker-offset: unset;
    marker: unset;
    mask-type: unset;
    mask: unset;
    max-block-size: unset;
    max-height: unset;
    max-inline-size: unset;
    max-width: unset;
    min-block-size: unset;
    min-height: unset;
    min-inline-size: unset;
    min-width: unset;
    mix-blend-mode: unset;
    object-fit: unset;
    object-position: unset;
    offset-block-end: unset;
    offset-block-start: unset;
    offset-inline-end: unset;
    offset-inline-start: unset;
    opacity: unset;
    order: unset;
    orient: unset;
    outline-offset: unset;
    outline-radius: unset;
    outline: unset;
    overflow: unset;
    padding-block-end: unset;
    padding-block-start: unset;
    padding-inline-end: unset;
    padding-inline-start: unset;
    padding: unset;
    page-break-after: unset;
    page-break-before: unset;
    page-break-inside: unset;
    paint-order: unset;
    perspective-origin: unset;
    perspective: unset;
    pointer-events: unset;
    position: unset;
    quotes: unset;
    resize: unset;
    right: unset;
    ruby-align: unset;
    ruby-position: unset;
    scroll-behavior: unset;
    scroll-snap-coordinate: unset;
    scroll-snap-destination: unset;
    scroll-snap-points-x: unset;
    scroll-snap-points-y: unset;
    scroll-snap-type: unset;
    shape-rendering: unset;
    stack-sizing: unset;
    stop-color: unset;
    stop-opacity: unset;
    stroke-dasharray: unset;
    stroke-dashoffset: unset;
    stroke-linecap: unset;
    stroke-linejoin: unset;
    stroke-miterlimit: unset;
    stroke-opacity: unset;
    stroke-width: unset;
    stroke: unset;
    tab-size: unset;
    table-layout: unset;
    text-align-last: unset;
    text-align: unset;
    text-anchor: unset;
    text-combine-upright: unset;
    text-decoration: unset;
    text-emphasis-position: unset;
    text-emphasis: unset;
    text-indent: unset;
    text-orientation: unset;
    text-overflow: unset;
    text-rendering: unset;
    text-shadow: unset;
    text-size-adjust: unset;
    text-transform: unset;
    top: unset;
    transform-origin: unset;
    transform-style: unset;
    transform: unset;
    transition: unset;
    user-focus: unset;
    user-input: unset;
    user-modify: unset;
    user-select: unset;
    vector-effect: unset;
    vertical-align: unset;
    visibility: unset;
    white-space: unset;
    width: unset;
    will-change: unset;
    window-dragging: unset;
    word-break: unset;
    word-spacing: unset;
    word-wrap: unset;
    writing-mode: unset;
    z-index: unset;
    

    How can you remove all documents from a collection with Mongoose?

    MongoDB shell version v4.2.6
    Node v14.2.0

    Assuming you have a Tour Model: tourModel.js

    const mongoose = require('mongoose');
    
    const tourSchema = new mongoose.Schema({
      name: {
        type: String,
        required: [true, 'A tour must have a name'],
        unique: true,
        trim: true,
      },
      createdAt: {
        type: Date,
        default: Date.now(),
      },
    });
    const Tour = mongoose.model('Tour', tourSchema);
    
    module.exports = Tour;
    

    Now you want to delete all tours at once from your MongoDB, I also providing connection code to connect with the remote cluster. I used deleteMany(), if you do not pass any args to deleteMany(), then it will delete all the documents in Tour collection.

    const mongoose = require('mongoose');
    const Tour = require('./../../models/tourModel');
    const conStr = 'mongodb+srv://lord:<PASSWORD>@cluster0-eeev8.mongodb.net/tour-guide?retryWrites=true&w=majority';
    const DB = conStr.replace('<PASSWORD>','ADUSsaZEKESKZX');
    mongoose.connect(DB, {
        useNewUrlParser: true,
        useCreateIndex: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
      })
      .then((con) => {
        console.log(`DB connection successful ${con.path}`);
      });
    
    const deleteAllData = async () => {
      try {
        await Tour.deleteMany();
        console.log('All Data successfully deleted');
      } catch (err) {
        console.log(err);
      }
    };
    

    C# DataRow Empty-check

    A simple method along the lines of:

    bool AreAllColumnsEmpty(DataRow dr)
    {
     if (dr == null)
     {
      return true;
     }
     else
     {
      foreach(var value in dr.ItemArray)
      {
        if (value != null)
        {
          return false;
        }
      }
      return true;
     }
    }
    

    Should give you what you're after, and to make it "nice" (as there's nothing as far as I'm aware, in the Framework), you could wrap it up as an extension method, and then your resultant code would be:

    if (datarow.AreAllColumnsEmpty())
    {
    }
    else
    {
    }
    

    How can I update a row in a DataTable in VB.NET?

    The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

    To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

    dtResult.Rows(i)("Foo") = strVerse
    

    MIME types missing in IIS 7 for ASP.NET - 404.17

    There are two reasons you might get this message:

    1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
    2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

    Is Java RegEx case-insensitive?

    Yes, case insensitivity can be enabled and disabled at will in Java regex.

    It looks like you want something like this:

        System.out.println(
            "Have a meRry MErrY Christmas ho Ho hO"
                .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
        );
        // Have a meRry Christmas ho
    

    Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

    The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

    It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

    To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

        System.out.println(
            "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
                .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
        ); // A e I O u
    

    Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

        System.out.println(
            "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
                .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
        ); // A eeEeeE I O uuUuUuu
    

    More generally, you can enable and disable any flag within the pattern as you wish.

    See also

    Related questions

    How to enable local network users to access my WAMP sites?

    if you use Windows and if you do all comments in above ,

    You can check your network and sharing center.

    Network and Sharing Center -> Advanced sharing settings ->Home or Work Profile Change

    Thanks good work!

    Passing Variable through JavaScript from one html page to another page

    There are two pages: Pageone.html :

    <script>
    var hello = "hi"
    location.replace("http://example.com/PageTwo.html?" + hi + "");
    </script>
    

    PageTwo.html :

    <script>
    var link = window.location.href;
    link = link.replace("http://example.com/PageTwo.html?","");
    document.write("The variable contained this content:" + link + "");
    </script>
    

    Hope it helps!

    How to change Screen buffer size in Windows Command Prompt from batch script

    You can change the buffer size of cmd by clicking the icon at top left corner -->properties --> layout --> screen buffer size.
    you can even change it with cmd command

    mode con:cols=100 lines=60
    Upto lines = 58 the height of the cmd window changes ..
    After lines value of 58 the buffer size of the cmd changes...

    HTML5 video - show/hide controls programmatically

    CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

    In HTML,

    <div id="hideme">
        <audio id="audioTag" controls>
            <source src="/path/to/audio.mp3">
        </audio>
    </div>
    

    with JS

    <script type="text/javascript">
    window.onload = function() {
        var audioEl = document.getElementById("audioTag");
        audioEl.load();
        audioEl.play();
    };
    </script>
    

    In CSS,

    #hideme {display: none;}
    

    CSS3 opacity gradient?

    We can do it by css like.

    body {
      background: #000;
      background-image: linear-gradient(90deg, rgba(255, 255, 255, .3) 0%, rgba(231, 231, 231, .3) 22.39%, rgba(209, 209, 209,  .3) 42.6%, rgba(182, 182, 182, .3) 79.19%, rgba(156, 156, 156, .3) 104.86%);
      
    }
    

    laravel 5 : Class 'input' not found

    This clean code snippet works fine for me:

    use Illuminate\Http\Request;
    Route::post('/register',function(Request $request){
    
       $user = new \App\User;
       $user->username = $request->input('username');
       $user->email  = $request->input('email');
       $user->password = Hash::make($request->input('username'));
       $user->designation = $request->input('designation');
       $user->save();
    });
    

    adb is not recognized as internal or external command on windows

    If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

    %USERPROFILE%\AppData\Local\Android\sdk\platform-tools

    Where %USERPROFILE% represents something like C:\Users\yourName.

    If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

    Loop through JSON object List

    I have the following call:

    $('#select_box_id').change(function() {
            var action = $('#my_form').attr('action');
        $.get(action,{},function(response){
            $.each(response.result,function(i) {
    
                alert("key is: " + i + ", val is: " + response.result[i]);
    
            });
        }, 'json');
        });
    

    The structure coming back from the server look like:

    {"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}
    

    how to use Blob datatype in Postgres

    I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

    Read the part with the title 'What is the best way to store the files in the Database?'

    Plotting using a CSV file

    This should get you started:

    set datafile separator ","
    plot 'infile' using 0:1
    

    Codeigniter $this->db->get(), how do I return values for a specific row?

    You simply use this in one row.

    $query = $this->db->get_where('mytable',array('id'=>'3'));
    

    Convert Base64 string to an image file?

    The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

    function base64_to_jpeg($base64_string, $output_file) {
        // open the output file for writing
        $ifp = fopen( $output_file, 'wb' ); 
    
        // split the string on commas
        // $data[ 0 ] == "data:image/png;base64"
        // $data[ 1 ] == <actual base64 string>
        $data = explode( ',', $base64_string );
    
        // we could add validation here with ensuring count( $data ) > 1
        fwrite( $ifp, base64_decode( $data[ 1 ] ) );
    
        // clean up the file resource
        fclose( $ifp ); 
    
        return $output_file; 
    }
    

    Change Circle color of radio button

    1. Declare custom style in your styles.xml file.

      <style name="MyRadioButton" parent="Theme.AppCompat.Light">  
        <item name="colorControlNormal">@color/indigo</item>
        <item name="colorControlActivated">@color/pink</item>
      </style>  
      
    2. Apply this style to your RadioButton via android:theme attribute.

      <RadioButton  
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:checked="true"
          android:text="Radio Button"
          android:theme="@style/MyRadioButton"/>
      

      only if your activity extends AppCompatActivity

    Selenium WebDriver and DropDown Boxes

    public static void mulptiTransfer(WebDriver driver, By dropdownID, String text, By to)
    {   
        String valuetext = null;
        WebElement element = locateElement(driver, dropdownID, 10);
        Select select = new Select(element);
        List<WebElement> options = element.findElements(By.tagName("option"));
        for (WebElement value: options) 
        {
            valuetext = value.getText();
            if (valuetext.equalsIgnoreCase(text))
            {
                try
                {
                    select.selectByVisibleText(valuetext);
                    locateElement(driver, to, 5).click();                           
                    break;
                }
                catch (Exception e)
                {
                    System.out.println(valuetext + "Value not found in Dropdown to Select");
                }       
            }
        }
    }
    

    Load HTML file into WebView

    The Accepted Answer is not working for me, This is what works for me

    WebSettings webSetting = webView.getSettings();
        webSetting.setBuiltInZoomControls(true);
        webView1.setWebViewClient(new WebViewClient());
    
       webView.loadUrl("file:///android_asset/index.html");
    

    Maven: How do I activate a profile from command line?

    Just remove activation section, I don't know why -Pdev1 doesn't override default false activation. But if you omit this:

    <activation> <activeByDefault>false</activeByDefault> </activation>

    then your profile will be activated only after explicit declaration as -Pdev1

    how to view the contents of a .pem certificate

    Use the -printcert command like this:

    keytool -printcert -file certificate.pem
    

    Convert a secure string to plain text

    You may also use PSCredential.GetNetworkCredential() :

    $SecurePassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt | ConvertTo-SecureString
    $UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password
    

    Oracle: If Table Exists

    One way is to use DBMS_ASSERT.SQL_OBJECT_NAME :

    This function verifies that the input parameter string is a qualified SQL identifier of an existing SQL object.

    DECLARE
        V_OBJECT_NAME VARCHAR2(30);
    BEGIN
       BEGIN
            V_OBJECT_NAME  := DBMS_ASSERT.SQL_OBJECT_NAME('tab1');
            EXECUTE IMMEDIATE 'DROP TABLE tab1';
    
            EXCEPTION WHEN OTHERS THEN NULL;
       END;
    END;
    /
    

    DBFiddle Demo

    500 Internal Server Error for php file not for html

    A PHP file must have permissions set to 644. Any folder containing PHP files and PHP access (to upload files, for example) must have permissions set to 755. PHP will run a 500 error when dealing with any file or folder that has permissions set to 777!

    How can I add an image file into json object?

    You will need to read the bytes from that File into a byte[] and put that object into your JSONObject.

    You should also have a look at the following posts :

    Hope this helps.

    scp via java

    Take a look here

    That is the source code for Ants' SCP task. The code in the "execute" method is where the nuts and bolts of it are. This should give you a fair idea of what is required. It uses JSch i believe.

    Alternatively you could also directly execute this Ant task from your java code.

    Bash: infinite sleep (infinite blocking)

    Maybe this seems ugly, but why not just run cat and let it wait for input forever?

    How to insert a file in MySQL database?

    The other answers will give you a good idea how to accomplish what you have asked for....

    However

    There are not many cases where this is a good idea. It is usually better to store only the filename in the database and the file on the file system.

    That way your database is much smaller, can be transported around easier and more importantly is quicker to backup / restore.

    How to load property file from classpath?

    final Properties properties = new Properties();
    try (final InputStream stream =
               this.getClass().getResourceAsStream("foo.properties")) {
        properties.load(stream);
        /* or properties.loadFromXML(...) */
    }
    

    How to get full width in body element

    If its in a landscape then you will be needing more width and less height! That's just what all websites have.

    Lets go with a basic first then the rest!

    The basic CSS:

    By CSS you can do this,

    #body {
    width: 100%;
    height: 100%;
    }
    

    Here you are using a div with id body, as:

    <body>
      <div id="body>
        all the text would go here!
      </div>
    </body>
    

    Then you can have a web page with 100% height and width.

    What if he tries to resize the window?

    The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

    #body {
    height: 100%;
    width: 100%;
    }
    

    And just add min-height max-height min-width and max-width.

    This way, the page element would stay at the place they were at the page load.

    Using JavaScript:

    Using JavaScript, you can control the UI, use jQuery as:

    $('#body').css('min-height', '100%');
    

    And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

    How to not add scroll to the web page:

    If you are not trying to add a scroll, then you can use this JS

    $('#body').css('min-height', screen.height); // or anyother like window.height
    

    This way, the document will get a new height whenever the user would load the page.

    Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

    Tip: So try using JS to find current Screen size and edit the page! :)

    Copy and Paste a set range in the next empty row

    Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11 meets in sheet "Calculator"

    I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.

    Dim i As Integer
    Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
    Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")
    
    For i = 2 To ws1.Range("A65536").End(xlUp).Row
    
        If ws1.Cells(i, 4) <= 11 Then
    
            ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
            ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
            ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
            ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
            ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)
    
        End If
    Next i
    

    $(...).datepicker is not a function - JQuery - Bootstrap

    You can try the following and it worked for me.

    Import following scripts and css files as there are used by the date picker.

    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/js/bootstrap-datepicker.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.1/css/bootstrap-datepicker3.css"/>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    

    The JS coding for the Date Picker I use.

    <script>
            $(document).ready(function(){
                // alert ('Cliecked');
                var date_input=$('input[name="orangeDateOfBirthForm"]'); //our date input has the name "date"
                var container=$('.bootstrap-iso form').length>0 ? $('.bootstrap-iso form').parent() : "body";
                var options={
                    format: 'dd/mm/yyyy', //format of the date
                    container: container,
                    changeYear: true, // you can change the year as you need
                    changeMonth: true, // you can change the months as you need
                    todayHighlight: true,
                    autoclose: true,
                    yearRange: "1930:2100" // the starting to end of year range 
                };
                date_input.datepicker(options);
            });
        </script>
    

    The HTML Coding:

     <input type="text" id="orangeDateOfBirthForm" name="orangeDateOfBirthForm" class="form-control validate" required>
     <label data-error="wrong" data-success="right" for="orangeForm-email">Date of Birth</label>
    

    "Port 4200 is already in use" when running the ng serve command

    Port 4200 is already in use. Use '--port' to specify a different port
    

    This means that you already have another service running on port 4200. If this is the case you can either . shut down the other service. use the --port flag when running ng serve like this:

     ng serve --port 9001
    

    Another thing to notice is that, on some machines, the domain localhost may not work. You may see a set of numbers such as 127.0.0.1. When you run ng serve it should show you what URL the server is running on, so be sure to read the messages on your machine to find your exact development URL.

    Which JDK version (Language Level) is required for Android Studio?

    Try not to use JDK versions higher than the ones supported. I've actually ran into a very ambiguous problem a few months ago.

    I had a jar library of my own that I compiled with JDK 8, and I was using it in my assignment. It was giving me some kind of preDexDebug error every time I tried running it. Eventually after hours of trying to decipher the error logs I finally had an idea of what was wrong. I checked the system requirements, changed compilers from 8 to 7, and it worked. Looks like putting my jar into a library cost me a few hours rather than save it...

    How to play an android notification sound

    Try this:

    public void ringtone(){
        try {
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
            r.play();
         } catch (Exception e) {
             e.printStackTrace();
         }
    }
    

    'Missing contentDescription attribute on image' in XML

    Follow this link for solution: Android Lint contentDescription warning

    Resolved this warning by setting attribute android:contentDescription for my ImageView

    android:contentDescription="@string/desc"

    Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription

    This defines text that briefly describes the content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.

    Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.

    This link for explanation: Accessibility, It's Impact and Development Resources

    Many Android users have disabilities that require them to interact with their Android devices in different ways. These include users who have visual, physical or age-related disabilities that prevent them from fully seeing or using a touchscreen.

    Android provides accessibility features and services for helping these users navigate their devices more easily, including text-to-speech, haptic feedback, trackball and D-pad navigation that augments their experience. Android application developers can take advantage of these services to make their applications more accessible and also build their own accessibility services.

    This guide is for making your app accessible: Making Apps More Accessible

    Making sure your application is accessible to all users is relatively easy, particularly when you use framework-provided user interface components. If you only use these standard components for your application, there are just a few steps required to ensure your application is accessible:

    1. Label your ImageButton, ImageView, EditText, CheckBox and other user interface controls using the android:contentDescription attribute.

    2. Make all of your user interface elements accessible with a directional controller, such as a trackball or D-pad.

    3. Test your application by turning on accessibility services like TalkBack and Explore by Touch, and try using your application using only directional controls.

    Connecting to smtp.gmail.com via command line

    This is command for connect

    • server_name: smtp.gmail.com
    • server_port: 587
    • user_name__hash: echo -n '{{user_name}}' | base64
    • user_password__hash: echo -n '{{user_password}}' | base64
    openssl s_client -connect {{server_name}}:{{server_port}} -crlf -quiet -starttls smtp
    

    and steps to accept message to send

    auth login
    {{user_name__hash}}
    {{user_password__hash}}
    helo {{server_name}}
    mail from: <{{message_from}}>
    rcpt to: <{{message_to}}>
    DATA
    from: <{{message_from}}>
    to: <{{message_to}}>
    subject:{{message_subject}}
    Content-Type: text/html; charset='UTF-8'; Content-Transfer-Encoding: base64;
    MIME-Version: 1.0
    {{message_content}}
    .
    quit
    

    Formatting text in a TextBlock

    Check out this example from Charles Petzolds Bool Application = Code + markup

    //----------------------------------------------
    // FormatTheText.cs (c) 2006 by Charles Petzold
    //----------------------------------------------
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Documents;
    
    namespace Petzold.FormatTheText
    {
        class FormatTheText : Window
        {
            [STAThread]
            public static void Main()
            {
                Application app = new Application();
                app.Run(new FormatTheText());
            }
            public FormatTheText()
            {
                Title = "Format the Text";
    
                TextBlock txt = new TextBlock();
                txt.FontSize = 32; // 24 points
                txt.Inlines.Add("This is some ");
                txt.Inlines.Add(new Italic(new Run("italic")));
                txt.Inlines.Add(" text, and this is some ");
                txt.Inlines.Add(new Bold(new Run("bold")));
                txt.Inlines.Add(" text, and let's cap it off with some ");
                txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
                txt.Inlines.Add(" text.");
                txt.TextWrapping = TextWrapping.Wrap;
    
                Content = txt;
            }
        }
    }
    

    Can you find all classes in a package using reflection?

    You need to look up every class loader entry in the class path:

        String pkg = "org/apache/commons/lang";
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        URL[] urls = ((URLClassLoader) cl).getURLs();
        for (URL url : urls) {
            System.out.println(url.getFile());
            File jar = new File(url.getFile());
            // ....
        }   
    

    If entry is directory, just look up in the right subdirectory:

    if (jar.isDirectory()) {
        File subdir = new File(jar, pkg);
        if (!subdir.exists())
            continue;
        File[] files = subdir.listFiles();
        for (File file : files) {
            if (!file.isFile())
                continue;
            if (file.getName().endsWith(".class"))
                System.out.println("Found class: "
                        + file.getName().substring(0,
                                file.getName().length() - 6));
        }
    }   
    

    If the entry is the file, and it's jar, inspect the ZIP entries of it:

    else {
        // try to open as ZIP
        try {
            ZipFile zip = new ZipFile(jar);
            for (Enumeration<? extends ZipEntry> entries = zip
                    .entries(); entries.hasMoreElements();) {
                ZipEntry entry = entries.nextElement();
                String name = entry.getName();
                if (!name.startsWith(pkg))
                    continue;
                name = name.substring(pkg.length() + 1);
                if (name.indexOf('/') < 0 && name.endsWith(".class"))
                    System.out.println("Found class: "
                            + name.substring(0, name.length() - 6));
            }
        } catch (ZipException e) {
            System.out.println("Not a ZIP: " + e.getMessage());
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
    

    Now once you have all class names withing package, you can try loading them with reflection and analyze if they are classes or interfaces, etc.

    Find all elements on a page whose element ID contains a certain text using jQuery

    Thanks to both of you. This worked perfectly for me.

    $("input[type='text'][id*=" + strID + "]:visible").each(function() {
        this.value=strVal;
    });
    

    Using AES encryption in C#

    Using AES or implementing AES? To use AES, there is the System.Security.Cryptography.RijndaelManaged class.

    Remove all items from RecyclerView

    For my case adding an empty list did the job.

    List<Object> data = new ArrayList<>();
    adapter.setData(data);
    adapter.notifyDataSetChanged();
    

    Finding duplicate rows in SQL Server

    select o.orgName, oc.dupeCount, o.id
    from organizations o
    inner join (
        SELECT orgName, COUNT(*) AS dupeCount
        FROM organizations
        GROUP BY orgName
        HAVING COUNT(*) > 1
    ) oc on o.orgName = oc.orgName
    

    How do I find files that do not contain a given string pattern?

    My grep does not have any -L option. I do find workaround to achieve this.

    The ideas are :

    1. to dump all the file name containing the deserved string to a txt1.txt.
    2. dump all the file name in the directory to a txt2.txt.
    3. make the difference between the 2 dump file with diff command.

      grep 'foo' *.log | cut -c1-14 | uniq > txt1.txt
      grep * *.log | cut -c1-14 | uniq > txt2.txt
      diff txt1.txt txt2.txt | grep ">"
      

    How can I remove the extension of a filename in a shell script?

    Answers provided previously have problems with paths containing dots. Some examples:

    /xyz.dir/file.ext
    ./file.ext
    /a.b.c/x.ddd.txt
    

    I prefer to use |sed -e 's/\.[^./]*$//'. For example:

    $ echo "/xyz.dir/file.ext" | sed -e 's/\.[^./]*$//'
    /xyz.dir/file
    $ echo "./file.ext" | sed -e 's/\.[^./]*$//'
    ./file
    $ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^./]*$//'
    /a.b.c/x.ddd
    

    Note: If you want to remove multiple extensions (as in the last example), use |sed -e 's/\.[^/]*$//':

    $ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^/]*$//'
    /a.b.c/x
    

    However, this method will fail in "dot-files" with no extension:

    $ echo "/a.b.c/.profile" | sed -e 's/\.[^./]*$//'
    /a.b.c/
    

    To cover also such cases, you can use:

    $ echo "/a.b.c/.profile" | sed -re 's/(^.*[^/])\.[^./]*$/\1/'
    /a.b.c/.profile
    

    set default schema for a sql query

    I do not believe there is a "per query" way to do this. (You can use the use keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go command afterward.)

    Remember, in SQL server fully qualified table names are in the format:

    [database].[schema].[table]

    In SQL Server Management Studio you can configure all the defaults you're asking about.

    • You can set up the default database on a per-user basis (or in your connection string):

      Security > Logins > (right click) user > Properties > General

    • You can set up the default schema on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo that is always the default):

      Security > Logins > (right click) user > Properties > User Mapping > Default Schema

    In short, if you use dbo for your schema, you'll likely have the least amount of headaches.

    Embed Google Map code in HTML with marker

    I would suggest this way, one line iframe. no javascript needed at all. In query ?q=,

    _x000D_
    _x000D_
    <iframe src="http://maps.google.com/maps?q=12.927923,77.627108&z=15&output=embed"></iframe>
    _x000D_
    _x000D_
    _x000D_

    How to draw a filled circle in Java?

    public void paintComponent(Graphics g) {
       super.paintComponent(g);
       Graphics2D g2d = (Graphics2D)g;
       // Assume x, y, and diameter are instance variables.
       Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
       g2d.fill(circle);
       ...
    }
    

    Here are some docs about paintComponent (link).

    You should override that method in your JPanel and do something similar to the code snippet above.

    In your ActionListener you should specify x, y, diameter and call repaint().

    Why does viewWillAppear not get called when an app comes back from the background?

    Swift

    Short answer

    Use a NotificationCenter observer rather than viewWillAppear.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        // set observer for UIApplication.willEnterForegroundNotification
        NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    
    }
    
    // my selector that was defined above
    @objc func willEnterForeground() {
        // do stuff
    }
    

    Long answer

    To find out when an app comes back from the background, use a NotificationCenter observer rather than viewWillAppear. Here is a sample project that shows which events happen when. (This is an adaptation of this Objective-C answer.)

    import UIKit
    class ViewController: UIViewController {
    
        // MARK: - Overrides
    
        override func viewDidLoad() {
            super.viewDidLoad()
            print("view did load")
    
            // add notification observers
            NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    
        }
    
        override func viewWillAppear(_ animated: Bool) {
            print("view will appear")
        }
    
        override func viewDidAppear(_ animated: Bool) {
            print("view did appear")
        }
    
        // MARK: - Notification oberserver methods
    
        @objc func didBecomeActive() {
            print("did become active")
        }
    
        @objc func willEnterForeground() {
            print("will enter foreground")
        }
    
    }
    

    On first starting the app, the output order is:

    view did load
    view will appear
    did become active
    view did appear
    

    After pushing the home button and then bringing the app back to the foreground, the output order is:

    will enter foreground
    did become active 
    

    So if you were originally trying to use viewWillAppear then UIApplication.willEnterForegroundNotification is probably what you want.

    Note

    As of iOS 9 and later, you don't need to remove the observer. The documentation states:

    If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

    How to configure Eclipse build path to use Maven dependencies?

    I'm assuming you are using m2eclipse as you mentioned it. However it is not clear whether you created your project under Eclipse or not so I'll try to cover all cases.

    1. If you created a "Java" project under Eclipse (Ctrl+N > Java Project), then right-click the project in the Package Explorer view and go to Maven > Enable Dependency Management (depending on the initial project structure, you may have modify it to match the maven's one, for example by adding src/java to the source folders on the build path).

    2. If you created a "Maven Project" under Eclipse (Ctrl+N > Maven Project), then it should be already "Maven ready".

    3. If you created a Maven project outside Eclipse (manually or with an archetype), then simply import it in Eclipse (right-click the Package Explorer view and select Import... > Maven Projects) and it will be "Maven ready".

    Now, to add a dependency, either right-click the project and select Maven > Add Dependency) or edit the pom manually.

    PS: avoid using the maven-eclipse-plugin if you are using m2eclipse. There is absolutely no need for it, it will be confusing, it will generate some mess. No, really, don't use it unless you really know what you are doing.

    Default values and initialization in Java

    These are the main factors involved:

    1. member variable (default OK)
    2. static variable (default OK)
    3. final member variable (not initialized, must set on constructor)
    4. final static variable (not initialized, must set on a static block {})
    5. local variable (not initialized)

    Note 1: you must initialize final member variables on every implemented constructor!

    Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:

    private final int memberVar;
    
    public Foo() {
        // Invalid initialization of a final member
        init();
    }
    
    private void init() {
        memberVar = 10;
    }
    

    Note 3: arrays are Objects in Java, even if they store primitives.

    Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.

    I am attaching a code example, presenting the aforementioned cases:

    public class Foo {
        // Static and member variables are initialized to default values
    
        // Primitives
        private int a; // Default 0
        private static int b; // Default 0
    
        // Objects
        private Object c; // Default NULL
        private static Object d; // Default NULL
    
        // Arrays (note: they are objects too, even if they store primitives)
        private int[] e; // Default NULL
        private static int[] f; // Default NULL
    
        // What if declared as final?
    
        // Primitives
        private final int g; // Not initialized. MUST set in the constructor
        private final static int h; // Not initialized. MUST set in a static {}
    
        // Objects
        private final Object i; // Not initialized. MUST set in constructor
        private final static Object j; // Not initialized. MUST set in a static {}
    
        // Arrays
        private final int[] k; // Not initialized. MUST set in constructor
        private final static int[] l; // Not initialized. MUST set in a static {}
    
        // Initialize final statics
        static {
            h = 5;
            j = new Object();
            l = new int[5]; // Elements of l are initialized to 0
        }
    
        // Initialize final member variables
        public Foo() {
            g = 10;
            i = new Object();
            k = new int[10]; // Elements of k are initialized to 0
        }
    
        // A second example constructor
        // You have to initialize final member variables to every constructor!
        public Foo(boolean aBoolean) {
            g = 15;
            i = new Object();
            k = new int[15]; // Elements of k are initialized to 0
        }
    
        public static void main(String[] args) {
            // Local variables are not initialized
            int m; // Not initialized
            Object n; // Not initialized
            int[] o; // Not initialized
    
            // We must initialize them before use
            m = 20;
            n = new Object();
            o = new int[20]; // Elements of o are initialized to 0
        }
    }
    

    How to do parallel programming in Python?

    In some cases, it's possible to automatically parallelize loops using Numba, though it only works with a small subset of Python:

    from numba import njit, prange
    
    @njit(parallel=True)
    def prange_test(A):
        s = 0
        # Without "parallel=True" in the jit-decorator
        # the prange statement is equivalent to range
        for i in prange(A.shape[0]):
            s += A[i]
        return s
    

    Unfortunately, it seems that Numba only works with Numpy arrays, but not with other Python objects. In theory, it might also be possible to compile Python to C++ and then automatically parallelize it using the Intel C++ compiler, though I haven't tried this yet.

    Convert the values in a column into row names in an existing data frame

    As of 2016 you can also use the tidyverse.

    library(tidyverse)
    samp %>% remove_rownames %>% column_to_rownames(var="names")
    

    Do I need to close() both FileReader and BufferedReader?

    The source code for BufferedReader shows that the underlying is closed when you close the BufferedReader.

    Can't install any package with node npm

    Translated:

    It happened the same to me and in my case in particular was because the package.json was wrong. example:

    {
       "name": "app",
       "version": "0.0.0",
       "description": "any description",
       "main": "index.js",
       "author": "me", ->wrong
    }
    

    The last comma was left over and it gave me error any instalacción with npm in this proyect

    then:

    {
       "name": "app",
       "version": "0.0.0",
       "description": "any description",
       "main": "index.js",
       "author": "me"
    }
    

    I hope it will help.

    NumPy array is not JSON serializable

    Also, some very interesting information further on lists vs. arrays in Python ~> Python List vs. Array - when to use?

    It could be noted that once I convert my arrays into a list before saving it in a JSON file, in my deployment right now anyways, once I read that JSON file for use later, I can continue to use it in a list form (as opposed to converting it back to an array).

    AND actually looks nicer (in my opinion) on the screen as a list (comma seperated) vs. an array (not-comma seperated) this way.

    Using @travelingbones's .tolist() method above, I've been using as such (catching a few errors I've found too):

    SAVE DICTIONARY

    def writeDict(values, name):
        writeName = DIR+name+'.json'
        with open(writeName, "w") as outfile:
            json.dump(values, outfile)
    

    READ DICTIONARY

    def readDict(name):
        readName = DIR+name+'.json'
        try:
            with open(readName, "r") as infile:
                dictValues = json.load(infile)
                return(dictValues)
        except IOError as e:
            print(e)
            return('None')
        except ValueError as e:
            print(e)
            return('None')
    

    Hope this helps!

    Inner join of DataTables in C#

    this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.

    public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
    {
        var dt = new DataTable();
        var joinTable = from t1 in dataTable1.AsEnumerable()
                                join t2 in dataTable2.AsEnumerable()
                                    on t1[joinField] equals t2[joinField]
                                select new { t1, t2 };
    
        foreach (DataColumn col in dataTable1.Columns)
            dt.Columns.Add(col.ColumnName, typeof(string));
    
        dt.Columns.Remove(joinField);
    
        foreach (DataColumn col in dataTable2.Columns)
            dt.Columns.Add(col.ColumnName, typeof(string));
    
        foreach (var row in joinTable)
        {
            var newRow = dt.NewRow();
            newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
            dt.Rows.Add(newRow);
        }
        return dt;
    }
    

    Stretch and scale a CSS image in the background - with CSS only

    Thanks!

    But then it was not working for the Google Chrome and Safari browsers (stretching worked, but the hight of the pictures was only 2 mm!), until someone told me what lacks:

    Try to set height:auto;min-height:100%;

    So change that for your height:100%; line, gives:

    #### #background {
        width: 100%; 
        height: 100%; 
        position: fixed; 
        left: 0px; 
        top: 0px; 
        z-index: -1;
    }
    
    .stretch {
        width:100%;
        height:auto;
        min-height:100%;
    }
    

    Just before that newly added code I have this in my Drupal Tendu themes style.css:

    html, body{height:100%;}

    #page{background:#ffffff; height:auto !important;height:100%;min-height:100%;position:relative;}

    Then I have to make a new block within Drupal with the picture while adding class=stretch:

    < img alt="" class="stretch" src="pic.url" />

    Just copying a picture with the editor in that Drupal block doesn't work; one has to change the editor to non-formatted text.

    Creating a DateTime in a specific Time Zone in c#

    I altered Jon Skeet answer a bit for the web with extension method. It also works on azure like a charm.

    public static class DateTimeWithZone
    {
    
    private static readonly TimeZoneInfo timeZone;
    
    static DateTimeWithZone()
    {
    //I added web.config <add key="CurrentTimeZoneId" value="Central Europe Standard Time" />
    //You can add value directly into function.
        timeZone = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["CurrentTimeZoneId"]);
    }
    
    
    public static DateTime LocalTime(this DateTime t)
    {
         return TimeZoneInfo.ConvertTime(t, timeZone);   
    }
    }
    

    Test if a string contains a word in PHP?

    Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:

    if (strpos($string, $substring) === false) {
        // substring is not found in string
    }
    
    if (strpos($string, $substring2) !== false) {
        // substring2 is found in string
    }
    

    postgresql - add boolean column to table set default

    In psql alter column query syntax like this

    Alter table users add column priv_user boolean default false ;
    

    boolean value (true-false) save in DB like (t-f) value .

    og:type and valid values : constantly being parsed as og:type=website

    I know this is an old one but it comes up top of Google and all the links provided now seem out of date.

    This is the latest list of types Facebook accepts: https://developers.facebook.com/docs/reference/opengraph

    If you don't use one of these then the type will default to 'website' which is best used for home pages/summarising a web site.

    In answer to the OP you would now want to use a place which will allow you to add lat/long location details.

    [Vue warn]: Cannot find element

    I've solved the problem by add attribute 'defer' to the 'script' element.

    How do I test a website using XAMPP?

    Just edit the httpd-vhost-conf scroll to the bottom and on the last example/demo for creating a virtual host, remove the hash-tags for DocumentRoot and ServerName. You may have hash-tags just before the <VirtualHost *.80> and </VirtualHost>

    After DocumentRoot, just add the path to your web-docs ... and add your domain-name after ServerNmane

    <VirtualHost *:80>
        ##ServerAdmin [email protected]
        DocumentRoot "C:/xampp/htdocs/www"
        ServerName example.com
        ##ErrorLog "logs/dummy-host2.example.com-error.log"
        ##CustomLog "logs/dummy-host2.example.com-access.log" common
    </VirtualHost>
    

    Be sure to create the www folder under htdocs. You do not have to name the folder www but I did just to be simple about it. Be sure to restart Apache and bang! you can now store files in the newly created directory. To test things out just create a simple index.html or index.php file and place in the www folder, then go to your browser and test it out localhost/ ... Note: if your server is serving php files over html then remember to add localhost/index.html if the html file is the one you choose to use for this test.

    Something I should add, in order to still have access to the xampp homepage then you will need to create another VirtualHost. To do this just add

    <VirtualHost *:80>
        ##ServerAdmin [email protected]
        DocumentRoot "C:/xampp/htdocs"
        ServerName htdocs.example.com
        ##ErrorLog "logs/dummy-host2.example.com-error.log"
        ##CustomLog "logs/dummy-host2.example.com-access.log" common
    </VirtualHost>
    

    underneath the last VirtualHost that you created. Next make the necessary changes to your host file and restart Apache. Now go to your browser and visit htdocs.example.com and your all set.

    How to execute a command in a remote computer?

    I use the little utility which comes with PureMPI.net called execcmd.exe. Its syntax is as follows:

    execcmd \\yourremoteserver <your command here>
    

    Doesn't get any simpler than this :)

    Format an Integer using Java String Format

    If you are using a third party library called apache commons-lang, the following solution can be useful:

    Use StringUtils class of apache commons-lang :

    int i = 5;
    StringUtils.leftPad(String.valueOf(i), 3, "0"); // --> "005"
    

    As StringUtils.leftPad() is faster than String.format()

    How to show empty data message in Datatables

    By default the grid view will take care, just pass empty data set.

    What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

    Another option if you're using Flavors in Android Studio:

    Click Build -> Select Build Variant.

    In the list click the variant you're working in and it will turn green and the others will have the red J.

    auto refresh for every 5 mins

    Page should be refresh auto using meta tag

    <meta http-equiv="Refresh" content="60"> 
    

    content value in seconds.after one minute page should be refresh

    How can I obfuscate (protect) JavaScript?

    I can recommend JavaScript Utility by Patrick J. O'Neil. It can obfuscate/compact and compress and it seems to be pretty good at these. That said, I never tried integrating it in a build script of any kind.

    As for obfuscating vs. minifying - I am not a big fan of the former. It makes debugging impossible (Error at line 1... "wait, there is only one line") and they always take time to unpack. But if you need to... well.

    How to convert string to long

    String s = "1";
    
    try {
       long l = Long.parseLong(s);       
    } catch (NumberFormatException e) {
       System.out.println("NumberFormatException: " + e.getMessage());
    }
    

    Visual C++: How to disable specific linker warnings?

    Update 2018-10-16

    Reportedly, as of VS 2013, this warning can be disabled. See the comment by @Mark Ransom.

    Original Answer

    You can't disable that specific warning.

    According to Geoff Chappell the 4099 warning is treated as though it's too important to ignore, even by using in conjunction with /wx (which would treat warnings as errors and ignore the specified warning in other situations)

    Here is the relevant text from the link:

    Not Quite Unignorable Warnings

    For some warning numbers, specification in a /ignore option is accepted but not necessarily acted upon. Should the warning occur while the /wx option is not active, then the warning message is still displayed, but if the /wx option is active, then the warning is ignored. It is as if the warning is thought important enough to override an attempt at ignoring it, but not if the user has put too high a price on unignored warnings.

    The following warning numbers are affected:

    4200, 4203, 4204, 4205, 4206, 4207, 4208, 4209, 4219, 4231 and 4237
    

    String.format() to format double in java

    Use DecimalFormat

     NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
     DecimalFormat decimalFormatter = (DecimalFormat) nf;
     decimalFormatter.applyPattern("#,###,###.##");
     String fString = decimalFormatter.format(myDouble);
     System.out.println(fString);
    

    How can I render Partial views in asp.net mvc 3?

    <%= Html.Partial("PartialName", Model) %>
    

    How do I make a simple makefile for gcc on Linux?

    all: program
    program.o: program.h headers.h
    

    is enough. the rest is implicit

    What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

    I'm super late to this but I didn't like the other answers

    Installing Homebrew

    For brew run

    "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
    

    Installing node & npm

    You SHOULD NOT use brew to install node and npm.

    I've seen a few places suggested that you should use Homebrew to install Node (like alexpods answer and in this Team Treehouse blog Post) but installing this way you're more prone to run into issues as npm and brew are both package managers and you should have a package manager manage another package manager this leads to problems, like this bug offical npm issues Error: Refusing to delete: /usr/local/bin/npm or this Can't uninstall npm module on OSX

    You can read more on the topic in DanHerbert's post Fixing npm On Mac OS X for Homebrew Users, where he goes on to say

    Also, using the Homebrew installation of npm will require you to use sudo when installing global packages. Since one of the core ideas behind Homebrew is that apps can be installed without giving them root access, this is a bad idea.

    For Everything else

    I'd use npm; but you really should just follow the install instruction for each modules following the directions on there website as they will be more aware of any issue or bug they have than anyone else

    Check if a string contains a substring in SQL Server 2005, using a stored procedure

    You can just use wildcards in the predicate (after IF, WHERE or ON):

    @mainstring LIKE '%' + @substring + '%'
    

    or in this specific case

    ' ' + @mainstring + ' ' LIKE '% ME[., ]%'
    

    (Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

    Creating the checkbox dynamically using JavaScript?

    The last line should read

    cbh.appendChild(document.createTextNode(cap));
    

    Appending the text (label?) to the same container as the checkbox, not the checkbox itself

    How do I get list of all tables in a database using TSQL?

    Well you can use sys.objects to get all database objects.

     GO
     select * from sys.objects where type_desc='USER_TABLE' order by name
     GO
    

    OR

    --  For all tables
    select * from INFORMATION_SCHEMA.TABLES 
    GO 
    
      --- For user defined tables
    select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'
    GO
    
      --- For Views
    select * from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='VIEW'
    GO
    

    Get Number of Rows returned by ResultSet in Java

    Another way to differentiate between 0 rows or some rows from a ResultSet:

    ResultSet res = getData();
    
    if(!res.isBeforeFirst()){          //res.isBeforeFirst() is true if the cursor
                                       //is before the first row.  If res contains
                                       //no rows, rs.isBeforeFirst() is false.
    
        System.out.println("0 rows");
    }
    else{
        while(res.next()){
            // code to display the rows in the table.
        }
    }
    

    If you must know the number of rows given a ResultSet, here is a method to get it:

    public int getRows(ResultSet res){
        int totalRows = 0;
        try {
            res.last();
            totalRows = res.getRow();
            res.beforeFirst();
        } 
        catch(Exception ex)  {
            return 0;
        }
        return totalRows ;    
    }
    

    Find what 2 numbers add to something and multiply to something

    With the multiplication, I recommend using the modulo operator (%) to determine which numbers divide evenly into the target number like:

    $factors = array();
    for($i = 0; $i < $target; $i++){
        if($target % $i == 0){
            $temp = array()
            $a = $i;
            $b = $target / $i;
            $temp["a"] = $a;
            $temp["b"] = $b;
            $temp["index"] = $i;
            array_push($factors, $temp);
        }
    }
    

    This would leave you with an array of factors of the target number.

    CSS - Syntax to select a class within an id

    .navigationLevel2 li { color: #aa0000 }
    

    How to prevent scrollbar from repositioning web page?

    overflow-y:scroll is correct, but you should use it with the html tag, not body or else you get a double scrollbar in IE 7
    So the correct css would be:

    html {
      overflow-y: scroll;
    }
    

    Bootstrap Modal sitting behind backdrop

    I Found that applying ionic framework (ionic.min.cs) after bootstrap coursing this issue for me.

    How to get the CUDA version?

    One can get the cuda version by typing the following in the terminal:

    $ nvcc -V
    
    # below is the result
    nvcc: NVIDIA (R) Cuda compiler driver
    Copyright (c) 2005-2017 NVIDIA Corporation
    Built on Fri_Nov__3_21:07:56_CDT_2017
    Cuda compilation tools, release 9.1, V9.1.85
    

    Alternatively, one can manually check for the version by first finding out the installation directory using:

    $ whereis -b cuda         
    cuda: /usr/local/cuda
    

    And then cd into that directory and check for the CUDA version.

    How do I create a simple 'Hello World' module in Magento?

    First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

    Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

    Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.

    Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

    I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

    Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

    Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.

    Create a module

    All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows

    cd /path/to/store/app
    touch etc/modules/MyCompanyName_HelloWorld.xml
    
    <?xml version="1.0"?>
    <config>
         <modules>
            <MyCompanyName_HelloWorld>
                <active>true</active>
                <codePool>local</codePool>
            </MyCompanyName_HelloWorld>
         </modules>
    </config>
    

    MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module.

    Clear the application cache

    Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application

    1. Go to System->Cache Management
    2. Select Refresh from the All Cache menu
    3. Click Save Cache settings

    Now, we make sure that Magento knows about the module

    1. Go to System->Configuration
    2. Click Advanced
    3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"

    If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

    Setup the directory structure

    Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

    mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
    mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
    mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
    mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
    mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
    mkdir -p app/code/local/MyCompanyName/HelloWorld/sql
    

    And add a configuration file

    touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml
    

    and inside the configuration file, add the following, which is essentially a "blank" configuration.

    <?xml version="1.0"?>
    <config>
        <modules>
            <MyCompanyName_HelloWorld>
                <version>0.1.0</version>
            </MyCompanyName_HelloWorld>
        </modules>
    </config>
    

    Oversimplifying things, this configuration file will let you tell Magento what code you want to run.

    Setting up the router

    Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of

    http://example.com/magento/index.php/helloworld
    

    So, in your configuration file, add the following section.

    <config>
    <!-- ... -->
        <frontend>
            <routers>
                <!-- the <helloworld> tagname appears to be arbitrary, but by
                convention is should match the frontName tag below-->
                <helloworld>
                    <use>standard</use>
                    <args>
                        <module>MyCompanyName_HelloWorld</module>
                        <frontName>helloworld</frontName>
                    </args>
                </helloworld>
            </routers>
        </frontend>
    <!-- ... -->
    </config>
    

    What you're saying here is "any URL with the frontName of helloworld ...

    http://example.com/magento/index.php/helloworld
    

    should use the frontName controller MyCompanyName_HelloWorld".

    So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

    touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php
    

    Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception

    Controller file was loaded but class does not exist
    

    So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

    <?php
    class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
        public function indexAction(){
            echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
        }
    }
    

    What we've just setup is the module/frontName controller. This is the default controller and the default action of the module. If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName

    So if you want to match this url

    http://example.com/magento/index.php/helloworld/foo
    

    You will have to have a FooController, which you can do this way :

    touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
    
    <?php
    class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
        public function indexAction(){
            echo 'Foo Index Action';
        }
    
        public function addAction(){
            echo 'Foo add Action';
        }
    
        public function deleteAction(){
            echo 'Foo delete Action';
        }
    }
    

    Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it. So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foo because the second part of the url is and will always be the controllerName. This behaviour is an inheritance of the Zend Framework bundled in Magento.

    You should now be able to hit the following URLs and see the results of your echo statements

    http://example.com/magento/index.php/helloworld/foo
    http://example.com/magento/index.php/helloworld/foo/add
    http://example.com/magento/index.php/helloworld/foo/delete
    

    So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

    Android set height and width of Custom view programmatically

    you can set the height and width of a view in a relative layout like this

    ViewGroup.LayoutParams params = view.getLayoutParams();
    params.height = 130;
    view.setLayoutParams(params);
    

    Getting input values from text box

    Javascript document.getElementById("<%=contrilid.ClientID%>").value; or using jquery

    $("#<%= txt_iplength.ClientID %>").val();

    How to efficiently count the number of keys/properties of an object in JavaScript?

    To iterate on Avi Flax answer Object.keys(obj).length is correct for an object that doesnt have functions tied to it

    example:

    obj = {"lol": "what", owo: "pfft"};
    Object.keys(obj).length; // should be 2
    

    versus

    arr = [];
    obj = {"lol": "what", owo: "pfft"};
    obj.omg = function(){
        _.each(obj, function(a){
            arr.push(a);
        });
    };
    Object.keys(obj).length; // should be 3 because it looks like this 
    /* obj === {"lol": "what", owo: "pfft", omg: function(){_.each(obj, function(a){arr.push(a);});}} */
    

    steps to avoid this:

    1. do not put functions in an object that you want to count the number of keys in

    2. use a seperate object or make a new object specifically for functions (if you want to count how many functions there are in the file using Object.keys(obj).length)

    also yes i used the _ or underscore module from nodejs in my example

    documentation can be found here http://underscorejs.org/ as well as its source on github and various other info

    And finally a lodash implementation https://lodash.com/docs#size

    _.size(obj)

    Executing "SELECT ... WHERE ... IN ..." using MySQLdb

    If you have other parameters in the query, beyond the IN list, then the following extension to JG's answer may be useful.

    ids = [1, 5, 7, 213]
    sql = "select * from person where type=%s and id in (%s)"
    in_ids = ', '.join(map(lambda x: '%s', ids))
    sql = sql % ('%s', in_ids)
    params = []
    params.append(type)
    params.extend(ids)
    cursor.execute(sql, tuple(params))
    

    That is, join all the params in a linear array, then pass it as a tuple to the execute method.

    Android: Changing Background-Color of the Activity (Main View)

    Try this:

    _x000D_
    _x000D_
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorPrimaryDark"
    
    
    </androidx.constraintlayout.widget.ConstraintLayout>
        />
    _x000D_
    _x000D_
    _x000D_

    XML parsing of a variable string in JavaScript

    Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

    In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

    Here is a function I use (it's part of the Browser compatibility library I'm currently building):

    function LoadXMLString(xmlString)
    {
      // ObjectExists checks if the passed parameter is not null.
      // isString (as the name suggests) checks if the type is a valid string.
      if (ObjectExists(xmlString) && isString(xmlString))
      {
        var xDoc;
        // The GetBrowserType function returns a 2-letter code representing
        // ...the type of browser.
        var bType = GetBrowserType();
    
        switch(bType)
        {
          case "ie":
            // This actually calls into a function that returns a DOMDocument 
            // on the basis of the MSXML version installed.
            // Simplified here for illustration.
            xDoc = new ActiveXObject("MSXML2.DOMDocument")
            xDoc.async = false;
            xDoc.loadXML(xmlString);
            break;
          default:
            var dp = new DOMParser();
            xDoc = dp.parseFromString(xmlString, "text/xml");
            break;
        }
        return xDoc;
      }
      else
        return null;
    }
    

    How do I prevent a form from being resized by the user?

    There is an option in vb.net that lets you do all this.

    Set <code>lock = false</code> to <code>locked = true</code>

    The user wont be able to re-size the form or move it around, although there are other ways, this I think is the best.

    Resolve build errors due to circular dependency amongst classes

    The way to think about this is to "think like a compiler".

    Imagine you are writing a compiler. And you see code like this.

    // file: A.h
    class A {
      B _b;
    };
    
    // file: B.h
    class B {
      A _a;
    };
    
    // file main.cc
    #include "A.h"
    #include "B.h"
    int main(...) {
      A a;
    }
    

    When you are compiling the .cc file (remember that the .cc and not the .h is the unit of compilation), you need to allocate space for object A. So, well, how much space then? Enough to store B! What's the size of B then? Enough to store A! Oops.

    Clearly a circular reference that you must break.

    You can break it by allowing the compiler to instead reserve as much space as it knows about upfront - pointers and references, for example, will always be 32 or 64 bits (depending on the architecture) and so if you replaced (either one) by a pointer or reference, things would be great. Let's say we replace in A:

    // file: A.h
    class A {
      // both these are fine, so are various const versions of the same.
      B& _b_ref;
      B* _b_ptr;
    };
    

    Now things are better. Somewhat. main() still says:

    // file: main.cc
    #include "A.h"  // <-- Houston, we have a problem
    

    #include, for all extents and purposes (if you take the preprocessor out) just copies the file into the .cc. So really, the .cc looks like:

    // file: partially_pre_processed_main.cc
    class A {
      B& _b_ref;
      B* _b_ptr;
    };
    #include "B.h"
    int main (...) {
      A a;
    }
    

    You can see why the compiler can't deal with this - it has no idea what B is - it has never even seen the symbol before.

    So let's tell the compiler about B. This is known as a forward declaration, and is discussed further in this answer.

    // main.cc
    class B;
    #include "A.h"
    #include "B.h"
    int main (...) {
      A a;
    }
    

    This works. It is not great. But at this point you should have an understanding of the circular reference problem and what we did to "fix" it, albeit the fix is bad.

    The reason this fix is bad is because the next person to #include "A.h" will have to declare B before they can use it and will get a terrible #include error. So let's move the declaration into A.h itself.

    // file: A.h
    class B;
    class A {
      B* _b; // or any of the other variants.
    };
    

    And in B.h, at this point, you can just #include "A.h" directly.

    // file: B.h
    #include "A.h"
    class B {
      // note that this is cool because the compiler knows by this time
      // how much space A will need.
      A _a; 
    }
    

    HTH.

    What is a stack pointer used for in microprocessors?

    The Stack is an area of memory for keeping temporary data. Stack is used by the CALL instruction to keep the return address for procedures The return RET instruction gets this value from the stack and returns to that offset. The same thing happens when an INT instruction calls an interrupt. It stores in the Stack the flag register, code segment and offset. The IRET instruction is used to return from interrupt call.

    The Stack is a Last In First Out (LIFO) memory. Data is placed onto the Stack with a PUSH instruction and removed with a POP instruction. The Stack memory is maintained by two registers: the Stack Pointer (SP) and the Stack Segment (SS) register. When a word of data is PUSHED onto the stack the the High order 8-bit Byte is placed in location SP-1 and the Low 8-bit Byte is placed in location SP-2. The SP is then decremented by 2. The SP addds to the (SS x 10H) register, to form the physical stack memory address. The reverse sequence occurs when data is POPPED from the Stack. When a word of data is POPPED from the stack the the High order 8-bit Byte is obtained in location SP-1 and the Low 8-bit Byte is obtained in location SP-2. The SP is then incremented by 2.

    How to trim leading and trailing white spaces of a string?

    @peterSO has correct answer. I am adding more examples here:

    package main
    
    import (
        "fmt"
        strings "strings"
    )
    
    func main() { 
        test := "\t pdftk 2.0.2  \n"
        result := strings.TrimSpace(test)
        fmt.Printf("Length of %q is %d\n", test, len(test))
        fmt.Printf("Length of %q is %d\n\n", result, len(result))
    
        test = "\n\r pdftk 2.0.2 \n\r"
        result = strings.TrimSpace(test)
        fmt.Printf("Length of %q is %d\n", test, len(test))
        fmt.Printf("Length of %q is %d\n\n", result, len(result))
    
        test = "\n\r\n\r pdftk 2.0.2 \n\r\n\r"
        result = strings.TrimSpace(test)
        fmt.Printf("Length of %q is %d\n", test, len(test))
        fmt.Printf("Length of %q is %d\n\n", result, len(result))
    
        test = "\r pdftk 2.0.2 \r"
        result = strings.TrimSpace(test)
        fmt.Printf("Length of %q is %d\n", test, len(test))
        fmt.Printf("Length of %q is %d\n\n", result, len(result))   
    }
    

    You can find this in Go lang playground too.

    How to capitalize the first letter in a String in Ruby

    capitalize first letter of first word of string

    "kirk douglas".capitalize
    #=> "Kirk douglas"
    

    capitalize first letter of each word

    In rails:

    "kirk douglas".titleize
    => "Kirk Douglas"
    

    OR

    "kirk_douglas".titleize
    => "Kirk Douglas"    
    

    In ruby:

    "kirk douglas".split(/ |\_|\-/).map(&:capitalize).join(" ") 
    #=> "Kirk Douglas"
    

    OR

    require 'active_support/core_ext'
    "kirk douglas".titleize
    

    Pythonically add header to a csv file

    You just add one additional row before you execute the loop. This row contains your CSV file header name.

    schema = ['a','b','c','b']
    row = 4
    generators = ['A','B','C','D']
    with open('test.csv','wb') as csvfile:    
         writer = csv.writer(csvfile, delimiter=delimiter)
    # Gives the header name row into csv
         writer.writerow([g for g in schema])   
    #Data add in csv file       
         for x in xrange(rows):
             writer.writerow([g() for g in generators])
    

    css 'pointer-events' property alternative for IE

    Best solution:

    .disabled{filter: alpha(opacity=50);opacity: 0.5;z-index: 1;pointer-events: none;}
    

    Runs perfectly on all browsers

    A good Sorted List for Java

    You need no sorted list. You need no sorting at all.

    I need to add/remove keys from the list when object is added / removed from database.

    But not immediately, the removal can wait. Use an ArrayList containing the ID's all alive objects plus at most some bounded percentage of deleted objects. Use a separate HashSet to keep track of deleted objects.

    private List<ID> mostlyAliveIds = new ArrayList<>();
    private Set<ID> deletedIds = new HashSet<>();
    

    I want to randomly select few dozens of element from the whole list.

    ID selectOne(Random random) {
        checkState(deletedIds.size() < mostlyAliveIds.size());
        while (true) {
            int index = random.nextInt(mostlyAliveIds.size());
            ID id = mostlyAliveIds.get(index);
            if (!deletedIds.contains(ID)) return ID;
        }
    }
    
    Set<ID> selectSome(Random random, int count) {
        checkArgument(deletedIds.size() <= mostlyAliveIds.size() - count);
        Set<ID> result = new HashSet<>();
        while (result.size() < count) result.add(selectOne(random));
    }
    

    For maintaining the data, do something like

    void insert(ID id) {
        if (!deletedIds.remove(id)) mostlyAliveIds.add(ID);
    } 
    
    void delete(ID id) {
        if (!deletedIds.add(id)) {
             throw new ImpossibleException("Deleting a deleted element);
        }
        if (deletedIds.size() > 0.1 * mostlyAliveIds.size()) {
            mostlyAliveIds.removeAll(deletedIds);
            deletedIds.clear();
        }
    }
    

    The only tricky part is the insert which has to check if an already deleted ID was resurrected.

    The delete ensures that no more than 10% of elements in mostlyAliveIds are deleted IDs. When this happens, they get all removed in one sweep (I didn't check the JDK sources, but I hope, they do it right) and the show goes on.

    With no more than 10% of dead IDs, the overhead of selectOne is no more than 10% on the average.

    I'm pretty sure that it's faster than any sorting as the amortized complexity is O(n).

    How can I alter a primary key constraint using SQL syntax?

    In my case, I want to add a column to a Primary key (column4). I used this script to add column4

    ALTER TABLE TableA
    DROP CONSTRAINT [PK_TableA]
    
    ALTER TABLE TableA
    ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
        [column1] ASC,
        [column2] ASC, 
        [column3] ASC,
        [column4] ASC
    )
    

    How can I detect window size with jQuery?

    Do you want to detect when the window has been resized?

    You can use JQuery's resize to attach a handler.

    iPad Safari scrolling causes HTML elements to disappear and reappear with a delay

    There are cases where a rotation is applied and/or a Z index is used.

    Rotation: An existing declaration of -webkit-transform to rotate an element might not be enough to tackle the appearance problem as well (like -webkit-transform: rotate(-45deg)). In this case you can use -webkit-transform: translateZ(0px) rotateZ(-45deg) as a trick (mind the rotateZ).

    Z index: Together with the rotation you might define a positive z-index property, like z-index: 42. The above steps described under "Rotation" were in my case enough to resolve the issue, even with the empty translateZ(0px). I suspect though that the Z index in this case may have caused the disappearing and reappearing in the first place. In any case the z-index: 42 property needs to be kept -- -webkit-transform: translateZ(42px) only is not enough.

    HTTP error 403 in Python 3 Web Scraping

    If you feel guilty about faking the user-agent as Mozilla (comment in the top answer from Stefano), it could work with a non-urllib User-Agent as well. This worked for the sites I reference:

        req = urlrequest.Request(link, headers={'User-Agent': 'XYZ/3.0'})
        urlrequest.urlopen(req, timeout=10).read()
    

    My application is to test validity by scraping specific links that I refer to, in my articles. Not a generic scraper.

    Avoiding "resource is out of sync with the filesystem"

    You can enable this in Window - Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)

    Eclipse Preferences "Refresh using native hooks or polling" - Screenshot

    The only reason I can think why this isn't enabled by default is performance related.

    For example, refreshing source folders automatically might trigger a build of the workspace. Perhaps some people want more control over this.

    There is also an article on the Eclipse site regarding auto refresh.

    Basically, there is no external trigger that notifies Eclipse of files changed outside the workspace. Rather a background thread is used by Eclipse to monitor file changes that can possibly lead to performance issues with large workspaces.

    max value of integer

    Actually the size in bits of the int, short, long depends on the compiler implementation.

    E.g. on my Ubuntu 64 bit I have short in 32 bits, when on another one 32bit Ubuntu version it is 16 bit.

    prevent property from being serialized in web API

    Works fine by just adding the: [IgnoreDataMember]

    On top of the propertyp, like:

    public class UserSettingsModel
    {
        public string UserName { get; set; }
        [IgnoreDataMember]
        public DateTime Created { get; set; }
    }
    

    This works with ApiController. The code:

    [Route("api/Context/UserSettings")]
        [HttpGet, HttpPost]
        public UserSettingsModel UserSettings()
        {
            return _contextService.GetUserSettings();
        }
    

    Leader Not Available Kafka in Console Producer

    For me, I didn't specify broker id for Kafka instance. It will get a new id from zookeeper sometimes when it restarts in Docker environment. If your broker id is greater than 1000, just specify the environment variable KAFKA_BROKER_ID.

    Use this to see brokers, topics and partitions.

    brew install kafkacat
    kafkacat -b [kafka_ip]:[kafka_poot] -L
    

    How to use the command update-alternatives --config java

    Have a look at https://wiki.debian.org/JavaPackage At the bottom of this page an other method is descibed using a command from the java-common package

    Access PHP variable in JavaScript

    metrobalderas is partially right. Partially, because the PHP variable's value may contain some special characters, which are metacharacters in JavaScript. To avoid such problem, use the code below:

    <script type="text/javascript">
    var something=<?php echo json_encode($a); ?>;
    </script>
    

    JS: iterating over result of getElementsByClassName using Array.forEach

    As already said, getElementsByClassName returns a HTMLCollection, which is defined as

    [Exposed=Window]
    interface HTMLCollection {
      readonly attribute unsigned long length;
      getter Element? item(unsigned long index);
      getter Element? namedItem(DOMString name);
    };

    Previously, some browsers returned a NodeList instead.

    [Exposed=Window]
    interface NodeList {
      getter Node? item(unsigned long index);
      readonly attribute unsigned long length;
      iterable<Node>;
    };

    The difference is important, because DOM4 now defines NodeLists as iterable.

    According to Web IDL draft,

    Objects implementing an interface that is declared to be iterable support being iterated over to obtain a sequence of values.

    Note: In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.

    That means that, if you want to use forEach, you can use a DOM method which returns a NodeList, like querySelectorAll.

    document.querySelectorAll(".myclass").forEach(function(element, index, array) {
      // do stuff
    });
    

    Note this is not widely supported yet. Also see forEach method of Node.childNodes?

    Preventing multiple clicks on button

    If you are doing a full round-trip post-back, you can just make the button disappear. If there are validation errors, the button will be visible again upon reload of the page.

    First set add a style to your button:

    <h:commandButton id="SaveBtn" value="Save"
        styleClass="hideOnClick"
        actionListener="#{someBean.saveAction()}"/>
    

    Then make it hide when clicked.

    $(document).ready(function() {
        $(".hideOnClick").click(function(e) {
            $(e.toElement).hide();
        });
    });
    

    std::wstring VS std::string

    I frequently use std::string to hold utf-8 characters without any problems at all. I heartily recommend doing this when interfacing with API's which use utf-8 as the native string type as well.

    For example, I use utf-8 when interfacing my code with the Tcl interpreter.

    The major caveat is the length of the std::string, is no longer the number of characters in the string.

    Bootstrap 3: How to get two form inputs on one line and other inputs on individual lines?

    You can wrap the inputs in col-* classes

    <form name="registration_form" id="registration_form" class="form-horizontal">
         <div class="form-group">
               <div class="col-sm-6">
                 <label for="firstname" class="sr-only"></label>
                 <input id="firstname" class="form-control input-group-lg reg_name" type="text" name="firstname" title="Enter first name" placeholder="First name">
               </div>       
               <div class="col-sm-6">
                 <label for="lastname" class="sr-only"></label>
                 <input id="lastname" class="form-control input-group-lg reg_name" type="text" name="lastname" title="Enter last name" placeholder="Last name">
               </div>
        </div><!--/form-group-->
    
        <div class="form-group">
            <div class="col-sm-12">
              <label for="username" class="sr-only"></label>
              <input id="username" class="form-control input-group-lg" type="text" autocapitalize="off" name="username" title="Enter username" placeholder="Username">
            </div>
        </div><!--/form-group-->
    
        <div class="form-group">
            <div class="col-sm-12">
            <label for="password" class="sr-only"></label>
            <input id="password" class="form-control input-group-lg" type="password" name="password" title="Enter password" placeholder="Password">
            </div>
        </div><!--/form-group-->
     </form>
    

    http://bootply.com/127825

    Where is Java's Array indexOf?

    Jeffrey Hantin's answer is good but it has some constraints, if its this do this or else to that...

    You can write your own extension method and it always works the way you want.

    Lists.indexOf(array, x -> item == x); // compare in the way you want
    

    And here is your extension

    public final class Lists {
        private Lists() {
        }
    
        public static <T> int indexOf(T[] array, Predicate<T> predicate) {
            for (int i = 0; i < array.length; i++) {
                if (predicate.test(array[i])) return i;
            }
            return -1;
        }
    
        public static <T> int indexOf(List<T> list, Predicate<T> predicate) {
            for (int i = 0; i < list.size(); i++) {
                if (predicate.test(list.get(i))) return i;
            }
            return -1;
        }
    
        public interface Predicate<T> {
            boolean test(T t);
        }
    }
    

    Why use Ruby's attr_accessor, attr_reader and attr_writer?

    All of the answers above are correct; attr_reader and attr_writer are more convenient to write than manually typing the methods they are shorthands for. Apart from that they offer much better performance than writing the method definition yourself. For more info see slide 152 onwards from this talk (PDF) by Aaron Patterson.

    Prepare for Segue in Swift

    Prepare for Segue in Swift 4.2 and Swift 5.

        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "OrderVC") {
            // pass data to next view
            let viewController = segue.destination as? MyOrderDetailsVC
            viewController!.OrderData = self.MyorderArray[selectedIndex]
    
    
        }
    }
    

    How to Call segue On specific Event(Like Button Click etc):

    performSegue(withIdentifier: "OrderVC", sender: self)
    

    Selecting data from two different servers in SQL Server

    Querying across 2 different databases is a distributed query. Here is a list of some techniques plus the pros and cons:

    1. Linked servers: Provide access to a wider variety of data sources than SQL Server replication provides
    2. Linked servers: Connect with data sources that replication does not support or which require ad hoc access
    3. Linked servers: Perform better than OPENDATASOURCE or OPENROWSET
    4. OPENDATASOURCE and OPENROWSET functions: Convenient for retrieving data from data sources on an ad hoc basis. OPENROWSET has BULK facilities as well that may/may not require a format file which might be fiddley
    5. OPENQUERY: Doesn't support variables
    6. All are T-SQL solutions. Relatively easy to implement and set up
    7. All are dependent on connection between source and destionation which might affect performance and scalability

    How to redirect the output of an application in background to /dev/null

    You use:

    yourcommand  > /dev/null 2>&1
    

    If it should run in the Background add an &

    yourcommand > /dev/null 2>&1 &
    

    >/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

    If you want stderr to occur on console and only stdout going to /dev/null you can use:

    yourcommand 2>&1 > /dev/null
    

    In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

    If the program should not terminate you can use:

    nohup yourcommand &
    

    Without any parameter all output lands in nohup.out

    How to transform array to comma separated words string?

    $arr = array ( 0 => "lorem", 1 => "ipsum", 2 => "dolor");
    
    $str = implode (", ", $arr);
    

    Escaping a forward slash in a regular expression

    Here are a few options:

    • In Perl, you can choose alternate delimiters. You're not confined to m//. You could choose another, such as m{}. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{} is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, // and {} seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...), m[...], and m!...!.

    • In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$}, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.

    Call Class Method From Another Class

    update: Just saw the reference to call_user_func_array in your post. that's different. use getattr to get the function object and then call it with your arguments

    class A(object):
        def method1(self, a, b, c):
            # foo
    
    method = A.method1
    

    method is now an actual function object. that you can call directly (functions are first class objects in python just like in PHP > 5.3) . But the considerations from below still apply. That is, the above example will blow up unless you decorate A.method1 with one of the two decorators discussed below, pass it an instance of A as the first argument or access the method on an instance of A.

    a = A()
    method = a.method1
    method(1, 2)
    

    You have three options for doing this

    1. Use an instance of A to call method1 (using two possible forms)
    2. apply the classmethod decorator to method1: you will no longer be able to reference self in method1 but you will get passed a cls instance in it's place which is A in this case.
    3. apply the staticmethod decorator to method1: you will no longer be able to reference self, or cls in staticmethod1 but you can hardcode references to A into it, though obviously, these references will be inherited by all subclasses of A unless they specifically override method1 and do not call super.

    Some examples:

    class Test1(object): # always inherit from object in 2.x. it's called new-style classes. look it up
        def method1(self, a, b):
            return a + b
    
        @staticmethod
        def method2(a, b):
            return a + b
    
        @classmethod
        def method3(cls, a, b):
            return cls.method2(a, b)
    
    t = Test1()  # same as doing it in another class
    
    Test1.method1(t, 1, 2) #form one of calling a method on an instance
    t.method1(1, 2)        # form two (the common one) essentially reduces to form one
    
    Test1.method2(1, 2)  #the static method can be called with just arguments
    t.method2(1, 2)      # on an instance or the class
    
    Test1.method3(1, 2)  # ditto for the class method. It will have access to the class
    t.method3(1, 2)      # that it's called on (the subclass if called on a subclass) 
                         # but will not have access to the instance it's called on 
                         # (if it is called on an instance)
    

    Note that in the same way that the name of the self variable is entirely up to you, so is the name of the cls variable but those are the customary values.

    Now that you know how to do it, I would seriously think about if you want to do it. Often times, methods that are meant to be called unbound (without an instance) are better left as module level functions in python.

    Anchor links in Angularjs?

    You can also Navigate to HTML id from inside controller

    $location.hash('id_in_html');
    

    SharePoint 2013 get current user using JavaScript

    You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.

    <script type="text/javascript" src="/_layouts/15/SP.js"></script>
    <script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
    <script type="text/javascript">
    
      var personProperties;
    
      SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.UserProfiles.js');
    
      function getCurrentUser() {
        var clientContext = new SP.ClientContext.get_current();
        personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
        clientContext.load(personProperties);
        clientContext.executeQueryAsync(gotAccount, requestFailed);
      }
    
      function gotAccount(sender, args) {
        alert("Display Name: "+ personProperties.get_displayName() + 
            ", Account Name: " + personProperties.get_accountName());
      }
    
      function requestFailed(sender, args) {
        alert('Cannot get user account information: ' + args.get_message());
      }
    
    </script>
    

    See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.

    Disable nginx cache for JavaScript files

    Remember set sendfile off; or cache headers doesn't work. I use this snipped:

    location / {
    
            index index.php index.html index.htm;
            try_files $uri $uri/ =404; #.s. el /index.html para html5Mode de angular
    
            #.s. kill cache. use in dev
            sendfile off;
            add_header Last-Modified $date_gmt;
            add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
            if_modified_since off;
            expires off;
            etag off;
            proxy_no_cache 1;
            proxy_cache_bypass 1; 
        }
    

    How to change text and background color?

    `enter code here`#include <stdafx.h> // Used with MS Visual Studio Express. Delete line if using something different
    #include <conio.h> // Just for WaitKey() routine
    #include <iostream>
    #include <string>
    #include <windows.h>
    
    using namespace std;
    
    HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); // For use of SetConsoleTextAttribute()
    
    void WaitKey();
    
    int main()
    {
    
        int len = 0,x, y=240; // 240 = white background, black foreground 
    
        string text = "Hello World. I feel pretty today!";
        len = text.length();
        cout << endl << endl << endl << "\t\t"; // start 3 down, 2 tabs, right
        for ( x=0;x<len;x++)
        {
            SetConsoleTextAttribute(console, y); // set color for the next print
            cout << text[x];
            y++; // add 1 to y, for a new color
            if ( y >254) // There are 255 colors. 255 being white on white. Nothing to see. Bypass it
                y=240; // if y > 254, start colors back at white background, black chars
            Sleep(250); // Pause between letters 
        }
    
        SetConsoleTextAttribute(console, 15); // set color to black background, white chars
        WaitKey(); // Program over, wait for a keypress to close program
    }
    
    
    void WaitKey()
    {
        cout  << endl << endl << endl << "\t\t\tPress any key";
        while (_kbhit()) _getch(); // Empty the input buffer
        _getch(); // Wait for a key
        while (_kbhit()) _getch(); // Empty the input buffer (some keys sends two messages)
    }
    

    Display only 10 characters of a long string?

    html

    <p id='longText'>Some very very very very very very very very very very very long string</p>
    

    javascript (on doc ready)

    var longText = $('#longText');
    longText.text(longText.text().substr(0, 10));
    

    If you have multiple words in the text, and want each to be limited to at most 10 chars, you could do:

    var longText = $('#longText');
    var text = longText.text();
    var regex = /\w{11}\w*/, match;
    while(match = regex.exec(text)) {
        text = text.replace(match[0], match[0].substr(0, 10));
    }
    longText.text(text);
    

    How to center a checkbox in a table cell?

    Try this, this should work,

    td input[type="checkbox"] {
        float: left;
        margin: 0 auto;
        width: 100%;
    }
    

    How to get the caller's method name in the called method?

    I would use inspect.currentframe().f_back.f_code.co_name. Its use hasn't been covered in any of the prior answers which are mainly of one of three types:

    • Some prior answers use inspect.stack but it's known to be too slow.
    • Some prior answers use sys._getframe which is an internal private function given its leading underscore, and so its use is implicitly discouraged.
    • One prior answer uses inspect.getouterframes(inspect.currentframe(), 2)[1][3] but it's entirely unclear what [1][3] is accessing.
    import inspect
    from types import FrameType
    from typing import cast
    
    
    def caller_name() -> str:
        """Return the calling function's name."""
        # Ref: https://stackoverflow.com/a/57712700/
        return cast(FrameType, cast(FrameType, inspect.currentframe()).f_back).f_code.co_name
    
    
    if __name__ == '__main__':
        def _test_caller_name() -> None:
            assert caller_name() == '_test_caller_name'
        _test_caller_name()
    

    Note that cast(FrameType, frame) is used to satisfy mypy.


    Acknowlegement: comment by 1313e for an answer.

    How to get text from each cell of an HTML table?

    its

    selenium.getTable("tablename".rowNumber.colNumber)

    not

    selenium.getTable("tablename".colNumber.rowNumber)

    How can I pass a member function where a free function is expected?

    Since 2011, if you can change function1, do so, like this:

    #include <functional>
    #include <cstdio>
    
    using namespace std;
    
    class aClass
    {
    public:
        void aTest(int a, int b)
        {
            printf("%d + %d = %d", a, b, a + b);
        }
    };
    
    template <typename Callable>
    void function1(Callable f)
    {
        f(1, 1);
    }
    
    void test(int a,int b)
    {
        printf("%d - %d = %d", a , b , a - b);
    }
    
    int main()
    {
        aClass obj;
    
        // Free function
        function1(&test);
    
        // Bound member function
        using namespace std::placeholders;
        function1(std::bind(&aClass::aTest, obj, _1, _2));
    
        // Lambda
        function1([&](int a, int b) {
            obj.aTest(a, b);
        });
    }
    

    (live demo)

    Notice also that I fixed your broken object definition (aClass a(); declares a function).

    Find nearest value in numpy array

    IF your array is sorted and is very large, this is a much faster solution:

    def find_nearest(array,value):
        idx = np.searchsorted(array, value, side="left")
        if idx > 0 and (idx == len(array) or math.fabs(value - array[idx-1]) < math.fabs(value - array[idx])):
            return array[idx-1]
        else:
            return array[idx]
    

    This scales to very large arrays. You can easily modify the above to sort in the method if you can't assume that the array is already sorted. It’s overkill for small arrays, but once they get large this is much faster.

    How to initialize an array in Kotlin with values?

    In my case I need to initialise my drawer items. I fill data by below code.

        val iconsArr : IntArray = resources.getIntArray(R.array.navigation_drawer_items_icon)
        val names : Array<String> = resources.getStringArray(R.array.navigation_drawer_items_name)
    
    
        // Use lambda function to add data in my custom model class i.e. DrawerItem
        val drawerItems = Array<DrawerItem>(iconsArr.size, init = 
                             { index -> DrawerItem(iconsArr[index], names[index])})
        Log.d(LOGGER_TAG, "Number of items in drawer is: "+ drawerItems.size)
    

    Custom Model class-

    class DrawerItem(var icon: Int, var name: String) {
    
    }
    

    JavaScript - cannot set property of undefined

    In javascript almost everything is an object, null and undefined are exception.

    Instances of Array is an object. so you can set property of an array, for the same reason,you can't set property of a undefined, because its NOT an object

    Are vectors passed to functions by value or by reference in C++

    If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

    void foo(vector<int> bar); // by value
    void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
    void foo(vector<int> const &bar); // by const-reference
    

    You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

    Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

    I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

    void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
    void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
    void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
    void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }
    
    int main()
    {
        int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        foo1(arr);
        foo2(arr);
        foo3(arr);
        foo4(arr);
    }
    

    Read .csv file in C

    Hopefully this would get you started

    See it live on http://ideone.com/l23He (using stdin)

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    const char* getfield(char* line, int num)
    {
        const char* tok;
        for (tok = strtok(line, ";");
                tok && *tok;
                tok = strtok(NULL, ";\n"))
        {
            if (!--num)
                return tok;
        }
        return NULL;
    }
    
    int main()
    {
        FILE* stream = fopen("input", "r");
    
        char line[1024];
        while (fgets(line, 1024, stream))
        {
            char* tmp = strdup(line);
            printf("Field 3 would be %s\n", getfield(tmp, 3));
            // NOTE strtok clobbers tmp
            free(tmp);
        }
    }
    

    Output:

    Field 3 would be nazwisko
    Field 3 would be Kowalski
    Field 3 would be Nowak
    

    How can I make a multipart/form-data POST request using Java?

    We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java

    private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
    private static String subdata1 = "@@ -2,3 +2,4 @@\r\n";
    private static String subdata2 = "<data>subdata2</data>";
    
    public static void main(String[] args) throws Exception{        
        String url = "https://" + ip + ":" + port + "/dataupload";
        String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());
    
        MultipartBuilder multipart = new MultipartBuilder(url,token);       
        multipart.addFormField("entity", "main", "application/json",body);
        multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
        multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);        
        List<String> response = multipart.finish();         
        for (String line : response) {
            System.out.println(line);
        }
    }
    

    How is VIP swapping + CNAMEs better than IP swapping + A records?

    A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

    Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

    My answer refers to a special case of the general problem the OP describes, but I'll add it just in case it helps somebody out.

    When using @EnableOAuth2Sso, Spring puts an OAuth2RestTemplate on the application context, and this component happens to assume thread-bound servlet-related stuff.

    My code has a scheduled async method that uses an autowired RestTemplate. This isn't running inside DispatcherServlet, but Spring was injecting the OAuth2RestTemplate, which produced the error the OP describes.

    The solution was to do name-based injection. In the Java config:

    @Bean
    public RestTemplate pingRestTemplate() {
        return new RestTemplate();
    }
    

    and in the class that uses it:

    @Autowired
    @Qualifier("pingRestTemplate")
    private RestTemplate restTemplate;
    

    Now Spring injects the intended, servlet-free RestTemplate.

    How to embed matplotlib in pyqt - for Dummies

    Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...

    
    import sys
    from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
    
    from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
    from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
    import matplotlib.pyplot as plt
    
    import random
    
    class Window(QDialog):
        def __init__(self, parent=None):
            super(Window, self).__init__(parent)
    
            # a figure instance to plot on
            self.figure = plt.figure()
    
            # this is the Canvas Widget that displays the `figure`
            # it takes the `figure` instance as a parameter to __init__
            self.canvas = FigureCanvas(self.figure)
    
            # this is the Navigation widget
            # it takes the Canvas widget and a parent
            self.toolbar = NavigationToolbar(self.canvas, self)
    
            # Just some button connected to `plot` method
            self.button = QPushButton('Plot')
            self.button.clicked.connect(self.plot)
    
            # set the layout
            layout = QVBoxLayout()
            layout.addWidget(self.toolbar)
            layout.addWidget(self.canvas)
            layout.addWidget(self.button)
            self.setLayout(layout)
    
        def plot(self):
            ''' plot some random stuff '''
            # random data
            data = [random.random() for i in range(10)]
    
            # instead of ax.hold(False)
            self.figure.clear()
    
            # create an axis
            ax = self.figure.add_subplot(111)
    
            # discards the old graph
            # ax.hold(False) # deprecated, see above
    
            # plot data
            ax.plot(data, '*-')
    
            # refresh canvas
            self.canvas.draw()
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
    
        main = Window()
        main.show()
    
        sys.exit(app.exec_())
    

    What is Activity.finish() method doing exactly?

    When calling finish() on an activity, the method onDestroy() is executed. This method can do things like:

    1. Dismiss any dialogs the activity was managing.
    2. Close any cursors the activity was managing.
    3. Close any open search dialog

    Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state. So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed, the process will be killed

    Rock, Paper, Scissors Game Java

    Why not check for what the user entered and then ask the user to enter correct input again?

    eg:

    //Get player's play from input-- note that this is 
    // stored as a string 
    System.out.println("Enter your play: "); 
    response = scan.next();
    if(response=="R"||response=="P"||response=="S"){
      personPlay = response;
    }else{
      System.out.println("Invaild Input")
    }
    

    for the other modifications, please check my total code at pastebin

    MySQL: Fastest way to count number of rows

    I've always understood that the below will give me the fastest response times.

    SELECT COUNT(1) FROM ... WHERE ...
    

    I keep getting "Uncaught SyntaxError: Unexpected token o"

    The problem is very simple

    jQuery.get('wokab.json', function(data) {
        var glacier = JSON.parse(data);
    });
    

    You're parsing it twice. get uses the dataType='json', so data is already in json format. Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!

    How do I serialize an object and save it to a file in Android?

    Saving (w/o exception handling code):

    FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
    ObjectOutputStream os = new ObjectOutputStream(fos);
    os.writeObject(this);
    os.close();
    fos.close();
    

    Loading (w/o exception handling code):

    FileInputStream fis = context.openFileInput(fileName);
    ObjectInputStream is = new ObjectInputStream(fis);
    SimpleClass simpleClass = (SimpleClass) is.readObject();
    is.close();
    fis.close();
    

    how to make log4j to write to the console as well

    Your log4j File should look something like below read comments.

    # Define the types of logger and level of logging    
    log4j.rootLogger = DEBUG,console, FILE
    
    # Define the File appender    
    log4j.appender.FILE=org.apache.log4j.FileAppender    
    
    # Define Console Appender    
    log4j.appender.console=org.apache.log4j.ConsoleAppender    
    
    # Define the layout for console appender. If you do not 
    # define it, you will get an error    
    log4j.appender.console.layout=org.apache.log4j.PatternLayout
    
    # Set the name of the file    
    log4j.appender.FILE.File=log.out
    
    # Set the immediate flush to true (default)    
    log4j.appender.FILE.ImmediateFlush=true
    
    # Set the threshold to debug mode    
    log4j.appender.FILE.Threshold=debug
    
    # Set the append to false, overwrite    
    log4j.appender.FILE.Append=false
    
    # Define the layout for file appender    
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout    
    log4j.appender.FILE.layout.conversionPattern=%m%n
    

    Check if a string is a date value

    How about something like this? It will test if it is a Date object or a date string:

    function isDate(value) {
        var dateFormat;
        if (toString.call(value) === '[object Date]') {
            return true;
        }
        if (typeof value.replace === 'function') {
            value.replace(/^\s+|\s+$/gm, '');
        }
        dateFormat = /(^\d{1,4}[\.|\\/|-]\d{1,2}[\.|\\/|-]\d{1,4})(\s*(?:0?[1-9]:[0-5]|1(?=[012])\d:[0-5])\d\s*[ap]m)?$/;
        return dateFormat.test(value);
    }
    

    I should mention that this doesn't test for ISO formatted strings but with a little more work to the RegExp you should be good.

    How to run a .jar in mac?

    Make Executable your jar and after that double click on it on Mac OS then it works successfully.

    sudo chmod +x filename.jar

    Try this, I hope this works.

    Printing with sed or awk a line following a matching pattern

    Piping some greps can do it (it runs in POSIX shell and under BusyBox):

    cat my-file | grep -A1 my-regexp | grep -v -- '--' | grep -v my-regexp
    
    1. -v will show non-matching lines
    2. -- is printed by grep to separate each match, so we skip that too

    How do you change the server header returned by nginx?

    Are you asking about the Server header value in the response? You can try changing that with an add_header directive, but I'm not sure if it'll work. http://wiki.codemongers.com/NginxHttpHeadersModule

    How to join on multiple columns in Pyspark?

    You should use & / | operators and be careful about operator precedence (== has lower precedence than bitwise AND and OR):

    df1 = sqlContext.createDataFrame(
        [(1, "a", 2.0), (2, "b", 3.0), (3, "c", 3.0)],
        ("x1", "x2", "x3"))
    
    df2 = sqlContext.createDataFrame(
        [(1, "f", -1.0), (2, "b", 0.0)], ("x1", "x2", "x3"))
    
    df = df1.join(df2, (df1.x1 == df2.x1) & (df1.x2 == df2.x2))
    df.show()
    
    ## +---+---+---+---+---+---+
    ## | x1| x2| x3| x1| x2| x3|
    ## +---+---+---+---+---+---+
    ## |  2|  b|3.0|  2|  b|0.0|
    ## +---+---+---+---+---+---+
    

    Can’t delete docker image with dependent child images

    I had this issue and none of the short answers here worked, even in the page mentioned by @tudor above. I thought I would share here how I got rid of the images. I came up with the idea that dependent images must be >= the size of the parent image, which helps identify it so we can remove it.

    I listed the images in size order to see if I could spot any correlations:

    docker images --format '{{.Size}}\t{{.Repository}}\t{{.Tag}}\t{{.ID}}' | sort -h -r | column -t
    

    What this does, is use some special formatting from docker to position the image size column first, then run a human readable sort in reverse order. Then I restore the easy-to-read columns.

    Then I looked at the <none> containers, and matched the first one in the list with a similar size. I performed a simple docker rmi <image:tag> on that image and all the <none> child images went with it.

    The problem image with all the child images was actually the damn myrepo/getstarted-lab image I used when I first started playing with docker. It was because I had created a new image from the first test image which created the chain.

    Hopefully that helps someone else at some point.

    How to do select from where x is equal to multiple values?

    Put parentheses around the "OR"s:

    SELECT ads.*, location.county 
    FROM ads
    LEFT JOIN location ON location.county = ads.county_id
    WHERE ads.published = 1 
    AND ads.type = 13
    AND
    (
        ads.county_id = 2
        OR ads.county_id = 5
        OR ads.county_id = 7
        OR ads.county_id = 9
    )
    

    Or even better, use IN:

    SELECT ads.*, location.county 
    FROM ads
    LEFT JOIN location ON location.county = ads.county_id
    WHERE ads.published = 1 
    AND ads.type = 13
    AND ads.county_id IN (2, 5, 7, 9)
    

    How to run Ruby code from terminal?

    You can run ruby commands in one line with the -e flag:

    ruby -e "puts 'hi'"
    

    Check the man page for more information.

    Adding padding to a tkinter widget only on one side

    There are multiple ways of doing that you can use either place or grid or even the packmethod.

    Sample code:

    from tkinter import *
    root = Tk()
    
    l = Label(root, text="hello" )
    l.pack(padx=6, pady=4) # where padx and pady represent the x and y axis respectively
    # well you can also use side=LEFT inside the pack method of the label widget.
    

    To place a widget to on basis of columns and rows , use the grid method:

    but = Button(root, text="hello" )
    but.grid(row=0, column=1)
    

    "An attempt was made to load a program with an incorrect format" even when the platforms are the same

    I got this issue solved in the 'Windows' way. After checking all my settings, cleaning the solution and rebuilding it, I simply close the solution and reopened it. Then it worked, so VS probably didn't get rid of some stuff during cleaning. When logical solutions don't work, I usually turn to illogical (or seemingly illogical) ones. Windows doesn't let me down. :)