Programs & Examples On #Yield

yield is (1) a keyword that facilitates creation of generator functions, (2) a Ruby statement to transfer control from one coroutine to another

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

What are the situations where "yield from" is useful?

Every situation where you have a loop like this:

for x in subgenerator:
  yield x

As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()/.send()/.close() mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.

What is the classic use case?

Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:

def traverse_tree(node):
  if not node.children:
    yield node
  for child in node.children:
    yield from traverse_tree(child)

Even more important is the fact that until the yield from, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:

def get_list_values(lst):
  for item in lst:
    yield int(item)
  for item in lst:
    yield str(item)
  for item in lst:
    yield float(item)

Now you decide to factor out these loops into separate generators. Without yield from, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from, it's actually nice to look at:

def get_list_values(lst):
  for sub in [get_list_values_as_int, 
              get_list_values_as_str, 
              get_list_values_as_float]:
    yield from sub(lst)

Why is it compared to micro-threads?

I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield and __next__(), respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).

The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.

That analogy isn't anything specific to yield from, though - it's rather a general property of generators in Python.

What is the yield keyword used for in C#?

The yield keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
    foreach(int i in Integers())
    {
        Console.WriteLine(i.ToString());
    }
}

public IEnumerable<int> Integers()
{
    yield return 1;
    yield return 2;
    yield return 4;
    yield return 8;
    yield return 16;
    yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
    using (var connection = CreateConnection())
    {
        using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
        {
            command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
            using (var reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    yield return make(reader);
                }
            }
        }
    }
}

What does "yield break;" do in C#?

The yield break statement causes the enumeration to stop. In effect, yield break completes the enumeration without returning any additional items.

Consider that there are actually two ways that an iterator method could stop iterating. In one case, the logic of the method could naturally exit the method after returning all the items. Here is an example:

IEnumerable<uint> FindPrimes(uint startAt, uint maxCount)
{
    for (var i = 0UL; i < maxCount; i++)
    {
        startAt = NextPrime(startAt);
        yield return startAt;
    }

    Debug.WriteLine("All the primes were found.");
}

In the above example, the iterator method will naturally stop executing once maxCount primes have been found.

The yield break statement is another way for the iterator to cease enumerating. It is a way to break out of the enumeration early. Here is the same method as above. This time, the method has a limit on the amount of time that the method can execute.

IEnumerable<uint> FindPrimes(uint startAt, uint maxCount, int maxMinutes)
{
    var sw = System.Diagnostics.Stopwatch.StartNew();
    for (var i = 0UL; i < maxCount; i++)
    {
        startAt = NextPrime(startAt);
        yield return startAt;

        if (sw.Elapsed.TotalMinutes > maxMinutes)
            yield break;
    }

    Debug.WriteLine("All the primes were found.");
}

Notice the call to yield break. In effect, it is exiting the enumeration early.

Notice too that the yield break works differently than just a plain break. In the above example, yield break exits the method without making the call to Debug.WriteLine(..).

What does the "yield" keyword do?

Shortcut to understanding yield

When you see a function with yield statements, apply this easy trick to understand what will happen:

  1. Insert a line result = [] at the start of the function.
  2. Replace each yield expr with result.append(expr).
  3. Insert a line return result at the bottom of the function.
  4. Yay - no more yield statements! Read and figure out code.
  5. Compare function to the original definition.

This trick may give you an idea of the logic behind the function, but what actually happens with yield is significantly different than what happens in the list based approach. In many cases, the yield approach will be a lot more memory efficient and faster too. In other cases, this trick will get you stuck in an infinite loop, even though the original function works just fine. Read on to learn more...

Don't confuse your Iterables, Iterators, and Generators

First, the iterator protocol - when you write

for x in mylist:
    ...loop body...

Python performs the following two steps:

  1. Gets an iterator for mylist:

    Call iter(mylist) -> this returns an object with a next() method (or __next__() in Python 3).

    [This is the step most people forget to tell you about]

  2. Uses the iterator to loop over items:

    Keep calling the next() method on the iterator returned from step 1. The return value from next() is assigned to x and the loop body is executed. If an exception StopIteration is raised from within next(), it means there are no more values in the iterator and the loop is exited.

The truth is Python performs the above two steps anytime it wants to loop over the contents of an object - so it could be a for loop, but it could also be code like otherlist.extend(mylist) (where otherlist is a Python list).

Here mylist is an iterable because it implements the iterator protocol. In a user-defined class, you can implement the __iter__() method to make instances of your class iterable. This method should return an iterator. An iterator is an object with a next() method. It is possible to implement both __iter__() and next() on the same class, and have __iter__() return self. This will work for simple cases, but not when you want two iterators looping over the same object at the same time.

So that's the iterator protocol, many objects implement this protocol:

  1. Built-in lists, dictionaries, tuples, sets, files.
  2. User-defined classes that implement __iter__().
  3. Generators.

Note that a for loop doesn't know what kind of object it's dealing with - it just follows the iterator protocol, and is happy to get item after item as it calls next(). Built-in lists return their items one by one, dictionaries return the keys one by one, files return the lines one by one, etc. And generators return... well that's where yield comes in:

def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print item

Instead of yield statements, if you had three return statements in f123() only the first would get executed, and the function would exit. But f123() is no ordinary function. When f123() is called, it does not return any of the values in the yield statements! It returns a generator object. Also, the function does not really exit - it goes into a suspended state. When the for loop tries to loop over the generator object, the function resumes from its suspended state at the very next line after the yield it previously returned from, executes the next line of code, in this case, a yield statement, and returns that as the next item. This happens until the function exits, at which point the generator raises StopIteration, and the loop exits.

So the generator object is sort of like an adapter - at one end it exhibits the iterator protocol, by exposing __iter__() and next() methods to keep the for loop happy. At the other end, however, it runs the function just enough to get the next value out of it, and puts it back in suspended mode.

Why Use Generators?

Usually, you can write code that doesn't use generators but implements the same logic. One option is to use the temporary list 'trick' I mentioned before. That will not work in all cases, for e.g. if you have infinite loops, or it may make inefficient use of memory when you have a really long list. The other approach is to implement a new iterable class SomethingIter that keeps the state in instance members and performs the next logical step in it's next() (or __next__() in Python 3) method. Depending on the logic, the code inside the next() method may end up looking very complex and be prone to bugs. Here generators provide a clean and easy solution.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

With ES6 supporting Promises, we can use them without any third-party aid.

const sleep = (seconds) => {
    return new Promise((resolve, reject) => {
        setTimeout(resolve, (seconds * 1000));
    });
};

// We are not using `reject` anywhere, but it is good to
// stick to standard signature.

Then use it like this:

const waitThenDo(howLong, doWhat) => {
    return sleep(howLong).then(doWhat);
};

Note that the doWhat function becomes the resolve callback within the new Promise(...).

Also note that this is ASYNCHRONOUS sleep. It does not block the event loop. If you need blocking sleep, use this library which realizes blocking sleep with the help of C++ bindings. (Although the need for a blocking sleep in Node like async environments is rare.)

https://github.com/erikdubbelboer/node-sleep

What is Scala's yield?

Yes, as Earwicker said, it's pretty much the equivalent to LINQ's select and has very little to do with Ruby's and Python's yield. Basically, where in C# you would write

from ... select ??? 

in Scala you have instead

for ... yield ???

It's also important to understand that for-comprehensions don't just work with sequences, but with any type which defines certain methods, just like LINQ:

  • If your type defines just map, it allows for-expressions consisting of a single generator.
  • If it defines flatMap as well as map, it allows for-expressions consisting of several generators.
  • If it defines foreach, it allows for-loops without yield (both with single and multiple generators).
  • If it defines filter, it allows for-filter expressions starting with an if in the for expression.

What's the yield keyword in JavaScript?

Simplifying/elaborating on Nick Sotiros' answer (which I think is awesome), I think it's best to describe how one would start coding with yield.

In my opinion, the biggest advantage of using yield is that it will eliminate all the nested callback problems we see in code. It's hard to see how at first, which is why I decided to write this answer (for myself, and hopefully others!)

The way it does it is by introducing the idea of a co-routine, which is a function that can voluntarily stop/pause until it gets what it needs. In javascript, this is denoted by function*. Only function* functions can use yield.

Here's some typical javascript:

loadFromDB('query', function (err, result) {
  // Do something with the result or handle the error
})

This is clunky because now all of your code (which obviously needs to wait for this loadFromDB call) needs to be inside this ugly looking callback. This is bad for a few reasons...

  • All of your code is indented one level in
  • You have this end }) which you need to keep track of everywhere
  • All this extra function (err, result) jargon
  • Not exactly clear that you're doing this to assign a value to result

On the other hand, with yield, all of this can be done in one line with the help of the nice co-routine framework.

function* main() {
  var result = yield loadFromDB('query')
}

And so now your main function will yield where necessary when it needs to wait for variables and things to load. But now, in order to run this, you need to call a normal (non-coroutine function). A simple co-routine framework can fix this problem so that all you have to do is run this:

start(main())

And start is defined (from Nick Sotiro' answer)

function start(routine, data) {
    result = routine.next(data);
    if(!result.done) {
        result.value(function(err, data) {
            if(err) routine.throw(err); // continue next iteration of routine with an exception
            else start(routine, data);  // continue next iteration of routine normally
        });
    }
}

And now, you can have beautiful code that is much more readable, easy to delete, and no need to fiddle with indents, functions, etc.

An interesting observation is that in this example, yield is actually just a keyword you can put before a function with a callback.

function* main() {
  console.log(yield function(cb) { cb(null, "Hello World") })
}

Would print "Hello World". So you can actually turn any callback function into using yield by simply creating the same function signature (without the cb) and returning function (cb) {}, like so:

function yieldAsyncFunc(arg1, arg2) {
  return function (cb) {
    realAsyncFunc(arg1, arg2, cb)
  }
}

Hopefully with this knowledge you can write cleaner, more readable code that is easy to delete!

Setting default value for TypeScript object passed as argument

Typescript supports default parameters now:

https://www.typescriptlang.org/docs/handbook/functions.html

Also, adding a default value allows you to omit the type declaration, because it can be inferred from the default value:

function sayName(firstName: string, lastName = "Smith") {
  const name = firstName + ' ' + lastName;
  alert(name);
}

sayName('Bob');

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

For me, the clue was the "org.codehaus.mojo:exec-maven-plugin:1.2.1:exec".
The only place this was referenced was in the "Run project" action under Project Properties=>Actions.

When I changed this action to match the HelloFXMLWithMaven sample project (available in Netbeans 11.1): "clean javafx:run" then executing the Run goal was able to proceed.

Note, I also had to update the pom file's javafx-maven-plugin to also match the sample project but with the mainClass changed for my project.

How exactly does the android:onClick XML attribute differ from setOnClickListener?

I am Write this code in xml file ...

<Button
    android:id="@+id/btn_register"
    android:layout_margin="1dp"
    android:layout_marginLeft="3dp"
    android:layout_marginTop="10dp"
    android:layout_weight="2"
    android:onClick="register"
    android:text="Register"
    android:textColor="#000000"/>

And write this code in fragment...

public void register(View view) {
}

php exec() is not executing the command

I already said that I was new to exec() function. After doing some more digging, I came upon 2>&1 which needs to be added at the end of command in exec().

Thanks @mattosmat for pointing it out in the comments too. I did not try this at once because you said it is a Linux command, I am on Windows.

So, what I have discovered, the command is actually executing in the back-end. That is why I could not see it actually running, which I was expecting to happen.

For all of you, who had similar problem, my advise is to use that command. It will point out all the errors and also tell you info/details about execution.

exec('some_command 2>&1', $output);
print_r($output);  // to see the response to your command

Thanks for all the help guys, I appreciate it ;)

Can regular JavaScript be mixed with jQuery?

Or no JavaScript load function at all...

<html>
<head></head>
<body>
    <canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
    var draw = function() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (10, 10, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);
        }
    }
    draw();

    //or self executing...

    (function(){
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (50, 50, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (70, 70, 55, 50);
        }
    })();
</script>
</html>

Using DISTINCT and COUNT together in a MySQL Query

Isn't it better with a group by? Something like:

SELECT COUNT(*) FROM t1 GROUP BY keywork;

How to Bootstrap navbar static to fixed on scroll?

If you are using Bootstrap 4, which is the latest version as writing this answer, the assingments have changed a bit. Here is an example of a navbar fixed on top:

<nav class="navbar fixed-top navbar-light bg-light">
    <a class="navbar-brand" href="#"><h1>Navbar</h1></a>
</nav>

How to access property of anonymous type in C#?

If you want a strongly typed list of anonymous types, you'll need to make the list an anonymous type too. The easiest way to do this is to project a sequence such as an array into a list, e.g.

var nodes = (new[] { new { Checked = false, /* etc */ } }).ToList();

Then you'll be able to access it like:

nodes.Any(n => n.Checked);

Because of the way the compiler works, the following then should also work once you have created the list, because the anonymous types have the same structure so they are also the same type. I don't have a compiler to hand to verify this though.

nodes.Add(new { Checked = false, /* etc */ });

Items in JSON object are out of order using "json.dumps"?

As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: http://code.activestate.com/recipes/576693/ ).

I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm not sure (and I don't have easy access to test).

Old pythons simplejson implementations dont handle the OrderedDict objects nicely .. and convert them to regular dicts before outputting them.. but you can overcome this by doing the following:

class OrderedJsonEncoder( simplejson.JSONEncoder ):
   def encode(self,o):
      if isinstance(o,OrderedDict.OrderedDict):
         return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
      else:
         return simplejson.JSONEncoder.encode(self, o)

now using this we get:

>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}

Which is pretty much as desired.

Another alternative would be to specialise the encoder to directly use your row class, and then you'd not need any intermediate dict or UnorderedDict.

HTTP Status 404 - The requested resource (/) is not available

If you are new in JSP/Tomcat don't modify tomcat's xml files.

I assume you have already deployed web application. But to be sure, try these steps: - right click on your web application - select Run As / Run on Server, choose your Tomcat 7

These steps will deploy and run in the browser your application. Another idea to check if your Tomcat works correctly is to find path where tomcat exists (in eclipse plugin), and copy some working WAR file to webapps (not to wtpwebapps), and then try to run the app.

Convert string to JSON array

Here you get JSONObject so change this line:

JSONArray jsonArray = new JSONArray(readlocationFeed); 

with following:

JSONObject jsnobject = new JSONObject(readlocationFeed);

and after

JSONArray jsonArray = jsnobject.getJSONArray("locations");
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject explrObject = jsonArray.getJSONObject(i);
}

How to run Ruby code from terminal?

If Ruby is installed, then

ruby yourfile.rb

where yourfile.rb is the file containing the ruby code.

Or

irb

to start the interactive Ruby environment, where you can type lines of code and see the results immediately.

How to access the services from RESTful API in my angularjs page?

Welcome to the wonderful world of Angular !!

I am very new to angularJS. I am searching for accessing services from RESTful API but I didn't get any idea. please help me to do that. Thank you

There are two (very big) hurdles to writing your first Angular scripts, if you're currently using 'GET' services.

First, your services must implement the "Access-Control-Allow-Origin" property, otherwise the services will work a treat when called from, say, a web browser, but fail miserably when called from Angular.

So, you'll need to add a few lines to your web.config file:

<configuration>
  ... 
  <system.webServer>
    <httpErrors errorMode="Detailed"/>
    <validation validateIntegratedModeConfiguration="false"/>
    <!-- We need the following 6 lines, to let AngularJS call our REST web services -->
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*"/>
            <add name="Access-Control-Allow-Headers" value="Content-Type"/>
        </customHeaders>
    </httpProtocol>
  </system.webServer>
  ... 
</configuration>

Next, you need to add a little bit of code to your HTML file, to force Angular to call 'GET' web services:

// Make sure AngularJS calls our WCF Service as a "GET", rather than as an "OPTION"
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

Once you have these fixes in place, actually calling a RESTful API is really straightforward.

function YourAngularController($scope, $http) 
{
    $http.get('http://www.iNorthwind.com/Service1.svc/getAllCustomers')
        .success(function (data) {
        //  
        //  Do something with the data !
        //  
    });
}

You can find a really clear walkthrough of these steps on this webpage:

Using Angular, with JSON data

Good luck !

Mike

Get the current displaying UIViewController on the screen in AppDelegate.m

zirinisp's Answer in Swift:

extension UIWindow {

    func visibleViewController() -> UIViewController? {
        if let rootViewController: UIViewController  = self.rootViewController {
            return UIWindow.getVisibleViewControllerFrom(rootViewController)
        }
        return nil
    }

    class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {

        if vc.isKindOfClass(UINavigationController.self) {

            let navigationController = vc as UINavigationController
            return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController)

        } else if vc.isKindOfClass(UITabBarController.self) {

            let tabBarController = vc as UITabBarController
            return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!)

        } else {

            if let presentedViewController = vc.presentedViewController {

                return UIWindow.getVisibleViewControllerFrom(presentedViewController.presentedViewController!)

            } else {

                return vc;
            }
        }
    }
}

Usage:

 if let topController = window.visibleViewController() {
            println(topController)
        }

How do I split a string into an array of characters?

The split() method in javascript accepts two parameters: a separator and a limit. The separator specifies the character to use for splitting the string. If you don't specify a separator, the entire string is returned, non-separated. But, if you specify the empty string as a separator, the string is split between each character.

Therefore:

s.split('')

will have the effect you seek.

More information here

Edit line thickness of CSS 'underline' attribute

Here is one way of achieving this :

HTML :

<h4>This is a heading</h4>

<h4><u>This is another heading</u></h4>

?CSS :

 u {
    text-decoration: none;
    border-bottom: 10px solid black;
  }?

Here is an example: http://jsfiddle.net/AQ9rL/

python dict to numpy structured array

I would prefer storing keys and values on separate arrays. This i often more practical. Structures of arrays are perfect replacement to array of structures. As most of the time you have to process only a subset of your data (in this cases keys or values, operation only with only one of the two arrays would be more efficient than operating with half of the two arrays together.

But in case this way is not possible, I would suggest to use arrays sorted by column instead of by row. In this way you would have the same benefit as having two arrays, but packed only in one.

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

names = 0
values = 1
array = np.empty(shape=(2, len(result)), dtype=float)
array[names] = result.keys()
array[values] = result.values()

But my favorite is this (simpler):

import numpy as np
result = {0: 1.1181753789488595, 1: 0.5566080288678394, 2: 0.4718269778030734, 3: 0.48716683119447185, 4: 1.0, 5: 0.1395076201641266, 6: 0.20941558441558442}

arrays = {'names': np.array(result.keys(), dtype=float),
          'values': np.array(result.values(), dtype=float)}

Understanding INADDR_ANY for socket programming

INADDR_ANY is a constant, that contain 0 in value . this will used only when you want connect from all active ports you don't care about ip-add . so if you want connect any particular ip you should mention like as my_sockaddress.sin_addr.s_addr = inet_addr("192.168.78.2")

submitting a GET form with query string params and hidden params disappear

<form ... action="http:/www.blabla.com?a=1&b=2" method ="POST">
<input type="hidden" name="c" value="3" /> 
</form>

change the request method to' POST' instead of 'GET'.

How can labels/legends be added for all chart types in chart.js (chartjs.org)?

I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :

_x000D_
_x000D_
Chart.Type.extend({_x000D_
      //Passing in a name registers this chart in the Chart namespace_x000D_
      name: "Doughnut",_x000D_
      //Providing a defaults will also register the deafults in the chart namespace_x000D_
      defaults: defaultConfig,_x000D_
      .......
_x000D_
_x000D_
_x000D_

My legendTemplate is changed from

_x000D_
_x000D_
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<datasets.length; i++){%>_x000D_
    <li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
      <%if(datasets[i].label){%>_x000D_
        <%=datasets[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

To

_x000D_
_x000D_
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
  <% for (var i=0; i<segments.length; i++){%>_x000D_
    <li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
      <%if(segments[i].label){%>_x000D_
        <%=s egments[i].label%>_x000D_
          <%}%>_x000D_
    </li>_x000D_
    <%}%>_x000D_
</ul>"
_x000D_
_x000D_
_x000D_

Webfont Smoothing and Antialiasing in Firefox and Opera

As Opera is powered by Blink since Version 15.0 -webkit-font-smoothing: antialiased does also work on Opera.

Firefox has finally added a property to enable grayscaled antialiasing. After a long discussion it will be available in Version 25 with another syntax, which points out that this property only works on OS X.

-moz-osx-font-smoothing: grayscale;

This should fix blurry icon fonts or light text on dark backgrounds.

.font-smoothing {
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

You may read my post about font rendering on OSX which includes a Sass mixin to handle both properties.

Getting the names of all files in a directory with PHP

Another way to list directories and files would be using the RecursiveTreeIterator answered here: https://stackoverflow.com/a/37548504/2032235.

A thorough explanation of RecursiveIteratorIterator and iterators in PHP can be found here: https://stackoverflow.com/a/12236744/2032235

Allow only numbers and dot in script

Try this for multiple text fileds (using class selector):

Click here for example..

_x000D_
_x000D_
var checking = function(event){_x000D_
 var data = this.value;_x000D_
 if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){_x000D_
  if(data.indexOf('.') > -1){_x000D_
    if(event.charCode== 46)_x000D_
      event.preventDefault();_x000D_
  }_x000D_
 }else_x000D_
  event.preventDefault();_x000D_
 };_x000D_
_x000D_
 function addListener(list){_x000D_
  for(var i=0;i<list.length;i++){_x000D_
      list[i].addEventListener('keypress',checking);_x000D_
     }_x000D_
 }_x000D_
 var classList = document.getElementsByClassName('number');_x000D_
 addListener(classList);
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Page Title</title>_x000D_
</head>_x000D_
<body>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
  <input type="text" class="number" value="" /><br><br>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Global Variable in app.js accessible in routes?

As others have already shared, app.set('config', config) is great for this. I just wanted to add something that I didn't see in existing answers that is quite important. A Node.js instance is shared across all requests, so while it may be very practical to share some config or router object globally, storing runtime data globally will be available across requests and users. Consider this very simple example:

var express = require('express');
var app = express();

app.get('/foo', function(req, res) {
    app.set('message', "Welcome to foo!");
    res.send(app.get('message'));
});

app.get('/bar', function(req, res) {
    app.set('message', "Welcome to bar!");

    // some long running async function
    var foo = function() {
        res.send(app.get('message'));
    };
    setTimeout(foo, 1000);
});

app.listen(3000);

If you visit /bar and another request hits /foo, your message will be "Welcome to foo!". This is a silly example, but it gets the point across.

There are some interesting points about this at Why do different node.js sessions share variables?.

Process list on Linux via Python

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

round a single column in pandas

No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

Placeholder in UITextView

Below is a Swift port of "SAMTextView" ObjC code posted as one of the first handful of replies to the question. I tested it on iOS 8. I tweaked a couple of things, including the bounds offset for the placement of the placeholder text, as the original was too high and too far right (used suggestion in one of the comments to that post).

I know there are a lot of simple solutions, but I like the approach of subclassing UITextView because it's reusable and I don't have to clutter classes utilizing it with the mechanisms.

Swift 2.2:

import UIKit

class PlaceholderTextView: UITextView {

    @IBInspectable var placeholderColor: UIColor = UIColor.lightGrayColor()
    @IBInspectable var placeholderText: String = ""

    override var font: UIFont? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            setNeedsDisplay()
        }
    }

    override var textAlignment: NSTextAlignment {
        didSet {
            setNeedsDisplay()
        }
    }

    override var text: String? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var attributedText: NSAttributedString? {
        didSet {
            setNeedsDisplay()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
    }

    private func setUp() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlaceholderTextView.textChanged(_:)),
                                                         name: UITextViewTextDidChangeNotification, object: self)
    }

    func textChanged(notification: NSNotification) {
        setNeedsDisplay()
    }

    func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        var x = contentInset.left + 4.0
        var y = contentInset.top  + 9.0
        let w = frame.size.width - contentInset.left - contentInset.right - 16.0
        let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0

        if let style = self.typingAttributes[NSParagraphStyleAttributeName] as? NSParagraphStyle {
            x += style.headIndent
            y += style.firstLineHeadIndent
        }
        return CGRect(x: x, y: y, width: w, height: h)
    }

    override func drawRect(rect: CGRect) {
        if text!.isEmpty && !placeholderText.isEmpty {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = textAlignment
            let attributes: [ String: AnyObject ] = [
                NSFontAttributeName : font!,
                NSForegroundColorAttributeName : placeholderColor,
                NSParagraphStyleAttributeName  : paragraphStyle]

            placeholderText.drawInRect(placeholderRectForBounds(bounds), withAttributes: attributes)
        }
        super.drawRect(rect)
    }
}

Swift 4.2:

import UIKit

class PlaceholderTextView: UITextView {

    @IBInspectable var placeholderColor: UIColor = UIColor.lightGray
    @IBInspectable var placeholderText: String = ""

    override var font: UIFont? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var contentInset: UIEdgeInsets {
        didSet {
            setNeedsDisplay()
        }
    }

    override var textAlignment: NSTextAlignment {
        didSet {
            setNeedsDisplay()
        }
    }

    override var text: String? {
        didSet {
            setNeedsDisplay()
        }
    }

    override var attributedText: NSAttributedString? {
        didSet {
            setNeedsDisplay()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setUp()
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
    }

    private func setUp() {
        NotificationCenter.default.addObserver(self,
         selector: #selector(self.textChanged(notification:)),
         name: Notification.Name("UITextViewTextDidChangeNotification"),
         object: nil)
    }

    @objc func textChanged(notification: NSNotification) {
        setNeedsDisplay()
    }

    func placeholderRectForBounds(bounds: CGRect) -> CGRect {
        var x = contentInset.left + 4.0
        var y = contentInset.top  + 9.0
        let w = frame.size.width - contentInset.left - contentInset.right - 16.0
        let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0

        if let style = self.typingAttributes[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle {
            x += style.headIndent
            y += style.firstLineHeadIndent
        }
        return CGRect(x: x, y: y, width: w, height: h)
    }

    override func draw(_ rect: CGRect) {
        if text!.isEmpty && !placeholderText.isEmpty {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = textAlignment
            let attributes: [NSAttributedString.Key: Any] = [
            NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : font!,
            NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : placeholderColor,
            NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue)  : paragraphStyle]

            placeholderText.draw(in: placeholderRectForBounds(bounds: bounds), withAttributes: attributes)
        }
        super.draw(rect)
    }
}

web.xml is missing and <failOnMissingWebXml> is set to true

For Project with web.xml present Project-->Properties-->Deployment Assembly,where you can add Folder src/main/webapp. Save change. Clean the project to get going.

For Project with web.xml not present Set failOnMissingWebXml to false in pom.xml under properties tag.

Inserting multiple rows in a single SQL query?

NOTE: This answer is for SQL Server 2005. For SQL Server 2008 and later, there are much better methods as seen in the other answers.

You can use INSERT with SELECT UNION ALL:

INSERT INTO MyTable  (FirstCol, SecondCol)
    SELECT  'First' ,1
    UNION ALL
SELECT  'Second' ,2
    UNION ALL
SELECT  'Third' ,3
...

Only for small datasets though, which should be fine for your 4 records.

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

Link to something more sensible than the top of the page in the first place. Then cancel the default event.

See rule 2 of pragmatic progressive enhancement.

c# datagridview doubleclick on row with FullRowSelect

In CellContentDoubleClick event fires only when double clicking on cell's content. I used this and works:

    private void dgvUserList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(e.RowIndex.ToString());
    }

How to execute python file in linux

If you have python 3 installed then add this line to the top of the file:

 #!/usr/bin/env python3

You should also check the file have the right to be execute. chmod +x file.py

For more details, follow the official forum:

https://askubuntu.com/questions/761365/how-to-run-a-python-program-directly

Get selected text from a drop-down list (select box) using jQuery

Various ways

1. $("#myselect option:selected").text();

2. $("#myselect :selected").text();

3. $("#myselect").children(":selected").text();

4. $("#myselect").find(":selected").text();

How do you use variables in a simple PostgreSQL script?

Here's an example of using a variable in plpgsql:

create table test (id int);
insert into test values (1);
insert into test values (2);
insert into test values (3);

create function test_fn() returns int as $$
    declare val int := 2;
    begin
        return (SELECT id FROM test WHERE id = val);
    end;
$$ LANGUAGE plpgsql;

SELECT * FROM test_fn();
 test_fn 
---------
       2

Have a look at the plpgsql docs for more information.

C++ Object Instantiation

On the contrary, you should always prefer stack allocations, to the extent that as a rule of thumb, you should never have new/delete in your user code.

As you say, when the variable is declared on the stack, its destructor is automatically called when it goes out of scope, which is your main tool for tracking resource lifetime and avoiding leaks.

So in general, every time you need to allocate a resource, whether it's memory (by calling new), file handles, sockets or anything else, wrap it in a class where the constructor acquires the resource, and the destructor releases it. Then you can create an object of that type on the stack, and you're guaranteed that your resource gets freed when it goes out of scope. That way you don't have to track your new/delete pairs everywhere to ensure you avoid memory leaks.

The most common name for this idiom is RAII

Also look into smart pointer classes which are used to wrap the resulting pointers on the rare cases when you do have to allocate something with new outside a dedicated RAII object. You instead pass the pointer to a smart pointer, which then tracks its lifetime, for example by reference counting, and calls the destructor when the last reference goes out of scope. The standard library has std::unique_ptr for simple scope-based management, and std::shared_ptr which does reference counting to implement shared ownership.

Many tutorials demonstrate object instantiation using a snippet such as ...

So what you've discovered is that most tutorials suck. ;) Most tutorials teach you lousy C++ practices, including calling new/delete to create variables when it's not necessary, and giving you a hard time tracking lifetime of your allocations.

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to fill the whole canvas with specific color?

If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

Create comma separated strings C#?

You can use the string.Join method to do something like string.Join(",", o.Number, o.Id, o.whatever, ...).

edit: As digEmAll said, string.Join is faster than StringBuilder. They use an external implementation for the string.Join.

Profiling code (of course run in release without debug symbols):

class Program
{
    static void Main(string[] args)
    {
        Stopwatch sw = new Stopwatch();
        string r;
        int iter = 10000;

        string[] values = { "a", "b", "c", "d", "a little bit longer please", "one more time" };

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringJoin(",", values);
        sw.Stop();
        Console.WriteLine("string.Join ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);

        sw.Restart();
        for (int i = 0; i < iter; i++)
            r = Program.StringBuilderAppend(",", values);
        sw.Stop();
        Console.WriteLine("StringBuilder.Append ({0} times): {1}ms", iter, sw.ElapsedMilliseconds);
        Console.ReadLine();
    }

    static string StringJoin(string seperator, params string[] values)
    {
        return string.Join(seperator, values);
    }

    static string StringBuilderAppend(string seperator, params string[] values)
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(values[0]);
        for (int i = 1; i < values.Length; i++)
        {
            builder.Append(seperator);
            builder.Append(values[i]);
        }
        return builder.ToString();
    }
}

string.Join took 2ms on my machine and StringBuilder.Append 5ms. So there is noteworthy difference. Thanks to digAmAll for the hint.

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

How to convert a selection to lowercase or uppercase in Sublime Text

For Windows:

  • Ctrl+K,Ctrl+U for UPPERCASE.
  • Ctrl+K,Ctrl+L for lowercase.

Method 1 (Two keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K, release K while holding Ctrl. (Do not release the Ctrl key)
  3. Immediately, press U (for uppercase) OR L (for lowercase) with Ctrl still being pressed, then release all pressed keys.

Method 2 (3 keys pressed at a time)

  1. Press Ctrl and hold.
  2. Now press K.
  3. Without releasing Ctrl and K, immediately press U (for uppercase) OR L (for lowercase) and release all pressed keys.

Please note: If you press and hold Ctrl+K for more than two seconds it will start deleting text so try to be quick with it.

I use the above shortcuts, and they work on my Windows system.

Make an HTTP request with android

The most simple way is using the Android lib called Volley

Volley offers the following benefits:

Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.

You can send a http/https request as simple as this:

        // Instantiate the RequestQueue.
        RequestQueue queue = Volley.newRequestQueue(this);
        String url ="http://www.yourapi.com";
        JsonObjectRequest request = new JsonObjectRequest(url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (null != response) {
                         try {
                             //handle your response
                         } catch (JSONException e) {
                             e.printStackTrace();
                         }
                    }
                }
            }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(request);

In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.

How to hide the Google Invisible reCAPTCHA badge

this does not disable the spam checking

div.g-recaptcha > div.grecaptcha-badge {
    width:0 !important;
}

How does PHP 'foreach' actually work?

PHP foreach loop can be used with Indexed arrays, Associative arrays and Object public variables.

In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy of the array rather than the original one. This is demonstrated in the below example:

<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
    $numbers[$index] = $number + 1; # this is making changes to the origial array
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).

Besides this, php does allow to use iterated values as a reference to the original array value as well. This is demonstrated below:

<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
    ++$number; # we are incrementing the original value
    echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value

Note: It does not allow original array indexes to be used as references.

Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples

Modify tick label text

It's been a while since this question was asked. As of today (matplotlib 2.2.2) and after some reading and trials, I think the best/proper way is the following:

Matplotlib has a module named ticker that "contains classes to support completely configurable tick locating and formatting". To modify a specific tick from the plot, the following works for me:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np 

def update_ticks(x, pos):
    if x == 0:
        return 'Mean'
    elif pos == 6:
        return 'pos is 6'
    else:
        return x

data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
ax.hist(data, bins=25, edgecolor='black')
ax.xaxis.set_major_formatter(mticker.FuncFormatter(update_ticks))
plt.show()

Histogram with random values from a normal distribution

Caveat! x is the value of the tick and pos is its relative position in order in the axis. Notice that pos takes values starting in 1, not in 0 as usual when indexing.


In my case, I was trying to format the y-axis of a histogram with percentage values. mticker has another class named PercentFormatter that can do this easily without the need to define a separate function as before:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np 

data = np.random.normal(0, 1, 1000)
fig, ax = plt.subplots()
weights = np.ones_like(data) / len(data)
ax.hist(data, bins=25, weights=weights, edgecolor='black')
ax.yaxis.set_major_formatter(mticker.PercentFormatter(xmax=1.0, decimals=1))
plt.show()

Histogram with random values from a normal distribution

In this case xmax is the data value that corresponds to 100%. Percentages are computed as x / xmax * 100, that's why we fix xmax=1.0. Also, decimals is the number of decimal places to place after the point.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How do you upload a file to a document library in sharepoint?

try
{
    //Variablen für die Verarbeitung
    string source_file = @"C:\temp\offer.pdf";
    string web_url = "https://stackoverflow.sharepoint.com";
    string library_name = "Documents";
    string admin_name = "[email protected]";
    string admin_password = "Password";

    //Verbindung mit den Login-Daten herstellen
    var sercured_password = new SecureString();
    foreach (var c in admin_password) sercured_password.AppendChar(c);
    SharePointOnlineCredentials credent = new 
    SharePointOnlineCredentials(admin_name, sercured_password);

    //Context mit Credentials erstellen
    ClientContext context = new ClientContext(web_url);
    context.Credentials = credent;

    //Bibliothek festlegen
    var library = context.Web.Lists.GetByTitle(library_name);

    //Ausgewählte Datei laden
    FileStream fs = System.IO.File.OpenRead(source_file);

    //Dateinamen aus Pfad ermitteln
    string source_filename = Path.GetFileName(source_file);

    //Datei ins SharePoint-Verzeichnis hochladen
    FileCreationInformation fci = new FileCreationInformation();
    fci.Overwrite = true;
    fci.ContentStream = fs;
    fci.Url = source_filename;
    var file_upload = library.RootFolder.Files.Add(fci);

    //Ausführen
    context.Load(file_upload);
    context.ExecuteQuery();
    
    //Datenübertragen schließen
    fs.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Fehler");
    throw;
}

How can I count the rows with data in an Excel sheet?

If you want a simple one liner that will do it all for you (assuming by no value you mean a blank cell):

=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, "")

If by no value you mean the cell contains a 0

=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, 0)

The formula works by first summing up all the rows that are in columns A, B, and C (if you need to count more rows, just increase the columns in the range. E.g. ROWS(A:A) + ROWS(B:B) + ROWS(C:C) + ROWS(D:D) + ... + ROWS(Z:Z)).

Then the formula counts the number of values in the same range that are blank (or 0 in the second example).

Last, the formula subtracts the total number of cells with no value from the total number of rows. This leaves you with the number of cells in each row that contain a value

Where and why do I have to put the "template" and "typename" keywords?

(See here also for my C++11 answer)

In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:

t * f;

How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what t means. If it's a type, then it will be a declaration of a pointer f. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):

Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.

How will the compiler find out what a name t::x refers to, if t refers to a template type parameter? x could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a dependent name (it "depends" on the template parameters).

You might recommend to just wait till the user instantiates the template:

Let's wait until the user instantiates the template, and then later find out the real meaning of t::x * f;.

This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place.

So there has to be a way to tell the compiler that certain names are types and that certain names aren't.

The "typename" keyword

The answer is: We decide how the compiler should parse this. If t::x is a dependent name, then we need to prefix it by typename to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):

A name used in a template declaration or definition and that is dependent on a template-parameter is assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified by the keyword typename.

There are many names for which typename is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with T *f;, when T is a type template parameter. But for t::x * f; to be a declaration, it must be written as typename t::x *f;. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:

// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;

The syntax allows typename only before qualified names - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.

A similar gotcha exists for names that denote templates, as hinted at by the introductory text.

The "template" keyword

Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example:

boost::function< int() > f;

It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of boost::function and f:

namespace boost { int function = 0; }
int main() { 
  int f = 0;
  boost::function< int() > f; 
}

That's actually a valid expression! It uses the less-than operator to compare boost::function against zero (int()), and then uses the greater-than operator to compare the resulting bool against f. However as you might well know, boost::function in real life is a template, so the compiler knows (14.2/3):

After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is always taken as the beginning of a template-argument-list and never as a name followed by the less-than operator.

Now we are back to the same problem as with typename. What if we can't know yet whether the name is a template when parsing the code? We will need to insert template immediately before the template name, as specified by 14.2/4. This looks like:

t::template f<int>(); // call a function template

Template names can not only occur after a :: but also after a -> or . in a class member access. You need to insert the keyword there too:

this->template f<int>(); // call a function template

Dependencies

For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.

In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to depend on template parameters.

The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:

  • Dependent types (e.g: a type template parameter T)
  • Value-dependent expressions (e.g: a non-type template parameter N)
  • Type-dependent expressions (e.g: a cast to a type template parameter (T)0)

Most of the rules are intuitive and are built up recursively: For example, a type constructed as T[N] is a dependent type if N is a value-dependent expression or T is a dependent type. The details of this can be read in section (14.6.2/1) for dependent types, (14.6.2.2) for type-dependent expressions and (14.6.2.3) for value-dependent expressions.

Dependent names

The Standard is a bit unclear about what exactly is a dependent name. On a simple read (you know, the principle of least surprise), all it defines as a dependent name is the special case for function names below. But since clearly T::x also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition).

To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:

A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)

An identifier is just a plain sequence of characters / digits, while the next two are the operator + and operator type form. The last form is template-name <argument list>. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.

A value dependent expression 1 + N is not a name, but N is. The subset of all dependent constructs that are names is called dependent name. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule.

Dependent function names

Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example f((T)0), f is a dependent name. In the Standard, this is specified at (14.6.2/1).

Additional notes and examples

In enough cases we need both of typename and template. Your code should look like the following

template <typename T, typename Tail>
struct UnionNode : public Tail {
    // ...
    template<typename U> struct inUnion {
        typedef typename Tail::template inUnion<U> dummy;
    };
    // ...
};

The keyword template doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example

typename t::template iterator<int>::value_type v;

In some cases, the keywords are forbidden, as detailed below

  • On the name of a dependent base class you are not allowed to write typename. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:

     template <typename T>
     struct derive_from_Has_type : /* typename */ SomeBase<T>::type 
     { };
    
  • In using-declarations it's not possible to use template after the last ::, and the C++ committee said not to work on a solution.

     template <typename T>
     struct derive_from_Has_type : SomeBase<T> {
        using SomeBase<T>::template type; // error
        using typename SomeBase<T>::type; // typename *is* allowed
     };
    

Can I pass a JavaScript variable to another browser window?

One can pass a message from the 'parent' window to the 'child' window:

in the 'parent window' open the child

    var win = window.open(<window.location.href>, '_blank');    
       setTimeout(function(){
                    win.postMessage(SRFBfromEBNF,"*")
                  },1000);
    win.focus();

the to be replaced according to the context

In the 'child'

    window.addEventListener('message', function(event) {
        if(event.srcElement.location.href==window.location.href){
        /* do what you want with event.data */
        }
    }); 

The if test must be changed according to the context

How can I delete a file from a Git repository?

If you need to remove files from a determined extension (for example, compiled files) you could do the following to remove them all at once:

git remove -f *.pyc

Running Bash commands in Python

You can use subprocess, but I always felt that it was not a 'Pythonic' way of doing it. So I created Sultan (shameless plug) that makes it easy to run command line functions.

https://github.com/aeroxis/sultan

PHP: Limit foreach() statement?

You can either use

break;

or

foreach() if ($tmp++ < 2) {
}

(the second solution is even worse)

How can I find which tables reference a given table in Oracle SQL Developer?

This has been in the product for years - although it wasn't in the product in 2011.

But, simply click on the Model page.

Make sure you are on at least version 4.0 (released in 2013) to access this feature.

enter image description here

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

How to remove hashbang from url?

window.router = new VueRouter({
   hashbang: false,
   //abstract: true,
  history: true,
    mode: 'html5',
  linkActiveClass: 'active',
  transitionOnLoad: true,
  root: '/'
});

and server is properly configured In apache you should write the url rewrite

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
 </IfModule>

How do I uninstall nodejs installed from pkg (Mac OS X)?

If you installed Node from their website, try this:

sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}

This worked for me, but if you have any questions, my GitHub is 'mnafricano'.

A good Sorted List for Java

Generally you can't have constant time look up and log time deletions/insertions, but if you're happy with log time look ups then you can use a SortedList.

Not sure if you'll trust my coding but I recently wrote a SortedList implementation in Java, which you can download from http://www.scottlogic.co.uk/2010/12/sorted_lists_in_java/. This implementation allows you to look up the i-th element of the list in log time.

What do parentheses surrounding an object/function/class declaration mean?

It is a self-executing anonymous function. The first set of parentheses contain the expressions to be executed, and the second set of parentheses executes those expressions.

It is a useful construct when trying to hide variables from the parent namespace. All the code within the function is contained in the private scope of the function, meaning it can't be accessed at all from outside the function, making it truly private.

See:

http://en.wikipedia.org/wiki/Closure_%28computer_science%29

http://peter.michaux.ca/articles/javascript-namespacing

how to overwrite css style

You can create one more class naming

.flex-control-thumbs-without-width li {
width: auto;
float: initial; or none
}

Add this class whenever you need to override like below,

<li class="flex-control-thumbs flex-control-thumbs-without-width"> </li>

And do remove whenever you don't need for other <li>

HtmlEncode from Class Library

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

how can I enable scrollbars on the WPF Datagrid?

Add grid with defined height and width for columns and rows. Then add ScrollViewer and inside it add the dataGrid.

I do not want to inherit the child opacity from the parent in CSS

Opacity of child element is inherited from the parent element.

But we can use the css position property to accomplish our achievement.

The text container div can be put outside of the parent div but with absolute positioning projecting the desired effect.

Ideal Requirement------------------>>>>>>>>>>>>

HTML

            <div class="container">       
              <div class="bar">
                  <div class="text">The text opacity is inherited   from the parent div    </div>
              </div>
            </div>

CSS

               .container{
                position:relative;
                                   }
           .bar{
               opacity:0.2;
               background-color:#000;
               z-index:3;
               position:absolute;
               top:0;
               left:0;
              }

              .text{
                color:#fff;

               }

Output:--

Inherited Opacity of Text(the text color is #000; but not visisble.)

the Text is not visible because inheriting opacity from parent div.

Solution ------------------->>>>>>

HTML

       <div class="container">  
         <div class="text">Opacity is not inherited from parent div "bar"</div>
         <div class="bar"></div>
       </div>

CSS

               .container{
                position:relative;
                                   }
           .bar{
               opacity:0.2;
               background-color:#000;
               z-index:3;
               position:absolute;
               top:0;
               left:0;
              }

              .text{
                color:#fff;
                z-index:3;
                position:absolute;
               top:0;
               left:0;  
               }

Output :

Not Inherited

the Text is visible with same color as of background because the div is not in the transparent div

How can I check if a user is logged-in in php?

Almost all of the answers on this page rely on checking a session variable's existence to validate a user login. That is absolutely fine, but it is important to consider that the PHP session state is not unique to your application if there are multiple virtual hosts/sites on the same bare metal.

If you have two PHP applications on a webserver, both checking a user's login status with a boolean flag in a session variable called 'isLoggedIn', then a user could log into one of the applications and then automagically gain access to the second without credentials.

I suspect even the most dinosaur of commercial shared hosting wouldn't let virtual hosts share the same PHP environment in such a way that this could happen across multiple customers site's (anymore), but its something to consider in your own environments.

The very simple solution is to use a session variable that identifies the app rather than a boolean flag. e.g $SESSION["isLoggedInToExample.com"].

Source: I'm a penetration tester, with a lot of experience on how you shouldn't do stuff.

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

Enable/disable buttons with Angular

    <div class="col-md-12">
      <p style="color: #28a745; font-weight: bold; font-size:25px; text-align: right " >Total Productos a pagar= {{ getTotal() }} {{ getResult() | currency }}
      <button class="btn btn-success" type="submit" [disabled]="!getResult()" (click)="onSubmit()">
        Ver Pedido
      </button>
     </p>
    </div>

jQuery - Appending a div to body, the body is the object?

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

Writing an input integer into a cell

I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.

So

Range("RefNo") = InputBox("....") 

is safer than

Range("H1") = InputBox("....") 

You can set the value of several cells, too.

Range("Results").Resize(10,3) = arrResults()

where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this

Option Base 1

at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).

Deep copy of a dict in python

A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:

my_dict={'a':1}

my_copy = {}

my_copy.update( my_dict )

my_dict['a']=2

my_dict['a']
Out[34]: 2

my_copy['a']
Out[35]: 1

The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:

my_dict1={'b':2}

my_dict2={'c':3}

my_dict3={ 'b': my_dict1, 'c':my_dict2 }

my_copy = {}

my_copy.update( my_dict3 )

my_dict1['b']='z'

my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}

By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:

import copy

my_copy2 = copy.deepcopy( my_dict3 )

my_dict1['b']='99'

my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}

How to copy a row from one SQL Server table to another

SELECT * INTO < new_table > FROM < existing_table > WHERE < clause >

All possible array initialization syntaxes

In case you want to initialize a fixed array of pre-initialized equal (non-null or other than default) elements, use this:

var array = Enumerable.Repeat(string.Empty, 37).ToArray();

Also please take part in this discussion.

how to read xml file from url using php

$url = 'http://www.example.com'; $xml = simpleXML_load_file($url,"SimpleXMLElement",LIBXML_NOCDATA);

$url can be php file, as long as the file generate xml format data as output.

How do you run a Python script as a service in Windows?

https://www.chrisumbel.com/article/windows_services_in_python

  1. Follow up the PySvc.py

  2. changing the dll folder

I know this is old but I was stuck on this forever. For me, this specific problem was solved by copying this file - pywintypes36.dll

From -> Python36\Lib\site-packages\pywin32_system32

To -> Python36\Lib\site-packages\win32

setx /M PATH "%PATH%;C:\Users\user\AppData\Local\Programs\Python\Python38-32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Scripts;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\pywin32_system32;C:\Users\user\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\win32
  1. changing the path to python folder by

cd C:\Users\user\AppData\Local\Programs\Python\Python38-32

  1. NET START PySvc
  2. NET STOP PySvc

Oracle get previous day records

Simple solution and understanding

To answer the question:

SELECT field,datetime_field 
FROM database
WHERE TO_CHAR(date_field, 'YYYYMMDD') = TO_CHAR(SYSDATE-1, 'YYYYMMDD');

Some explanation

If you have a field that is not in date format but want to compare using date i.e. field is considered as date but in number format e.g. 20190823 (YYYYMMDD)

SELECT * FROM YOUR_TABLE WHERE ID_DATE = TO_CHAR(SYSDATE-1, 'YYYYMMDD') 

If you have a field that is in date/timestamp format and you need to compare, Just change the format

SELECT TO_CHAR(SYSDATE-1, 'YYYY-MM-DD HH24:MI:SS')  FROM DUAL

IF you want to return it to date format

SELECT TO_DATE(TO_CHAR(SYSDATE-1, 'YYYY-MM-DD HH24:MI:SS'), 'YYYY-MM-DD HH24:MI:SS') AS NEW_DATE  FROM DUAL

Conclusion.

With this knowledge you can convert the filed you want to compare to a YYYYMMDD or YYYY-MM-DD or any year-month-date format then compare with the same sysdate format.

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player);     // I get the error here.

void showInventory(player& obj) {   // By Johnny :D

this means that player is an datatype and showInventory expect an referance to an variable of type player.

so the correct code will be

  void showInventory(player& obj) {   // By Johnny :D
    for(int i = 0; i < 20; i++) {
        std::cout << "\nINVENTORY:\n" + obj.getItem(i);
        i++;
        std::cout << "\t\t\t" + obj.getItem(i) + "\n";
        i++;
    }
    }

players myPlayers[10];

    std::string toDo() //BY KEATON
    {
    std::string commands[5] =   // This is the valid list of commands.
        {"help", "inv"};

    std::string ans;
    std::cout << "\nWhat do you wish to do?\n>> ";
    std::cin >> ans;

    if(ans == commands[0]) {
        helpMenu();
        return NULL;
    }
    else if(ans == commands[1]) {
        showInventory(myPlayers[0]);     // or any other index,also is not necessary to have an array
        return NULL;
    }

}

How do I check for equality using Spark Dataframe without SQL Query?

You should be using where, select is a projection that returns the output of the statement, thus why you get boolean values. where is a filter that keeps the structure of the dataframe, but only keeps data where the filter works.

Along the same line though, per the documentation, you can write this in 3 different ways

// The following are equivalent:
peopleDf.filter($"age" > 15)
peopleDf.where($"age" > 15)
peopleDf($"age" > 15)

'float' vs. 'double' precision

A float has 23 bits of precision, and a double has 52.

COUNT DISTINCT with CONDITIONS

You can try this:

select
  count(distinct tag) as tag_count,
  count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
  your_table_name;

The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

Why does pycharm propose to change method to static

Rather than implementing another method just to work around this error in a particular IDE, does the following make sense? PyCharm doesn't suggest anything with this implementation.

class Animal:
    def __init__(self):
        print("Animal created")

    def eat(self):
        not self # <-- This line here
        print("I am eating")


my_animal = Animal()

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

You can suppress basic auth popup with request url looking like this:

https://username:[email protected]/admin/...

If you get 401 error (wrong username or password) it will be correctly handled with jquery error callback. It can cause some security issues (in case of http protocol instead of https), but it's works.

UPD: This solution support will be removed in Chrome 59

Oracle 11g SQL to get unique values in one column of a multi-column query

I'd use the RANK() function in a subselect and then just pull the row where rank = 1.

select person, language
from
( 
    select person, language, rank() over(order by language) as rank
    from table A
    group by person, language
)
where rank = 1

Pandas: drop a level from a multi-level column index?

You can use MultiIndex.droplevel:

>>> cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
>>> df = pd.DataFrame([[1,2], [3,4]], columns=cols)
>>> df
   a   
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]
>>> df.columns = df.columns.droplevel()
>>> df
   b  c
0  1  2
1  3  4

[2 rows x 2 columns]

SQL query return data from multiple tables

Part 3 - Tricks and Efficient Code

MySQL in() efficiency

I thought I would add some extra bits, for tips and tricks that have come up.

One question I see come up a fair bit, is How do I get non-matching rows from two tables and I see the answer most commonly accepted as something like the following (based on our cars and brands table - which has Holden listed as a brand, but does not appear in the cars table):

select
    a.ID,
    a.brand
from
    brands a
where
    a.ID not in(select brand from cars)

And yes it will work.

+----+--------+
| ID | brand  |
+----+--------+
|  6 | Holden |
+----+--------+
1 row in set (0.00 sec)

However it is not efficient in some database. Here is a link to a Stack Overflow question asking about it, and here is an excellent in depth article if you want to get into the nitty gritty.

The short answer is, if the optimiser doesn't handle it efficiently, it may be much better to use a query like the following to get non matched rows:

select
    a.brand
from
    brands a
        left join cars b
            on a.id=b.brand
where
    b.brand is null

+--------+
| brand  |
+--------+
| Holden |
+--------+
1 row in set (0.00 sec)

Update Table with same table in subquery

Ahhh, another oldie but goodie - the old You can't specify target table 'brands' for update in FROM clause.

MySQL will not allow you to run an update... query with a subselect on the same table. Now, you might be thinking, why not just slap it into the where clause right? But what if you want to update only the row with the max() date amoung a bunch of other rows? You can't exactly do that in a where clause.

update 
    brands 
set 
    brand='Holden' 
where 
    id=
        (select 
            id 
        from 
            brands 
        where 
            id=6);
ERROR 1093 (HY000): You can't specify target table 'brands' 
for update in FROM clause

So, we can't do that eh? Well, not exactly. There is a sneaky workaround that a surprisingly large number of users don't know about - though it does include some hackery that you will need to pay attention to.

You can stick the subquery within another subquery, which puts enough of a gap between the two queries so that it will work. However, note that it might be safest to stick the query within a transaction - this will prevent any other changes being made to the tables while the query is running.

update 
    brands 
set 
    brand='Holden' 
where id=
    (select 
        id 
    from 
        (select 
            id 
        from 
            brands 
        where 
            id=6
        ) 
    as updateTable);

Query OK, 0 rows affected (0.02 sec)
Rows matched: 1  Changed: 0  Warnings: 0

Node.js check if file exists

Using typescript and fs/promises in node14

import * as fsp from 'fs/promises';
try{
const = await fsp.readFile(fullFileName)
...
} catch(e) { ...}

It is better to use fsp.readFile than fsp.stator fsp.access for two reasons:

  1. The least important reason - it is one less access.
  2. It is possible that fsp.statand fsp.readFile would give different answers. Either due to subtle differences in the questions they ask, or because the files status changed between the calls. So the coder would have to code for two conditional branches instead of one, and the user might see more behaviors.

How to coerce a list object to type 'double'

You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.

as.numeric(a[[1]])

Node.js: Python not found exception due to node-sass and node-gyp

I found the same issue with Node 12.19.0 and yarn 1.22.5 on Windows 10. I fixed the problem by installing latest stable python 64-bit with adding the path to Environment Variables during python installation. After python installation, I restarted my machine for env vars.

Detecting when the 'back' button is pressed on a navbar

I have solved this problem by adding a UIControl to the navigationBar on the left side .

UIControl *leftBarItemControl = [[UIControl alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
[leftBarItemControl addTarget:self action:@selector(onLeftItemClick:) forControlEvents:UIControlEventTouchUpInside];
self.leftItemControl = leftBarItemControl;
[self.navigationController.navigationBar addSubview:leftBarItemControl];
[self.navigationController.navigationBar bringSubviewToFront:leftBarItemControl];

And you need to remember to remove it when view will disappear:

- (void) viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    if (self.leftItemControl) {
        [self.leftItemControl removeFromSuperview];
    }    
}

That's all!

Set and Get Methods in java?

I think you want something like this:

public class Person {

  private int age;

  //public method to get the age variable
  public int getAge(){
       return this.age
  }

  //public method to set the age variable
  public void setAge(int age){
       this.age = age;
  }
}

You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:

  public void setAge(int age){

       this.age = age;

       double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;

       if(averageCigarettesPerYear >= 7300.0) {
           this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
       }
  }

Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.

How do I prevent DIV tag starting a new line?

A better way to do a break line is using span with CSS style parameter white-space: nowrap;

span.nobreak {
  white-space: nowrap;
}

or
span.nobreak {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

Example directly in your HTML

<span style='overflow:hidden; white-space: nowrap;'> YOUR EXTENSIVE TEXT THAT YOU CAN´T BREAK LINE ....</span>

Subscript out of range error in this Excel VBA script

Set sh1 = Worksheets(filenum(lngPosition)).Activate

You are getting Subscript out of range error error becuase it cannot find that Worksheet.

Also please... please... please do not use .Select/.Activate/Selection/ActiveCell You might want to see How to Avoid using Select in Excel VBA Macros.

Session variables in ASP.NET MVC

I would think you'll want to think about if things really belong in a session state. This is something I find myself doing every now and then and it's a nice strongly typed approach to the whole thing but you should be careful when putting things in the session context. Not everything should be there just because it belongs to some user.

in global.asax hook the OnSessionStart event

void OnSessionStart(...)
{
    HttpContext.Current.Session.Add("__MySessionObject", new MySessionObject());
}

From anywhere in code where the HttpContext.Current property != null you can retrive that object. I do this with an extension method.

public static MySessionObject GetMySessionObject(this HttpContext current)
{
    return current != null ? (MySessionObject)current.Session["__MySessionObject"] : null;
}

This way you can in code

void OnLoad(...)
{
    var sessionObj = HttpContext.Current.GetMySessionObject();
    // do something with 'sessionObj'
}

Adding days to $Date in PHP

Here is a small snippet to demonstrate the date modifications:

$date = date("Y-m-d");
//increment 2 days
$mod_date = strtotime($date."+ 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//decrement 2 days
$mod_date = strtotime($date."- 2 days");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 month
$mod_date = strtotime($date."+ 1 months");
echo date("Y-m-d",$mod_date) . "\n";

//increment 1 year
$mod_date = strtotime($date."+ 1 years");
echo date("Y-m-d",$mod_date) . "\n";

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

One addendum to the excellent answers above, on a point that confused me even after I had read Stroustrup and thought I understood the rvalue/lvalue distinction. When you see

int&& a = 3,

it's very tempting to read the int&& as a type and conclude that a is an rvalue. It's not:

int&& a = 3;
int&& c = a; //error: cannot bind 'int' lvalue to 'int&&'
int& b = a; //compiles

a has a name and is ipso facto an lvalue. Don't think of the && as part of the type of a; it's just something telling you what a is allowed to bind to.

This matters particularly for T&& type arguments in constructors. If you write

Foo::Foo(T&& _t) : t{_t} {}

you will copy _t into t. You need

Foo::Foo(T&& _t) : t{std::move(_t)} {} if you want to move. Would that my compiler warned me when I left out the move!

Android Studio Google JAR file causing GC overhead limit exceeded error

I disable my Instant Run by:

Menu Preference ? Build ? Instant Run "Enable Instant Run to hot swap code"

I guess it is the Instant Run that makes the build slow and creates a large size pidXXX.hprof file which causes the AndroidStudio gc overhead limit exceeded.

(My device SDK is 19.)

Android Device not recognized by adb

I recently had this issue (but before that debug over wifi was working fine) and since none of the above answers helped me let me share what I did.

  1. Go to developer options
  2. Find Select USB configurations and click it
  3. Choose MTP (Media Transfer Protocol)

Note: If it's set to this option chose another option such as PTP first then set it to MTP again.

UPDATE:

PTP stands for “Picture Transfer Protocol.” When Android uses this protocol, it appears to the computer as a digital camera.

MTP is actually based on PTP, but adds more features, or “extensions.” PTP works similarly to MTP and is commonly used by digital cameras.

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.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

From the experiment branch

git rebase master
git push -f origin <experiment-branch>

This creates a common commit history to be able to compare both branches.

Call javascript from MVC controller action

If I understand correctly the question, you want to have a JavaScript code in your Controller. (Your question is clear enough, but the voted and accepted answers are throwing some doubt) So: you can do this by using the .NET's System.Windows.Forms.WebBrowser control to execute javascript code, and everything that a browser can do. It requires reference to System.Windows.Forms though, and the interaction is somewhat "old school". E.g:

void webBrowser1_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    HtmlElement search = webBrowser1.Document.GetElementById("searchInput");
    if(search != null)
    {
        search.SetAttribute("value", "Superman");
        foreach(HtmlElement ele in search.Parent.Children)
        {
            if (ele.TagName.ToLower() == "input" && ele.Name.ToLower() == "go")
            {
                ele.InvokeMember("click");
                break;
            }
        }
    }
}

So probably nowadays, that would not be the easiest solution.

The other option is to use Javascript .NET or jint to run javasctipt, or another solution, based on the specific case.

Some related questions on this topic or possible duplicates:

Embedding JavaScript engine into .NET

Load a DOM and Execute javascript, server side, with .Net

Hope this helps.

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

What is a Maven artifact?

An artifact is a JAR or something that you store in a repository. Maven gets them out and builds your code.

How to find rows in one table that have no corresponding row in another table

You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.

H2 does support the MINUS syntax so you should try this

select id from tableA
minus
select id from tableB
order by id desc

That may perform faster; it is certainly worth benchmarking.

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

Equal height rows in a flex container

No, you can't achieve that without setting a fixed height (or using a script).


Here are 2 answers of mine, showing how to use a script to achieve something like that:

How to force a line break on a Javascript concatenated string?

Using Backtick

Backticks are commonly used for multi-line strings or when you want to interpolate an expression within your string

_x000D_
_x000D_
let title = 'John';_x000D_
let address = 'address';_x000D_
let address2 = 'address2222';_x000D_
let address3 = 'address33333';_x000D_
let address4 = 'address44444';_x000D_
document.getElementById("address_box").innerText = `${title} _x000D_
${address}_x000D_
${address2}_x000D_
${address3} _x000D_
${address4}`;
_x000D_
<div id="address_box">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

Set System.Drawing.Color values

You must use Color.FromArgb method to create new color structure

var newColor = Color.FromArgb(0xCC,0xBB,0xAA);

Check if Key Exists in NameValueCollection

This could also be a solution without having to introduce a new method:

    item = collection["item"] != null ? collection["item"].ToString() : null;

Saving an Object (Data persistence)

I think it's a pretty strong assumption to assume that the object is a class. What if it's not a class? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__ after creation, pickle doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle serializes by reference to the object definition).

In all these cases, pickle and cPickle can fail you horribly.

If you are looking to save an object (arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill, which can serialize almost anything in python.

We start with a class…

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
...     pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
... 
>>> 

Now shut down, and restart...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
...     company1 = pickle.load(f)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>> 

Oops… pickle can't handle it. Let's try dill. We'll throw in another object type (a lambda) for good measure.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill       
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> with open('company_dill.pkl', 'wb') as f:
...     dill.dump(company1, f)
...     dill.dump(company2, f)
... 
>>> 

And now read the file.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
...     company1 = dill.load(f)
...     company2 = dill.load(f)
... 
>>> company1 
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>    

It works. The reason pickle fails, and dill doesn't, is that dill treats __main__ like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle does). The reason dill can pickle a lambda is that it gives it a name… then pickling magic can happen.

Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> dill.dump_session('dill.pkl')
>>> 

Now shut down your computer, go enjoy an espresso or whatever, and come back later...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>

The only major drawback is that dill is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.

However, if you are able to install python packages on your system, you can get the latest dill with git+https://github.com/uqfoundation/dill.git@master#egg=dill. And you can get the latest released version with pip install dill.

Crontab Day of the Week syntax

0 and 7 both stand for Sunday, you can use the one you want, so writing 0-6 or 1-7 has the same result.

Also, as suggested by @Henrik, it is possible to replace numbers by shortened name of days, such as MON, THU, etc:

0 - Sun      Sunday
1 - Mon      Monday
2 - Tue      Tuesday
3 - Wed      Wednesday
4 - Thu      Thursday
5 - Fri      Friday
6 - Sat      Saturday
7 - Sun      Sunday

Graphically:

 +---------- minute (0 - 59)
 ¦ +-------- hour (0 - 23)
 ¦ ¦ +------ day of month (1 - 31)
 ¦ ¦ ¦ +---- month (1 - 12)
 ¦ ¦ ¦ ¦ +-- day of week (0 - 6 => Sunday - Saturday, or
 ¦ ¦ ¦ ¦ ¦                1 - 7 => Monday - Sunday)
 ? ? ? ? ?
 * * * * * command to be executed

Finally, if you want to specify day by day, you can separate days with commas, for example SUN,MON,THU will exectute the command only on sundays, mondays on thursdays.

You can read further details in Wikipedia's article about Cron.

How to "test" NoneType in python?

Not sure if this answers the question. But I know this took me a while to figure out. I was looping through a website and all of sudden the name of the authors weren't there anymore. So needed a check statement.

if type(author) == type(None):
     my if body
else:
    my else body

Author can be any variable in this case, and None can be any type that you are checking for.

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

Extract regression coefficient values

To answer your question, you can explore the contents of the model's output by saving the model as a variable and clicking on it in the environment window. You can then click around to see what it contains and what is stored where.

Another way is to type yourmodelname$ and select the components of the model one by one to see what each contains. When you get to yourmodelname$coefficients, you will see all of beta-, p, and t- values you desire.

"Data too long for column" - why?

in mysql if you take VARCHAR then change it to TEXT bcoz its size is 65,535 and if you can already take TEXT the change it with LONGTEXT only if u need more then 65,535.

total size of LONGTEXT is 4,294,967,295 characters

Matplotlib/pyplot: How to enforce axis range?

To answer my own question, the trick is to turn auto scaling off...

p.axis([0.0,600.0, 10000.0,20000.0])
ax = p.gca()
ax.set_autoscale_on(False)

In Bash, how can I check if a string begins with some value?

This snippet on the Advanced Bash Scripting Guide says:

# The == comparison operator behaves differently within a double-brackets
# test than within single brackets.

[[ $a == z* ]]   # True if $a starts with a "z" (wildcard matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).

So you had it nearly correct; you needed double brackets, not single brackets.


With regards to your second question, you can write it this way:

HOST=user1
if  [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes1
fi

HOST=node001
if [[ $HOST == user1 ]] || [[ $HOST == node* ]] ;
then
    echo yes2
fi

Which will echo

yes1
yes2

Bash's if syntax is hard to get used to (IMO).

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

How to format a java.sql Timestamp for displaying?

java.sql.Timestamp extends java.util.Date. You can do:

String s = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);

Or to also include time:

String s = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);

Error handling in getJSON calls

This is quite an old thread, but it does come up in Google search, so I thought I would add a jQuery 3 answer using promises. This snippet also shows:

  • You no longer need to switch to $.ajax to pass in your bearer token
  • Uses .then() to make sure you can process synchronously any outcome (I was coming across this problem .always() callback firing too soon - although I'm not sure that was 100% true)
  • I'm using .always() to simply show the outcome whether positive or negative
  • In the .always() function I'm updating two targets with the HTTP Status code and message body

The code snippet is:

    $.getJSON({
         url: "https://myurl.com/api",
         headers: { "Authorization": "Bearer " + user.access_token}
    }).then().always(   function (data, textStatus) {
        $("#txtAPIStatus").html(data.status);
        $("#txtAPIValue").html(data.responseText);
    });

Query to list all users of a certain group

memberOf (in AD) is stored as a list of distinguishedNames. Your filter needs to be something like:

(&(objectCategory=user)(memberOf=cn=MyCustomGroup,ou=ouOfGroup,dc=subdomain,dc=domain,dc=com))

If you don't yet have the distinguished name, you can search for it with:

(&(objectCategory=group)(cn=myCustomGroup))

and return the attribute distinguishedName. Case may matter.

ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)

Yea, Indeed @Evert answer is perfectly correct. In addition I'll like to add one more reason that could encounter such error.

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,200))])

This will be perfectly fine, However, This leads to error:

>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,201))])

ValueError: could not broadcast input array from shape (20,200) into shape (20)

The numpy arry within the list, must also be the same size.

Enable & Disable a Div and its elements in Javascript

The following selects all descendant elements and disables them:

$("#dcacl").find("*").prop("disabled", true);

But it only really makes sense to disable certain element types: inputs, buttons, etc., so you want a more specific selector:

$("#dcac1").find(":input").prop("disabled",true);
// noting that ":input" gives you the equivalent of
$("#dcac1").find("input,select,textarea,button").prop("disabled",true);

To re-enable you just set "disabled" to false.

I want to Disable them at loading the page and then by a click i can enable them

OK, so put the above code in a document ready handler, and setup an appropriate click handler:

$(document).ready(function() {
    var $dcac1kids = $("#dcac1").find(":input");
    $dcac1kids.prop("disabled",true);

    // not sure what you want to click on to re-enable
    $("selector for whatever you want to click").one("click",function() {
       $dcac1kids.prop("disabled",false);
    }
}

I've cached the results of the selector on the assumption that you're not adding more elements to the div between the page load and the click. And I've attached the click handler with .one() since you haven't specified a requirement to re-disable the elements so presumably the event only needs to be handled once. Of course you can change the .one() to .click() if appropriate.

Can not find module “@angular-devkit/build-angular”

If you are using angular version 8 please run the below command to fix this issue.

ng update @angular/cli @angular/core

Integer expression expected error in shell script

You can use this syntax:

#!/bin/bash

echo " Write in your age: "
read age

if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
    echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
    echo " You have to pay for ticket "
fi

How to get Text BOLD in Alert or Confirm box?

The alert() dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.

You'd need to use a custom modal to achieve that.

Implementation difference between Aggregation and Composition in Java

I would use a nice UML example.

Take a university that has 1 to 20 different departments and each department has 1 to 5 professors. There is a composition link between a University and its' departments. There is an aggregation link between a department and its' professors.

Composition is just a STRONG aggregation, if the university is destroyed then the departments should also be destroyed. But we shouldn't kill the professors even if their respective departments disappear.

In java :

public class University {

     private List<Department> departments;

     public void destroy(){
         //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clean();
         departments = null;
     }
}

public class Department {

     private List<Professor> professors;
     private University university;

     Department(University univ){
         this.university = univ;
         //check here univ not null throw whatever depending on your needs
     }

     public void destroy(){
         //It's aggregation here, we just tell the professor they are fired but they can still keep living
         for(Professor p:professors)
             p.fire(this);
         professors.clean();
         professors = null;
     }
}

public class Professor {

     private String name;
     private List<Department> attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Something around this.

EDIT: an example as requested

public class Test
{
    public static void main(String[] args)
    {
        University university = new University();
        //the department only exists in the university
        Department dep = university.createDepartment();
        // the professor exists outside the university
        Professor prof = new Professor("Raoul");
        System.out.println(university.toString());
        System.out.println(prof.toString());

        dep.assign(prof);
        System.out.println(university.toString());
        System.out.println(prof.toString());
        dep.destroy();

        System.out.println(university.toString());
        System.out.println(prof.toString());

    }


}

University class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class University {

    private List<Department> departments = new ArrayList<>();

    public Department createDepartment() {
        final Department dep = new Department(this, "Math");
        departments.add(dep);
        return dep;
    }

    public void destroy() {
        System.out.println("Destroying university");
        //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
        if (departments != null)
            departments.forEach(Department::destroy);
        departments = null;
    }

    @Override
    public String toString() {
        return "University{\n" +
                "departments=\n" + departments.stream().map(Department::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Department class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Department {

    private final String name;
    private List<Professor> professors = new ArrayList<>();
    private final University university;

    public Department(University univ, String name) {
        this.university = univ;
        this.name = name;
        //check here univ not null throw whatever depending on your needs
    }

    public void assign(Professor p) {
        //maybe use a Set here
        System.out.println("Department hiring " + p.getName());
        professors.add(p);
        p.join(this);
    }

    public void fire(Professor p) {
        //maybe use a Set here
        System.out.println("Department firing " + p.getName());
        professors.remove(p);
        p.quit(this);
    }

    public void destroy() {
        //It's aggregation here, we just tell the professor they are fired but they can still keep living
        System.out.println("Destroying department");
        professors.forEach(professor -> professor.quit(this));
        professors = null;
    }

    @Override
    public String toString() {
        return professors == null
                ? "Department " + name + " doesn't exists anymore"
                : "Department " + name + "{\n" +
                "professors=" + professors.stream().map(Professor::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Professor class

import java.util.ArrayList;
import java.util.List;

public class Professor {

    private final String name;
    private final List<Department> attachedDepartments = new ArrayList<>();

    public Professor(String name) {
        this.name = name;
    }

    public void destroy() {

    }

    public void join(Department d) {
        attachedDepartments.add(d);
    }

    public void quit(Department d) {
        attachedDepartments.remove(d);
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Professor " + name + " working for " + attachedDepartments.size() + " department(s)\n";
    }
}

The implementation is debatable as it depends on how you need to handle creation, hiring deletion etc. Unrelevant for the OP

Compare two files and write it to "match" and "nomatch" files

Though its really long back this question was posted, I wish to answer as it might help others. This can be done easily by means of JOINKEYS in a SINGLE step. Here goes the pseudo code:

  • Code JOINKEYS PAIRED(implicit) and get both the records via reformatting filed. If there is NO match from either of files then append/prefix some special character say '$'
  • Compare via IFTHEN for '$', if exists then it doesnt have a paired record, it'll be written into unpaired file and rest to paired file.

Please do get back incase of any questions.

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

throwing an exception in objective-c/cocoa

You should only throw exceptions if you find yourself in a situation that indicates a programming error, and want to stop the application from running. Therefore, the best way to throw exceptions is using the NSAssert and NSParameterAssert macros, and making sure that NS_BLOCK_ASSERTIONS is not defined.

Setting default value in select drop-down using Angularjs

This is an old question and you might have got the answer already.

My plnkr explains on my approach to accomplish selecting a default dropdown value. Basically, I have a service which would return the dropdown values [hard coded to test]. I was not able to select the value by default and almost spend a day and finally figured out that I should have set $scope.proofGroupId = "47"; instead of $scope.proofGroupId = 47; in the script.js file. It was my bad and I did not notice that I was setting an integer 47 instead of the string "47". I retained the plnkr as it is just in case if some one would like to see. Hopefully, this would help some one.

Unsupported Media Type in postman

I also got this error .I was using Text inside body after changing to XML(text/xml) , got result as expected.

  • If your request is XML Request use XML(text/xml).

  • If your request is JSON Request use JSON(application/json)

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

Markdown to create pages and table of contents?

For the Visual Studio Code users the best option to use today (2020) is the Markdown All in One plugin.

To install it, launch the VS Code Quick Open (Control/?+P), paste the following command, and press enter.

ext install yzhang.markdown-all-in-one

And to generate the TOC, open the command palette (Control/?+Shift+P) and select the Select Markdown: Create Table of Contentsoption.


Another option is the Markdown TOC plugin.

To install it, launch the VS Code Quick Open (Control/?+P), paste the following command, and press enter.

ext install markdown-toc

And to generate the TOC, open the command palette (Control/?+Shift+P) and select the Markdown TOC:Insert/Update option or use Control/?+MT.

How do I create a link to add an entry to a calendar?

To add to squarecandy's google calendar contribution, here the brand new

OUTLOOK CALENDAR format (Without a need to create .ics) !!

<a href="https://bay02.calendar.live.com/calendar/calendar.aspx?rru=addevent&dtstart=20151119T140000Z&dtend=20151119T160000Z&summary=Summary+of+the+event&location=Location+of+the+event&description=example+text.&allday=false&uid=">add to Outlook calendar</a>

test it

Best would be to url_encode the summary, location and description variable's values.

For the sake of knowledge,

YAHOO CALENDAR format

<a href="https://calendar.yahoo.com/?v=60&view=d&type=20&title=Summary+of+the+event&st=20151119T090000&et=20151119T110000&desc=example+text.%0A%0AThis+is+the+text+entered+in+the+event+description+field.&in_loc=Location+of+the+event&uid=">add to Yahoo calendar</a>

test it

Doing it without a third party holds a lot of advantages for example using it in emails.

Change language for bootstrap DateTimePicker

you need to add the javascript language file,after the moment library, example:

<script type="text/javascript" src="js/moment/moment.js"></script>
<script type="text/javascript" src="js/moment/es.js"></script>

now you can set a language.

<script type="text/javascript">
$(function () {
  $('#datetimepicker1').datetimepicker({locale:'es'});
});
</script>

Here are all language: https://github.com/moment/moment

How to convert float to varchar in SQL Server

The only query bit I found that returns the EXACT same original number is

CONVERT (VARCHAR(50), float_field,128)

See http://www.connectsql.com/2011/04/normal-0-microsoftinternetexplorer4.html

The other solutions above will sometimes round or add digits at the end

UPDATE: As per comments below and what I can see in https://msdn.microsoft.com/en-us/library/ms187928.aspx:

CONVERT (VARCHAR(50), float_field,3)

Should be used in new SQL Server versions (Azure SQL Database, and starting in SQL Server 2016 RC3)

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How to get phpmyadmin username and password

Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.

Video streaming over websockets using JavaScript

To answer the question:

What is the fastest way to stream live video using JavaScript? Is WebSockets over TCP a fast enough protocol to stream a video of, say, 30fps?

Yes, Websocket can be used to transmit over 30 fps and even 60 fps.

The main issue with Websocket is that it is low-level and you have to deal with may other issues than just transmitting video chunks. All in all it's a great transport for video and also audio.

How to parse date string to Date?

new SimpleDateFormat("EEE MMM dd kk:mm:ss ZZZ yyyy");

and

new SimpleDateFormat("EEE MMM dd kk:mm:ss Z yyyy");

still runs. However, if your code throws an exception it is because your tool or jdk or any other reason. Because I got same error in my IDE but please check these http://ideone.com/Y2cRr (online ide) with ZZZ and with Z

output is : Thu Sep 28 11:29:30 GMT 2000

How to position a Bootstrap popover?

I've created a jQuery plugin that provides 4 additonal placements: topLeft, topRight, bottomLeft, bottomRight

You just include either the minified js or unminified js and have the matching css (minified vs unminified) in the same folder.

https://github.com/dkleehammer/bootstrap-popover-extra-placements

Explain ggplot2 warning: "Removed k rows containing missing values"

Just for the shake of completing the answer given by eipi10.

I was facing the same problem, without using scale_y_continuous nor coord_cartesian.

The conflict was coming from the x axis, where I defined limits = c(1, 30). It seems such limits do not provide enough space if you want to "dodge" your bars, so R still throws the error

Removed 8 rows containing missing values (geom_bar)

Adjusting the limits of the x axis to limits = c(0, 31) solved the problem.

In conclusion, even if you are not putting limits to your y axis, check out your x axis' behavior to ensure you have enough space

How to get the containing form of an input?

would this work? (leaving action blank submits form back to itself too, right?)

<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>

"this" would be the select element, .form would be its parent form. Right?

How to Load Ajax in Wordpress

I'm not allowed to comment, so regarding Shane's answer, keep in mind that

wp_localize_scripts()

must be hooked to wp or admin enqueue scripts. So a good example would be as follows:

function local() {

    wp_localize_script( 'js-file-handle', 'ajax', array(
        'url' => admin_url( 'admin-ajax.php' )
    ) );

}

add_action('admin_enqueue_scripts', 'local');
add_action('wp_enqueue_scripts', 'local');`

Convert dictionary to list collection in C#

To convert the Keys to a List of their own:

listNumber = dicNumber.Select(kvp => kvp.Key).ToList();

Or you can shorten it up and not even bother using select:

listNumber = dicNumber.Keys.ToList();

How can I delete all Git branches which have been merged?

My Bash script contribution is based loosely on mmrobin's answer.

It takes some useful parameters specifying includes and excludes, or to examine/remove only local or remote branches instead of both.

#!/bin/bash

# exclude branches regex, configure as "(branch1|branch2|etc)$"
excludes_default="(master|next|ag/doc-updates)$"
excludes="__NOTHING__"
includes=
merged="--merged"
local=1
remote=1

while [ $# -gt 0 ]; do
  case "$1" in
  -i) shift; includes="$includes $1" ;;
  -e) shift; excludes="$1" ;;
  --no-local) local=0 ;;
  --no-remote) remote=0 ;;
  --all) merged= ;;
  *) echo "Unknown argument $1"; exit 1 ;;
  esac
  shift   # next option
done

if [ "$includes" == "" ]; then
  includes=".*"
else
  includes="($(echo $includes | sed -e 's/ /|/g'))"
fi

current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
  echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching branches...\n"

git remote update --prune
remote_branches=$(git branch -r $merged | grep -v "/$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
local_branches=$(git branch $merged | grep -v "$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
  echo "No existing branches have been merged into $current_branch."
else
  echo "This will remove the following branches:"
  if [ "$remote" == 1 -a -n "$remote_branches" ]; then
    echo "$remote_branches"
  fi
  if [ "$local" == 1 -a -n "$local_branches" ]; then
    echo "$local_branches"
  fi
  read -p "Continue? (y/n): " -n 1 choice
  echo
  if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
    if [ "$remote" == 1 ]; then
      remotes=$(git remote)
      # Remove remote branches
      for remote in $remotes
      do
        branches=$(echo "$remote_branches" | grep "$remote/" | sed "s/$remote\/\(.*\)/:\1 /g" | tr -d '\n')
        git push $remote $branches
      done
    fi

    if [ "$local" == 1 ]; then
      # Remove local branches
      locals=$(echo "$local_branches" | sed 's/origin\///g' | tr -d '\n')
      if [ -z "$locals" ]; then
        echo "No branches removed."
      else
        git branch -d $(echo "$locals" | tr -d '\n')
      fi
    fi
  fi
fi

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

Did you install/update the driver for the FTDI cable? (Step three on http://arduino.cc/en/Guide/Howto). Running the Arduino IDE from my Raspberry Pi worked fine without explicitly installing the drivers (either they were pre-installed or the Arduino IDE installer took care of it). On my Mac this was not the case and I had to install the cable drivers in addition to the IDE.

how to get files from <input type='file' .../> (Indirect) with javascript

If you are looking to style a file input element, look at open file dialog box in javascript. If you are looking to grab the files associated with a file input element, you must do something like this:

inputElement.onchange = function(event) {
   var fileList = inputElement.files;
   //TODO do something with fileList.  
}

See this MDN article for more info on the FileList type.

Note that the code above will only work in browsers that support the File API. For IE9 and earlier, for example, you only have access to the file name. The input element has no files property in non-File API browsers.

How can I count the number of elements with same class?

I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:

document.getElementsByClassName('realClasssName').length

Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.

document.querySelectorAll('.realClasssName').length

Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.

Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.


I also write one method, but using two name conventions to solve this problem using jQuery:

jQuery('.realClasssName').length

or

$('.realClasssName').length

Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.

Recommendations of Python REST (web services) framework?

We're using Django for RESTful web services.

Note that -- out of the box -- Django did not have fine-grained enough authentication for our needs. We used the Django-REST interface, which helped a lot. [We've since rolled our own because we'd made so many extensions that it had become a maintenance nightmare.]

We have two kinds of URL's: "html" URL's which implement the human-oriented HTML pages, and "json" URL's which implement the web-services oriented processing. Our view functions often look like this.

def someUsefulThing( request, object_id ):
    # do some processing
    return { a dictionary with results }

def htmlView( request, object_id ):
    d = someUsefulThing( request, object_id )
    render_to_response( 'template.html', d, ... )

def jsonView( request, object_id ):
    d = someUsefulThing( request, object_id )
    data = serializers.serialize( 'json', d['object'], fields=EXPOSED_FIELDS )
    response = HttpResponse( data, status=200, content_type='application/json' )
    response['Location']= reverse( 'some.path.to.this.view', kwargs={...} )
    return response

The point being that the useful functionality is factored out of the two presentations. The JSON presentation is usually just one object that was requested. The HTML presentation often includes all kinds of navigation aids and other contextual clues that help people be productive.

The jsonView functions are all very similar, which can be a bit annoying. But it's Python, so make them part of a callable class or write decorators if it helps.

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

INNER JOIN in UPDATE sql for DB2

Here's a good example of something I just got working:

update cac c
set ga_meth_id = (
    select cim.ga_meth_id 
    from cci ci, ccim cim 
    where ci.cus_id_key_n = cim.cus_id_key_n
    and ci.cus_set_c = cim.cus_set_c
    and ci.cus_set_c = c.cus_set_c
    and ci.cps_key_n = c.cps_key_n
)
where exists (
    select 1  
    from cci ci2, ccim cim2 
    where ci2.cus_id_key_n = cim2.cus_id_key_n
    and ci2.cus_set_c = cim2.cus_set_c
    and ci2.cus_set_c = c.cus_set_c
    and ci2.cps_key_n = c.cps_key_n
)

Java - how do I write a file to a specified directory

Use:

File file = new File("Z:\\results\\results.txt");

You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.

For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.

File file = new File("/home/userName/Documents/results.txt");

C++ wait for user input

Several ways to do so, here are some possible one-line approaches:

  1. Use getch() (need #include <conio.h>).

  2. Use getchar() (expected for Enter, need #include <iostream>).

  3. Use cin.get() (expected for Enter, need #include <iostream>).

  4. Use system("pause") (need #include <iostream>).

    PS: This method will also print Press any key to continue . . . on the screen. (seems perfect choice for you :))


Edit: As discussed here, There is no completely portable solution for this. Question 19.1 of the comp.lang.c FAQ covers this in some depth, with solutions for Windows, Unix-like systems, and even MS-DOS and VMS.

VS 2017 Git Local Commit DB.lock error on every commit

if you are using an IDE like visual studio and it is open while you sending commands close IDE and try again

git add .

and other commands, it will workout

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Copy from one workbook and paste into another

    You copied using Cells.
    If so, no need to PasteSpecial since you are copying data at exactly the same format.
    Here's your code with some fixes.

    Dim x As Workbook, y As Workbook
    Dim ws1 As Worksheet, ws2 As Worksheet
    
    Set x = Workbooks.Open("path to copying book")
    Set y = Workbooks.Open("path to pasting book")
    
    Set ws1 = x.Sheets("Sheet you want to copy from")
    Set ws2 = y.Sheets("Sheet you want to copy to")
    
    ws1.Cells.Copy ws2.cells
    y.Close True
    x.Close False
    

    If however you really want to paste special, use a dynamic Range("Address") to copy from.
    Like this:

    ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
    y.Close True
    x.Close False
    

    Take note of the : colon after the .Copy which is a Statement Separating character.
    Using Object.PasteSpecial requires to be executed in a new line.
    Hope this gets you going.

    How to get the ASCII value in JavaScript for the characters

    Here is the example:

    _x000D_
    _x000D_
    var charCode = "a".charCodeAt(0);_x000D_
    console.log(charCode);
    _x000D_
    _x000D_
    _x000D_

    Or if you have longer strings:

    _x000D_
    _x000D_
    var string = "Some string";_x000D_
    _x000D_
    for (var i = 0; i < string.length; i++) {_x000D_
      console.log(string.charCodeAt(i));_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    String.charCodeAt(x) method will return ASCII character code at a given position.

    C# equivalent to Java's charAt()?

    please try to make it as a character

    string str = "Tigger";
    //then str[0] will return 'T' not "T"
    

    Best way to include CSS? Why use @import?

    I experienced a "high peak" of linked stylesheets you can add. While adding any number of linked Javascript wasn't a problem for my free host provider, after doubling number of external stylesheets I got a crash/slow down. And the right code example is:

    @import 'stylesheetB.css';
    

    So, I find it useful for having a good mental map, as Nitram mentioned, while still at hard-coding the design. Godspeed. And I pardon for English grammatical mistakes, if any.

    VBA Object doesn't support this property or method

    Object doesn't support this property or method.

    Think of it like if anything after the dot is called on an object. It's like a chain.

    An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

    (you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

    Type this much anywhere in your code area

    Dim a As Worksheets
    a.
    

    you get help from VBE, it's a little dropdown called Intelli-sense

    enter image description here

    It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

    Object doesn't support this property or method.

    If you look at the example on MSDN

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count
    

    It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

    What about

    Sub DisplayColumnCount()
        Dim iAreaCount As Integer
        Dim i As Integer
    
        Worksheets("GRA").Activate
        iAreaCount = Selection.Areas.Count
    
        If iAreaCount <= 1 Then
            MsgBox "The selection contains " & Selection.Columns.Count & " columns."
        Else
            For i = 1 To iAreaCount
            MsgBox "Area " & i & " of the selection contains " & _
            Selection.Areas(i).Columns.Count & " columns."
            Next i
        End If
    End Sub
    

    from HERE

    Converting List<Integer> to List<String>

    You can't avoid the "boxing overhead"; Java's faux generic containers can only store Objects, so your ints must be boxed into Integers. In principle it could avoid the downcast from Object to Integer (since it's pointless, because Object is good enough for both String.valueOf and Object.toString) but I don't know if the compiler is smart enough to do that. The conversion from String to Object should be more or less a no-op, so I would be disinclined to worry about that one.

    How to retrieve Key Alias and Key Password for signed APK in android studio(migrated from Eclipse)

    I have found my key password in below path

    Project\.gradle\2.14.1\taskArtifacts\taskArtifacts.bin open the file and search with the part of the password that you remember. You will found it definitely.

    Also, You can refer this answer stackoverflow.com/a/43007357/7089151

    What is the python "with" statement designed for?

    In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

    General form of with:

    with open(“file name”, “mode”) as file-var:
        processing statements
    

    note: no need to close the file by calling close() upon file-var.close()

    nodejs send html file to client

    After years, I want to add another approach by using a view engine in Express.js

    var fs = require('fs');
    
    app.get('/test', function(req, res, next) {
        var html = fs.readFileSync('./html/test.html', 'utf8')
        res.render('test', { html: html })
        // or res.send(html)
    })
    

    Then, do that in your views/test if you choose res.render method at the above code (I'm writing in EJS format):

    <%- locals.html %>
    

    That's all.

    In this way, you don't need to break your View Engine arrangements.

    Print line numbers starting at zero using awk

    If Perl is an option, you can try this:

    perl -ne 'printf "%s,$_" , $.-1' file
    

    $_ is the line
    $. is the line number

    Create JPA EntityManager without persistence.xml configuration file

    Here's a solution without Spring. Constants are taken from org.hibernate.cfg.AvailableSettings :

    entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
                archiverPersistenceUnitInfo(),
                ImmutableMap.<String, Object>builder()
                        .put(JPA_JDBC_DRIVER, JDBC_DRIVER)
                        .put(JPA_JDBC_URL, JDBC_URL)
                        .put(DIALECT, Oracle12cDialect.class)
                        .put(HBM2DDL_AUTO, CREATE)
                        .put(SHOW_SQL, false)
                        .put(QUERY_STARTUP_CHECKING, false)
                        .put(GENERATE_STATISTICS, false)
                        .put(USE_REFLECTION_OPTIMIZER, false)
                        .put(USE_SECOND_LEVEL_CACHE, false)
                        .put(USE_QUERY_CACHE, false)
                        .put(USE_STRUCTURED_CACHE, false)
                        .put(STATEMENT_BATCH_SIZE, 20)
                        .build());
    
    entityManager = entityManagerFactory.createEntityManager();
    

    And the infamous PersistenceUnitInfo

    private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
        return new PersistenceUnitInfo() {
            @Override
            public String getPersistenceUnitName() {
                return "ApplicationPersistenceUnit";
            }
    
            @Override
            public String getPersistenceProviderClassName() {
                return "org.hibernate.jpa.HibernatePersistenceProvider";
            }
    
            @Override
            public PersistenceUnitTransactionType getTransactionType() {
                return PersistenceUnitTransactionType.RESOURCE_LOCAL;
            }
    
            @Override
            public DataSource getJtaDataSource() {
                return null;
            }
    
            @Override
            public DataSource getNonJtaDataSource() {
                return null;
            }
    
            @Override
            public List<String> getMappingFileNames() {
                return Collections.emptyList();
            }
    
            @Override
            public List<URL> getJarFileUrls() {
                try {
                    return Collections.list(this.getClass()
                                                .getClassLoader()
                                                .getResources(""));
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }
    
            @Override
            public URL getPersistenceUnitRootUrl() {
                return null;
            }
    
            @Override
            public List<String> getManagedClassNames() {
                return Collections.emptyList();
            }
    
            @Override
            public boolean excludeUnlistedClasses() {
                return false;
            }
    
            @Override
            public SharedCacheMode getSharedCacheMode() {
                return null;
            }
    
            @Override
            public ValidationMode getValidationMode() {
                return null;
            }
    
            @Override
            public Properties getProperties() {
                return new Properties();
            }
    
            @Override
            public String getPersistenceXMLSchemaVersion() {
                return null;
            }
    
            @Override
            public ClassLoader getClassLoader() {
                return null;
            }
    
            @Override
            public void addTransformer(ClassTransformer transformer) {
    
            }
    
            @Override
            public ClassLoader getNewTempClassLoader() {
                return null;
            }
        };
    }
    

    Maximum concurrent Socket.IO connections

    For +300k concurrent connection:

    Set these variables in /etc/sysctl.conf:

    fs.file-max = 10000000 
    fs.nr_open = 10000000
    

    Also, change these variables in /etc/security/limits.conf:

    * soft nofile 10000000
    * hard nofile 10000000
    root soft nofile 10000000
    root hard nofile 10000000
    

    And finally, increase TCP buffers in /etc/sysctl.conf, too:

    net.ipv4.tcp_mem = 786432 1697152 1945728
    net.ipv4.tcp_rmem = 4096 4096 16777216
    net.ipv4.tcp_wmem = 4096 4096 16777216
    

    for more information please refer to this.

    passing JSON data to a Spring MVC controller

    1. Html

      $('#save').click(function(event) {        
          var jenis = $('#jenis').val();
          var model = $('#model').val();
          var harga = $('#harga').val();
          var json = { "jenis" : jenis, "model" : model, "harga": harga};
          $.ajax({
              url: 'phone/save',
              data: JSON.stringify(json),
              type: "POST",           
              beforeSend: function(xhr) {
                  xhr.setRequestHeader("Accept", "application/json");
                  xhr.setRequestHeader("Content-Type", "application/json");
              },
              success: function(data){ 
                  alert(data);
              }
          });
      
          event.preventDefault();
      });
      
      1. Controller

        @Controller
        @RequestMapping(value="/phone")
        public class phoneController {
        
            phoneDao pd=new phoneDao();
        
            @RequestMapping(value="/save",method=RequestMethod.POST)
            public @ResponseBody
            int save(@RequestBody Smartphones phone)
            {
                return pd.save(phone);
            }
        
      2. Dao

        public Integer save(Smartphones i) {
            int id = 0;
            Session session=HibernateUtil.getSessionFactory().openSession();
            Transaction trans=session.beginTransaction();
            try {
                session.save(i);   
                id=i.getId();
                trans.commit();
            }
            catch(HibernateException he){}
            return id;
        }
        

    redistributable offline .NET Framework 3.5 installer for Windows 8

    Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:

    Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

    There's a guide on MSDN.

    System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

    The problem is that every System.BadImageFormatException: Could not load file or assembly including the ones not associated with installutil.exe at all point to this very thread.

    1. If your issue is related to WindowsBase or PresentationFramework dlls and you got analyzers installed make sure to either have them installed for all of the projects in your solution or for none of them.

      enter image description here

    2. Reference the entire framework in .csproj file of your library rather than just the two dlls:

      <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
      
        <PropertyGroup>
          <OutputType>Library</OutputType>
          <TargetFramework>netcoreapp3.0</TargetFramework>
          <RazorLangVersion>3.0</RazorLangVersion>
          <UseWpf>True</UseWpf>
        </PropertyGroup>
      
    3. Remove bin and obj dirs, clean solution and rebuild.

    Submit button doesn't work

    I ran into this on a friend's HTML code and in his case, he was missing quotes.

    For example:

    <form action="formHandler.php" name="yourForm" id="theForm" method="post">    
    <input type="text" name="fname" id="fname" style="width:90;font-size:10>     
    <input type="submit" value="submit"/>
    </form>
    

    In this example, a missing quote on the input text fname will simply render the submit button un-usable and the form will not submit.

    Of course, this is a bad example because I should be using CSS in the first place ;) but anyways, check all your single and double quotes to see that they are closing properly.

    Also, if you have any tags like center, move them out of the form.

    <form action="formHandler.php" name="yourForm" id="theForm" method="post">  
    <center> <-- bad
    

    As strange it may seems, it can have an impact.

    Internet Explorer 11 detection

    To detect MSIE (from version 6 to 11) quickly:

    if(navigator.userAgent.indexOf('MSIE')!==-1
    || navigator.appVersion.indexOf('Trident/') > -1){
       /* Microsoft Internet Explorer detected in. */
    }
    

    How to delete duplicate lines in a file without sorting it in Unix?

    cat filename | sort | uniq -c | awk -F" " '$1<2 {print $2}'
    

    Deletes the duplicate lines using awk.

    The 'packages' element is not declared

    Use <packages xmlns="urn:packages">in the place of <packages>

    How to Add Incremental Numbers to a New Column Using Pandas

    df.insert(0, 'New_ID', range(880, 880 + len(df)))
    df
    

    enter image description here

    DisplayName attribute from Resources?

    How about writing a custom attribute:

    public class LocalizedDisplayNameAttribute: DisplayNameAttribute
    {
        public LocalizedDisplayNameAttribute(string resourceId) 
            : base(GetMessageFromResource(resourceId))
        { }
    
        private static string GetMessageFromResource(string resourceId)
        {
            // TODO: Return the string from the resource file
        }
    }
    

    which could be used like this:

    public class MyModel 
    {
        [Required]
        [LocalizedDisplayName("labelForName")]
        public string Name { get; set; }
    }
    

    javascript regex - look behind alternative?

    If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.

    Best way to import Observable from rxjs

    One thing I've learnt the hard way is being consistent

    Watch out for mixing:

     import { BehaviorSubject } from "rxjs";
    

    with

     import { BehaviorSubject } from "rxjs/BehaviorSubject";
    

    This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

     (myBehaviorSubject instanceof Observable)
    

    It fails because the prototype chain will be different and it will be false.

    I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

    How to get current relative directory of your Makefile?

    As taken from here;

    ROOT_DIR:=$(shell dirname $(realpath $(firstword $(MAKEFILE_LIST))))
    

    Shows up as;

    $ cd /home/user/
    
    $ make -f test/Makefile 
    /home/user/test
    
    $ cd test; make Makefile 
    /home/user/test
    

    Hope this helps

    How to check if a directory containing a file exist?

    To check if a folder exists or not, you can simply use the exists() method:

    // Create a File object representing the folder 'A/B'
    def folder = new File( 'A/B' )
    
    // If it doesn't exist
    if( !folder.exists() ) {
      // Create all folders up-to and including B
      folder.mkdirs()
    }
    
    // Then, write to file.txt inside B
    new File( folder, 'file.txt' ).withWriterAppend { w ->
      w << "Some text\n"
    }
    

    What does the term "canonical form" or "canonical representation" in Java mean?

    Wikipedia points to the term Canonicalization.

    A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.

    The Unicode example made the most sense to me:

    Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.

    In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.

    What is token-based authentication?

    When you register for a new website, often you are sent an email to activate your account. That email typically contains a link to click on. Part of that link, contains a token, the server knows about this token and can associate it with your account. The token would usually have an expiry date associated with it, so you may only have an hour to click on the link and activate your account. None of this would be possible with cookies or session variables, since its unknown what device or browser the customer is using to check emails.

    How long would it take a non-programmer to learn C#, the .NET Framework, and SQL?

    Simple answer: a lot longer than two months. Learning to program competently will take longer than that, no matter what. It took me years to learn to be a competent object-oriented programmer, and I'm good at this stuff.

    More detailed answers: it doesn't really matter whether you learn C# or SQL first, as they're very different. I'd probably suggest SQL, as it's easier to learn and more independently useful.

    You will have a hard time getting used to the on-the-job realities at home, much as if you were studying plumbing or quantitative finance.

    You're going to have a hard time putting all the information together without one or more projects you try to do. You're going to need to have other people to tell you when you're being stupid, when you're being overclever and will pay for it later, and when you're actually getting it.

    Try to find an open source project you find vaguely interesting. Study their code. Figure out why they do what they do. Look at the bug list, and try to find something as trivial as possible to fix. Work from there. Learning to contribute is going to teach you things that are useful in the work world, and it will give you something to point at. It will be far easier to get your first job if you have some experience to point to.

    Support for the experimental syntax 'classProperties' isn't currently enabled

    According to this GitHub issue if you using create-react-app you should copy your .babelrc or babel.config.js configurations to webpack.config.js and delete those.because of htis two line of code babelrc: false,configFile: false, your config in babelrc,.. are useless. and your webpack.config.js is in your ./node_madules/react-scripts/config folder I solved my problem like this:

    {
                  test: /\.(js|mjs)$/,
                  exclude: /@babel(?:\/|\\{1,2})runtime/,
                  loader: require.resolve('babel-loader'),
                  options: {
                    babelrc: false,
                    configFile: false,
                    compact: false,
                    presets: [
                      [
                        require.resolve('babel-preset-react-app/dependencies'),
                        { helpers: true },
    
                      ],
                      '@babel/preset-env', '@babel/preset-react'
                    ],
                    plugins: ['@babel/plugin-proposal-class-properties'],
                    .
                    .
                    .
    

    Get the size of the screen, current web page and browser window

    function wndsize(){
      var w = 0;var h = 0;
      //IE
      if(!window.innerWidth){
        if(!(document.documentElement.clientWidth == 0)){
          //strict mode
          w = document.documentElement.clientWidth;h = document.documentElement.clientHeight;
        } else{
          //quirks mode
          w = document.body.clientWidth;h = document.body.clientHeight;
        }
      } else {
        //w3c
        w = window.innerWidth;h = window.innerHeight;
      }
      return {width:w,height:h};
    }
    function wndcent(){
      var hWnd = (arguments[0] != null) ? arguments[0] : {width:0,height:0};
      var _x = 0;var _y = 0;var offsetX = 0;var offsetY = 0;
      //IE
      if(!window.pageYOffset){
        //strict mode
        if(!(document.documentElement.scrollTop == 0)){offsetY = document.documentElement.scrollTop;offsetX = document.documentElement.scrollLeft;}
        //quirks mode
        else{offsetY = document.body.scrollTop;offsetX = document.body.scrollLeft;}}
        //w3c
        else{offsetX = window.pageXOffset;offsetY = window.pageYOffset;}_x = ((wndsize().width-hWnd.width)/2)+offsetX;_y = ((wndsize().height-hWnd.height)/2)+offsetY;
        return{x:_x,y:_y};
    }
    var center = wndcent({width:350,height:350});
    document.write(center.x+';<br>');
    document.write(center.y+';<br>');
    document.write('<DIV align="center" id="rich_ad" style="Z-INDEX: 10; left:'+center.x+'px;WIDTH: 350px; POSITION: absolute; TOP: '+center.y+'px; HEIGHT: 350px"><!--? ?????????, ? ??? ?? ?????????? flash ?????.--></div>');
    

    How to get current route in Symfony 2?

    With Symfony 3.3, I have used this method and working fine.

    I have 4 routes like

    admin_category_index, admin_category_detail, admin_category_create, admin_category_update

    And just one line make an active class for all routes.

    <li  {% if app.request.get('_route') starts with 'admin_category' %} class="active"{% endif %}>
     <a href="{{ path('admin_category_index') }}">Product Categoires</a>
    </li>
    

    Converting byte array to string in javascript

    Simply apply your byte array to String.fromCharCode. For example

    String.fromCharCode.apply(null, [102, 111, 111]) equals 'foo'.

    Caveat: works for arrays shorter than 65535. MDN docs here.

    GridLayout (not GridView) how to stretch all children evenly

    Starting in API 21 without v7 support library with ScrollView:

    enter image description here

    XML:

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >
    
        <GridLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnCount="2"
                >
    
            <TextView
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:gravity="center"
                android:layout_gravity="fill_horizontal"
                android:background="@color/colorAccent"
                android:text="Tile1" />
    
            <TextView
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:gravity="center"
                android:layout_gravity="fill_horizontal"
                android:background="@color/colorPrimaryDark"
                android:text="Tile2" />
    
            <TextView
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:gravity="center"
                android:layout_gravity="fill_horizontal"
                android:background="@color/colorPrimary"
                android:text="Tile3" />
    
            <TextView
                android:layout_width="0dp"
                android:layout_height="100dp"
                android:layout_columnWeight="1"
                android:gravity="center"
                android:layout_gravity="fill_horizontal"
                android:background="@color/colorAccent"
                android:text="Tile4" />
    
        </GridLayout>
    </ScrollView>
    

    ES6 export all values from object

    try this ugly but workable solution:

    // use CommonJS to export all keys
    module.exports = { a: 1, b: 2, c: 3 };
    
    // import by key
    import { a, b, c } from 'commonjs-style-module';
    console.log(a, b, c);
    

    The create-react-app imports restriction outside of src directory

    This restriction makes sure all files or modules (exports) are inside src/ directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js, in following lines of code.

    // Resolve the issuer from our appSrc and make sure it's one of our files
    // Maybe an indexOf === 0 would be better?
         const relative = path.relative(appSrc, request.context.issuer);
    // If it's not in src/ or a subdirectory, not our request!
         if (relative.startsWith('../') || relative.startsWith('..\\')) {
            return callback();
          }
    

    You can remove this restriction by

    1. either changing this piece of code (not recommended)
    2. or do eject then remove ModuleScopePlugin.js from the directory.
    3. or comment/remove const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); from ./node_modules/react-scripts/config/webpack.config.dev.js

    PS: beware of the consequences of eject.