Programs & Examples On #Slackware

"No X11 DISPLAY variable" - what does it mean?

Don't forget to execute "host +" on your "home" display machine, and when you ssh to the machine you're doing "ssh -x hostname"

"for loop" with two variables?

If you want the effect of a nested for loop, use:

import itertools
for i, j in itertools.product(range(x), range(y)):
    # Stuff...

If you just want to loop simultaneously, use:

for i, j in zip(range(x), range(y)):
    # Stuff...

Note that if x and y are not the same length, zip will truncate to the shortest list. As @abarnert pointed out, if you don't want to truncate to the shortest list, you could use itertools.zip_longest.

UPDATE

Based on the request for "a function that will read lists "t1" and "t2" and return all elements that are identical", I don't think the OP wants zip or product. I think they want a set:

def equal_elements(t1, t2):
    return list(set(t1).intersection(set(t2)))
    # You could also do
    # return list(set(t1) & set(t2))

The intersection method of a set will return all the elements common to it and another set (Note that if your lists contains other lists, you might want to convert the inner lists to tuples first so that they are hashable; otherwise the call to set will fail.). The list function then turns the set back into a list.

UPDATE 2

OR, the OP might want elements that are identical in the same position in the lists. In this case, zip would be most appropriate, and the fact that it truncates to the shortest list is what you would want (since it is impossible for there to be the same element at index 9 when one of the lists is only 5 elements long). If that is what you want, go with this:

def equal_elements(t1, t2):
    return [x for x, y in zip(t1, t2) if x == y]

This will return a list containing only the elements that are the same and in the same position in the lists.

How to disable scrolling the document body?

I know this is an ancient question, but I just thought that I'd weigh in.

I'm using disableScroll. Simple and it works like in a dream.

I have had some trouble disabling scroll on body, but allowing it on child elements (like a modal or a sidebar). It looks like that something can be done using disableScroll.on([element], [options]);, but I haven't gotten that to work just yet.


The reason that this is prefered compared to overflow: hidden; on body is that the overflow-hidden can get nasty, since some things might add overflow: hidden; like this:

... This is good for preloaders and such, since that is rendered before the CSS is finished loading.

But it gives problems, when an open navigation should add a class to the body-tag (like <body class="body__nav-open">). And then it turns into one big tug-of-war with overflow: hidden; !important and all kinds of crap.

Deserialize a json string to an object in python

You can specialize an encoder for object creation: http://docs.python.org/2/library/json.html

import json
class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, complex):
            return {"real": obj.real,
            "imag": obj.imag,
            "__class__": "complex"}
        return json.JSONEncoder.default(self, obj)

print json.dumps(2 + 1j, cls=ComplexEncoder)

Using FileUtils in eclipse

FileUtils is class from apache org.apache.commons.io package, you need to download org.apache.commons.io.jar and then configure that jar file in your class path.

I am getting an "Invalid Host header" message when connecting to webpack-dev-server remotely

Hello React Developers,

Instead of doing this disableHostCheck: true, in webpackDevServer.config.js. You can easily solve 'invalid host headers' error by adding a .env file to you project, add the variables HOST=0.0.0.0 and DANGEROUSLY_DISABLE_HOST_CHECK=true in .env file. If you want to make changes in webpackDevServer.config.js, you need to extract the react-scripts by using 'npm run eject' which is not recommended to do it. So the better solution is adding above mentioned variables in .env file of your project.

Happy Coding :)

Why is "using namespace std;" considered bad practice?

A concrete example to clarify the concern. Imagine you have a situation where you have two libraries, foo and bar, each with their own namespace:

namespace foo {
    void a(float) { /* Does something */ }
}

namespace bar {
    ...
}

Now let's say you use foo and bar together in your own program as follows:

using namespace foo;
using namespace bar;

void main() {
    a(42);
}

At this point everything is fine. When you run your program it 'Does something'. But later you update bar and let's say it has changed to be like:

namespace bar {
    void a(float) { /* Does something completely different */ }
}

At this point you'll get a compiler error:

using namespace foo;
using namespace bar;

void main() {
    a(42);  // error: call to 'a' is ambiguous, should be foo::a(42)
}

So you'll need to do some maintenance to clarify that 'a' meant foo::a. That's undesirable, but fortunately it is pretty easy (just add foo:: in front of all calls to a that the compiler marks as ambiguous).

But imagine an alternative scenario where bar changed instead to look like this instead:

namespace bar {
    void a(int) { /* Does something completely different */ }
}

At this point your call to a(42) suddenly binds to bar::a instead of foo::a and instead of doing 'something' it does 'something completely different'. No compiler warning or anything. Your program just silently starts doing something complete different than before.

When you use a namespace you're risking a scenario like this, which is why people are uncomfortable using namespaces. The more things in a namespace, the greater the risk of conflict, so people might be even more uncomfortable using namespace std (due to the number of things in that namespace) than other namespaces.

Ultimately this is a trade-off between writability vs. reliability/maintainability. Readability may factor in also, but I could see arguments for that going either way. Normally I would say reliability and maintainability are more important, but in this case you'll constantly pay the writability cost for an fairly rare reliability/maintainability impact. The 'best' trade-off will determine on your project and your priorities.

REST API Best practice: How to accept list of parameter values as input

I will side with nategood's answer as it is complete and it seemed to have please your needs. Though, I would like to add a comment on identifying multiple (1 or more) resource that way:

http://our.api.com/Product/101404,7267261

In doing so, you:

Complexify the clients by forcing them to interpret your response as an array, which to me is counter intuitive if I make the following request: http://our.api.com/Product/101404

Create redundant APIs with one API for getting all products and the one above for getting 1 or many. Since you shouldn't show more than 1 page of details to a user for the sake of UX, I believe having more than 1 ID would be useless and purely used for filtering the products.

It might not be that problematic, but you will either have to handle this yourself server side by returning a single entity (by verifying if your response contains one or more) or let clients manage it.

Example

I want to order a book from Amazing. I know exactly which book it is and I see it in the listing when navigating for Horror books:

  1. 10 000 amazing lines, 0 amazing test
  2. The return of the amazing monster
  3. Let's duplicate amazing code
  4. The amazing beginning of the end

After selecting the second book, I am redirected to a page detailing the book part of a list:

--------------------------------------------
Book #1
--------------------------------------------
    Title: The return of the amazing monster
    Summary:
    Pages:
    Publisher:
--------------------------------------------

Or in a page giving me the full details of that book only?

---------------------------------
The return of the amazing monster
---------------------------------
Summary:
Pages:
Publisher:
---------------------------------

My Opinion

I would suggest using the ID in the path variable when unicity is guarantied when getting this resource's details. For example, the APIs below suggest multiple ways to get the details for a specific resource (assuming a product has a unique ID and a spec for that product has a unique name and you can navigate top down):

/products/{id}
/products/{id}/specs/{name}

The moment you need more than 1 resource, I would suggest filtering from a larger collection. For the same example:

/products?ids=

Of course, this is my opinion as it is not imposed.

In excel how do I reference the current row but a specific column?

If you dont want to hard-code the cell addresses you can use the ROW() function.

eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))

Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.

jQuery get selected option value (not the text, but the attribute 'value')

It's working better. Try it.

let value = $("select#yourId option").filter(":selected").val();

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Rails has_many with alias name

To complete @SamSaffron's answer :

You can use class_name with either foreign_key or inverse_of. I personally prefer the more abstract declarative, but it's really just a matter of taste :

class BlogPost
  has_many :images, class_name: "BlogPostImage", inverse_of: :blog_post  
end

and you need to make sure you have the belongs_to attribute on the child model:

class BlogPostImage
  belongs_to :blog_post
end

Manifest merger failed : uses-sdk:minSdkVersion 14

I also had the same issue and changing following helped me:

from:

dependencies {
    compile 'com.android.support:support-v4:+'

to:

dependencies {
 compile 'com.android.support:support-v4:20.0.0'
}

Converting time stamps in excel to dates

If you get a Error 509 in Libre office you may replace , by ; in the DATE() function

=(((COLUMN_ID_HERE/60)/60)/24)+DATE(1970;1;1)

How to retrieve the last autoincremented ID from a SQLite table?

According to Android Sqlite get last insert row id there is another query:

SELECT rowid from your_table_name order by ROWID DESC limit 1

Is it possible to GROUP BY multiple columns using MySQL?

group by fV.tier_id, f.form_template_id

Is there a way to make mv create the directory to be moved to if it doesn't exist?

i accomplished this with the install command on linux:

root@logstash:# myfile=bash_history.log.2021-02-04.gz ; install -v -p -D $myfile /tmp/a/b/$myfile

bash_history.log.2021-02-04.gz -> /tmp/a/b/bash_history.log.2021-02-04.gz

the only downside being the file permissions are changed:

root@logstash:# ls -lh /tmp/a/b/

-rwxr-xr-x 1 root root 914 Fev  4 09:11 bash_history.log.2021-02-04.gz

if you dont mind resetting the permission, you can use:

-g, --group=GROUP   set group ownership, instead of process' current group
-m, --mode=MODE     set permission mode (as in chmod), instead of rwxr-xr-x
-o, --owner=OWNER   set ownership (super-user only)

What is WEB-INF used for in a Java EE web application?

This convention is followed for security reasons. For example if unauthorized person is allowed to access root JSP file directly from URL then they can navigate through whole application without any authentication and they can access all the secured data.

What is memoization and how can I use it in Python?

Memoization effectively refers to remembering ("memoization" ? "memorandum" ? to be remembered) results of method calls based on the method inputs and then returning the remembered result rather than computing the result again. You can think of it as a cache for method results. For further details, see page 387 for the definition in Introduction To Algorithms (3e), Cormen et al.

A simple example for computing factorials using memoization in Python would be something like this:

factorial_memo = {}
def factorial(k):
    if k < 2: return 1
    if k not in factorial_memo:
        factorial_memo[k] = k * factorial(k-1)
    return factorial_memo[k]

You can get more complicated and encapsulate the memoization process into a class:

class Memoize:
    def __init__(self, f):
        self.f = f
        self.memo = {}
    def __call__(self, *args):
        if not args in self.memo:
            self.memo[args] = self.f(*args)
        #Warning: You may wish to do a deepcopy here if returning objects
        return self.memo[args]

Then:

def factorial(k):
    if k < 2: return 1
    return k * factorial(k - 1)

factorial = Memoize(factorial)

A feature known as "decorators" was added in Python 2.4 which allow you to now simply write the following to accomplish the same thing:

@Memoize
def factorial(k):
    if k < 2: return 1
    return k * factorial(k - 1)

The Python Decorator Library has a similar decorator called memoized that is slightly more robust than the Memoize class shown here.

What's the difference between “mod” and “remainder”?

sign of remainder will be same as the divisible and the sign of modulus will be same as divisor.

Remainder is simply the remaining part after the arithmetic division between two integer number whereas Modulus is the sum of remainder and divisor when they are oppositely signed and remaining part after the arithmetic division when remainder and divisor both are of same sign.

Example of Remainder:

10 % 3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % 3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

10 % -3 = 1 [here divisible is 10 which is positively signed so the result will also be positively signed]

-10 % -3 = -1 [here divisible is -10 which is negatively signed so the result will also be negatively signed]

Example of Modulus:

5 % 3 = 2 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is also positively signed. As both remainder and divisor are of same sign the result will be same as remainder]

-5 % 3 = 1 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is positively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor -2 + 3 = 1]

5 % -3 = -1 [here divisible is 5 which is positively signed so the remainder will also be positively signed and the divisor is negatively signed. As both remainder and divisor are of opposite sign the result will be sum of remainder and divisor 2 + -3 = -1]

-5 % -3 = -2 [here divisible is -5 which is negatively signed so the remainder will also be negatively signed and the divisor is also negatively signed. As both remainder and divisor are of same sign the result will be same as remainder]

I hope this will clearly distinguish between remainder and modulus.

AWS S3: how do I see how much disk space is using

In addition to Christopher's answer.

If you need to count total size of versioned bucket use:

aws s3api list-object-versions --bucket BUCKETNAME --output json --query "[sum(Versions[].Size)]"

It counts both Latest and Archived versions.

How to declare a global variable in C++

In addition to other answers here, if the value is an integral constant, a public enum in a class or struct will work. A variable - constant or otherwise - at the root of a namespace is another option, or a static public member of a class or struct is a third option.

MyClass::eSomeConst (enum)
MyNamespace::nSomeValue 
MyStruct::nSomeValue (static) 

random.seed(): What does it do?

Set the seed(x) before generating a set of random numbers and use the same seed to generate the same set of random numbers. Useful in case of reproducing the issues.

>>> from random import *
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> seed(20)
>>> randint(1,100)
93
>>> randint(1,100)
88
>>> randint(1,100)
99
>>> 

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

I know this is an old question, but with my quick read of the responses here, I didn't really see anyone mention that at times a synchronized method may be the wrong lock.
From Java Concurrency In Practice (pg. 72):

public class ListHelper<E> {
  public List<E> list = Collections.syncrhonizedList(new ArrayList<>());
...

public syncrhonized boolean putIfAbsent(E x) {
 boolean absent = !list.contains(x);
if(absent) {
 list.add(x);
}
return absent;
}

The above code has the appearance of being thread-safe. However, in reality it is not. In this case the lock is obtained on the instance of the class. However, it is possible for the list to be modified by another thread not using that method. The correct approach would be to use

public boolean putIfAbsent(E x) {
 synchronized(list) {
  boolean absent = !list.contains(x);
  if(absent) {
    list.add(x);
  }
  return absent;
}
}

The above code would block all threads trying to modify list from modifying the list until the synchronized block has completed.

How to use a parameter in ExecStart command line?

Although systemd indeed does not provide way to pass command-line arguments for unit files, there are possibilities to write instances: http://0pointer.de/blog/projects/instances.html

For example: /lib/systemd/system/[email protected] looks something like this:

[Unit]
Description=Serial Getty on %I
BindTo=dev-%i.device
After=dev-%i.device systemd-user-sessions.service

[Service]
ExecStart=-/sbin/agetty -s %I 115200,38400,9600
Restart=always
RestartSec=0

So, you may start it like:

$ systemctl start [email protected]
$ systemctl start [email protected]

For systemd it will different instances:

$ systemctl status [email protected]
[email protected] - Getty on ttyUSB0
      Loaded: loaded (/lib/systemd/system/[email protected]; static)
      Active: active (running) since Mon, 26 Sep 2011 04:20:44 +0200; 2s ago
    Main PID: 5443 (agetty)
      CGroup: name=systemd:/system/[email protected]/ttyUSB0
          + 5443 /sbin/agetty -s ttyUSB0 115200,38400,9600

It also mean great possibility enable and disable it separately.

Off course it lack much power of command line parsing, but in common way it is used as some sort of config files selection. For example you may look at Fedora [email protected]: http://pkgs.fedoraproject.org/cgit/openvpn.git/tree/[email protected]

How to test if parameters exist in rails

I try a late, but from far sight answer:

If you want to know if values in a (any) hash are set, all above answers a true, depending of their point of view.

If you want to test your (GET/POST..) params, you should use something more special to what you expect to be the value of params[:one], something like

if params[:one]~=/   / and  params[:two]~=/[a-z]xy/

ignoring parameter (GET/POST) as if they where not set, if they dont fit like expected

just a if params[:one] with or without nil/true detection is one step to open your page for hacking, because, it is typically the next step to use something like select ... where params[:one] ..., if this is intended or not, active or within or after a framework.

an answer or just a hint

Can I create a One-Time-Use Function in a Script or Stored Procedure?

I know I might get criticized for suggesting dynamic SQL, but sometimes it's a good solution. Just make sure you understand the security implications before you consider this.

DECLARE @add_a_b_func nvarchar(4000) = N'SELECT @c = @a + @b;';
DECLARE @add_a_b_parm nvarchar(500) = N'@a int, @b int, @c int OUTPUT';

DECLARE @result int;
EXEC sp_executesql @add_a_b_func, @add_a_b_parm, 2, 3, @c = @result OUTPUT;
PRINT CONVERT(varchar, @result); -- prints '5'

Switch statement for greater-than/less-than

What exactly are you doing in //do stuff?

You may be able to do something like:

(scrollLeft < 1000) ? //do stuff
: (scrollLeft > 1000 && scrollLeft < 2000) ? //do stuff
: (scrollLeft > 2000) ? //do stuff
: //etc. 

Download File Using jQuery

If you don't want search engines to index certain files, you can use robots.txt to tell web spiders not to access certain parts of your website.

If you rely only on javascript, then some users who browse without it won't be able to click your links.

Adding attribute in jQuery

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

get the latest fragment in backstack

you can use getBackStackEntryAt(). In order to know how many entry the activity holds in the backstack you can use getBackStackEntryCount()

int lastFragmentCount = getBackStackEntryCount() - 1;

Resolve build errors due to circular dependency amongst classes

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

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

// file: A.h
class A {
  B _b;
};

// file: B.h
class B {
  A _a;
};

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

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

Clearly a circular reference that you must break.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

HTH.

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

Get the current date in java.sql.Date format

These are all too long.

Just use:

new Date(System.currentTimeMillis())

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your HTTP client disconnected.

This could have a couple of reasons:

  • Responding to the request took too long, the client gave up
  • You responded with something the client did not understand
  • The end-user actually cancelled the request
  • A network error occurred
  • ... probably more

You can fairly easily emulate the behavior:

URL url = new URL("http://example.com/path/to/the/file");

int numberOfBytesToRead = 200;

byte[] buffer = new byte[numberOfBytesToRead];
int numberOfBytesRead = url.openStream().read(buffer);

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

Ansible - Use default if a variable is not defined

You can use Jinja's default:

- name: Create user
  user:
    name: "{{ my_variable | default('default_value') }}"

Ruby: How to get the first character of a string

If you use a recent version of Ruby (1.9.0 or later), the following should work:

'Smith'[0] # => 'S'

If you use either 1.9.0+ or 1.8.7, the following should work:

'Smith'.chars.first # => 'S'

If you use a version older than 1.8.7, this should work:

'Smith'.split(//).first # => 'S'

Note that 'Smith'[0,1] does not work on 1.8, it will not give you the first character, it will only give you the first byte.

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

Evaluate list.contains string in JSTL

Another way of doing this is using a Map (HashMap) with Key, Value pairs representing your object.

Map<Long, Object> map = new HashMap<Long, Object>();
map.put(new Long(1), "one");
map.put(new Long(2), "two");

In JSTL

<c:if test="${not empty map[1]}">

This should return true if the pair exist in the map

Calling virtual functions inside constructors

Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. All C++ implementations should call the version of the function defined at the level of the hierarchy in the current constructor and no further.

The C++ FAQ Lite covers this in section 23.7 in pretty good detail. I suggest reading that (and the rest of the FAQ) for a followup.

Excerpt:

[...] In a constructor, the virtual call mechanism is disabled because overriding from derived classes hasn’t yet happened. Objects are constructed from the base up, “base before derived”.

[...]

Destruction is done “derived class before base class”, so virtual functions behave as in constructors: Only the local definitions are used – and no calls are made to overriding functions to avoid touching the (now destroyed) derived class part of the object.

EDIT Corrected Most to All (thanks litb)

How to add color to Github's README.md file

I'm inclined to agree with Qwertman that it's not currently possible to specify color for text in GitHub markdown, at least not through HTML.

GitHub does allow some HTML elements and attributes, but only certain ones (see their documentation about their HTML sanitization). They do allow p and div tags, as well as color attribute. However, when I tried using them in a markdown document on GitHub, it didn't work. I tried the following (among other variations), and they didn't work:

  • <p style='color:red'>This is some red text.</p>
  • <font color="red">This is some text!</font>
  • These are <b style='color:red'>red words</b>.

As Qwertman suggested, if you really must use color you could do it in a README.html and refer them to it.

Instantiate and Present a viewController in Swift

I would like to suggest a much cleaner way. This will be useful when we have multiple storyboards

1.Create a structure with all your storyboards

struct Storyboard {
      static let main = "Main"
      static let login = "login"
      static let profile = "profile" 
      static let home = "home"
    }

2. Create a UIStoryboard extension like this

extension UIStoryboard {
  @nonobjc class var main: UIStoryboard {
    return UIStoryboard(name: Storyboard.main, bundle: nil)
  }
  @nonobjc class var journey: UIStoryboard {
    return UIStoryboard(name: Storyboard.login, bundle: nil)
  }
  @nonobjc class var quiz: UIStoryboard {
    return UIStoryboard(name: Storyboard.profile, bundle: nil)
  }
  @nonobjc class var home: UIStoryboard {
    return UIStoryboard(name: Storyboard.home, bundle: nil)
  }
}

Give the storyboard identifier as the class name, and use the below code to instantiate

let loginVc = UIStoryboard.login.instantiateViewController(withIdentifier: "\(LoginViewController.self)") as! LoginViewController

MySQL vs MongoDB 1000 reads

Do you have concurrency, i.e simultaneous users ? If you just run 1000 times the query straight, with just one thread, there will be almost no difference. Too easy for these engines :)

BUT I strongly suggest that you build a true load testing session, which means using an injector such as JMeter with 10, 20 or 50 users AT THE SAME TIME so you can really see a difference (try to embed this code inside a web page JMeter could query).

I just did it today on a single server (and a simple collection / table) and the results are quite interesting and surprising (MongoDb was really faster on writes & reads, compared to MyISAM engine and InnoDb engine).

This really should be part of your test : concurrency & MySQL engine. Then, data/schema design & application needs are of course huge requirements, beyond response times. Let me know when you get results, I'm also in need of inputs about this!

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

How to make a floated div 100% height of its parent?

For #outer height to be based on its content, and have #inner base its height on that, make both elements absolutely positioned.

More details can be found in the spec for the css height property, but essentially, #inner must ignore #outer height if #outer's height is auto, unless #outer is positioned absolutely. Then #inner height will be 0, unless #inner itself is positioned absolutely.

<style>
    #outer {
        position:absolute; 
        height:auto; width:200px; 
        border: 1px solid red; 
    }
    #inner {
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
    }
</style>

<div id='outer'>
    <div id='inner'>
    </div>
    text
</div>

However... By positioning #inner absolutely, a float setting will be ignored, so you will need to choose a width for #inner explicitly, and add padding in #outer to fake the text wrapping I suspect you want. For example, below, the padding of #outer is the width of #inner +3. Conveniently (as the whole point was to get #inner height to 100%) there's no need to wrap text beneath #inner, so this will look just like #inner is floated.

<style>
    #outer2{
        padding-left: 23px;
        position:absolute; 
        height:auto; 
        width:200px; 
        border: 1px solid red; 
    }
    #inner2{
        left:0;
        position:absolute; 
        height:100%; 
        width:20px; 
        border: 1px solid black; 
   }
</style>

<div id='outer2'>
    <div id='inner2'>
    </div>
    text
</div>

I deleted my previous answer, as it was based on too many wrong assumptions about your goal.

How to automatically convert strongly typed enum into int?

As many said, there is no way to automatically convert without adding overheads and too much complexity, but you can reduce your typing a bit and make it look better by using lambdas if some cast will be used a bit much in a scenario. That would add a bit of function overhead call, but will make code more readable compared to long static_cast strings as can be seen below. This may not be useful project wide, but only class wide.

#include <bitset>
#include <vector>

enum class Flags { ......, Total };
std::bitset<static_cast<unsigned int>(Total)> MaskVar;
std::vector<Flags> NewFlags;

-----------
auto scui = [](Flags a){return static_cast<unsigned int>(a); };

for (auto const& it : NewFlags)
{
    switch (it)
    {
    case Flags::Horizontal:
        MaskVar.set(scui(Flags::Horizontal));
        MaskVar.reset(scui(Flags::Vertical)); break;
    case Flags::Vertical:
        MaskVar.set(scui(Flags::Vertical));
        MaskVar.reset(scui(Flags::Horizontal)); break;

   case Flags::LongText:
        MaskVar.set(scui(Flags::LongText));
        MaskVar.reset(scui(Flags::ShorTText)); break;
    case Flags::ShorTText:
        MaskVar.set(scui(Flags::ShorTText));
        MaskVar.reset(scui(Flags::LongText)); break;

    case Flags::ShowHeading:
        MaskVar.set(scui(Flags::ShowHeading));
        MaskVar.reset(scui(Flags::NoShowHeading)); break;
    case Flags::NoShowHeading:
        MaskVar.set(scui(Flags::NoShowHeading));
        MaskVar.reset(scui(Flags::ShowHeading)); break;

    default:
        break;
    }
}

How to set URL query params in Vue with Vue-Router

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

How to access child's state in React?

Now You can access the InputField's state which is the child of FormEditor .

Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

On button click we are just printing the state of the Input fields.

The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

class InputField extends React.Component{
  handleChange = (event)=> {
    const val = event.target.value;
    this.props.onChange(this.props.id , val);
  }

  render() {
    return(
      <div>
        <input type="text" onChange={this.handleChange} value={this.props.value}/>
        <br/><br/>
      </div>
    );
  }
}       


class FormEditorParent extends React.Component {
  state = {};
  handleFieldChange = (inputFieldId , inputFieldValue) => {
    this.setState({[inputFieldId]:inputFieldValue});
  }
  //on Button click simply get the state of the input field
  handleClick = ()=>{
    console.log(JSON.stringify(this.state));
  }

  render() {
    const fields = this.props.fields.map(field => (
      <InputField
        key={field}
        id={field}
        onChange={this.handleFieldChange}
        value={this.state[field]}
      />
    ));

    return (
      <div>
        <div>
          <button onClick={this.handleClick}>Click Me</button>
        </div>
        <div>
          {fields}
        </div>
      </div>
    );
  }
}

const App = () => {
  const fields = ["field1", "field2", "anotherField"];
  return <FormEditorParent fields={fields} />;
};

ReactDOM.render(<App/>, mountNode);

How do I pass command-line arguments to a WinForms application?

You can grab the command line of any .Net application by accessing the Environment.CommandLine property. It will have the command line as a single string but parsing out the data you are looking for shouldn't be terribly difficult.

Having an empty Main method will not affect this property or the ability of another program to add a command line parameter.

Export to CSV using MVC, C# and jQuery

With MVC you can simply return a file like this:

public ActionResult ExportData()
{
    System.IO.FileInfo exportFile = //create your ExportFile
    return File(exportFile.FullName, "text/csv", string.Format("Export-{0}.csv", DateTime.Now.ToString("yyyyMMdd-HHmmss")));
}

Programmatically change the src of an img tag

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

Bootstrap 4 File Input

I just add this in my CSS file and it works:

.custom-file-label::after{content: 'New Text Button' !important;}


Use of *args and **kwargs

Here's an example that uses 3 different types of parameters.

def func(required_arg, *args, **kwargs):
    # required_arg is a positional-only parameter.
    print required_arg

    # args is a tuple of positional arguments,
    # because the parameter name has * prepended.
    if args: # If args is not empty.
        print args

    # kwargs is a dictionary of keyword arguments,
    # because the parameter name has ** prepended.
    if kwargs: # If kwargs is not empty.
        print kwargs

>>> func()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: func() takes at least 1 argument (0 given)

>>> func("required argument")
required argument

>>> func("required argument", 1, 2, '3')
required argument
(1, 2, '3')

>>> func("required argument", 1, 2, '3', keyword1=4, keyword2="foo")
required argument
(1, 2, '3')
{'keyword2': 'foo', 'keyword1': 4}

Print PDF directly from JavaScript

you can download the pdf file using fetch, and print it with print.js

                          fetch("url")
                            .then(function (response) {

                                response.blob().then(function (blob) {
                                    var reader = new FileReader();
                                    reader.onload = function () {

                                        //Remove the data:application/pdf;base64,
                                        printJS({
                                            printable: reader.result.substring(28),
                                            type: 'pdf',
                                            base64: true
                                        });
                                    };
                                    reader.readAsDataURL(blob);
                                })
                            });

Setting the filter to an OpenFileDialog to allow the typical image formats?

Complete solution in C# is here:

private void btnSelectImage_Click(object sender, RoutedEventArgs e)
{
    // Configure open file dialog box 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Filter = "";

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    string sep = string.Empty;

    foreach (var c in codecs)
    {
       string codecName = c.CodecName.Substring(8).Replace("Codec", "Files").Trim();
       dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, codecName, c.FilenameExtension);
       sep = "|";
    }

    dlg.Filter = String.Format("{0}{1}{2} ({3})|{3}", dlg.Filter, sep, "All Files", "*.*"); 

    dlg.DefaultExt = ".png"; // Default file extension 

    // Show open file dialog box 
    Nullable<bool> result = dlg.ShowDialog();

    // Process open file dialog box results 
    if (result == true)
    {
       // Open document 
       string fileName  = dlg.FileName;
       // Do something with fileName  
    }
} 

MySql : Grant read only options?

If there is any single privilege that stands for ALL READ operations on database.

It depends on how you define "all read."

"Reading" from tables and views is the SELECT privilege. If that's what you mean by "all read" then yes:

GRANT SELECT ON *.* TO 'username'@'host_or_wildcard' IDENTIFIED BY 'password';

However, it sounds like you mean an ability to "see" everything, to "look but not touch." So, here are the other kinds of reading that come to mind:

"Reading" the definition of views is the SHOW VIEW privilege.

"Reading" the list of currently-executing queries by other users is the PROCESS privilege.

"Reading" the current replication state is the REPLICATION CLIENT privilege.

Note that any or all of these might expose more information than you intend to expose, depending on the nature of the user in question.

If that's the reading you want to do, you can combine any of those (or any other of the available privileges) in a single GRANT statement.

GRANT SELECT, SHOW VIEW, PROCESS, REPLICATION CLIENT ON *.* TO ...

However, there is no single privilege that grants some subset of other privileges, which is what it sounds like you are asking.

If you are doing things manually and looking for an easier way to go about this without needing to remember the exact grant you typically make for a certain class of user, you can look up the statement to regenerate a comparable user's grants, and change it around to create a new user with similar privileges:

mysql> SHOW GRANTS FOR 'not_leet'@'localhost';
+------------------------------------------------------------------------------------------------------------------------------------+
| Grants for not_leet@localhost                                                                                                      |
+------------------------------------------------------------------------------------------------------------------------------------+
| GRANT SELECT, REPLICATION CLIENT ON *.* TO 'not_leet'@'localhost' IDENTIFIED BY PASSWORD '*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' |
+------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Changing 'not_leet' and 'localhost' to match the new user you want to add, along with the password, will result in a reusable GRANT statement to create a new user.

Of, if you want a single operation to set up and grant the limited set of privileges to users, and perhaps remove any unmerited privileges, that can be done by creating a stored procedure that encapsulates everything that you want to do. Within the body of the procedure, you'd build the GRANT statement with dynamic SQL and/or directly manipulate the grant tables themselves.

In this recent question on Database Administrators, the poster wanted the ability for an unprivileged user to modify other users, which of course is not something that can normally be done -- a user that can modify other users is, pretty much by definition, not an unprivileged user -- however -- stored procedures provided a good solution in that case, because they run with the security context of their DEFINER user, allowing anybody with EXECUTE privilege on the procedure to temporarily assume escalated privileges to allow them to do the specific things the procedure accomplishes.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

CMD:

  • CMD ["executable","param1","param2"]: ["executable","param1","param2"] is the first process.
  • CMD command param1 param2: /bin/sh -c CMD command param1 param2 is the first process. CMD command param1 param2 is forked from the first process.
  • CMD ["param1","param2"]: This form is used to provide default arguments for ENTRYPOINT.

ENTRYPOINT (The following list does not consider the case where CMD and ENTRYPOINT are used together):

  • ENTRYPOINT ["executable", "param1", "param2"]: ["executable", "param1", "param2"] is the first process.
  • ENTRYPOINT command param1 param2: /bin/sh -c command param1 param2 is the first process. command param1 param2 is forked from the first process.

As creack said, CMD was developed first. Then ENTRYPOINT was developed for more customization. Since they are not designed together, there are some functionality overlaps between CMD and ENTRYPOINT, which often confuse people.

Vertical dividers on horizontal UL menu

I do it as Pekka says. Put an inline style on each <li>:

style="border-right: solid 1px #555; border-left: solid 1px #111;"

Take off first and last as appropriate.

How to find the users list in oracle 11g db?

The command select username from all_users; requires less privileges

Create XML file using java

I liked the Xembly syntax, but it is not a statically typed API. You can get this with XMLBeam:

// Declare a projection
public interface Projection {

    @XBWrite("/root/order/@id")
    Projection setID(int id);

    @XBWrite("/root/order")
    Projection setValue(String value);
}

public static void main(String[] args) {
    // create a projector
    XBProjector projector = new XBProjector();

    // use it to create a projection instance
    Projection projection = projector.projectEmptyDocument(Projection.class);

    // You get a fluent API, with java types in parameters 
    projection.setID(553).setValue("$140.00");

    // Use the projector again to do IO stuff or create an XML-string
    projector.toXMLString(projection);
}

My experience is that this works great even when the XML gets more complicated. You can just decouple the XML structure from your java code structure.

How to start new line with space for next line in Html.fromHtml for text view in android

Did you try <br/>, <br><br/> or simply \n ? <br> should be supported according to this source, though.

Supported HTML tags

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

PHP __get and __set magic methods

From the PHP manual:

  • __set() is run when writing data to inaccessible properties.
  • __get() is utilized for reading data from inaccessible properties.

This is only called on reading/writing inaccessible properties. Your property however is public, which means it is accessible. Changing the access modifier to protected solves the issue.

Git: Create a branch from unstaged/uncommitted changes on master

In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:

enter image description here

The same applies if you simply switch the branch too.

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

Using OR in SQLAlchemy

SQLAlchemy overloads the bitwise operators &, | and ~ so instead of the ugly and hard-to-read prefix syntax with or_() and and_() (like in Bastien's answer) you can use these operators:

.filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Note that the parentheses are not optional due to the precedence of the bitwise operators.

So your whole query could look like this:

addr = session.query(AddressBook) \
    .filter(AddressBook.city == "boston") \
    .filter((AddressBook.lastname == 'bulger') | (AddressBook.firstname == 'whitey'))

Regex number between 1 and 100

This is very simple logic, So no need of regx.

Instead go for using ternary operator

var num = 89;
var isValid = (num <=  100 && num > 0 ) ? true : false;

It will do the magic for you!!

How to implement a queue using two stacks?

public class QueueUsingStacks<T>
{
    private LinkedListStack<T> stack1;
    private LinkedListStack<T> stack2;

    public QueueUsingStacks()
    {
        stack1=new LinkedListStack<T>();
        stack2 = new LinkedListStack<T>();

    }
    public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )
    {
        while(source.Head!=null)
        {
            dest.Push(source.Head.Data);
            source.Head = source.Head.Next;
        }
    }
    public void Enqueue(T entry)
    {

       stack1.Push(entry);
    }
    public T Dequeue()
    {
        T obj;
        if (stack2 != null)
        {
            Copy(stack1, stack2);
             obj = stack2.Pop();
            Copy(stack2, stack1);
        }
        else
        {
            throw new Exception("Stack is empty");
        }
        return obj;
    }

    public void Display()
    {
        stack1.Display();
    }


}

For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack

Ajax call Into MVC Controller- Url Issue

Simple way to access the Url Try this Code

 $.ajax({
     type: "POST",
      url: '/Controller/Search', 
     data: "{queryString:'" + searchVal + "'}",
     contentType: "application/json; charset=utf-8",
     dataType: "html",
     success: function (data) {
     alert("here" + data.d.toString());
    });

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

View JSON file in Browser

If there is a Content-Disposition: attachment reponse header, Firefox will ask you to save the file, even if you have JSONView installed to format JSON.

To bypass this problem, I removed the header ("Content-Disposition" : null) with moz-rewrite Firefox addon that allows you to modify request and response headers https://addons.mozilla.org/en-US/firefox/addon/moz-rewrite-js/

An example of JSON file served with this header is the Twitter API (it looks like they added it recently). If you want to try this JSON file, I have a script to access Twitter API in browser: https://gist.github.com/baptx/ffb268758cd4731784e3

Adding 1 hour to time variable

Beware of adding 3600!! may be a problem on day change because of unix timestamp format uses moth before day.

e.g. 2012-03-02 23:33:33 would become 2014-01-13 13:00:00 by adding 3600 better use mktime and date functions they can handle this and things like adding 25 hours etc.

How do I remove a CLOSE_WAIT socket connection

It is also worth noting that if your program spawns a new process, that process may inherit all your opened handles. Even after your own program closs, those inherited handles can still be alive via the orphaned child process. And they don't necessarily show up quite the same in netstat. But all the same, the socket will hang around in CLOSE_WAIT while this child process is alive.

I had a case where I was running ADB. ADB itself spawns a server process if its not already running. This inherited all my handles initially, but did not show up as owning any of them when I was investigating (the same was true for both macOS and Windows - not sure about Linux).

Group By Multiple Columns

A thing to note is that you need to send in an object for Lambda expressions and can't use an instance for a class.

Example:

public class Key
{
    public string Prop1 { get; set; }

    public string Prop2 { get; set; }
}

This will compile but will generate one key per cycle.

var groupedCycles = cycles.GroupBy(x => new Key
{ 
  Prop1 = x.Column1, 
  Prop2 = x.Column2 
})

If you wan't to name the key properties and then retreive them you can do it like this instead. This will GroupBy correctly and give you the key properties.

var groupedCycles = cycles.GroupBy(x => new 
{ 
  Prop1 = x.Column1, 
  Prop2= x.Column2 
})

foreach (var groupedCycle in groupedCycles)
{
    var key = new Key();
    key.Prop1 = groupedCycle.Key.Prop1;
    key.Prop2 = groupedCycle.Key.Prop2;
}

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Make virtualenv inherit specific packages from your global site-packages

Install virtual env with

virtualenv --system-site-packages

and use pip install -U to install matplotlib

How can I wait for a thread to finish with .NET?

When I want the UI to be able to update its display while waiting for a task to complete, I use a while-loop that tests IsAlive on the thread:

    Thread t = new Thread(() => someMethod(parameters));
    t.Start();
    while (t.IsAlive)
    {
        Thread.Sleep(500);
        Application.DoEvents();
    }

How to read a single character from the user?

sys.stdin.read(1)

will basically read 1 byte from STDIN.

If you must use the method which does not wait for the \n you can use this code as suggested in previous answer:

class _Getch:
    """Gets a single character from standard input.  Does not echo to the screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

(taken from http://code.activestate.com/recipes/134892/)

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Search File And Find Exact Match And Print Line?

you should use regular expressions to find all you need:

import re
p = re.compile(r'(\d+)')  # a pattern for a number

for line in file :
    if num in p.findall(line) :
        print line

regular expression will return you all numbers in a line as a list, for example:

>>> re.compile(r'(\d+)').findall('123kh234hi56h9234hj29kjh290')
['123', '234', '56', '9234', '29', '290']

so you don't match '200' or '220' for '20'.

How to read a specific line using the specific line number from a file in Java?

You may try indexed-file-reader (Apache License 2.0). The class IndexedFileReader has a method called readLines(int from, int to) which returns a SortedMap whose key is the line number and the value is the line that was read.

Example:

File file = new File("src/test/resources/file.txt");
reader = new IndexedFileReader(file);

lines = reader.readLines(6, 10);
assertNotNull("Null result.", lines);
assertEquals("Incorrect length.", 5, lines.size());
assertTrue("Incorrect value.", lines.get(6).startsWith("[6]"));
assertTrue("Incorrect value.", lines.get(7).startsWith("[7]"));
assertTrue("Incorrect value.", lines.get(8).startsWith("[8]"));
assertTrue("Incorrect value.", lines.get(9).startsWith("[9]"));
assertTrue("Incorrect value.", lines.get(10).startsWith("[10]"));      

The above example reads a text file composed of 50 lines in the following format:

[1] The quick brown fox jumped over the lazy dog ODD
[2] The quick brown fox jumped over the lazy dog EVEN

Disclamer: I wrote this library

Eclipse - java.lang.ClassNotFoundException

I've come across that situation several times and, after a lot of attempts, I found the solution.

Check your project build-path and enable specific output folders for each folder. Go one by one though each source-folder of your project and set the output folder that maven would use.

For example, your web project's src/main/java should have target/classes under the web project, test classes should have target/test-classes also under the web project and so.

Using this configuration will allow you to execute unit tests in eclipse.

Just one more advice, if your web project's tests require some configuration files that are under the resources, be sure to include that folder as a source folder and to make the proper build-path configuration.

Hope it helps.

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

my solution:`

   public void onTextChanged(CharSequence s, int start, int before, int count) {
   char ch=s.charAt(start + count - 1);
   if (Character.isLetter(ch)) {
       s=s.subSequence(start, count-1);
       edittext.setText(s);
    }

Find value in an array

Like this?

a = [ "a", "b", "c", "d", "e" ]
a[2] +  a[0] + a[1]    #=> "cab"
a[6]                   #=> nil
a[1, 2]                #=> [ "b", "c" ]
a[1..3]                #=> [ "b", "c", "d" ]
a[4..7]                #=> [ "e" ]
a[6..10]               #=> nil
a[-3, 3]               #=> [ "c", "d", "e" ]
# special cases
a[5]                   #=> nil
a[5, 1]                #=> []
a[5..10]               #=> []

or like this?

a = [ "a", "b", "c" ]
a.index("b")   #=> 1
a.index("z")   #=> nil

See the manual.

How to create a DB link between two oracle instances

If you want to access the data in instance B from the instance A. Then this is the query, you can edit your respective credential.

CREATE DATABASE LINK dblink_passport
CONNECT TO xxusernamexx IDENTIFIED BY xxpasswordxx
USING
'(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST=xxipaddrxx / xxhostxx )
(PORT=xxportxx))
(CONNECT_DATA=
(SID=xxsidxx)))';

After executing this query access table

SELECT * FROM tablename@dblink_passport;

You can perform any operation DML, DDL, DQL

What Makes a Method Thread-safe? What are the rules?

If a method (instance or static) only references variables scoped within that method then it is thread safe because each thread has its own stack:

In this instance, multiple threads could call ThreadSafeMethod concurrently without issue.

public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number; // each thread will have its own variable for number.
        number = parameter1.Length;
        return number;
    }
}

This is also true if the method calls other class method which only reference locally scoped variables:

public class Thing
{
    public int ThreadSafeMethod(string parameter1)
    {
        int number;
        number = this.GetLength(parameter1);
        return number;
    }

    private int GetLength(string value)
    {
        int length = value.Length;
        return length;
    }
}

If a method accesses any (object state) properties or fields (instance or static) then you need to use locks to ensure that the values are not modified by a different thread.

public class Thing
{
    private string someValue; // all threads will read and write to this same field value

    public int NonThreadSafeMethod(string parameter1)
    {
        this.someValue = parameter1;

        int number;

        // Since access to someValue is not synchronised by the class, a separate thread
        // could have changed its value between this thread setting its value at the start 
        // of the method and this line reading its value.
        number = this.someValue.Length;
        return number;
    }
}

You should be aware that any parameters passed in to the method which are not either a struct or immutable could be mutated by another thread outside the scope of the method.

To ensure proper concurrency you need to use locking.

for further information see lock statement C# reference and ReadWriterLockSlim.

lock is mostly useful for providing one at a time functionality,
ReadWriterLockSlim is useful if you need multiple readers and single writers.

Android Support Design TabLayout: Gravity Center and Mode Scrollable

 <android.support.design.widget.TabLayout
                    android:id="@+id/tabList"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    app:tabMode="scrollable"/>

Serializing class instance to JSON

This can be easily handled with pydantic, as it already has this functionality built-in.

Option 1: normal way

from pydantic import BaseModel

class testclass(BaseModel):
    value1: str = "a"
    value2: str = "b"

test = testclass()

>>> print(test.json(indent=4))
{
    "value1": "a",
    "value2": "b"
}

Option 2: using pydantic's dataclass

import json
from pydantic.dataclasses import dataclass
from pydantic.json import pydantic_encoder

@dataclass
class testclass:
    value1: str = "a"
    value2: str = "b"

test = testclass()
>>> print(json.dumps(test, indent=4, default=pydantic_encoder))
{
    "value1": "a",
    "value2": "b"
}

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

How to get label of select option with jQuery?

Try this:

$('select option:selected').prop('label');

This will pull out the displayed text for both styles of <option> elements:

  • <option label="foo"><option> -> "foo"
  • <option>bar<option> -> "bar"

If it has both a label attribute and text inside the element, it'll use the label attribute, which is the same behavior as the browser.

For posterity, this was tested under jQuery 3.1.1

How do I get the localhost name in PowerShell?

Long form:

get-content env:computername

Short form:

gc env:computername

Python SQL query string formatting

sql = ("select field1, field2, field3, field4 "
       "from table "
       "where condition1={} "
       "and condition2={}").format(1, 2)

Output: 'select field1, field2, field3, field4 from table 
         where condition1=1 and condition2=2'

if the value of condition should be a string, you can do like this:

sql = ("select field1, field2, field3, field4 "
       "from table "
       "where condition1='{0}' "
       "and condition2='{1}'").format('2016-10-12', '2017-10-12')

Output: "select field1, field2, field3, field4 from table where
         condition1='2016-10-12' and condition2='2017-10-12'"

How to remove carriage returns and new lines in Postgresql?

In the case you need to remove line breaks from the begin or end of the string, you may use this:

UPDATE table 
SET field = regexp_replace(field, E'(^[\\n\\r]+)|([\\n\\r]+$)', '', 'g' );

Have in mind that the hat ^ means the begin of the string and the dollar sign $ means the end of the string.

Hope it help someone.

++i or i++ in for loops ??

For integers, there is no difference between pre- and post-increment.

If i is an object of a non-trivial class, then ++i is generally preferred, because the object is modified and then evaluated, whereas i++ modifies after evaluation, so requires a copy to be made.

How to specify different Debug/Release output directories in QMake .pro file

This is my Makefile for different debug/release output directories. This Makefile was tested successfully on Ubuntu linux. It should work seamlessly on Windows provided that Mingw-w64 is installed correctly.

ifeq ($(OS),Windows_NT)
    ObjExt=obj
    mkdir_CMD=mkdir
    rm_CMD=rmdir /S /Q
else
    ObjExt=o
    mkdir_CMD=mkdir -p
    rm_CMD=rm -rf
endif

CC     =gcc
CFLAGS =-Wall -ansi
LD     =gcc

OutRootDir=.
DebugDir  =Debug
ReleaseDir=Release


INSTDIR =./bin
INCLUDE =.

SrcFiles=$(wildcard *.c)
EXEC_main=myapp

OBJ_C_Debug   =$(patsubst %.c,  $(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SrcFiles))
OBJ_C_Release =$(patsubst %.c,  $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SrcFiles))

.PHONY: Release Debug cleanDebug cleanRelease clean

# Target specific variables
release: CFLAGS += -O -DNDEBUG
debug:   CFLAGS += -g

################################################
#Callable Targets
release: $(OutRootDir)/$(ReleaseDir)/$(EXEC_main)
debug:   $(OutRootDir)/$(DebugDir)/$(EXEC_main)

cleanDebug:
    -$(rm_CMD) "$(OutRootDir)/$(DebugDir)"
    @echo cleanDebug done

cleanRelease:
    -$(rm_CMD) "$(OutRootDir)/$(ReleaseDir)"
    @echo cleanRelease done

clean: cleanDebug cleanRelease
################################################

# Pattern Rules
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(ReleaseDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

$(OutRootDir)/$(DebugDir)/%.$(ObjExt):   %.c | $(OutRootDir)/$(DebugDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

# Create output directory
$(OutRootDir)/$(ReleaseDir) $(OutRootDir)/$(DebugDir) $(INSTDIR):
    -$(mkdir_CMD) $@

# Create the executable
# Multiple targets [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main): $(OBJ_C_Release)
$(OutRootDir)/$(DebugDir)/$(EXEC_main):   $(OBJ_C_Debug)
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main) $(OutRootDir)/$(DebugDir)/$(EXEC_main):
    $(LD) $^ -o$@

how to prevent "directory already exists error" in a makefile when using mkdir

It works under mingw32/msys/cygwin/linux

ifeq "$(wildcard .dep)" ""
-include $(shell mkdir .dep) $(wildcard .dep/*)
endif

MySQL load NULL values from CSV data

Converted the input file to include \N for the blank column data using the below sed command in UNix terminal:

sed -i 's/,,/,\\N,/g' $file_name

and then use LOAD DATA INFILE command to load to mysql

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

Changing Font Size For UITableView Section Headers

Swift 2:

As OP asked, only adjust the size, not setting it as a system bold font or whatever:

func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if let headerView = view as? UITableViewHeaderFooterView, textLabel = headerView.textLabel {

            let newSize = CGFloat(16)
            let fontName = textLabel.font.fontName
            textLabel.font = UIFont(name: fontName, size: newSize)
        }
    }

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

Sometime gcc had created as /usr/bin/gcc32. so please create a ln -s /usr/bin/gcc32 /usr/bin/gcc and then compile that ./configure.

Get the closest number out of an array

Another variant here we have circular range connecting head to toe and accepts only min value to given input. This had helped me get char code values for one of the encryption algorithm.

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

How to get Domain name from URL using jquery..?

You can do this with plain js by using

  1. location.host , same as document.location.hostname
  2. document.domain Not recommended

Connecting to remote URL which requires authentication using Java

You can also use the following, which does not require using external packages:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

Change SVN repository URL

If U want commit to a new empty Repo ,You can checkout the new empty Repo and commit to new remote repo.
chekout a new empty Repo won't delete your local files.
try this: for example, remote repo url : https://example.com/SVNTest cd [YOUR PROJECT PATH] rm -rf .svn svn co https://example.com/SVNTest ../[YOUR PROJECT DIR NAME] svn add ./* svn ci -m"changed repo url"

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

What is the difference between __dirname and ./ in node.js?

./ refers to the current working directory, except in the require() function. When using require(), it translates ./ to the directory of the current file called. __dirname is always the directory of the current file.

For example, with the following file structure

/home/user/dir/files/config.json

{
  "hello": "world"
}

/home/user/dir/files/somefile.txt

text file

/home/user/dir/dir.js

var fs = require('fs');

console.log(require('./files/config.json'));
console.log(fs.readFileSync('./files/somefile.txt', 'utf8'));

If I cd into /home/user/dir and run node dir.js I will get

{ hello: 'world' }
text file

But when I run the same script from /home/user/ I get

{ hello: 'world' }

Error: ENOENT, no such file or directory './files/somefile.txt'
    at Object.openSync (fs.js:228:18)
    at Object.readFileSync (fs.js:119:15)
    at Object.<anonymous> (/home/user/dir/dir.js:4:16)
    at Module._compile (module.js:432:26)
    at Object..js (module.js:450:10)
    at Module.load (module.js:351:31)
    at Function._load (module.js:310:12)
    at Array.0 (module.js:470:10)
    at EventEmitter._tickCallback (node.js:192:40)

Using ./ worked with require but not for fs.readFileSync. That's because for fs.readFileSync, ./ translates into the cwd (in this case /home/user/). And /home/user/files/somefile.txt does not exist.

Best way to handle list.index(might-not-exist) in python?

The dict type has a get function, where if the key doesn't exist in the dictionary, the 2nd argument to get is the value that it should return. Similarly there is setdefault, which returns the value in the dict if the key exists, otherwise it sets the value according to your default parameter and then returns your default parameter.

You could extend the list type to have a getindexdefault method.

class SuperDuperList(list):
    def getindexdefault(self, elem, default):
        try:
            thing_index = self.index(elem)
            return thing_index
        except ValueError:
            return default

Which could then be used like:

mylist = SuperDuperList([0,1,2])
index = mylist.getindexdefault( 'asdf', -1 )

Delete last commit in bitbucket

you can reset to HEAD^ then force push it.

git reset HEAD^
git push -u origin master --force

It will delete your last commit and will reflect on bitbucket as commit deleted but will still remain on their server.

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

(As of 2018, I would advise trying out JupyterHub/JupyterLab. It uses the full width of the monitor. If this is not an option, maybe since you are using one of the cloud-based Jupyter-as-a-service providers, keep reading)

(Stylish is accused of stealing user data, I have moved on to using Stylus plugin instead)

I recommend using Stylish Browser Plugin. This way you can override css for all notebooks, without adding any code to notebooks. We don't like to change configuration in .ipython/profile_default, since we are running a shared Jupyter server for the whole team and width is a user preference.

I made a style specifically for vertically-oriented high-res screens, that makes cells wider and adds a bit of empty-space in the bottom, so you can position the last cell in the centre of the screen. https://userstyles.org/styles/131230/jupyter-wide You can, of course, modify my css to your liking, if you have a different layout, or you don't want extra empty-space in the end.

Last but not least, Stylish is a great tool to have in your toolset, since you can easily customise other sites/tools to your liking (e.g. Jira, Podio, Slack, etc.)

@media (min-width: 1140px) {
  .container {
    width: 1130px;
  }
}

.end_space {
  height: 800px;
}

How to preview an image before and after upload?

                    #######################
                    ###  the img page   ###
                    #######################


<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#f').live('change' ,function(){
            $('#fo').ajaxForm({target: '#d'}).submit();
        });
    });
</script>
<form id="fo" name="fo" action="nextimg.php" enctype="multipart/form-data" method="post">
    <input type="file" name="f" id="f" value="start upload" />
    <input type="submit" name="sub" value="upload" />
</form>
<div id="d"></div>


                    #############################
                    ###    the nextimg page   ###
                    #############################


<?php
     $name=$_FILES['f']['name'];
     $tmp=$_FILES['f']['tmp_name'];
     $new=time().$name;
     $new="upload/".$new;
     move_uploaded_file($tmp,$new);
     if($_FILES['f']['error']==0)
     {
?>
     <h1>PREVIEW</h1><br /><img src="<?php echo $new;?>" width="100" height="100" />
<?php
     }
?>

How do I restart a service on a remote machine in Windows?

Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).

Parse JSON in C#

Your data class doesn't match the JSON object. Use this instead:

[DataContract]
public class GoogleSearchResults
{
    [DataMember]
    public ResponseData responseData { get; set; }
}

[DataContract]
public class ResponseData
{
    [DataMember]
    public IEnumerable<Results> results { get; set; }
}

[DataContract]
public class Results
{
    [DataMember]
    public string unescapedUrl { get; set; }

    [DataMember]
    public string url { get; set; }

    [DataMember]
    public string visibleUrl { get; set; }

    [DataMember]
    public string cacheUrl { get; set; }

    [DataMember]
    public string title { get; set; }

    [DataMember]
    public string titleNoFormatting { get; set; }

    [DataMember]
    public string content { get; set; }
}

Also, you don't have to instantiate the class to get its type for deserialization:

public static T Deserialise<T>(string json)
{
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {
        var serialiser = new DataContractJsonSerializer(typeof(T));
        return (T)serialiser.ReadObject(ms);
    }
}

How do I move a file from one location to another in Java?

Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));

System.currentTimeMillis() vs. new Date() vs. Calendar.getInstance().getTime()

If you're USING a date then I strongly advise that you use jodatime, http://joda-time.sourceforge.net/. Using System.currentTimeMillis() for fields that are dates sounds like a very bad idea because you'll end up with a lot of useless code.

Both date and calendar are seriously borked, and Calendar is definitely the worst performer of them all.

I'd advise you to use System.currentTimeMillis() when you are actually operating with milliseconds, for instance like this

 long start = System.currentTimeMillis();
    .... do something ...
 long elapsed = System.currentTimeMillis() -start;

How to avoid reverse engineering of an APK file?

The main question here is that can the dex files be decompiled and the answer is they can be "sort of". There are disassemblers like dedexer and smali.

ProGuard, properly configured, will obfuscate your code. DexGuard which is a commercial extended version of ProGuard, may help a bit more. However, your code can still be converted into smali and developers with reverse-engineering experience will be able to figure out what you are doing from the smali.

Maybe choose a good license and enforce it by the law in best possible way.

Python: Get HTTP headers from urllib2.urlopen call?

Use the response.info() method to get the headers.

From the urllib2 docs:

urllib2.urlopen(url[, data][, timeout])

...

This function returns a file-like object with two additional methods:

  • geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
  • info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)

So, for your example, try stepping through the result of response.info().headers for what you're looking for.

Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.

Arduino COM port doesn't work

Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.

Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".

In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.

Step1: recognize the Arduino device unplug your Arduino and list /dev files:

#ls -l /dev

plug your Arduino and go and list /dev files

#ls -l /dev

Find the new file (device) that was not before plugging, for example:

ttyACM0 or ttyUSB1

Read this properties:

ls -l /dev/ttyACM0

crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0

the first c mean that Arduino is a character device.

user owner: root

group owner: dialout

mayor number: 166

minor number: 0

Step2: set your user as group owner.

If you do:

groups <yourUser>

And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:

usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>

restart the pc, and set /dev/<yourDeviceFile> as your serial port before upload.

How to get selected value from Dropdown list in JavaScript

I would say change var sv = sel.options[sel.selectedIndex].value; to var sv = sel.options[sel.selectedIndex].text;

It worked for me. Directing you to where I found my solution Getting the selected value dropdown jstl

Useful example of a shutdown hook in Java?

You could do the following:

  • Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false
  • (Optionally, .interrupt the working threads if they wait for data in some blocking call)
  • Wait for the working threads (executing writeBatch in your case) to finish, by calling the Thread.join() method on the working threads.
  • Terminate the program

Some sketchy code:

  • Add a static volatile boolean keepRunning = true;
  • In run() you change to

    for (int i = 0; i < N && keepRunning; ++i)
        writeBatch(pw, i);
    
  • In main() you add:

    final Thread mainThread = Thread.currentThread();
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            keepRunning = false;
            mainThread.join();
        }
    });
    

That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.


From the docs:

When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.

That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the run()-method.

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

KeyedCollection works like dictionary and is serializable.

First create a class containing key and value:

/// <summary>
/// simple class
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCulture
{
    /// <summary>
    /// culture
    /// </summary>
    public string culture;

    /// <summary>
    /// word list
    /// </summary>
    public List<string> list;

    /// <summary>
    /// status
    /// </summary>
    public string status;
}

then create a class of type KeyedCollection, and define a property of your class as key.

/// <summary>
/// keyed collection.
/// </summary>
/// <remarks></remarks>
[Serializable()]
public class cCultures : System.Collections.ObjectModel.KeyedCollection<string, cCulture>
{
    protected override string GetKeyForItem(cCulture item)
    {
        return item.culture;
    }
}

Usefull to serialize such type of datas.

Remove a modified file from pull request

You would want to amend the commit and then do a force push which will update the branch with the PR.

Here's how I recommend you do this:

  1. Close the PR so that whomever is reviewing it doesn't pull it in until you've made your changes.
  2. Do a Soft reset to the commit before your unwanted change (if this is the last commit you can use git reset --soft HEAD^ or if it's a different commit, you would want to replace 'HEAD^' with the commit id)
  3. Discard (or undo) any changes to the file that you didn't intend to update
  4. Make a new commit git commit -a -c ORIG_HEAD
  5. Force Push to your branch
  6. Re-Open Pull Request

The now that your branch has been updated, the Pull Request will include your changes.

Here's a link to Gits documentation where they have a pretty good example under Undo a commit and redo.

What is the difference between rb and r+b modes in file objects

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Source: Reading and Writing Files

How do I select a random value from an enumeration?

Adapted as a Random class extension:

public static class RandomExtensions
{   
    public static T NextEnum<T>(this Random random)
    {
        var values = Enum.GetValues(typeof(T));
        return (T)values.GetValue(random.Next(values.Length));
    }
}

Example of usage:

var random = new Random();
var myEnumRandom = random.NextEnum<MyEnum>();

Print Html template in Angular 2 (ng-print in Angular 2)

EDIT: updated the snippets for a more generic approach

Just as an extension to the accepted answer,

For getting the existing styles to preserve the look 'n feel of the targeted component, you can:

  1. make a query to pull the <style> and <link> elements from the top-level document

  2. inject it into the HTML string.

To grab a HTML tag:

private getTagsHtml(tagName: keyof HTMLElementTagNameMap): string
{
    const htmlStr: string[] = [];
    const elements = document.getElementsByTagName(tagName);
    for (let idx = 0; idx < elements.length; idx++)
    {
        htmlStr.push(elements[idx].outerHTML);
    }

    return htmlStr.join('\r\n');
}

Then in the existing snippet:

const printContents = document.getElementById('print-section').innerHTML;
const stylesHtml = this.getTagsHtml('style');
const linksHtml = this.getTagsHtml('link');

const popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
popupWin.document.open();
popupWin.document.write(`
    <html>
        <head>
            <title>Print tab</title>
            ${linksHtml}
            ${stylesHtml}
            ^^^^^^^^^^^^^ add them as usual to the head
        </head>
        <body onload="window.print(); window.close()">
            ${printContents}
        </body>
    </html>
    `
);
popupWin.document.close();

Now using existing styles (Angular components create a minted style for itself), as well as existing style frameworks (e.g. Bootstrap, MaterialDesign, Bulma) it should look like a snippet of the existing screen

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

What is the minimum I have to do to create an RPM file?

If make config works for your program or you have a shell script which copies your two files to the appropriate place you can use checkinstall. Just go to the directory where your makefile is in and call it with the parameter -R (for RPM) and optionally with the installation script.

Are lists thread-safe?

To clarify a point in Thomas' excellent answer, it should be mentioned that append() is thread safe.

This is because there is no concern that data being read will be in the same place once we go to write to it. The append() operation does not read data, it only writes data to the list.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Probably not helpful, but if the array is the only thing that you'll be displaying, you could always set

header('Content-type: text/plain');

Remove part of string in Java

Use String.Replace():

http://www.daniweb.com/software-development/java/threads/73139

Example:

String original = "manchester united (with nice players)";
String newString = original.replace(" (with nice players)","");

Is it possible to hide the cursor in a webpage using CSS or Javascript?

Pointer Lock API

While the cursor: none CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.

You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove events to that element (which you may or may not handle):

document.body.requestPointerLock();

To release the lock, you can use exitPointerLock:

document.exitPointerLock();

Additional notes

No cursor, for real

This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock or pressing ESC in some browsers).

That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.

Restrictions

As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:

document.addEventListener("click", function () {
    document.body.requestPointerLock();
});

Also, requestPointerLock won't work from a sandboxed iframe unless the allow-pointer-lock permission is set.

User-notifications

Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange event on the element on which requestPointerLock was called:

document.body.addEventListener("pointerlockchange", function () {
    if (document.pointerLockElement === document.body) {
        // Pointer is now locked to <body>.
    }
});

Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.

Listening to raw mouse movement

The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock was called on. This can be listened to simply by using the mousemove event, then accessing the movementX and movementY properties on the event object:

document.body.addEventListener("mousemove", function (e) {
    console.log("Moved by " + e.movementX + ", " + e.movementY);
});

What is recursion and when should I use it?

I have created a recursive function to concatenate a list of strings with a separator between them. I use it mostly to create SQL expressions, by passing a list of fields as the 'items' and a 'comma+space' as the separator. Here's the function (It uses some Borland Builder native data types, but can be adapted to fit any other environment):

String ArrangeString(TStringList* items, int position, String separator)
{
  String result;

  result = items->Strings[position];

  if (position <= items->Count)
    result += separator + ArrangeString(items, position + 1, separator);

  return result;
}

I call it this way:

String columnsList;
columnsList = ArrangeString(columns, 0, ", ");

Imagine you have an array named 'fields' with this data inside it: 'albumName', 'releaseDate', 'labelId'. Then you call the function:

ArrangeString(fields, 0, ", ");

As the function starts to work, the variable 'result' receives the value of the position 0 of the array, which is 'albumName'.

Then it checks if the position it's dealing with is the last one. As it isn't, then it concatenates the result with the separator and the result of a function, which, oh God, is this same function. But this time, check it out, it call itself adding 1 to the position.

ArrangeString(fields, 1, ", ");

It keeps repeating, creating a LIFO pile, until it reaches a point where the position being dealt with IS the last one, so the function returns only the item on that position on the list, not concatenating anymore. Then the pile is concatenated backwards.

Got it? If you don't, I have another way to explain it. :o)

How do you append to a file?

If multiple processes are writing to the file, you must use append mode or the data will be scrambled. Append mode will make the operating system put every write, at the end of the file irrespective of where the writer thinks his position in the file is. This is a common issue for multi-process services like nginx or apache where multiple instances of the same process, are writing to the same log file. Consider what happens if you try to seek, then write:

Example does not work well with multiple processes: 

f = open("logfile", "w"); f.seek(0, os.SEEK_END); f.write("data to write");

writer1: seek to end of file.           position 1000 (for example)
writer2: seek to end of file.           position 1000
writer2: write data at position 1000    end of file is now 1000 + length of data.
writer1: write data at position 1000    writer1's data overwrites writer2's data.

By using append mode, the operating system will place any write at the end of the file.

f = open("logfile", "a"); f.seek(0, os.SEEK_END); f.write("data to write");

Append most does not mean, "open file, go to end of the file once after opening it". It means, "open file, every write I do will be at the end of the file".

WARNING: For this to work you must write all your record in one shot, in one write call. If you split the data between multiple writes, other writers can and will get their writes in between yours and mangle your data.

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

Can I store images in MySQL

You'll need to save as a blob, LONGBLOB datatype in mysql will work.

Ex:

CREATE TABLE 'test'.'pic' (
    'idpic' INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
    'caption' VARCHAR(45) NOT NULL,
    'img' LONGBLOB NOT NULL,
  PRIMARY KEY ('idpic')
)

As others have said, its a bad practice but it can be done. Not sure if this code would scale well, though.

Regular expression to stop at first match

Because you are using quantified subpattern and as descried in Perl Doc,

By default, a quantified subpattern is "greedy", that is, it will match as many times as possible (given a particular starting location) while still allowing the rest of the pattern to match. If you want it to match the minimum number of times possible, follow the quantifier with a "?" . Note that the meanings don't change, just the "greediness":

*?        //Match 0 or more times, not greedily (minimum matches)
+?        //Match 1 or more times, not greedily

Thus, to allow your quantified pattern to make minimum match, follow it by ? :

/location="(.*?)"/

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

C#: how to get first char of a string?

Or you can do this:

MyString[0];

What is the difference between ndarray and array in numpy?

I think with np.array() you can only create C like though you mention the order, when you check using np.isfortran() it says false. but with np.ndarrray() when you specify the order it creates based on the order provided.

How to compare binary files to check if they are the same?

You can use MD5 hash function to check if two files are the same, with this you can not see the differences in a low level, but is a quick way to compare two files.

md5 <filename1>
md5 <filename2>

If both MD5 hashes (the command output) are the same, then, the two files are not different.

See changes to a specific file using git

You can execute

git status -s

This will show modified files name and then by copying the interested file path you can see changes using git diff

git diff <filepath + filename>

How to check if a Java 8 Stream is empty?

The other answers and comments are correct in that to examine the contents of a stream, one must add a terminal operation, thereby "consuming" the stream. However, one can do this and turn the result back into a stream, without buffering up the entire contents of the stream. Here are a couple examples:

static <T> Stream<T> throwIfEmpty(Stream<T> stream) {
    Iterator<T> iterator = stream.iterator();
    if (iterator.hasNext()) {
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
    } else {
        throw new NoSuchElementException("empty stream");
    }
}

static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Supplier<T> supplier) {
    Iterator<T> iterator = stream.iterator();
    if (iterator.hasNext()) {
        return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
    } else {
        return Stream.of(supplier.get());
    }
}

Basically turn the stream into an Iterator in order to call hasNext() on it, and if true, turn the Iterator back into a Stream. This is inefficient in that all subsequent operations on the stream will go through the Iterator's hasNext() and next() methods, which also implies that the stream is effectively processed sequentially (even if it's later turned parallel). However, this does allow you to test the stream without buffering up all of its elements.

There is probably a way to do this using a Spliterator instead of an Iterator. This potentially allows the returned stream to have the same characteristics as the input stream, including running in parallel.

Callback functions in C++

Boost's signals2 allows you to subscribe generic member functions (without templates!) and in a threadsafe way.

Example: Document-View Signals can be used to implement flexible Document-View architectures. The document will contain a signal to which each of the views can connect. The following Document class defines a simple text document that supports mulitple views. Note that it stores a single signal to which all of the views will be connected.

class Document
{
public:
    typedef boost::signals2::signal<void ()>  signal_t;

public:
    Document()
    {}

    /* Connect a slot to the signal which will be emitted whenever
      text is appended to the document. */
    boost::signals2::connection connect(const signal_t::slot_type &subscriber)
    {
        return m_sig.connect(subscriber);
    }

    void append(const char* s)
    {
        m_text += s;
        m_sig();
    }

    const std::string& getText() const
    {
        return m_text;
    }

private:
    signal_t    m_sig;
    std::string m_text;
};

Next, we can begin to define views. The following TextView class provides a simple view of the document text.

class TextView
{
public:
    TextView(Document& doc): m_document(doc)
    {
        m_connection = m_document.connect(boost::bind(&TextView::refresh, this));
    }

    ~TextView()
    {
        m_connection.disconnect();
    }

    void refresh() const
    {
        std::cout << "TextView: " << m_document.getText() << std::endl;
    }
private:
    Document&               m_document;
    boost::signals2::connection  m_connection;
};

What does the "More Columns than Column Names" error mean?

you have have strange characters in your heading # % -- or ,

Reset the Value of a Select Box

The easiest method without using javaScript is to put all your <select> dropdown inside a <form> tag and use form reset button. Example:

<form>
  <select>
    <option>one</option>
    <option>two</option>
    <option selected>three</option>
  </select>
  <input type="reset" value="Reset" />
</form>

Or, using JavaScript, it can be done in following way:

HTML Code:

<select>
  <option selected>one</option>
  <option>two</option>
  <option>three</option>
</select>
<button id="revert">Reset</button>

And JavaScript code:

const button = document.getElementById("revert");
const options = document.querySelectorAll('select option');
button.onclick = () => {
  for (var i = 0; i < options.length; i++) {
    options[i].selected = options[i].defaultSelected;
  }
}

Both of these methods will work if you have multiple selected items or single selected item.

HTTP Error 503. The service is unavailable. App pool stops on accessing website

One possible reason this might happen is that you don't have enough disk space in your server machine. You can find more information in event viewer. if such thing happen, just stop the IIS, clean some free disk space and restart the IIS and then start the App Poll. enter image description here

Adding an onclick event to a table row

selectRowToInput();
function selectRowToInput(){
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
    var currentRow = table.rows[i];
    currentRow.onclick = function() {

       rows=this.rowIndex;
        console.log(rows);  
    };
}

}

position fixed header in html

Your #container should be outside of the #header-wrap, then specify a fixed height for #header-wrap, after, specify margin-top for #container equal to the #header-wrap's height. Something like this:

#header-wrap {
    position: fixed;
    height: 200px;
    top: 0;
    width: 100%;
    z-index: 100;
}
#container{ 
    margin-top: 200px;
}

Hope this is what you need: http://jsfiddle.net/KTgrS/

what is the difference between XSD and WSDL

XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.

UnicodeEncodeError: 'charmap' codec can't encode characters

For those still getting this error, adding encode("utf-8") to soup will also fix this.

soup = BeautifulSoup(html_doc, 'html.parser').encode("utf-8")
print(soup)

Google access token expiration time

Have a look at: https://developers.google.com/accounts/docs/OAuth2UserAgent#handlingtheresponse

It says:

Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds...

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

How to get a file or blob from an object URL?

Modern solution:

let blob = await fetch(url).then(r => r.blob());

The url can be an object url or a normal url.

What is getattr() exactly and how do I use it?

I think this example is self explanatory. It runs the method of first parameter, whose name is given in the second parameter.

class MyClass:
   def __init__(self):
      pass
   def MyMethod(self):
      print("Method ran")

# Create an object
object = MyClass()
# Get all the methods of a class
method_list = [func for func in dir(MyClass) if callable(getattr(MyClass, func))]
# You can use any of the methods in method_list
# "MyMethod" is the one we want to use right now

# This is the same as running "object.MyMethod()"
getattr(object,'MyMethod')()

Android Studio: Application Installation Failed

For me it only started working after I rebooted device (Motorola-Nexus-6).

(I also tried to clean, disable "instant run", reopen Android Studio, verified installed applications to be sure there are no clashes, disable and reenable Debug mode in phone, reconnect USB cable)

SELECT INTO using Oracle

If NEW_TABLE already exists then ...

insert into new_table 
select * from old_table
/

If you want to create NEW_TABLE based on the records in OLD_TABLE ...

create table new_table as 
select * from old_table
/

If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:

create table new_table as 
select * from old_table
where 1 = 2
/

Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).

When is a C++ destructor called?

Others have already addressed the other issues, so I'll just look at one point: do you ever want to manually delete an object.

The answer is yes. @DavidSchwartz gave one example, but it's a fairly unusual one. I'll give an example that's under the hood of what a lot of C++ programmers use all the time: std::vector (and std::deque, though it's not used quite as much).

As most people know, std::vector will allocate a larger block of memory when/if you add more items than its current allocation can hold. When it does this, however, it has a block of memory that's capable of holding more objects than are currently in the vector.

To manage that, what vector does under the covers is allocate raw memory via the Allocator object (which, unless you specify otherwise, means it uses ::operator new). Then, when you use (for example) push_back to add an item to the vector, internally the vector uses a placement new to create an item in the (previously) unused part of its memory space.

Now, what happens when/if you erase an item from the vector? It can't just use delete -- that would release its entire block of memory; it needs to destroy one object in that memory without destroying any others, or releasing any of the block of memory it controls (for example, if you erase 5 items from a vector, then immediately push_back 5 more items, it's guaranteed that the vector will not reallocate memory when you do so.

To do that, the vector directly destroys the objects in the memory by explicitly calling the destructor, not by using delete.

If, perchance, somebody else were to write a container using contiguous storage roughly like a vector does (or some variant of that, like std::deque really does), you'd almost certainly want to use the same technique.

Just for example, let's consider how you might write code for a circular ring-buffer.

#ifndef CBUFFER_H_INC
#define CBUFFER_H_INC

template <class T>
class circular_buffer {
    T *data;
    unsigned read_pos;
    unsigned write_pos;
    unsigned in_use;
    const unsigned capacity;
public:
    circular_buffer(unsigned size) :
        data((T *)operator new(size * sizeof(T))),
        read_pos(0),
        write_pos(0),
        in_use(0),
        capacity(size)
    {}

    void push(T const &t) {
        // ensure there's room in buffer:
        if (in_use == capacity) 
            pop();

        // construct copy of object in-place into buffer
        new(&data[write_pos++]) T(t);
        // keep pointer in bounds.
        write_pos %= capacity;
        ++in_use;
    }

    // return oldest object in queue:
    T front() {
        return data[read_pos];
    }

    // remove oldest object from queue:
    void pop() { 
        // destroy the object:
        data[read_pos++].~T();

        // keep pointer in bounds.
        read_pos %= capacity;
        --in_use;
    }
  
~circular_buffer() {
    // first destroy any content
    while (in_use != 0)
        pop();

    // then release the buffer.
    operator delete(data); 
}

};

#endif

Unlike the standard containers, this uses operator new and operator delete directly. For real use, you probably do want to use an allocator class, but for the moment it would do more to distract than contribute (IMO, anyway).

RSA Public Key format

You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ---- to -----BEGIN RSA PUBLIC KEY----- and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).

This article has a good explanation about both formats.

What you get in an RSA PUBLIC KEY is closer to the content of a PUBLIC KEY, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse and -strparse 19, as described in this answer.

EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER:

    0:d=0  hl=4 l= 266 cons: SEQUENCE          
    4:d=1  hl=4 l= 257 prim: INTEGER           :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
  265:d=1  hl=2 l=   3 prim: INTEGER           :010001

To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:

   The "ssh-rsa" key format has the following specific encoding:

      string    "ssh-rsa"
      mpint     e
      mpint     n

For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61. The first four bytes (00 00 00 07) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61=ssh-rsa, followed by the exponent of length 1 (00 00 00 01 25) and the modulus of length 256 (00 00 01 00 7f ...).

How to kill a process in MacOS?

I have experienced that if kill -9 PID doesn't work and you own the process, you can use kill -s kill PID which is kind of surprising as the man page says you can kill -signal_number PID.

OrderBy pipe issue

Recommend u use lodash with angular, then your pipe will be next:

import {Pipe, PipeTransform} from '@angular/core';
import * as _ from 'lodash'
@Pipe({
    name: 'orderBy'
})
export class OrderByPipe implements PipeTransform {

    transform(array: Array<any>, args?: any): any {
        return _.sortBy(array, [args]);
    }

}

and use it in html like

*ngFor = "#todo of todos | orderBy:'completed'"

and don't forget add Pipe to your module

@NgModule({
    ...,
    declarations: [OrderByPipe, ...],
    ...
})

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

This is a very confusing topic. django stores all applied migrations in a table called django_migrations. perform this sql ( i am using postgres . so in query tool section)

select * from django_migrations where app='your appname'  (app in which u have issue with).

This will list all applied migrations for that app.
Go to your app/migration folder and check all migrations . find the migration file associated with your error . file where your table was created or column added or modified.
look for the id of this migration file in django_migrations table( select * from django_migrations where app='your app') .

Then do :

delete from django_migrations where id='id of your migration';

delete multiple id's if you have multiple migrations file associated with your issue.

now reapply migrate

Python manage.py migrate yourappname

second option

  1. Drop tables in your app where you have issue.

  2. delete all migrations for that app from app/migrations folder.(don't delete init.py from that folder).

  3. now run

    python manage.py makemigrations appname

  4. now run

python manage.py migrate appname

How do I select elements of an array given condition?

Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:

For satisfying multiple (all) conditions:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

For satisfying multiple (or) conditions:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

How to wait until an element exists?

For a simple approach using jQuery I've found this to work well:

  // Wait for element to exist.
  function elementLoaded(el, cb) {
    if ($(el).length) {
      // Element is now loaded.
      cb($(el));
    } else {
      // Repeat every 500ms.
      setTimeout(function() {
        elementLoaded(el, cb)
      }, 500);
    }
  };

  elementLoaded('.element-selector', function(el) {
    // Element is ready to use.
    el.click(function() {
      alert("You just clicked a dynamically inserted element");
    });
  });

Here we simply check every 500ms to see whether the element is loaded, when it is, we can use it.

This is especially useful for adding click handlers to elements which have been dynamically added to the document.

Align HTML input fields by :

I know that this approach has been taken before, But I believe that using tables, the layout can be generated easily, Though this may not be the best practice.

JSFiddle

HTML

<table>

    <tr><td>Name:</td><td><input type="text"/></td></tr>

    <tr><td>Age:</td><td><input type="text"/></td></tr>

</table>

<!--You can add the fields as you want-->

CSS

td{
    text-align:right;
}

How do I change the title of the "back" button on a Navigation Bar

in Xcode 4.5 using storyboard, by far the easiest solution i've found when the value of the Back button doesn't have to change dynamically is to use the "Back Button" field associated with the Navigation Item of the View Controller to which you want the "Back" button to say something else.

e.g. in the screenshot below, i want the Back button for the view controller(s) that i push to have "Back" as the title of the Back button.

enter image description here

of course, this won't work if you need the back button to say something slightly different each time … there are all of the other solutions here for that.

Reference member variables as class members

Is there a name to describe this idiom?

In UML it is called aggregation. It differs from composition in that the member object is not owned by the referring class. In C++ you can implement aggregation in two different ways, through references or pointers.

I am assuming it is to prevent the possibly large overhead of copying a big complex object?

No, that would be a really bad reason to use this. The main reason for aggregation is that the contained object is not owned by the containing object and thus their lifetimes are not bound. In particular the referenced object lifetime must outlive the referring one. It might have been created much earlier and might live beyond the end of the lifetime of the container. Besides that, the state of the referenced object is not controlled by the class, but can change externally. If the reference is not const, then the class can change the state of an object that lives outside of it.

Is this generally good practice? Are there any pitfalls to this approach?

It is a design tool. In some cases it will be a good idea, in some it won't. The most common pitfall is that the lifetime of the object holding the reference must never exceed the lifetime of the referenced object. If the enclosing object uses the reference after the referenced object was destroyed, you will have undefined behavior. In general it is better to prefer composition to aggregation, but if you need it, it is as good a tool as any other.

What should a JSON service return on failure / error

I've spend some hours solving this problem. My solution is based on the following wishes/requirements:

  • Don't have repetitive boilerplate error handling code in all JSON controller actions.
  • Preserve HTTP (error) status codes. Why? Because higher level concerns should not affect lower level implementation.
  • Be able to get JSON data when an error/exception occur on the server. Why? Because I might want rich error information. E.g. error message, domain specific error status code, stack trace (in debug/development environment).
  • Ease of use client side - preferable using jQuery.

I create a HandleErrorAttribute (see code comments for explanation of the details). A few details including "usings" has been left out, so the code might not compile. I add the filter to the global filters during application initialization in Global.asax.cs like this:

GlobalFilters.Filters.Add(new UnikHandleErrorAttribute());

Attribute:

namespace Foo
{
  using System;
  using System.Diagnostics;
  using System.Linq;
  using System.Net;
  using System.Reflection;
  using System.Web;
  using System.Web.Mvc;

  /// <summary>
  /// Generel error handler attribute for Foo MVC solutions.
  /// It handles uncaught exceptions from controller actions.
  /// It outputs trace information.
  /// If custom errors are enabled then the following is performed:
  /// <ul>
  ///   <li>If the controller action return type is <see cref="JsonResult"/> then a <see cref="JsonResult"/> object with a <c>message</c> property is returned.
  ///       If the exception is of type <see cref="MySpecialExceptionWithUserMessage"/> it's message will be used as the <see cref="JsonResult"/> <c>message</c> property value.
  ///       Otherwise a localized resource text will be used.</li>
  /// </ul>
  /// Otherwise the exception will pass through unhandled.
  /// </summary>
  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
  public sealed class FooHandleErrorAttribute : HandleErrorAttribute
  {
    private readonly TraceSource _TraceSource;

    /// <summary>
    /// <paramref name="traceSource"/> must not be null.
    /// </summary>
    /// <param name="traceSource"></param>
    public FooHandleErrorAttribute(TraceSource traceSource)
    {
      if (traceSource == null)
        throw new ArgumentNullException(@"traceSource");
      _TraceSource = traceSource;
    }

    public TraceSource TraceSource
    {
      get
      {
        return _TraceSource;
      }
    }

    /// <summary>
    /// Ctor.
    /// </summary>
    public FooHandleErrorAttribute()
    {
      var className = typeof(FooHandleErrorAttribute).FullName ?? typeof(FooHandleErrorAttribute).Name;
      _TraceSource = new TraceSource(className);
    }

    public override void OnException(ExceptionContext filterContext)
    {
      var actionMethodInfo = GetControllerAction(filterContext.Exception);
      // It's probably an error if we cannot find a controller action. But, hey, what should we do about it here?
      if(actionMethodInfo == null) return;

      var controllerName = filterContext.Controller.GetType().FullName; // filterContext.RouteData.Values[@"controller"];
      var actionName = actionMethodInfo.Name; // filterContext.RouteData.Values[@"action"];

      // Log the exception to the trace source
      var traceMessage = string.Format(@"Unhandled exception from {0}.{1} handled in {2}. Exception: {3}", controllerName, actionName, typeof(FooHandleErrorAttribute).FullName, filterContext.Exception);
      _TraceSource.TraceEvent(TraceEventType.Error, TraceEventId.UnhandledException, traceMessage);

      // Don't modify result if custom errors not enabled
      //if (!filterContext.HttpContext.IsCustomErrorEnabled)
      //  return;

      // We only handle actions with return type of JsonResult - I don't use AjaxRequestExtensions.IsAjaxRequest() because ajax requests does NOT imply JSON result.
      // (The downside is that you cannot just specify the return type as ActionResult - however I don't consider this a bad thing)
      if (actionMethodInfo.ReturnType != typeof(JsonResult)) return;

      // Handle JsonResult action exception by creating a useful JSON object which can be used client side
      // Only provide error message if we have an MySpecialExceptionWithUserMessage.
      var jsonMessage = FooHandleErrorAttributeResources.Error_Occured;
      if (filterContext.Exception is MySpecialExceptionWithUserMessage) jsonMessage = filterContext.Exception.Message;
      filterContext.Result = new JsonResult
        {
          Data = new
            {
              message = jsonMessage,
              // Only include stacktrace information in development environment
              stacktrace = MyEnvironmentHelper.IsDebugging ? filterContext.Exception.StackTrace : null
            },
          // Allow JSON get requests because we are already using this approach. However, we should consider avoiding this habit.
          JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };

      // Exception is now (being) handled - set the HTTP error status code and prevent caching! Otherwise you'll get an HTTP 200 status code and running the risc of the browser caching the result.
      filterContext.ExceptionHandled = true;
      filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; // Consider using more error status codes depending on the type of exception
      filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

      // Call the overrided method
      base.OnException(filterContext);
    }

    /// <summary>
    /// Does anybody know a better way to obtain the controller action method info?
    /// See http://stackoverflow.com/questions/2770303/how-to-find-in-which-controller-action-an-error-occurred.
    /// </summary>
    /// <param name="exception"></param>
    /// <returns></returns>
    private static MethodInfo GetControllerAction(Exception exception)
    {
      var stackTrace = new StackTrace(exception);
      var frames = stackTrace.GetFrames();
      if(frames == null) return null;
      var frame = frames.FirstOrDefault(f => typeof(IController).IsAssignableFrom(f.GetMethod().DeclaringType));
      if (frame == null) return null;
      var actionMethod = frame.GetMethod();
      return actionMethod as MethodInfo;
    }
  }
}

I've developed the following jQuery plugin for client side ease of use:

(function ($, undefined) {
  "using strict";

  $.FooGetJSON = function (url, data, success, error) {
    /// <summary>
    /// **********************************************************
    /// * UNIK GET JSON JQUERY PLUGIN.                           *
    /// **********************************************************
    /// This plugin is a wrapper for jQuery.getJSON.
    /// The reason is that jQuery.getJSON success handler doesn't provides access to the JSON object returned from the url
    /// when a HTTP status code different from 200 is encountered. However, please note that whether there is JSON
    /// data or not depends on the requested service. if there is no JSON data (i.e. response.responseText cannot be
    /// parsed as JSON) then the data parameter will be undefined.
    ///
    /// This plugin solves this problem by providing a new error handler signature which includes a data parameter.
    /// Usage of the plugin is much equal to using the jQuery.getJSON method. Handlers can be added etc. However,
    /// the only way to obtain an error handler with the signature specified below with a JSON data parameter is
    /// to call the plugin with the error handler parameter directly specified in the call to the plugin.
    ///
    /// success: function(data, textStatus, jqXHR)
    /// error: function(data, jqXHR, textStatus, errorThrown)
    ///
    /// Example usage:
    ///
    ///   $.FooGetJSON('/foo', { id: 42 }, function(data) { alert('Name :' + data.name); }, function(data) { alert('Error: ' + data.message); });
    /// </summary>

    // Call the ordinary jQuery method
    var jqxhr = $.getJSON(url, data, success);

    // Do the error handler wrapping stuff to provide an error handler with a JSON object - if the response contains JSON object data
    if (typeof error !== "undefined") {
      jqxhr.error(function(response, textStatus, errorThrown) {
        try {
          var json = $.parseJSON(response.responseText);
          error(json, response, textStatus, errorThrown);
        } catch(e) {
          error(undefined, response, textStatus, errorThrown);
        }
      });
    }

    // Return the jQueryXmlHttpResponse object
    return jqxhr;
  };
})(jQuery);

What do I get from all this? The final result is that

  • None of my controller actions has requirements on HandleErrorAttributes.
  • None of my controller actions contains any repetitive boiler plate error handling code.
  • I have a single point of error handling code allowing me to easily change logging and other error handling related stuff.
  • A simple requirement: Controller actions returning JsonResult's must have return type JsonResult and not some base type like ActionResult. Reason: See code comment in FooHandleErrorAttribute.

Client side example:

var success = function(data) {
  alert(data.myjsonobject.foo);
};
var onError = function(data) {
  var message = "Error";
  if(typeof data !== "undefined")
    message += ": " + data.message;
  alert(message);
};
$.FooGetJSON(url, params, onSuccess, onError);

Comments are most welcome! I'll probably blog about this solution some day...

Getting a union of two arrays in JavaScript

You can try these:

function union(a, b) {
    return a.concat(b).reduce(function(prev, cur) {
        if (prev.indexOf(cur) === -1) prev.push(cur);
        return prev;
    }, []);    
}

or

function union(a, b) {
    return a.concat(b.filter(function(el) {
        return a.indexOf(el) === -1;
    }));
}

Is it possible to open a Windows Explorer window from PowerShell?

Single line command ,this worked for me

explorer .\

Is there a command to undo git init?

I'm running Windows 7 with git bash console. The above commands wouldn't work for me.

So I did it via Windows Explorer. I checked show hidden files, went to my projects directory and manually deleted the .git folder. Then back in the command line I checked by running git status.

Which returned...

fatal: Not a git repository (or any of the parent directories): .git

Which is exactly the result I wanted. It returned that the directory is not a git repository (anymore!).

How do I add more members to my ENUM-type column in MySQL?

ALTER TABLE
    `table_name`
MODIFY COLUMN
    `column_name2` enum(
        'existing_value1',
        'existing_value2',
        'new_value1',
        'new_value2'
    )
NOT NULL AFTER `column_name1`;

Target class controller does not exist - Laravel 8

I had this error

(Illuminate\Contracts\Container\BindingResolutionException Target class [App\Http\Controllers\ControllerFileName] does not exist.

Solution: just check your class Name, it should be the exact same of your file name.

How do I list all loaded assemblies?

Using Visual Studio

  1. Attach a debugger to the process (e.g. start with debugging or Debug > Attach to process)
  2. While debugging, show the Modules window (Debug > Windows > Modules)

This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).

enter image description here

Using Process Explorer

If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)

Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.

Programmatically

Check this SO question that explains how to do it.

Using jQuery, Restricting File Size Before Uploading

I don't think it's possible unless you use a flash, activex or java uploader.

For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.

Comparing mongoose _id and strings

The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Ids by using the equals method. Instead, it would make more sense to always cast to string and compare the keys.

Here's an example answer in case if you need to use indexOf() to check within an array of references for a specific id. assume query is a query you are executing, assume someModel is a mongo model for the id you are looking for, and finally assume results.idList is the field you are looking for your object id in.

query.exec(function(err,results){
   var array = results.idList.map(function(v){ return v.toString(); });
   var exists = array.indexOf(someModel._id.toString()) >= 0;
   console.log(exists);
});

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

Fast way of finding lines in one file that are not in another?

whats the speed of as sort and diff?

sort file1 -u > file1.sorted
sort file2 -u > file2.sorted
diff file1.sorted file2.sorted

Print string to text file

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

How to increment datetime by custom months in python without using library

This is short and sweet method to add a month to a date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_after_month = datetime.today()+ relativedelta(months=1)
print 'Today: ',datetime.today().strftime('%d/%m/%Y')
print 'After Month:', date_after_month.strftime('%d/%m/%Y')

Output:

Today: 01/03/2013

After Month: 01/04/2013

A word of warning: relativedelta(months=1) and relativedelta(month=1) have different meanings. Passing month=1 will replace the month in original date to January whereas passing months=1 will add one month to original date.

Note: this will requires python-dateutil. To install it you need to run in Linux terminal.

sudo apt-get update && sudo apt-get install python-dateutil

Explanation : Add month value in python

Convert Current date to integer

Your Problem is because of getTime() . it always return following.

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Because the max integer value is less then the return value by getTime() that why is showing wrong result.

How to get host name with port from a http or https request

Seems like you need to strip the URL from the URL, so you can do it in a following way:

request.getRequestURL().toString().replace(request.getRequestURI(), "")

Array.size() vs Array.length

Actually, .size() is not pure JavaScript method, there is a accessor property .size of Set object that is a little looks like .size() but it is not a function method, just as I said, it is an accessor property of a Set object to show the unique number of (unique) elements in a Set object.

The size accessor property returns the number of (unique) elements in a Set object.

const set1 = new Set();
const object1 = new Object();

set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);

console.log(set1.size);
// expected output: 3

And length is a property of an iterable object(array) that returns the number of elements in that array. The value is an unsigned, 32-bit integer that is always numerically greater than the highest index in the array.

const clothing = ['shoes', 'shirts', 'socks', 'sweaters'];

console.log(clothing.length);
// expected output: 4

How to cache Google map tiles for offline usage?

On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.

How to use Git and Dropbox together?

Another approach:

All the answers so far, including @Dan answer which is the most popular, address the idea of using Dropbox to centralize a shared repository instead of using a service focused on git like github, bitbucket, etc.

But, as the original question does not specify what using "Git and Dropbox together effectively" really means, let's work on another approach: "Using Dropbox to sync only the worktree."

The how-to has these steps:

  1. inside the project directory, one creates an empty .git directory (e.g. mkdir -p myproject/.git)

  2. un-sync the .git directory in Dropbox. If using the Dropbox App: go to Preferences, Sync, and "choose folders to sync", where the .git directory needs to get unmarked. This will remove the .git directory.

  3. run git init in the project directory

It also works if the .git already exists, then only do the step 2. Dropbox will keep a copy of the git files in the website though.

Step 2 will cause Dropbox not to sync the git system structure, which is the desired outcome for this approach.

Why one would use this approach?

  • The not-yet-pushed changes will have a Dropbox backup, and they would be synced across devices.

  • In case Dropbox screws something up when syncing between devices, git status and git diff will be handy to sort things out.

  • It saves space in the Dropbox account (the whole history will not be stored there)

  • It avoids the concerns raised by @dubek and @Ates in the comments on @Dan's answer, and the concerns by @clu in another answer.

The existence of a remote somewhere else (github, etc.) will work fine with this approach.

Working on different branches brings some issues, that need to be taken care of:

  • One potential problem is having Dropbox (unnecessarily?) syncing potentially many files when one checks out different branches.

  • If two or more Dropbox synced devices have different branches checked out, non committed changes to both devices can be lost,

One way around these issues is to use git worktree to keep branch checkouts in separate directories.

Error inflating when extending a class

I had the same problem extending a TextEdit. For me the mistake was I did non add "public" to the constructor. In my case it works even if I define only one constructor, the one with arguments Context and AttributeSet. The wired thing is that the bug reveals itself only when I build an APK (singed or not) and I transfer it to the devices. When the application is run via AndroidStudio -> RunApp on a USB connected device the app works.

Execute PowerShell Script from C# with Commandline Arguments

I had trouble passing parameters to the Commands.AddScript method.

C:\Foo1.PS1 Hello World Hunger
C:\Foo2.PS1 Hello World

scriptFile = "C:\Foo1.PS1"

parameters = "parm1 parm2 parm3" ... variable length of params

I Resolved this by passing null as the name and the param as value into a collection of CommandParameters

Here is my function:

private static void RunPowershellScript(string scriptFile, string scriptParameters)
{
    RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
    Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
    runspace.Open();
    RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
    Pipeline pipeline = runspace.CreatePipeline();
    Command scriptCommand = new Command(scriptFile);
    Collection<CommandParameter> commandParameters = new Collection<CommandParameter>();
    foreach (string scriptParameter in scriptParameters.Split(' '))
    {
        CommandParameter commandParm = new CommandParameter(null, scriptParameter);
        commandParameters.Add(commandParm);
        scriptCommand.Parameters.Add(commandParm);
    }
    pipeline.Commands.Add(scriptCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
}

Googlemaps API Key for Localhost

You can follow this tutorial on how to use Google Maps for testing on localhost.

Check these related SO threads:

Hope this helps!

How to escape JSON string?

In .Net Core 3+ and .Net 5+:

string escapedJsonString = JsonEncodedText.Encode(jsonString);

Excel VBA code to copy a specific string to clipboard

If the url is in a cell in your workbook, you can simply copy the value from that cell:

Private Sub CommandButton1_Click()
    Sheets("Sheet1").Range("A1").Copy
End Sub

(Add a button by using the developer tab. Customize the ribbon if it isn't visible.)

If the url isn't in the workbook, you can use the Windows API. The code that follows can be found here: http://support.microsoft.com/kb/210216

After you've added the API calls below, change the code behind the button to copy to the clipboard:

Private Sub CommandButton1_Click()
    ClipBoard_SetData ("http:\\stackoverflow.com")
End Sub

Add a new module to your workbook and paste in the following code:

Option Explicit

Declare Function GlobalUnlock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalLock Lib "kernel32" (ByVal hMem As Long) _
   As Long
Declare Function GlobalAlloc Lib "kernel32" (ByVal wFlags As Long, _
   ByVal dwBytes As Long) As Long
Declare Function CloseClipboard Lib "User32" () As Long
Declare Function OpenClipboard Lib "User32" (ByVal hwnd As Long) _
   As Long
Declare Function EmptyClipboard Lib "User32" () As Long
Declare Function lstrcpy Lib "kernel32" (ByVal lpString1 As Any, _
   ByVal lpString2 As Any) As Long
Declare Function SetClipboardData Lib "User32" (ByVal wFormat _
   As Long, ByVal hMem As Long) As Long

Public Const GHND = &H42
Public Const CF_TEXT = 1
Public Const MAXSIZE = 4096

Function ClipBoard_SetData(MyString As String)
   Dim hGlobalMemory As Long, lpGlobalMemory As Long
   Dim hClipMemory As Long, X As Long

   ' Allocate moveable global memory.
   '-------------------------------------------
   hGlobalMemory = GlobalAlloc(GHND, Len(MyString) + 1)

   ' Lock the block to get a far pointer
   ' to this memory.
   lpGlobalMemory = GlobalLock(hGlobalMemory)

   ' Copy the string to this global memory.
   lpGlobalMemory = lstrcpy(lpGlobalMemory, MyString)

   ' Unlock the memory.
   If GlobalUnlock(hGlobalMemory) <> 0 Then
      MsgBox "Could not unlock memory location. Copy aborted."
      GoTo OutOfHere2
   End If

   ' Open the Clipboard to copy data to.
   If OpenClipboard(0&) = 0 Then
      MsgBox "Could not open the Clipboard. Copy aborted."
      Exit Function
   End If

   ' Clear the Clipboard.
   X = EmptyClipboard()

   ' Copy the data to the Clipboard.
   hClipMemory = SetClipboardData(CF_TEXT, hGlobalMemory)

OutOfHere2:

   If CloseClipboard() = 0 Then
      MsgBox "Could not close Clipboard."
   End If

End Function

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

Despite following most of the advice on this page, I was still getting problems on Windows Server 2012. Installing .NET Extensibility 4.5 solved it for me:

Add Roles and Features > Server Roles > Web Server (IIS) > Web Server > Application Development > .NET Extensibility 4.5

JavaScript Array splice vs slice

Another example:

[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]

[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]

Add/remove HTML inside div using JavaScript

please try following to generate

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

import { HttpClientModule } from '@angular/common/http';

The HttpClient API was introduced in the version 4.3.0. It is an evolution of the existing HTTP API and has it's own package @angular/common/http. One of the most notable changes is that now the response object is a JSON by default, so there's no need to parse it with map method anymore .Straight away we can use like below

http.get('friends.json').subscribe(result => this.result =result);

Change the class from factor to numeric of many columns in a data frame

That's what's worked for me. The apply() function tries to coerce df to matrix and it returns NA's.

numeric.df <- as.data.frame(sapply(df, 2, as.numeric))

Peak-finding algorithm for Python/SciPy

For those not sure about which peak-finding algorithms to use in Python, here a rapid overview of the alternatives: https://github.com/MonsieurV/py-findpeaks

Wanting myself an equivalent to the MatLab findpeaks function, I've found that the detect_peaks function from Marcos Duarte is a good catch.

Pretty easy to use:

import numpy as np
from vector import vector, plot_peaks
from libs import detect_peaks
print('Detect peaks with minimum height and distance filters.')
indexes = detect_peaks.detect_peaks(vector, mph=7, mpd=2)
print('Peaks are: %s' % (indexes))

Which will give you:

detect_peaks results

Converting a string to a date in JavaScript

If you want to convert from the format "dd/MM/yyyy". Here is an example:

var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = stringDate.match(pattern);
var dt = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);

This solution works in IE versions less than 9.

Run PHP Task Asynchronously

PHP HAS multithreading, its just not enabled by default, there is an extension called pthreads which does exactly that. You'll need php compiled with ZTS though. (Thread Safe) Links:

Examples

Another tutorial

pthreads PECL Extension