Programs & Examples On #Membershipuser

ASP.NET MVC - Set custom IIdentity or IPrincipal

Based on LukeP's answer, and add some methods to setup timeout and requireSSL cooperated with Web.config.

The references links

Modified Codes of LukeP

1, Set timeout based on Web.Config. The FormsAuthentication.Timeout will get the timeout value, which is defined in web.config. I wrapped the followings to be a function, which return a ticket back.

int version = 1;
DateTime now = DateTime.Now;

// respect to the `timeout` in Web.config.
TimeSpan timeout = FormsAuthentication.Timeout;
DateTime expire = now.Add(timeout);
bool isPersist = false;

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
     version,          
     name,
     now,
     expire,
     isPersist,
     userData);

2, Configure the cookie to be secure or not, based on the RequireSSL configuration.

HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
// respect to `RequreSSL` in `Web.Config`
bool bSSL = FormsAuthentication.RequireSSL;
faCookie.Secure = bSSL;

Why Would I Ever Need to Use C# Nested Classes

There is good uses of public nested members too...

Nested classes have access to the private members of the outer class. So a scenario where this is the right way would be when creating a Comparer (ie. implementing the IComparer interface).

In this example, the FirstNameComparer has access to the private _firstName member, which it wouldn't if the class was a separate class...

public class Person
{
    private string _firstName;
    private string _lastName;
    private DateTime _birthday;

    //...
    
    public class FirstNameComparer : IComparer<Person>
    {
        public int Compare(Person x, Person y)
        {
            return x._firstName.CompareTo(y._firstName);
        }
    }
}

How to change color of Toolbar back button in Android?

I am using <style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar> theme in my android application and in NoActionBar theme, colorControlNormal property is used to change the color of navigation icon default Back button arrow in my toolbar

styles.xml

<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
  <item name="colorControlNormal">@color/your_color</item> 
</style>

Transform char array into String

Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:

void setup() {
  // turn on Serial so we can see...
  Serial.begin(9600);

  // the culprit:
  uint8_t my_str[6];    // an array big enough for a 5 character string

  // give it something so we can see what it's doing
  my_str[0] = 'H';
  my_str[1] = 'e';
  my_str[2] = 'l';
  my_str[3] = 'l';
  my_str[4] = 'o';
  my_str[5] = 0;  // be sure to set the null terminator!!!

  // can we see it?
  Serial.println((char*)my_str);

  // can we do logical operations with it as-is?
  Serial.println((char*)my_str == 'Hello');

  // okay, it can't; wrong data type (and no terminator!), so let's do this:
  String str((char*)my_str);

  // can we see it now?
  Serial.println(str);

  // make comparisons
  Serial.println(str == 'Hello');

  // one more time just because
  Serial.println(str == "Hello");

  // one last thing...!
  Serial.println(sizeof(str));
}

void loop() {
  // nothing
}

And we get:

Hello    // as expected
0        // no surprise; wrong data type and no terminator in comparison value
Hello    // also, as expected
1        // YAY!
1        // YAY!
6        // as expected

Hope this helps someone!

Writing a list to a file with Python

You can use a loop:

with open('your_file.txt', 'w') as f:
    for item in my_list:
        f.write("%s\n" % item)

In Python 2, you can also use

with open('your_file.txt', 'w') as f:
    for item in my_list:
        print >> f, item

If you're keen on a single function call, at least remove the square brackets [], so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.

tar: add all files and directories in current directory INCLUDING .svn and so on

You can include the hidden directories by going back a directory and doing:

cd ..
tar czf workspace.tar.gz workspace

Assuming the directory you wanted to gzip was called workspace.

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

How to find out the MySQL root password

You can't view the hashed password; the only thing you can do is reset it!

Stop MySQL:

sudo service mysql stop

or

$ sudo /usr/local/mysql/support-files/mysql.server stop

Start it in safe mode:

$ sudo mysqld_safe --skip-grant-tables

(above line is the whole command)

This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:

$ mysql -u root

mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';

MySQL 5.7 and over:

mysql> use mysql; 
mysql> update user set authentication_string=password('password') where user='root'; 

Start MySQL:

sudo mysql start

or

sudo /usr/local/mysql/support-files/mysql.server start

Your new password is 'password'.

How to hash a password

  1. Create a salt,
  2. Create a hash password with salt
  3. Save both hash and salt
  4. decrypt with password and salt... so developers cant decrypt password
public class CryptographyProcessor
{
    public string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
          RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
         byte[] buff = new byte[size];
         rng.GetBytes(buff);
         return Convert.ToBase64String(buff);
    }


      public string GenerateHash(string input, string salt)
      { 
         byte[] bytes = Encoding.UTF8.GetBytes(input + salt);
         SHA256Managed sHA256ManagedString = new SHA256Managed();
         byte[] hash = sHA256ManagedString.ComputeHash(bytes);
         return Convert.ToBase64String(hash);
      }

      public bool AreEqual(string plainTextInput, string hashedInput, string salt)
      {
           string newHashedPin = GenerateHash(plainTextInput, salt);
           return newHashedPin.Equals(hashedInput); 
      }
 }

How do I clone a Django model instance object and save it to the database?

setting pk to None is better, sinse Django can correctly create a pk for you

object_copy = MyObject.objects.get(pk=...)
object_copy.pk = None
object_copy.save()

How to enable remote access of mysql in centos?

Bind-address XXX.XX.XX.XXX in /etc/my.cnf

comment line:

skip-networking

or

skip-external-locking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL PRIVILEGES ON dbname.* TO 'username'@'%' IDENTIFIED BY 'password';

FLUSH PRIVILEGES;
quit;

add firewall rule:

iptables -I INPUT -i eth0 -p tcp --destination-port 3306 -j ACCEPT

Convert HTML Character Back to Text Using Java Standard Library

java.net.URLDecoder deals only with the application/x-www-form-urlencoded MIME format (e.g. "%20" represents space), not with HTML character entities. I don't think there's anything on the Java platform for that. You could write your own utility class to do the conversion, like this one.

Use of "global" keyword in Python

This is the difference between accessing the name and binding it within a scope.

If you're just looking up a variable to read its value, you've got access to global as well as local scope.

However if you assign to a variable who's name isn't in local scope, you are binding that name into this scope (and if that name also exists as a global, you'll hide that).

If you want to be able to assign to the global name, you need to tell the parser to use the global name rather than bind a new local name - which is what the 'global' keyword does.

Binding anywhere within a block causes the name everywhere in that block to become bound, which can cause some rather odd looking consequences (e.g. UnboundLocalError suddenly appearing in previously working code).

>>> a = 1
>>> def p():
    print(a) # accessing global scope, no binding going on
>>> def q():
    a = 3 # binding a name in local scope - hiding global
    print(a)
>>> def r():
    print(a) # fail - a is bound to local scope, but not assigned yet
    a = 4
>>> p()
1
>>> q()
3
>>> r()
Traceback (most recent call last):
  File "<pyshell#35>", line 1, in <module>
    r()
  File "<pyshell#32>", line 2, in r
    print(a) # fail - a is bound to local scope, but not assigned yet
UnboundLocalError: local variable 'a' referenced before assignment
>>> 

Get the height and width of the browser viewport without scrollbars using jquery?

As Kyle suggested, you can measure the client browser viewport size without taking into account the size of the scroll bars this way.

Sample (Viewport dimensions WITHOUT scroll bars)

// First you forcibly request the scroll bars to hidden regardless if they will be needed or not.
$('body').css('overflow', 'hidden');

// Take your measures.
// (These measures WILL NOT take into account scroll bars dimensions)
var heightNoScrollBars = $(window).height();
var widthNoScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

Alternatively if you wish to find the dimensions of the client viewport while taking into account the size of the scroll bars, then this sample bellow best suits you.

First don't forget to set you body tag to be 100% width and height just to make sure the measurement is accurate.

body { 
width: 100%; // if you wish to measure the width and take into account the horizontal scroll bar.
height: 100%; // if you wish to measure the height while taking into account the vertical scroll bar.
}

Sample (Viewport dimensions WITH scroll bars)

// First you forcibly request the scroll bars to be shown regardless if they will be needed or not.
$('body').css('overflow', 'scroll');

// Take your measures.
// (These measures WILL take into account scroll bars dimensions)
var heightWithScrollBars = $(window).height();
var widthWithScrollBars = $(window).width();

// Set the overflow css property back to it's original value (default is auto)
$('body').css('overflow', 'auto');

What is the meaning of curly braces?

In Python, curly braces are used to define a dictionary.

a={'one':1, 'two':2, 'three':3}
a['one']=1
a['three']=3

In other languages, { } are used as part of the flow control. Python however used indentation as its flow control because of its focus on readable code.

for entry in entries:
     code....

There's a little easter egg in Python when it comes to braces. Try running this on the Python Shell and enjoy.

from __future__ import braces

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

use jQuery to get values of selected checkboxes

A bit more modern way to do it:

const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
        return $(this).val(); 
    })
    .get()
    .join(', ');

We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.

ab load testing

Steps to set up Apache Bench(AB) on windows (IMO - Recommended).

Step 1 - Install Xampp.
Step 2 - Open CMD.
Step 3 - Go to the apache bench destination (cd C:\xampp\apache\bin) from CMD
Step 4 - Paste the command (ab -n 100 -c 10 -k -H "Accept-Encoding: gzip, deflate" http://localhost:yourport/)
Step 5 - Wait for it. Your done

Instagram API to fetch pictures with specific hashtags

It is not possible yet to search for content using multiple tags, for now only single tags are supported.

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

This is not quite true, you only need an API-Key. Just register an application and add it to your requests. Example:

https://api.instagram.com/v1/users/userIdYouWantToGetMediaFrom/media/recent?client_id=yourAPIKey

Also note that the username is not the user-id. You can look up user-Id`s here.

A workaround for searching multiple keywords would be if you start one request for each tag and compare the results on your server. Of course this could slow down your site depending on how much keywords you want to compare.

What is the difference between method overloading and overriding?

Method overloading deals with the notion of having two or more methods in the same class with the same name but different arguments.

void foo(int a)
void foo(int a, float b)

Method overriding means having two methods with the same arguments, but different implementations. One of them would exist in the parent class, while another will be in the derived, or child class. The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.

class Parent {
    void foo(double d) {
        // do something
    }
}

class Child extends Parent {

    @Override
    void foo(double d){
        // this method is overridden.  
    }
}

SVN Error - Not a working copy

If you created a file inside a new directory, instead of 'svn add newdir/newfile' use 'svn add newdir' because you need to add the directory. All the files inside the directory will be added by default.

HTML5 best practices; section/header/aside/article elements

[explanations in my “main answer”]

line 7. section around the whole website? Or only a div?

Neither. For styling: use the <body>, it’s already there. For sectioning/semantics: as detailed in my example HTML its effect is contrary to usefulness. Extra wrappers to already wrapped content is no improvement, but noise.


line 8. Each section start with a header?

No, it is the author’s choice where to put content typically summarized as “header”. And if that header-content is clearly recognizable without extra marking, it may perfectly stay without <header>. This is also the author’s choice.


line 23. Is this div right? or must this be a section?

The <div> is probably wrong. It depends on the intentions: is it for styling only it could be right. If it’s for semantic purposes it is wrong: it should be an <article> instead as shown in my other answer. <article> is also right if it is for both styling and sectioning combined.

<section> looks wrong here, as there are no similar sections before or after this one, like chapters in a book. (This is the purpose of <section>).


line 24. Split left/right column with a div.

No. Why?


line 25. Right place for the article tag?

Yes, makes sense.


line 26. Is it required to put your h1-tag in the header-tag?

No. A lone <h*> element probably never needs to go in a <header> (but it can if you want to) as it is already clear that it’s the heading of what is about to come. – It would make sense if that <header> also encompassed a tagline (marked with <p>), for example.


line 43. The content is not related to the main article, so I decided this is a section and not an aside.

It is a misunderstanding that an <aside> has to be “tangentially related” to the content around. The point is: use an <aside> if the content is only “tangentially related” or not at all!

Nevertheless, apart from <aside> being a decent choice, <article> might still be better than a <section> as “hot items” and “new items” are not to be read like two chapters in a book. You can perfectly go for one of them and not the other like an alternative sorting of something, not like two parts of a whole.


line 44. H2 without header

Is great.


line 53. section without header

Well, there is no <header>, but the <h2>-heading leaves pretty clear which part in this section is the header.


line 63. Div with all (non-related) news items

<article> or <aside> might be better.


line 64. header with h2

Discussed already.


line 65. Hmm, div or section? Or remove this div and only use the article-tag

Exactly! Remove the <div>.


line 105. Footer :-)

Very reasonable.

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

JavaScript global event mechanism

I would recommend giving Trackjs a try.

It's error logging as a service.

It's amazingly simple to set up. Just add one <script> line to each page and that's it. This also means it will be amazingly simple to remove if you decide you don't like it.

There are other services like Sentry (which is open-source if you can host your own server), but it doesn't do what Trackjs does. Trackjs records the user's interaction between their browser and your webserver so that you can actually trace the user steps that led to the error, as opposed to just a file and line number reference (and maybe stack trace).

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

Base64 Decoding in iOS 7+

Swift 3+

let plainString = "foo"

Encoding

let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString()
print(base64String!) // Zm9v

Decoding

if let decodedData = Data(base64Encoded: base64String!),
   let decodedString = String(data: decodedData, encoding: .utf8) {
  print(decodedString) // foo
}

Swift < 3

let plainString = "foo"

Encoding

let plainData = plainString.dataUsingEncoding(NSUTF8StringEncoding)
let base64String = plainData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print(base64String!) // Zm9v

Decoding

let decodedData = NSData(base64EncodedString: base64String!, options: NSDataBase64DecodingOptions(rawValue: 0))
let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding)
print(decodedString) // foo

Objective-C

NSString *plainString = @"foo";

Encoding

NSData *plainData = [plainString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
NSLog(@"%@", base64String); // Zm9v

Decoding

NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:base64String options:0];
NSString *decodedString = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
NSLog(@"%@", decodedString); // foo 

Get div to take up 100% body height, minus fixed-height header and footer

this version will work in all the latest browsers and ie8 if you have the modernizr script (if not just change header and footer into divs):

Fiddle

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  min-height: 100%;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
  padding: 50px 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  min-height: 100%;_x000D_
  background-color: green;_x000D_
}_x000D_
_x000D_
header {_x000D_
  margin-top: -50px;_x000D_
  height: 50px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
footer {_x000D_
  margin-bottom: -50px;_x000D_
  height: 50px;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
p {_x000D_
  margin: 0;_x000D_
  padding: 0 0 1em 0;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
  <header>dfs</header>_x000D_
  <div id="content">_x000D_
  </div>_x000D_
  <footer>sdf</footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Scrolling with content: Fiddle

Carousel with Thumbnails in Bootstrap 3.0

Bootstrap 4 (update 2019)

A multi-item carousel can be accomplished in several ways as explained here. Another option is to use separate thumbnails to navigate the carousel slides.

Bootstrap 3 (original answer)

This can be done using the grid inside each carousel item.

       <div id="myCarousel" class="carousel slide">
                <div class="carousel-inner">
                    <div class="item active">
                        <div class="row">
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                        </div>
                        <!--/row-->
                    </div>
                    ...add more item(s)
                 </div>
        </div>

Demo example thumbnail slider using the carousel:
http://www.bootply.com/81478

Another example with carousel indicators as thumbnails: http://www.bootply.com/79859

Not equal <> != operator on NULL

I would like to suggest this code I made to find if there is a change in a value, i being the new value and d being the old (although the order does not matter). For that matter, a change from value to null or vice versa is a change but from null to null is not (of course, from value to another value is a change but from value to the same it is not).

CREATE FUNCTION [dbo].[ufn_equal_with_nulls]
(
    @i sql_variant,
    @d sql_variant
)
RETURNS bit
AS
BEGIN
    DECLARE @in bit = 0, @dn bit = 0
    if @i is null set @in = 1
    if @d is null set @dn = 1

    if @in <> @dn
        return 0

    if @in = 1 and @dn = 1
        return 1

    if @in = 0 and @dn = 0 and @i = @d
        return 1

    return 0

END

To use this function, you can

declare @tmp table (a int, b int)
insert into @tmp values
(1,1),
(1,2),
(1,null),
(null,1),
(null,null)

---- in select ----
select *, [dbo].[ufn_equal_with_nulls](a,b) as [=] from @tmp

---- where equal ----
select *,'equal' as [Predicate] from @tmp where  [dbo].[ufn_equal_with_nulls](a,b) = 1

---- where not equal ----
select *,'not equal' as [Predicate] from @tmp where  [dbo].[ufn_equal_with_nulls](a,b) = 0

The results are:

---- in select ----
a   b   =
1   1   1
1   2   0
1   NULL    0
NULL    1   0
NULL    NULL    1

---- where equal ----
1   1   equal
NULL    NULL    equal

---- where not equal ----
1   2   not equal
1   NULL    not equal
NULL    1   not equal

The usage of sql_variant makes it compatible for variety of types

Best way to define error codes/strings in Java?

Just to keep flogging this particular dead horse- we've had good use of numeric error codes when errors are shown to end-customers, since they frequently forget or misread the actual error message but may sometimes retain and report a numeric value that can give you a clue to what actually happened.

Inconsistent Accessibility: Parameter type is less accessible than method

Try making your constructor private like this:

private Foo newClass = new Foo();

Is Fortran easier to optimize than C for heavy calculations?

I haven't heard that Fortan is significantly faster than C, but it might be conceivable tht in certain cases it would be faster. And the key is not in the language features that are present, but in those that (usually) absent.

An example are C pointers. C pointers are used pretty much everywhere, but the problem with pointers is that the compiler usually can't tell if they're pointing to the different parts of the same array.

For example if you wrote a strcpy routine that looked like this:

strcpy(char *d, const char* s)
{
  while(*d++ = *s++);
}

The compiler has to work under the assumption that the d and s might be overlapping arrays. So it can't perform an optimization that would produce different results when the arrays overlap. As you'd expect, this considerably restricts the kind of optimizations that can be performed.

[I should note that C99 has a "restrict" keyword that explictly tells the compilers that the pointers don't overlap. Also note that the Fortran too has pointers, with semantics different from those of C, but the pointers aren't ubiquitous as in C.]

But coming back to the C vs. Fortran issue, it is conceivable that a Fortran compiler is able to perform some optimizations that might not be possible for a (straightforwardly written) C program. So I wouldn't be too surprised by the claim. However, I do expect that the performance difference wouldn't be all that much. [~5-10%]

Sorting dropdown alphabetically in AngularJS

Angular has an orderBy filter that can be used like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>

See this fiddle for an example.

It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

<select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>

Datatables Select All Checkbox

I made a simple implementation of this functionality using fontawesome, also taking advantage of the Select Extension, this covers select all, deselect some items, deselect all. https://codepen.io/pakogn/pen/jJryLo

HTML:

<table id="example" class="display" style="width:100%">
    <thead>
        <tr>
            <th>
                <button style="border: none; background: transparent; font-size: 14px;" id="MyTableCheckAllButton">
                <i class="far fa-square"></i>  
                </button>
            </th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td></td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>$320,800</td>
        </tr>
        <tr>
            <td></td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>$170,750</td>
        </tr>
        <tr>
            <td></td>
            <td>Ashton Cox</td>
            <td>Junior Technical Author</td>
            <td>San Francisco</td>
            <td>66</td>
            <td>$86,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Cedric Kelly</td>
            <td>Senior Javascript Developer</td>
            <td>Edinburgh</td>
            <td>22</td>
            <td>$433,060</td>
        </tr>
        <tr>
            <td></td>
            <td>Airi Satou</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>33</td>
            <td>$162,700</td>
        </tr>
        <tr>
            <td></td>
            <td>Brielle Williamson</td>
            <td>Integration Specialist</td>
            <td>New York</td>
            <td>61</td>
            <td>$372,000</td>
        </tr>
        <tr>
            <td></td>
            <td>Herrod Chandler</td>
            <td>Sales Assistant</td>
            <td>San Francisco</td>
            <td>59</td>
            <td>$137,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Rhona Davidson</td>
            <td>Integration Specialist</td>
            <td>Tokyo</td>
            <td>55</td>
            <td>$327,900</td>
        </tr>
        <tr>
            <td></td>
            <td>Colleen Hurst</td>
            <td>Javascript Developer</td>
            <td>San Francisco</td>
            <td>39</td>
            <td>$205,500</td>
        </tr>
        <tr>
            <td></td>
            <td>Sonya Frost</td>
            <td>Software Engineer</td>
            <td>Edinburgh</td>
            <td>23</td>
            <td>$103,600</td>
        </tr>
        <tr>
            <td></td>
            <td>Jena Gaines</td>
            <td>Office Manager</td>
            <td>London</td>
            <td>30</td>
            <td>$90,560</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Salary</th>
        </tr>
    </tfoot>
</table>

Javascript:

$(document).ready(function() {
    let myTable = $('#example').DataTable({
        columnDefs: [{
            orderable: false,
            className: 'select-checkbox',
            targets: 0,
        }],
        select: {
            style: 'os', // 'single', 'multi', 'os', 'multi+shift'
            selector: 'td:first-child',
        },
        order: [
            [1, 'asc'],
        ],
    });

    $('#MyTableCheckAllButton').click(function() {
        if (myTable.rows({
                selected: true
            }).count() > 0) {
            myTable.rows().deselect();
            return;
        }

        myTable.rows().select();
    });

    myTable.on('select deselect', function(e, dt, type, indexes) {
        if (type === 'row') {
            // We may use dt instead of myTable to have the freshest data.
            if (dt.rows().count() === dt.rows({
                    selected: true
                }).count()) {
                // Deselect all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-check-square');
                return;
            }

            if (dt.rows({
                    selected: true
                }).count() === 0) {
                // Select all items button.
                $('#MyTableCheckAllButton i').attr('class', 'far fa-square');
                return;
            }

            // Deselect some items button.
            $('#MyTableCheckAllButton i').attr('class', 'far fa-minus-square');
        }
    });
});

R for loop skip to next iteration ifelse

for(n in 1:5) {
  if(n==3) next # skip 3rd iteration and go to next iteration
  cat(n)
}

How do you get a list of the names of all files present in a directory in Node.js?

This will work and store the result in test.txt file which will be present in the same directory

  fs.readdirSync(__dirname).forEach(file => {
    fs.appendFileSync("test.txt", file+"\n", function(err){
    })
})

PHP convert XML to JSON

After researching a little bit all of the answers, I came up with a solution that worked just fine with my JavaScript functions across browsers (Including consoles / Dev Tools) :

<?php

 // PHP Version 7.2.1 (Windows 10 x86)

 function json2xml( $domNode ) {
  foreach( $domNode -> childNodes as $node) {
   if ( $node -> hasChildNodes() ) { json2xml( $node ); }
   else {
    if ( $domNode -> hasAttributes() && strlen( $domNode -> nodeValue ) ) {
     $domNode -> setAttribute( "nodeValue", $node -> textContent );
     $node -> nodeValue = "";
    }
   }
  }
 }

 function jsonOut( $file ) {
  $dom = new DOMDocument();
  $dom -> loadXML( file_get_contents( $file ) );
  json2xml( $dom );
  header( 'Content-Type: application/json' );
  return str_replace( "@", "", json_encode( simplexml_load_string( $dom -> saveXML() ), JSON_PRETTY_PRINT ) );
 }

 $output = jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' );

 echo( $output );

 /*
  Or simply 
  echo( jsonOut( 'https://boxelizer.com/assets/a1e10642e9294f39/b6f30987f0b66103.xml' ) );
 */

?>

It basically creates a new DOMDocument, loads and XML file into it and traverses through each one of the nodes and children getting the data / parameters and exporting it into JSON without the annoying "@" signs.

Link to the XML file.

Get value of input field inside an iframe

Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---

var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
    encodeURIComponent(purl) + '&callback=?',
    function (data) {
    $('#viewer').html(data.contents);
});

JavaScript displaying a float to 2 decimal places

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

Fail to create Android virtual Device, "No system image installed for this Target"

As a workaround, go to sdk installation directory and perform the following steps:

  • Navigate to system-images/android-19/default
  • Move everything in there to system-images/android-19/

The directory structure should look like this: enter image description here

And it should work!

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

How to iterate over the files of a certain directory, in Java?

Use java.io.File.listFiles
Or
If you want to filter the list prior to iteration (or any more complicated use case), use apache-commons FileUtils. FileUtils.listFiles

Why doesn't CSS ellipsis work in table cell?

Just offering an alternative as I had this problem and none of the other answers here had the desired effect I wanted. So instead I used a list. Now semantically the information I was outputting could have been regarded as both tabular data but also listed data.

So in the end what I did was:

<ul>
    <li class="group">
        <span class="title">...</span>
        <span class="description">...</span>
        <span class="mp3-player">...</span>
        <span class="download">...</span>
        <span class="shortlist">...</span>
    </li>
    <!-- looped <li> -->
</ul>

So basically ul is table, li is tr, and span is td.

Then in CSS I set the span elements to be display:block; and float:left; (I prefer that combination to inline-block as it'll work in older versions of IE, to clear the float effect see: http://css-tricks.com/snippets/css/clear-fix/) and to also have the ellipses:

span {
    display: block;
    float: left;
    width: 100%;

    // truncate when long
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Then all you do is set the max-widths of your spans and that'll give the list an appearance of a table.

Counting unique / distinct values by group in a data frame

In dplyr you may use n_distinct to "count the number of unique values":

library(dplyr)
myvec %>%
  group_by(name) %>%
  summarise(n_distinct(order_no))

How can I initialise a static Map?

I've done something a bit different. Not the best, but it works for me. Maybe it could be "genericized".

private static final Object[][] ENTRIES =
{
  {new Integer(1), "one"},
  {new Integer(2), "two"},
};
private static final Map myMap = newMap(ENTRIES);

private static Map newMap(Object[][] entries)
{
  Map map = new HashMap();

  for (int x = 0; x < entries.length; x++)
  {
    Object[] entry = entries[x];

    map.put(entry[0], entry[1]);
  }

  return map;
}

Creating a Menu in Python

It looks like you've just finished step 3. Instead of running a function, you just print out a statement. A function is defined in the following way:

def addstudent():
    print("Student Added.")

then called by writing addstudent().

I would recommend using a while loop for your input. You can define the menu option outside the loop, put the print statement inside the loop, and do while(#valid option is not picked), then put the if statements after the while. Or you can do a while loop and continue the loop if a valid option is not selected.

Additionally, a dictionary is defined in the following way:

my_dict = {key:definition,...}

Using Gradle to build a jar with dependencies

This works fine for me.

My Main class:

package com.curso.online.gradle;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class Main {

    public static void main(String[] args) {
        Logger logger = Logger.getLogger(Main.class);
        logger.debug("Starting demo");

        String s = "Some Value";

        if (!StringUtils.isEmpty(s)) {
            System.out.println("Welcome ");
        }

        logger.debug("End of demo");
    }

}

And it is the content of my file build.gradle:

apply plugin: 'java'

apply plugin: 'eclipse'

repositories {
    mavenCentral()
}

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
    compile  'org.apache.commons:commons-lang3:3.0'
    compile  'log4j:log4j:1.2.16'
}

task fatJar(type: Jar) {
    manifest {
        attributes 'Main-Class': 'com.curso.online.gradle.Main'
    }
    baseName = project.name + '-all'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

And I write the following in my console:

java -jar ProyectoEclipseTest-all.jar

And the output is great:

log4j:WARN No appenders could be found for logger (com.curso.online.gradle.Main)
.
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more in
fo.
Welcome

NSDate get year/month/day

Try the following:

    NSString *birthday = @"06/15/1977";
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM/dd/yyyy"];
    NSDate *date = [formatter dateFromString:birthday];
    if(date!=nil) {
        NSInteger age = [date timeIntervalSinceNow]/31556926;
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];

        NSLog(@"Day:%d Month:%d Year:%d Age:%d",day,month,year,age);
    }
    [formatter release];

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

Taking a point from both Boycs Answer and mtmurdock's subsequent answer I have the following stored proc on all of my development or staging databases. I've added some switches to fit my own requirement if I need to add in statements to reseed the data for certain columns.

(Note: I would have added this as a comment to Boycs brilliant answer but I haven't got enough reputation to do that yet. So please accept my apologies for adding this as an entirely new answer.)

ALTER PROCEDURE up_ResetEntireDatabase
@IncludeIdentReseed BIT,
@IncludeDataReseed BIT
AS

EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'

IF @IncludeIdentReseed = 1
BEGIN
    EXEC sp_MSForEachTable 'DBCC CHECKIDENT (''?'' , RESEED, 1)'
END

EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'

IF @IncludeDataReseed = 1
BEGIN
    -- Populate Core Data Table Here
END
GO

And then once ready the execution is really simple:

EXEC up_ResetEntireDatabase 1, 1

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

You also can use ng-attr-src="{{variable}}" instead of src="{{variable}}" and the attribute will only be generated once the compiler compiled the templates. This is mentioned here in the documentation: https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings

Combining (concatenating) date and time into a datetime

Solution (1): datetime arithmetic

Given @myDate, which can be anything that can be cast as a DATE, and @myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:

CAST(CAST(@myDate as DATE) AS DATETIME) + CAST(CAST(@myTime as TIME) as DATETIME)

You can verify with:

SELECT  GETDATE(), 
        CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)

Solution (2): string manipulation

SELECT  GETDATE(), 
        CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))

However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.

See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation

Is JavaScript a pass-by-reference or pass-by-value language?

It's always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it's really pass by value.

Example:

_x000D_
_x000D_
function changeObject(x) {_x000D_
  x = { member: "bar" };_x000D_
  console.log("in changeObject: " + x.member);_x000D_
}_x000D_
_x000D_
function changeMember(x) {_x000D_
  x.member = "bar";_x000D_
  console.log("in changeMember: " + x.member);_x000D_
}_x000D_
_x000D_
var x = { member: "foo" };_x000D_
_x000D_
console.log("before changeObject: " + x.member);_x000D_
changeObject(x);_x000D_
console.log("after changeObject: " + x.member); /* change did not persist */_x000D_
_x000D_
console.log("before changeMember: " + x.member);_x000D_
changeMember(x);_x000D_
console.log("after changeMember: " + x.member); /* change persists */
_x000D_
_x000D_
_x000D_

Output:

before changeObject: foo
in changeObject: bar
after changeObject: foo

before changeMember: foo
in changeMember: bar
after changeMember: bar

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

count number of characters in nvarchar column

Use

SELECT length(yourfield) FROM table;

Java stack overflow error - how to increase the stack size in Eclipse?

You need to have a launch configuration inside Eclipse in order to adjust the JVM parameters.

After running your program with either F11 or Ctrl-F11, open the launch configurations in Run -> Run Configurations... and open your program under "Java Applications". Select the Arguments pane, where you will find "VM arguments".

This is where -Xss1024k goes.

If you want the launch configuration to be a file in your workspace (so you can right click and run it), select the Common pane, and check the Save as -> Shared File checkbox and browse to the location you want the launch file. I usually have them in a separate folder, as we check them into CVS.

How do I tell a Python script to use a particular version

put at the start of my programs its use full for work with python

import sys

if sys.version_info[0] < 3:
    raise Exception("Python 3 or a more recent version is required.")

This code will help full for the progress

Default value in Go's method

No, there is no way to specify defaults. I believer this is done on purpose to enhance readability, at the cost of a little more time (and, hopefully, thought) on the writer's end.

I think the proper approach to having a "default" is to have a new function which supplies that default to the more generic function. Having this, your code becomes clearer on your intent. For example:

func SaySomething(say string) {
    // All the complicated bits involved in saying something
}

func SayHello() {
    SaySomething("Hello")
}

With very little effort, I made a function that does a common thing and reused the generic function. You can see this in many libraries, fmt.Println for example just adds a newline to what fmt.Print would otherwise do. When reading someone's code, however, it is clear what they intend to do by the function they call. With default values, I won't know what is supposed to be happening without also going to the function to reference what the default value actually is.

How to convert a char array back to a string?

String text = String.copyValueOf(data);

or

String text = String.valueOf(data);

is arguably better (encapsulates the new String call).

Is Java a Compiled or an Interpreted programming language ?

enter image description here

Code written in Java is:

  • First compiled to bytecode by a program called javac as shown in the left section of the image above;
  • Then, as shown in the right section of the above image, another program called java starts the Java runtime environment and it may compile and/or interpret the bytecode by using the Java Interpreter/JIT Compiler.

When does java interpret the bytecode and when does it compile it? The application code is initially interpreted, but the JVM monitors which sequences of bytecode are frequently executed and translates them to machine code for direct execution on the hardware. For bytecode which is executed only a few times, this saves the compilation time and reduces the initial latency; for frequently executed bytecode, JIT compilation is used to run at high speed, after an initial phase of slow interpretation. Additionally, since a program spends most time executing a minority of its code, the reduced compilation time is significant. Finally, during the initial code interpretation, execution statistics can be collected before compilation, which helps to perform better optimization.

Import txt file and having each line as a list

lines=[]
with open('file') as file:
   lines.append(file.readline())

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

How to parse XML in Bash?

After some research for translation between Linux and Windows formats of the file paths in XML files I found interesting tutorials and solutions on:

Running javascript in Selenium using Python

Use execute_script, here's a python example:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python") 
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")

How does one output bold text in Bash?

In order to apply a style on your string, you can use a command like:

echo -e '\033[1mYOUR_STRING\033[0m'

Explanation:

  • echo -e - The -e option means that escaped (backslashed) strings will be interpreted
  • \033 - escaped sequence represents beginning/ending of the style
  • lowercase m - indicates the end of the sequence
  • 1 - Bold attribute (see below for more)
  • [0m - resets all attributes, colors, formatting, etc.

The possible integers are:

  • 0 - Normal Style
  • 1 - Bold
  • 2 - Dim
  • 3 - Italic
  • 4 - Underlined
  • 5 - Blinking
  • 7 - Reverse
  • 8 - Invisible

Using Google Text-To-Speech in Javascript

I don't know of Google voice, but using the javaScript speech SpeechSynthesisUtterance, you can add a click event to the element you are reference to. eg:

_x000D_
_x000D_
const listenBtn = document.getElementById('myvoice');

listenBtn.addEventListener('click', (e) => {
  e.preventDefault();

  const msg = new SpeechSynthesisUtterance(
    "Hello, hope my code is helpful"
  );
  window.speechSynthesis.speak(msg);

});
_x000D_
<button type="button" id='myvoice'>Listen to me</button>
_x000D_
_x000D_
_x000D_

What is JavaScript's highest integer value that a number can go to without losing precision?

Anything you want to use for bitwise operations must be between 0x80000000 (-2147483648 or -2^31) and 0x7fffffff (2147483647 or 2^31 - 1).

The console will tell you that 0x80000000 equals +2147483648, but 0x80000000 & 0x80000000 equals -2147483648.

Sort array of objects by single key with date value

I have created a sorting function in Typescript which we can use to search strings, dates and numbers in array of objects. It can also sort on multiple fields.

export type SortType = 'string' | 'number' | 'date';
export type SortingOrder = 'asc' | 'desc';

export interface SortOptions {
  sortByKey: string;
  sortType?: SortType;
  sortingOrder?: SortingOrder;
}


class CustomSorting {
    static sortArrayOfObjects(fields: SortOptions[] = [{sortByKey: 'value', sortType: 'string', sortingOrder: 'desc'}]) {
        return (a, b) => fields
          .map((field) => {
            if (!a[field.sortByKey] || !b[field.sortByKey]) {
              return 0;
            }

            const direction = field.sortingOrder === 'asc' ? 1 : -1;

            let firstValue;
            let secondValue;

            if (field.sortType === 'string') {
              firstValue = a[field.sortByKey].toUpperCase();
              secondValue = b[field.sortByKey].toUpperCase();
            } else if (field.sortType === 'number') {
              firstValue = parseInt(a[field.sortByKey], 10);
              secondValue = parseInt(b[field.sortByKey], 10);
            } else if (field.sortType === 'date') {
              firstValue = new Date(a[field.sortByKey]);
              secondValue = new Date(b[field.sortByKey]);
            }
            return firstValue > secondValue ? direction : firstValue < secondValue ? -(direction) : 0;

          })
          .reduce((pos, neg) => pos ? pos : neg, 0);
      }
    }
}

Usage:

const sortOptions = [{
      sortByKey: 'anyKey',
      sortType: 'string',
      sortingOrder: 'asc',
    }];

arrayOfObjects.sort(CustomSorting.sortArrayOfObjects(sortOptions));

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

In Python 3.3, added new method timestamp:

import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()

Your question stated that you needed milliseconds, which you can get like this:

milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000

If you use timestamp on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.

What does the term "canonical form" or "canonical representation" in Java mean?

An easy way to remember it is the way "canonical" is used in theological circles, canonical truth is the real truth so if two people find it they have found the same truth. Same with canonical instance. If you think you have found two of them (i.e. a.equals(b)) you really only have one (i.e. a == b). So equality implies identity in the case of canonical object.

Now for the comparison. You now have the choice of using a==b or a.equals(b), since they will produce the same answer in the case of canonical instance but a==b is comparison of the reference (the JVM can compare two numbers extremely rapidly as they are just two 32 bit patterns compared to a.equals(b) which is a method call and involves more overhead.

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

If you want to use Angular with an unsupported TypeScript version, add this to your tsconfig.json to ignore the warning:

  "angularCompilerOptions": {
    "disableTypeScriptVersionCheck": true,
  },

Verifying that a string contains only letters in C#

If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again

       bool check = false;

       Console.WriteLine("Please Enter the Name");
       name=Console.ReadLine();

       for (int i = 0; i < name.Length; i++)
       {
           if (name[i]>='a' && name[i]<='z' || name[i]==' ')
           {
               check = true;
           }
           else
           {
               check = false;
               break;
           }

       }

       if (check==false)
       {
           Console.WriteLine("Enter Valid Value");
           name = Console.ReadLine();
       }

How do I fix a NoSuchMethodError?

It means the respective method is not present in the class:

  1. If you are using jar then decompile and check if the respective version of jar have proper class.
  2. Check if you have compiled proper class from your source.

"Bitmap too large to be uploaded into a texture"

As pointed by Larcho, starting from API level 10, you can use BitmapRegionDecoder to load specific regions from an image and with that, you can accomplish to show a large image in high resolution by allocating in memory just the needed regions. I've recently developed a lib that provides the visualisation of large images with touch gesture handling. The source code and samples are available here.

How to set css style to asp.net button?

nobody wants to go to the clutter of using a class, try this:

<asp:button Style="margin:0px" runat="server" />

Intellisense won't suggest it but it will get the job done without throwing errors, warnings, or messages. Don't forget the capital S in Style

ImportError: No module named PyQt4.QtCore

I got the same error, when I was trying to import matplotlib.pyplot

In [1]: import matplotlib.pyplot as plt
...
...
ImportError: No module named PyQt4.QtCore

But in my case the problem was due to a missing linux library libGL.so.1

OS : Cent OS 64 bit

Python version : 3.5.2

$> locate libGL.so.1

If this command returns a value, your problem could be different, so please ignore my answer. If it does not return any value and your environment is same as mine, below steps would fix your problem.

$> yum install mesa-libGL.x86_64

This installs the necessary OpenGL libraries for 64 bit Cent OS.

$> locate libGL.so.1
/usr/lib/libGL.so.1

Now go back to iPython and try to import

In [1]: import matplotlib.pyplot as plt

This time it imported successfully.

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);

How do I read a response from Python Requests?

If you push for example image to some API and want the result address(response) back you could do:

import requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)

Grep characters before and after match?

You can use regexp grep for finding + second grep for highlight

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23_string_and

enter image description here

git clone from another directory

Use git clone c:/folder1 c:/folder2

git clone [--template=<template_directory>] [-l] [-s] [--no-hardlinks]
[-q] [-n] [--bare] [--mirror] [-o <name>] [-b <name>] [-u <upload-pack>]
[--reference <repository>] [--separate-git-dir <git dir>] [--depth <depth>]
[--[no-]single-branch] [--recursive|--recurse-submodules] [--]<repository>
[<directory>]


<repository>

    The (possibly remote) repository to clone from.
    See the URLS section below for more information on specifying repositories.
<directory>

    The name of a new directory to clone into.
    The "humanish" part of the source repository is used if no directory 
    is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
    Cloning into an existing directory is only allowed if the directory is empty.

Android Studio cannot resolve R in imported project?

  1. Press F4 into Project Structure, Check SDKs on left
  2. Click Modules ---> Source Tab, check gen and src as sources

PS: The answer over a year old and the menus have changed.

How to call window.alert("message"); from C#?

if you are using ajax in your page that require script manager Page.ClientScript
will not work, Try this and it would do the work:

ScriptManager.RegisterClientScriptBlock(this, GetType(),
            "alertMessage", @"alert('your Message ')", true);

Change color inside strings.xml

You don't. strings.xml is just here to define the raw text messages. You should (must) use styles.xml to define reusable visual styles to apply to your widgets.

Think of it as a good practice to separate the concerns. You can work on the visual styles independently from the text messages.

add created_at and updated_at fields to mongoose schemas

Use a function to return the computed default value:

var ItemSchema = new Schema({
    name: {
      type: String,
      required: true,
      trim: true
    },
    created_at: {
      type: Date,
      default: function(){
        return Date.now();
      }
    },
    updated_at: {
      type: Date,
      default: function(){
        return Date.now();
      }
    }
});

ItemSchema.pre('save', function(done) {
  this.updated_at = Date.now();
  done();
});

ClassNotFoundException com.mysql.jdbc.Driver

You should download MariaDB connector.
Then:

  1. Expand your project.
  2. Right-click on Libraries.
  3. Select Add Jar/Folder.
  4. Add mariadb-java-client-2.0.2.jar which you just downloaded.

How do I make a simple crawler in PHP?

In it's simplest form:

function crawl_page($url, $depth = 5) {
    if($depth > 0) {
        $html = file_get_contents($url);

        preg_match_all('~<a.*?href="(.*?)".*?>~', $html, $matches);

        foreach($matches[1] as $newurl) {
            crawl_page($newurl, $depth - 1);
        }

        file_put_contents('results.txt', $newurl."\n\n".$html."\n\n", FILE_APPEND);
    }
}

crawl_page('http://www.domain.com/index.php', 5);

That function will get contents from a page, then crawl all found links and save the contents to 'results.txt'. The functions accepts an second parameter, depth, which defines how long the links should be followed. Pass 1 there if you want to parse only links from the given page.

How to convert from java.sql.Timestamp to java.util.Date?

Class java.sql.TimeStamp extends from java.util.Date.

You can directly assign a TimeStamp object to Date reference:

TimeStamp timeStamp = //whatever value you have;
Date startDate = timestampValue;

String replace method is not replacing characters

package com.tulu.ds;

public class EmailSecurity {
    public static void main(String[] args) {
        System.out.println(returnSecuredEmailID("[email protected]"));
    }
    private static String returnSecuredEmailID(String email){
        String str=email.substring(1, email.lastIndexOf("@")-1);
        return email.replaceAll(email.substring(1, email.lastIndexOf("@")-1),replacewith(str.length(),"*"));
    }
    private static String replacewith(int length,String replace) {
        String finalStr="";
        for(int i=0;i<length;i++){
            finalStr+=replace;
        }
        return finalStr;
    }   
}

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

CSS Div stretch 100% page height

I ran into the same problem as you. I wanted to make a DIV as background, why, because its easy to manipulate div through javascript. Anyways three things I did in the css for that div.

CSS:

{    
position:absolute; 
display:block; 
height:100%; 
width:100%; 
top:0px; 
left:0px; 
z-index:-1;    
}

Tuples( or arrays ) as Dictionary keys in C#

Between tuple and nested dictionaries based approaches, it's almost always better to go for tuple based.

From maintainability point of view,

  • its much easier to implement a functionality that looks like:

    var myDict = new Dictionary<Tuple<TypeA, TypeB, TypeC>, string>();
    

    than

    var myDict = new Dictionary<TypeA, Dictionary<TypeB, Dictionary<TypeC, string>>>();
    

    from the callee side. In the second case each addition, lookup, removal etc require action on more than one dictionary.

  • Furthermore, if your composite key require one more (or less) field in future, you will need to change code a significant lot in the second case (nested dictionary) since you have to add further nested dictionaries and subsequent checks.

From performance perspective, the best conclusion you can reach is by measuring it yourself. But there are a few theoretical limitations which you can consider beforehand:

  • In the nested dictionary case, having an additional dictionary for every keys (outer and inner) will have some memory overhead (more than what creating a tuple would have).

  • In the nested dictionary case, every basic action like addition, updation, lookup, removal etc need to be carried out in two dictionaries. Now there is a case where nested dictionary approach can be faster, i.e., when the data being looked up is absent, since the intermediate dictionaries can bypass the full hash code computation & comparison, but then again it should be timed to be sure. In presence of data, it should be slower since lookups should be performed twice (or thrice depending on nesting).

  • Regarding tuple approach, .NET tuples are not the most performant when they're meant to be used as keys in sets since its Equals and GetHashCode implementation causes boxing for value types.

I would go with tuple based dictionary, but if I want more performance, I would use my own tuple with better implementation.


On a side note, few cosmetics can make the dictionary cool:

  1. Indexer style calls can be a lot cleaner and intuitive. For eg,

    string foo = dict[a, b, c]; //lookup
    dict[a, b, c] = ""; //update/insertion
    

    So expose necessary indexers in your dictionary class which internally handles the insertions and lookups.

  2. Also, implement a suitable IEnumerable interface and provide an Add(TypeA, TypeB, TypeC, string) method which would give you collection initializer syntax, like:

    new MultiKeyDictionary<TypeA, TypeB, TypeC, string> 
    { 
        { a, b, c, null }, 
        ...
    };
    

How to dynamically add a class to manual class names?

A simple possible syntax will be:

<div className={`wrapper searchDiv ${this.state.something}`}>

How to get a table cell value using jQuery?

try this :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
    <title>Untitled</title>

<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    alert(targ.innerHTML);
}

onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;
}

</script>



<body>

<table id="main"><tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
</tr><tr>
    <td>5</td>
    <td>6</td>
    <td>7</td>
    <td>8</td>
</tr><tr>
    <td>9</td>
    <td>10</td>
    <td>11</td>
    <td>12</td>
</tr></table>

</body>
</html>

How to check if a column exists before adding it to an existing table in PL/SQL?

Normally, I'd suggest trying the ANSI-92 standard meta tables for something like this but I see now that Oracle doesn't support it.

-- this works against most any other database
SELECT
    * 
FROM 
    INFORMATION_SCHEMA.COLUMNS C 
    INNER JOIN 
        INFORMATION_SCHEMA.TABLES T 
        ON T.TABLE_NAME = C.TABLE_NAME 
WHERE 
    C.COLUMN_NAME = 'columnname'
    AND T.TABLE_NAME = 'tablename'

Instead, it looks like you need to do something like

-- Oracle specific table/column query
SELECT
    * 
FROM
    ALL_TAB_COLUMNS 
WHERE
    TABLE_NAME = 'tablename'
    AND COLUMN_NAME = 'columnname'

I do apologize in that I don't have an Oracle instance to verify the above. If it does not work, please let me know and I will delete this post.

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Rounding integer division (instead of truncating)

From Linux kernel (GPLv2):

/*
 * Divide positive or negative dividend by positive divisor and round
 * to closest integer. Result is undefined for negative divisors and
 * for negative dividends if the divisor variable type is unsigned.
 */
#define DIV_ROUND_CLOSEST(x, divisor)(          \
{                           \
    typeof(x) __x = x;              \
    typeof(divisor) __d = divisor;          \
    (((typeof(x))-1) > 0 ||             \
     ((typeof(divisor))-1) > 0 || (__x) > 0) ?  \
        (((__x) + ((__d) / 2)) / (__d)) :   \
        (((__x) - ((__d) / 2)) / (__d));    \
}                           \
)

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

The first problem is that your query string is wrong:

I think this: "INSERT INTO employee(hans,germany) values(?,?)" should be like this: "INSERT INTO employee(name,country) values(?,?)"

The other problem is that you have a parameterized PreparedStatement and you don't set the parameters before running it.

You should add these to your code:

String inserting = "INSERT INTO employee(name,country) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1,"hans"); // <----- this
ps.setString(2,"germany");// <---- and this
ps.executeUpdate();

What does -1 mean in numpy reshape?

It is fairly easy to understand. The "-1" stands for "unknown dimension" which can should be infered from another dimension. In this case, if you set your matrix like this:

a = numpy.matrix([[1, 2, 3, 4], [5, 6, 7, 8]])

Modify your matrix like this:

b = numpy.reshape(a, -1)

It will call some deafult operations to the matrix a, which will return a 1-d numpy array/martrix.

However, I don't think it is a good idea to use code like this. Why not try:

b = a.reshape(1,-1)

It will give you the same result and it's more clear for readers to understand: Set b as another shape of a. For a, we don't how much columns it should have(set it to -1!), but we want a 1-dimension array(set the first parameter to 1!).

How to create an Excel File with Nodejs?

XLSx in the new Office is just a zipped collection of XML and other files. So you could generate that and zip it accordingly.

Bonus: you can create a very nice template with styles and so on:

  1. Create a template in 'your favorite spreadsheet program'
  2. Save it as ODS or XLSx
  3. Unzip the contents
  4. Use it as base and fill content.xml (or xl/worksheets/sheet1.xml) with your data
  5. Zip it all before serving

However I found ODS (openoffice) much more approachable (excel can still open it), here is what I found in content.xml

<table:table-row table:style-name="ro1">
    <table:table-cell office:value-type="string" table:style-name="ce1">
        <text:p>here be a1</text:p>
    </table:table-cell>
    <table:table-cell office:value-type="string" table:style-name="ce1">
        <text:p>here is b1</text:p>
    </table:table-cell>
    <table:table-cell table:number-columns-repeated="16382"/>
</table:table-row>

Javascript: 'window' is not defined

The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.

Fit image into ImageView, keep aspect ratio and then resize ImageView to image dimensions?

Use Simple math to resize the image . either you can resize ImageView or you can resize drawable image than set on ImageView . find the width and height of your bitmap which you want to set on ImageView and call the desired method. suppose your width 500 is greater than height than call method

//250 is the width you want after resize bitmap
Bitmat bmp = BitmapScaler.scaleToFitWidth(bitmap, 250) ;
ImageView image = (ImageView) findViewById(R.id.picture);
image.setImageBitmap(bmp);

You use this class for resize bitmap.

public class BitmapScaler{
// Scale and maintain aspect ratio given a desired width
// BitmapScaler.scaleToFitWidth(bitmap, 100);
 public static Bitmap scaleToFitWidth(Bitmap b, int width)
  {
    float factor = width / (float) b.getWidth();
    return Bitmap.createScaledBitmap(b, width, (int) (b.getHeight() * factor), true);
  }


  // Scale and maintain aspect ratio given a desired height
  // BitmapScaler.scaleToFitHeight(bitmap, 100);
  public static Bitmap scaleToFitHeight(Bitmap b, int height)
  {
    float factor = height / (float) b.getHeight();
    return Bitmap.createScaledBitmap(b, (int) (b.getWidth() * factor), height, true);
   }
 }

xml code is

<ImageView
android:id="@+id/picture"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:adjustViewBounds="true"
android:scaleType="fitcenter" />

How to list active / open connections in Oracle?

Use the V$SESSION view.

V$SESSION displays session information for each current session.

How can I get the key value in a JSON object?

Try out this

var str ="{ "name" : "user"}";
var jsonData = JSON.parse(str);     
console.log(jsonData.name)

//Array Object

str ="[{ "name" : "user"},{ "name" : "user2"}]";
jsonData = JSON.parse(str);     
console.log(jsonData[0].name)

Disabling and enabling a html input button

Using Javascript

  • Disabling a html button

    document.getElementById("Button").disabled = true;
    
  • Enabling a html button

    document.getElementById("Button").disabled = false;
    
  • Demo Here


Using jQuery

All versions of jQuery prior to 1.6

  • Disabling a html button

    $('#Button').attr('disabled','disabled');
    
  • Enabling a html button

    $('#Button').removeAttr('disabled');
    
  • Demo Here

All versions of jQuery after 1.6

  • Disabling a html button

    $('#Button').prop('disabled', true);
    
  • Enabling a html button

    $('#Button').prop('disabled', false);
    
  • Demo Here

P.S. Updated the code based on jquery 1.6.1 changes. As a suggestion, always use the latest jquery files and the prop() method.

How do I format date in jQuery datetimepicker?

Here you go.

$('#timePicker').datetimepicker({
   // dateFormat: 'dd-mm-yy',
   format:'DD/MM/YYYY HH:mm:ss',
    minDate: getFormattedDate(new Date())
});

function getFormattedDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getFullYear().toString().slice(2);
    return day + '-' + month + '-' + year;
}

You need to pass datepicker() the date formatted correctly.

How to get error message when ifstream open fails

Every system call that fails update the errno value.

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.

On system with POSIX standard:

errno is thread-local; setting it in one thread does not affect its value in any other thread.


Edit (thanks to Arne Mertz and other people in the comments):

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

Where can I find the Java SDK in Linux after installing it?

Simple, try it:

It's /usr/local/java/jdk[version]

What's the best way to check if a file exists in C?

Use stat like this:

#include <sys/stat.h>   // stat
#include <stdbool.h>    // bool type

bool file_exists (char *filename) {
  struct stat   buffer;   
  return (stat (filename, &buffer) == 0);
}

and call it like this:

#include <stdio.h>      // printf

int main(int ac, char **av) {
    if (ac != 2)
        return 1;

    if (file_exists(av[1]))
        printf("%s exists\n", av[1]);
    else
        printf("%s does not exist\n", av[1]);

    return 0;
}

Update Eclipse with Android development tools v. 23

This worked for me. I kept upgrading to version 23.02 (or 23.03 if presented) using a new install of ADT bundle, and migrating the your original workspace across and add the patches. This is the procedure for ADT Bundle only.

(Backup your workspace first)

1/ install latest adt bundle from google. (For some reason using Googles download page just goes around in a loop on Chrome!?!)

2/ download the patch from here:

3/ Apply the patch as per Googles (poorly described) instructions


...and copy over the following files:

tools/hprof-conv
tools/support/annotations.jar
tools/proguard

Which means => Copy the file only of tools/hprof-conv
Which means => Copy the file only of tools/support/annotations.jar
Which means => Copy the directory and all contents for tools/proguard

3/ Point your old workspace to the new install on startup. (Projects will still come up with errors, don't worry)

4/ select Help-> Install new software, select update site, and select version 23.03 when prompted.

  • Check the update sites, and edit the one for google from https => http like this: Change to "http". This seems to make Eclipse Updater build a new update profile that avoided download errors. You might also get "unsigned" prompt warning prompts from Windoze but just "Allow Access" to prevent blocking.

5/ If you still get errors on references to "android.R", this is because you may not have the appropriate "platform build tools". Check the "Android SDK Manager" for which build tools you have like this: enter image description here Also check your "Android" build for the project to make sure you have the compatible Android API.

Version 23.02 should be downloaded, and your projects should now compile.

Google have abandoned all the UI trimmings for Eclipse ADT (ie you'll see the Juno splash). I thought this would be a problem but it seems ok. I think it shows how desperate Google were to get the fix out. Given that Android studio is not far away Google don't want invest any more time into ADT. I suppose this is what you get with "free" software. Hopefully the adults are back in charge now, and Google Studio won't be such a disaster.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

You actually do not have to wait a full second for each request. I found that if I wait 200 miliseconds between each request I am able to avoid the OVER_QUERY_LIMIT response and the user experience is passable. With this solution you can load 20 items in 4 seconds.

$(items).each(function(i, item){

  setTimeout(function(){

    geoLocate("my address", function(myLatlng){
      ...
    });

  }, 200 * i);

}

Java Date cut off time information

Here's a simple way to get date without time if you are using Java 8+: Use java.time.LocalDate type instead of Date.

LocalDate now = LocalDate.now();
 System.out.println(now.toString());

The output:

2019-05-30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

How to fix Error: listen EADDRINUSE while using nodejs?

On Debian i found out to run on port 80 you need to issue the command as root i.e

sudo node app.js

I hope it helps

Android WebView not loading URL

First, check if you have internet permission in Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

You can then add following code in onCreate() or initialize() method-

final WebView webview = (WebView) rootView.findViewById(R.id.webview);
        webview.setWebViewClient(new MyWebViewClient());
        webview.getSettings().setBuiltInZoomControls(false);
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.loadUrl(URL);

And write a class to handle callbacks of webview -

public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                           //your handling...
                return super.shouldOverrideUrlLoading(view, url);
        }
    }

in same class, you can also use other important callbacks such as -

- onPageStarted()
- onPageFinished()
- onReceivedSslError()

Also, you can add "SwipeRefreshLayout" to enable swipe refresh and refresh the webview.

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

And refresh the webview when user swipes screen:

SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(false);
                            webview.reload();
                        }
                    }, 3000);
                }
            });

How do I determine height and scrolling position of window in jQuery?

$(window).height()

$(window).width()

There is also a plugin to jquery to determine element location and offsets

http://plugins.jquery.com/project/dimensions

scrolling offset = offsetHeight property of an element

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

How to use Console.WriteLine in ASP.NET (C#) during debug?

Make sure you start your application in Debug mode (F5), not without debugging (Ctrl+F5) and then select "Show output from: Debug" in the Output panel in Visual Studio.

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Same error i faced in eclipse version Oxygen.3a Release (4.7.3a) . There is issue in Maven Dependencies mismatch.To solve i have updated my Pom.xml with following dependecies.

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.netapp.junitnmactiopractice JunitAndMactioPractice 0.0.1-SNAPSHOT

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <junit.jupiter.version>5.1.1</junit.jupiter.version>
    <junit.platform.version>1.1.1</junit.platform.version>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

How can javascript upload a blob?

I was able to get @yeeking example to work by not using FormData but using javascript object to transfer the blob. Works with a sound blob created using recorder.js. Tested in Chrome version 32.0.1700.107

function uploadAudio( blob ) {
  var reader = new FileReader();
  reader.onload = function(event){
    var fd = {};
    fd["fname"] = "test.wav";
    fd["data"] = event.target.result;
    $.ajax({
      type: 'POST',
      url: 'upload.php',
      data: fd,
      dataType: 'text'
    }).done(function(data) {
        console.log(data);
    });
  };
  reader.readAsDataURL(blob);
}

Contents of upload.php

<?
// pull the raw binary data from the POST array
$data = substr($_POST['data'], strpos($_POST['data'], ",") + 1);
// decode it
$decodedData = base64_decode($data);
// print out the raw data,
$filename = $_POST['fname'];
echo $filename;
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $decodedData);
fclose($fp);
?>

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

Enable Multidex through build.gradle of your app module

multiDexEnabled true

Same as below -

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

Then follow below steps -

  1. From the Build menu -> press the Clean Project button.
  2. When task completed, press the Rebuild Project button from the Build menu.
  3. From menu File -> Invalidate cashes / Restart

compile is now deprecated so it's better to use implementation or api

how to start the tomcat server in linux?

Go to the appropriate subdirectory of the EDQP Tomcat installation directory. The default directories are:

On Linux: /opt/server/tomcat/bin

On Windows: c:\server\tomcat\bin

Run the startup command:

On Linux: ./startup.sh

On Windows: % startup.bat

Run the shutdown command:

On Linux: ./shutdown.sh

On Windows: % shutdown.bat

How do you refresh the MySQL configuration file without restarting?

You were so close! The kill -HUP method wasn't working for me either.

You were calling:

select @@global.max_connections;

All you needed was to set instead of select:

set @@global.max_connections = 400;

See:

http://www.netadmintools.com/art573.html

http://www.electrictoolbox.com/update-max-connections-mysql/

SUM OVER PARTITION BY

You could have used DISTINCT or just remove the PARTITION BY portions and use GROUP BY:

SELECT BrandId
       ,SUM(ICount)
       ,TotalICount = SUM(ICount) OVER ()    
       ,Percentage = SUM(ICount) OVER ()*1.0 / SUM(ICount) 
FROM Table 
WHERE DateId  = 20130618
GROUP BY BrandID

Not sure why you are dividing the total by the count per BrandID, if that's a mistake and you want percent of total then reverse those bits above to:

SELECT BrandId
           ,SUM(ICount)
           ,TotalICount = SUM(ICount) OVER ()    
           ,Percentage = SUM(ICount)*1.0 / SUM(ICount) OVER () 
    FROM Table 
    WHERE DateId  = 20130618
    GROUP BY BrandID

rand() returns the same number each time the program is run

For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.

rand() % 101

in addition to calling srand() as mentioned by others.

Use latest version of Internet Explorer in the webbrowser control

A cheap and easy workaround for it is that you can just put a value which is bigger than 11001 in the FEATURE_BROWSER_EMULATION key. Then it takes the latest IE that is available in the system.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

How to convert string to XML using C#

xDoc.LoadXML("<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer>                    
                    </body></head>");

ReactJS: setTimeout() not working?

There's a 3 ways to access the scope inside of the 'setTimeout' function

First,

const self = this
setTimeout(function() {
  self.setState({position:1})
}, 3000)

Second is to use ES6 arrow function, cause arrow function didn't have itself scope(this)

setTimeout(()=> {
   this.setState({position:1})
}, 3000)

Third one is to bind the scope inside of the function

setTimeout(function(){
   this.setState({position:1})
}.bind(this), 3000)

Insert results of a stored procedure into a temporary table

Here is my T-SQL with parameters

--require one time execution if not configured before
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO

--require one time execution if not configured before
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO


--the query
DECLARE @param1 int = 1, @param2 int = 2
DECLARE @SQLStr varchar(max) = 'SELECT * INTO #MyTempTable
                                FROM OPENROWSET(''SQLNCLI'',  
''Server=ServerName;Database=DbName;Trusted_Connection=yes'',
''exec StoredProcedureName '+ CAST(@param1 AS varchar(15)) +','+ CAST(@param2 AS varchar(15)) +''') AS a ;
 select * from #MyTempTable;
 drop table #MyTempTable        
';
EXECUTE(@SQLStr);

How can I select from list of values in Oracle

You can do this:

create type number_tab is table of number;

select * from table (number_tab(1,2,3,4,5,6));

The column is given the name COLUMN_VALUE by Oracle, so this works too:

select column_value from table (number_tab(1,2,3,4,5,6));

Extract substring from a string

substring(int startIndex, int endIndex)

If you don't specify endIndex, the method will return all the characters from startIndex.

startIndex : starting index is inclusive

endIndex : ending index is exclusive

Example:

String str = "abcdefgh"

str.substring(0, 4) => abcd

str.substring(4, 6) => ef

str.substring(6) => gh

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

Dark theme in Netbeans 7 or 8

Darcula

UPDATE 2016-02: NetBeans 8 now has a Darcula plugin, better and more complete than the alternatives discussed in old version of this Answer.

The attractive and productive Darcula theme in JetBrains IntelliJ is now available in NetBeans 8.0 & 8.1!

The Real Thing

This plugin provides the real Darcula, not an imitation.

Konstantin Bulenkov of the JetBrains company open-sourced the Darcula look-and-feel originally built for the IntelliJ IDE. This NetBeans plugin discussed here wraps that original implementation, adapting it to NetBeans. So we see close fidelity to the original Darcula. [By the way, there are many other reasons beyond Darcula to use IntelliJ – both IntelliJ and NetBeans are truly excellent and amazing products.]

This NetBeans plugin is itself open-source as well.

Installation

Comes in two parts:

  • A plugin
  • A Fonts & Colors profile

Plugin

The plugin Darcula LAF for NetBeans is easily available through the usual directory within NetBeans.

Choose Tools > Plugins. On the Available Plugins tab, scroll or search for "Darcula LAF for NetBeans". As per usual, check the checkbox and click the Install button. Restart NetBeans.

enter image description here

Profile

  1. In NetBeans > Preferences > Fonts & Colors (tab) > Profile (popup menu), choose the new Darcula item.
  2. Click the Apply button.

I suggest also hitting Duplicate in case you ever make any modifications (discussed below).

enter image description here

Fix overly-bright background colors

You may find the background color of lines of code may be too bright such as lines marked with a breakpoint, or the currently executing line in the debugger. These are categories listed on the Annotations tab of the Fonts & Colors tab.

Of course you can change the background color of each Category manually but that is tedious.

Workaround: Click the Restore button found to the right of the Profile name. Double-check to make sure you have Darcula as the selected Profile of course. Then click the Apply and OK buttons at the bottom.

enter image description here

Font

You may want to change the font in the method editor. I most highly recommend the commercial font for programmers, PragmataPro. For a free-of-cost and open-source font, the best is Hack. Hack was built on the very successful DejaVu font which in turn was built on Bitstream Vera.

To change the font, add these steps to the above to duplicate the profile as a backup before making your modification:

  1. Click the Duplicate button.
  2. Save the duplicate with a different name such as appending your name.
    Example: “Darcula - Juliette”.
  3. Click the Apply button.

While in that same Fonts & Colors tab, select Default in the Category list and hit the button to choose a font.

You might also want to change the font seen in the Output and the Terminal panes. From that Fonts & Colors tab, switch to the sibling tab Miscellaneous. Then see both the Output tab and the Terminal tab.

Experience So Far

While still new I am reserving final judgement on Darcula. So far, so good. Already the makers have had a few updates fixing a few glitches, so that is good to see. This seems to be a very thorough product. As a plugin this affects the entire user interface of NetBeans; that can be very tricky to get right.

There was a similar plugin product predating Darcula: the “Dark Look And Feel Themes” plugin. While I was grateful to use that for a while, I am much happier with Darcula. That other one was more clunky and I had to spend much time tweaking colors of “Norway Today” to work together. Also, that plugin was not savvy with Mac OS X menus so the main Mac menu bar was nearly empty while NetBeans’ own menu bar was embedded within the window. The Darcula plugin has no such problem; the Mac menu bar appears normally.


The rest of this Answer is left intact for history, and for alternatives if Darcula proves problematic.


NetBeans 8 – Dark Editor

At least in NetBeans 8.0, two dark profiles are now built-in. Profile names:

  • Norway Today
  • City Lights

The profiles affect only the code editing pane, not the entire NetBeans user-interface. That should mean much less risk of side-effects and bugs than a plugin.

Norway Today

screen shot of NetBeans editor using the dark profile 'Norway Today'

City Lights

screen shot of NetBeans editor using the dark profile 'City Lights'

Tip: You can alter the font in either theme, while preserving the other aspects. Perhaps Menlo on a Mac, or its parent DejaVu. Or my fav, the commercial font Pragmata.

Unfortunately, neither theme suits my eyes. They do not begin to compare to the excellent Darcula theme in JetBrains IntelliJ.

Choose Profile in Font Settings

On a Mac, the menu path is Netbeans > Preferences > Fonts & Colors (tab) > Profile (popup menu).

On other host operating systems, the menu path may be Tools > Options > Fonts & Colors. Not sure, but it was so in previous versions.

screen shot of picking either of the built-in dark themes in NetBeans 8 Prefences > Fonts & Colors > Profile pop-up menu

How do I get this javascript to run every second?

Use setInterval:

$(function(){
setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
// stuff you want to do every second
}

Here's an article on the difference between setTimeout and setInterval. Both will provide the functionality you need, they just require different implementations.

Android - Center TextView Horizontally in LinearLayout

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/title_bar_background">

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:padding="10dp"
    android:text="HELLO WORLD" />

</LinearLayout>

Run JavaScript code on window close or page refresh?

You can use window.onbeforeunload.

window.onbeforeunload = confirmExit;
function confirmExit(){
    alert("confirm exit is being called");
    return false;
}

Change language of Visual Studio 2017 RC

Polish-> English (VS on MAC) answer: When I started a project and was forced to download Visual Studio, went to their page and saw that Microsoft logo I knew there would be problems... And here it is. It occurred difficult to change the language of VS on Mac. My OS is purely English and only because of the fact I downloaded it using a browser with Polish set as a default language I got the wrong version. I had to reinstall the version to the newest and then Visual Studio Community -> Preferences(in the environment section) -> Visual Style-> User Interface Language.

It translates to polish: Visual Studio Community -> Preferencje -> Styl Wizualny w sekcji Srodowisko -> Jezyk interfejsu uzytkownika -> English.

If you don't see such an option then, as I was, you are forced to upgrade this crappy VS to the newest version.

Delete a database in phpMyAdmin

After successful login to cPanel, near to the phpMyAdmin icon there is another icon MySQL Databases; click on that.

enter image description here

That brings you to the database listing page.

In the action column you can find the delete database option click on that to delete your database!

How do I run msbuild from the command line using Windows SDK 7.1?

Your bat file could be like:

CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319

msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj

PAUSE

EXIT

Python idiom to return first item or None

How about this:

(my_list and my_list[0]) or None

Note: This should work fine for lists of objects but it might return incorrect answer in case of number or string list per the comments below.

Spring - @Transactional - What happens in background?

When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).

However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.

As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.

Does that help?

CSS root directory

This problem that the "../" means step up (parent folder) link "../images/img.png" will not work because when you are using ajax like data passing to the web site from the server.

What you have to do is point the image location to root with "./" then the second folder (in this case the second folder is "images")

url("./images/img.png")

if you have folders like this

root -> content -> images

then you use url("./content/images/img.png"), remember your image will not visible in the editor window but when it passed to the browser using ajax it will display.

What is difference between cacerts and keystore?

Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security. Your JAVA_HOME should always be ../JAVA/JDK.

JavaScript array to CSV

The cited answer was wrong. You had to change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

to

csvContent += dataString + "\n";

As to why the cited answer was wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

EDIT

Six years have passed now since I wrote this answer. Many things have changed, including browsers. The following was part of the answer:

START of aged part

BTW, the cited code is suboptimal. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

END of aged part

(Keep in mind that the CSV case is a bit different from generic string concatenation, since for every string you also have to add the separator.)

Anyway, the above seems not to be true anymore, at least not for Chrome and Firefox (it seems to still be true for Safari, though).

To put an end to uncertainty, I wrote a jsPerf test that tests whether, in order to concatenate strings in a comma-separated way, it's faster to push them onto an array and join the array, or to concatenate them first with the comma, and then directly with the result string using the += operator.

Please follow the link and run the test, so that we have enough data to be able to talk about facts instead of opinions.

How To Make Circle Custom Progress Bar in Android

I've encountered same problem and not found any appropriate solution for my case, so I decided to go another way. I've created custom drawable class. Within this class I've created 2 Paints for progress line and background line (with some bigger stroke). First of all set startAngle and sweepAngle in constructor:

    mSweepAngle = 0;
    mStartAngle = 270;

Here is onDraw method of this class:

@Override
public void draw(Canvas canvas) {
    // draw background line
    canvas.drawArc(mRectF, 0, 360, false, mPaintBackground);
    // draw progress line
    canvas.drawArc(mRectF, mStartAngle, mSweepAngle, false, mPaintProgress);
}

So now all you need to do is set this drawable as a backgorund of the view, in background thread change sweepAngle:

mSweepAngle += 360 / totalTimerTime // this is mStep

and directly call InvalidateSelf() with some interval (e.g every 1 second or more often if you want smooth progress changes) on the view that have this drawable as a background. Thats it!

P.S. I know, I know...of course you want some more code. So here it is all flow:

  1. Create XML view :

     <View
     android:id="@+id/timer"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>
    
  2. Create and configure Custom Drawable class (as I described above). Don't forget to setup Paints for lines. Here paint for progress line:

    mPaintProgress = new Paint();
    mPaintProgress.setAntiAlias(true);
    mPaintProgress.setStyle(Paint.Style.STROKE);
    mPaintProgress.setStrokeWidth(widthProgress);
    mPaintProgress.setStrokeCap(Paint.Cap.ROUND);
    mPaintProgress.setColor(colorThatYouWant);
    

Same for backgroung paint (set width little more if you want)

  1. In drawable class create method for updating (Step calculation described above)

    public void update() {
        mSweepAngle += mStep;
        invalidateSelf();
    }
    
  2. Set this drawable class to YourTimerView (I did it in runtime) - view with @+id/timer from xml above:

    OurSuperDrawableClass superDrawable = new OurSuperDrawableClass(); YourTimerView.setBackgroundDrawable(superDrawable);

  3. Create background thread with runnable and update view:

    YourTimerView.post(new Runnable() {
        @Override
        public void run() {
            // update progress view
            superDrawable.update();
        }
    });
    

Thats it ! Enjoy your cool progress bar. Here screenshot of result if you're too bored of this amount of text.enter image description here

How do I record audio on iPhone with AVAudioRecorder?

for wav format below audio setting

NSDictionary *audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat:44100.0],AVSampleRateKey,
                              [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                              [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                              [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                              [NSNumber numberWithBool:NO], AVLinearPCMIsFloatKey, 
                              [NSNumber numberWithBool:0], AVLinearPCMIsBigEndianKey,
                              [NSNumber numberWithBool:NO], AVLinearPCMIsNonInterleaved,
                              [NSData data], AVChannelLayoutKey, nil];

ref: http://objective-audio.jp/2010/09/avassetreaderavassetwriter.html

What is the meaning of "POSIX"?

In 1985, individuals from companies throughout the computer industry joined together to develop the POSIX (Portable Operating System Interface for Computer Environments) standard, which is based largely on the UNIX System V Interface Definition (SVID) and other earlier standardization efforts. These efforts were spurred by the U.S. government, which needed a standard computing environment to minimize its training and procurement costs. Released in 1988, POSIX is a group of IEEE standards that define the API, shell, and utility interfaces for an operating system. Although aimed at UNIX-like systems, the standards can apply to any compatible operating system. Now that these stan- dards have gained acceptance, software developers are able to develop applications that run on all conforming versions of UNIX, Linux, and other operating systems.

From the book: A Practical Guide To Linux

MySQL maximum memory usage

in /etc/my.cnf:

[mysqld]
...

performance_schema = 0

table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000

query_cache_size = 0
query_cache_limit = 0

...

Good work on server with 256MB Memory.

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.

How do I return to an older version of our code in Subversion?

The following has worked for me.

I had a lot of local changes and needed to discard those in the local copy and checkout the last stable version in SVN.

  1. Check the status of all files, including the ignored files.

  2. Grep all the lines to get the newly added and ignored files.

  3. Replace those with //.

  4. and rm -rf all the lines.

    svn status --no-ignore | grep '^[?I]' | sed "s/^[?I] //" | xargs -I{} rm -rf "{}"

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

How do I get the YouTube video ID from a URL?

Since YouTube video ids is set to be 11 characters, we can simply just substring after we split the url with v=. Then we are not dependent on the ampersand at the end.

var sampleUrl = "http://www.youtube.com/watch?v=JcjoGn6FLwI&asdasd";

var video_id = sampleUrl.split("v=")[1].substring(0, 11)

Nice and simple :)

Could not load type from assembly error

I get this occasionally and it's always been down to have the assembly in the GAC

Setting Action Bar title and subtitle

Nope! You have to do it at runtime.

If you want to make your app backwards compatible, then simply check the device API level. If it is higher than 11, then you can fiddle with the ActionBar and set the subtitle.

if(Integer.valueOf(android.os.Build.VERSION.SDK) >= 11){
    //set actionbar title
}

Text border using css (border around text)

The following will cover all browsers worth covering:

text-shadow: 0 0 2px #fff; /* Firefox 3.5+, Opera 9+, Safari 1+, Chrome, IE10 */
filter: progid:DXImageTransform.Microsoft.Glow(Color=#ffffff,Strength=1); /* IE<10 */

How to delete session cookie in Postman?

Manually deleting it in the chrome browser removes the cookie from Postman.

In your chrome browser go to chrome://settings/cookies

Find the cookie and delete it

Edit: As per Max890 comment below (in my version of Google Chrome (ver 63)) this is now chrome://settings/content/cookies Then go to "See all cookies and site data"

Update for Google Chrome 79.0.3945.88

chrome://settings/siteData?search=cookies

How can I query a value in SQL Server XML column

select
  Roles
from
  MyTable
where
  Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'

In case your column is not XML, you need to convert it. You can also use other syntax to query certain attributes of your XML data. Here is an example...

Let's suppose that data column has this:

<Utilities.CodeSystems.CodeSystemCodes iid="107" CodeSystem="2" Code="0001F" CodeTags="-19-"..../>

... and you only want the ones where CodeSystem = 2 then your query will be:

select 
  [data] 
from
  [dbo].[CodeSystemCodes_data]
  
where
  CAST([data] as XML).value('(/Utilities.CodeSystems.CodeSystemCodes/@CodeSystem)[1]', 'varchar(max)') = '2'

These pages will show you more about how to query XML in T-SQL:

Querying XML fields using t-sql

Flattening XML Data in SQL Server

EDIT

After playing with it a little bit more, I ended up with this amazing query that uses CROSS APPLY. This one will search every row (role) for the value you put in your like expression...

Given this table structure:

create table MyTable (Roles XML)

insert into MyTable values
('<root>
   <role>Alpha</role>
   <role>Gamma</role>
   <role>Beta</role>
</root>')

We can query it like this:

select * from 

(select 
       pref.value('(text())[1]', 'varchar(32)') as RoleName
from 
       MyTable CROSS APPLY

       Roles.nodes('/root/role') AS Roles(pref)
)  as Result

where RoleName like '%ga%'

You can check the SQL Fiddle here: http://sqlfiddle.com/#!18/dc4d2/1/0

Using stored procedure output parameters in C#

Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:

DECLARE @NewId int
EXEC    @return_value = [dbo].[usp_InsertContract]
            N'Gary',
            @NewId OUTPUT
SELECT  @NewId

See what it returns. This may give you some hints of why your out param is not filled.

How can I make my match non greedy in vim?

Plugin eregex.vim handles Perl-style non-greedy operators *? and +?

.htaccess rewrite to redirect root URL to subdirectory

try to use below lines in htaccess

Note: you may need to check what is the name of the default.html

default.html is the file that load by default in the root folder.

RewriteEngine

Redirect /default.html http://example.com/store/

CSS hide scroll bar if not needed

Set overflow-y property to auto, or remove the property altogether if it is not inherited.

Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

We can use query instead of queryForObject, major difference between query and queryForObject is that query return list of Object(based on Row mapper return type) and that list can be empty if no data is received from database while queryForObject always expect only single object be fetched from db neither null nor multiple rows and in case if result is empty then queryForObject throws EmptyResultDataAccessException, I had written one code using query that will overcome the problem of EmptyResultDataAccessException in case of null result.

----------


public UserInfo getUserInfo(String username, String password) {
      String sql = "SELECT firstname, lastname,address,city FROM users WHERE id=? and pass=?";
      List<UserInfo> userInfoList = jdbcTemplate.query(sql, new Object[] { username, password },
              new RowMapper<UserInfo>() {
                  public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
                      UserInfo user = new UserInfo();
                      user.setFirstName(rs.getString("firstname"));
                      user.setLastName(rs.getString("lastname"));
                      user.setAddress(rs.getString("address"));
                      user.setCity(rs.getString("city"));

                      return user;
                  }
              });

      if (userInfoList.isEmpty()) {
          return null;
      } else {
          return userInfoList.get(0);
      }
  }

Testing for empty or nil-value string

If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

An Iframe I need to refresh every 30 seconds (but not the whole page)

I have a simpler solution. In your destination page (irc_online.php) add an auto-refresh tag in the header.

Using OpenGl with C#?

XNA 2.0 requires a minimum of a shader 1.1 card. While old tech, not everyone has one. Some newer laptops (in our experience Toshiba tablets with Intel graphics) have no shader 1.1 support. XNA simply wont run on these machines.

This is a significant issue for us and we have shifted to Tao and OpenGL. Plus with Tao we have bindings for audio & Lua support.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

Despite not fully answering the original question, this is probably what most people googling this wanted to see.

For GCC:

$ cat test.cpp 
#include <iostream>

int main(int argc, char **argv)
{
    std::cout << __func__ << std::endl
              << __FUNCTION__ << std::endl
              << __PRETTY_FUNCTION__ << std::endl;
}
$ g++ test.cpp 
$ ./a.out 
main
main
int main(int, char**)

Databinding an enum property to a ComboBox in WPF

you can consider something like that:

  1. define a style for textblock, or any other control you want to use to display your enum:

    <Style x:Key="enumStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Text" Value="&lt;NULL&gt;"/>
        <Style.Triggers>
            <Trigger Property="Tag">
                <Trigger.Value>
                    <proj:YourEnum>Value1<proj:YourEnum>
                </Trigger.Value>
                <Setter Property="Text" Value="{DynamicResource yourFriendlyValue1}"/>
            </Trigger>
            <!-- add more triggers here to reflect your enum -->
        </Style.Triggers>
    </Style>
    
  2. define your style for ComboBoxItem

    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Tag="{Binding}" Style="{StaticResource enumStyle}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
  3. add a combobox and load it with your enum values:

    <ComboBox SelectedValue="{Binding Path=your property goes here}" SelectedValuePath="Content">
        <ComboBox.Items>
            <ComboBoxItem>
                <proj:YourEnum>Value1</proj:YourEnum>
            </ComboBoxItem>
        </ComboBox.Items>
    </ComboBox>
    

if your enum is large, you can of course do the same in code, sparing a lot of typing. i like that approach, since it makes localization easy - you define all the templates once, and then, you only update your string resource files.

How to use opencv in using Gradle?

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
    maven {
        url 'http://maven2.javacv.googlecode.com/git/'
    }
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
    compile 'com.googlecode.javacv:javacv:0.5'
    instrumentTestCompile 'junit:junit:4.4'
}

android {
    compileSdkVersion 14
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 14
    }
}

This is worked for me :)

How do you performance test JavaScript code?

The golden rule is to NOT under ANY circumstances lock your users browser. After that, I usually look at execution time, followed by memory usage (unless you're doing something crazy, in which case it could be a higher priority).

Python: Get the first character of the first string in a list?

Get the first character of a bare python string:

>>> mystring = "hello"
>>> print(mystring[0])
h
>>> print(mystring[:1])
h
>>> print(mystring[3])
l
>>> print(mystring[-1])
o
>>> print(mystring[2:3])
l
>>> print(mystring[2:4])
ll

Get the first character from a string in the first position of a python list:

>>> myarray = []
>>> myarray.append("blah")
>>> myarray[0][:1]
'b'
>>> myarray[0][-1]
'h'
>>> myarray[0][1:3]
'la'

Many people get tripped up here because they are mixing up operators of Python list objects and operators of Numpy ndarray objects:

Numpy operations are very different than python list operations.

Wrap your head around the two conflicting worlds of Python's "list slicing, indexing, subsetting" and then Numpy's "masking, slicing, subsetting, indexing, then numpy's enhanced fancy indexing".

These two videos cleared things up for me:

"Losing your Loops, Fast Numerical Computing with NumPy" by PyCon 2015: https://youtu.be/EEUXKG97YRw?t=22m22s

"NumPy Beginner | SciPy 2016 Tutorial" by Alexandre Chabot LeClerc: https://youtu.be/gtejJ3RCddE?t=1h24m54s

Declare a Range relative to the Active Cell with VBA

There is an .Offset property on a Range class which allows you to do just what you need

ActiveCell.Offset(numRows, numCols)

follow up on a comment:

Dim newRange as Range
Set newRange = Range(ActiveCell, ActiveCell.Offset(numRows, numCols))

and you can verify by MsgBox newRange.Address

and here's how to assign this range to an array

Add leading zeroes to number in Java?

String.format (https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax)

In your case it will be:

String formatted = String.format("%03d", num);
  • 0 - to pad with zeros
  • 3 - to set width to 3

How can I get a file's size in C++?

Have you considered not computing the file size and just growing the array if necessary? Here's an example (with error checking ommitted):

#define CHUNK 1024

/* Read the contents of a file into a buffer.  Return the size of the file 
 * and set buf to point to a buffer allocated with malloc that contains  
 * the file contents.
 */
int read_file(FILE *fp, char **buf) 
{
  int n, np;
  char *b, *b2;

  n = CHUNK;
  np = n;
  b = malloc(sizeof(char)*n);
  while ((r = fread(b, sizeof(char), CHUNK, fp)) > 0) {
    n += r;
    if (np - n < CHUNK) { 
      np *= 2;                      // buffer is too small, the next read could overflow!
      b2 = malloc(np*sizeof(char));
      memcpy(b2, b, n * sizeof(char));
      free(b);
      b = b2;
    }
  }
  *buf = b;
  return n;
}

This has the advantage of working even for streams in which it is impossible to get the file size (like stdin).

Specifying Font and Size in HTML table

The font tag has been deprecated for some time now.

That being said, the reason why both of your tables display with the same font size is that the 'size' attribute only accepts values ranging from 1 - 7. The smallest size is 1. The largest size is 7. The default size is 3. Any values larger than 7 will just display the same as if you had used 7, because 7 is the maximum value allowed.

And as @Alex H said, you should be using CSS for this.

How do I find all of the symlinks in a directory tree?

Kindly find below one liner bash script command to find all broken symbolic links recursively in any linux based OS

a=$(find / -type l); for i in $(echo $a); do file $i ; done |grep -i broken 2> /dev/null

Print multiple arguments in Python

This was probably a casting issue. Casting syntax happens when you try to combine two different types of variables. Since we cannot convert a string to an integer or float always, we have to convert our integers into a string. This is how you do it.: str(x). To convert to a integer, it's: int(x), and a float is float(x). Our code will be:

print('Total score for ' + str(name) + ' is ' + str(score))

Also! Run this snippet to see a table of how to convert different types of variables!

_x000D_
_x000D_
<table style="border-collapse: collapse; width: 100%;background-color:maroon; color: #00b2b2;">
<tbody>
<tr>
<td style="width: 50%;font-family: serif; padding: 3px;">Booleans</td>
<td style="width: 50%;font-family: serif; padding: 3px;"><code>bool()</code></td>
  </tr>
 <tr>
<td style="width: 50%;font-family: serif;padding: 3px">Dictionaries</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>dict()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Floats</td>
<td style="width: 50%;font-family: serif;padding: 3px"><code>float()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding:3px">Integers</td>
<td style="width: 50%;font-family: serif;padding:3px;"><code>int()</code></td>
</tr>
<tr>
<td style="width: 50%;font-family: serif;padding: 3px">Lists</td>
<td style="width: 50%font-family: serif;padding: 3px;"><code>list()</code></td>
</tr>
</tbody>
</table>
_x000D_
_x000D_
_x000D_

Set size of HTML page and browser window

You could try:

<html>
    <head>
        <style>
            #main {
                width: 500; /*Set to whatever*/
                height: 500;/*Set to whatever*/
            }
        </style>
    </head>
    <body id="main">
    </body>
</html>

How to convert float number to Binary?

Keep multiplying the number after decimal by 2 till it becomes 1.0:

0.25*2 = 0.50
0.50*2 = 1.00

and the result is in reverse order being .01

Iterate through the fields of a struct in Go

If you want to Iterate through the Fields and Values of a struct then you can use the below Go code as a reference.

package main

import (
    "fmt"
    "reflect"
)

type Student struct {
    Fname  string
    Lname  string
    City   string
    Mobile int64
}

func main() {
    s := Student{"Chetan", "Kumar", "Bangalore", 7777777777}
    v := reflect.ValueOf(s)
    typeOfS := v.Type()

    for i := 0; i< v.NumField(); i++ {
        fmt.Printf("Field: %s\tValue: %v\n", typeOfS.Field(i).Name, v.Field(i).Interface())
    }
}

Run in playground

Note: If the Fields in your struct are not exported then the v.Field(i).Interface() will give panic panic: reflect.Value.Interface: cannot return value obtained from unexported field or method.

How to exit an application properly

Application.Exit() does the trick too: any forms you have can still cancel this for instance if you want to present a save changes dialog.

Change windows hostname from command line

If you are looking to do this from Windows 10 IoT, then there is a built in command you can use:

setcomputername [newname]

Unfortunately, this command does not exist in the full build of Windows 10.

Why does adb return offline after the device string?

Run SDk Manager and install Android SDK Tools and Android SDK Platform-tools updates. ADB must be updated to a new version for 4.2.x

How to convert array values to lowercase in PHP?

Just for completeness: you may also use array_walk:

array_walk($yourArray, function(&$value)
{
  $value = strtolower($value);
});

From PHP docs:

If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself.

Or directly via foreach loop using references:

foreach($yourArray as &$value)
  $value = strtolower($value);

Note that these two methods change the array "in place", whereas array_map creates and returns a copy of the array, which may not be desirable in case of very large arrays.

How to install "ifconfig" command in my ubuntu docker image?

You could also consider:

RUN apt-get update && apt-get install -y iputils-ping

(as Contango comments: you must first run apt-get update, to avoid error with missing repository).

See "Replacing ifconfig with ip"

it is most often recommended to move forward with the command that has replaced ifconfig. That command is ip, and it does a great job of stepping in for the out-of-date ifconfig.

But as seen in "Getting a Docker container's IP address from the host", using docker inspect can be more useful depending on your use case.

Why declare unicode by string in python?

I made the following module called unicoder to be able to do the transformation on variables:

import sys
import os

def ustr(string):

    string = 'u"%s"'%string

    with open('_unicoder.py', 'w') as script:

        script.write('# -*- coding: utf-8 -*-\n')
        script.write('_ustr = %s'%string)

    import _unicoder
    value = _unicoder._ustr

    del _unicoder
    del sys.modules['_unicoder']

    os.system('del _unicoder.py')
    os.system('del _unicoder.pyc')

    return value

Then in your program you could do the following:

# -*- coding: utf-8 -*-

from unicoder import ustr

txt = 'Hello, Unicode World'
txt = ustr(txt)

print type(txt) # <type 'unicode'>

Checkbox angular material checked by default

There are several ways you can achieve this based on the approach you take. For reactive approach, you can pass the default value to the constructor of the FormControl(import from @angular/forms)

this.randomForm = new FormGroup({
      'amateur': new FormControl(false),
});

Instead of true or false value, yes you can send variable name as well like FormControl(this.booleanVariable)

In template driven approach you can use 1 way binding [ngModel]="this.booleanVariable" or 2 way binding [(ngModel)]="this.booleanVariable" like this

<mat-checkbox
     name="controlName"
     [(ngModel)]="booleanVariable">
     {{col.title}}
</mat-checkbox>

You can also use the checked directive provided by angular material and bind in similar manner

How can I change the date format in Java?

SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));

Sieve of Eratosthenes - Finding Primes Python

import math
def sieve(n):
    primes = [True]*n
    primes[0] = False
    primes[1] = False
    for i in range(2,int(math.sqrt(n))+1):
            j = i*i
            while j < n:
                    primes[j] = False
                    j = j+i
    return [x for x in range(n) if primes[x] == True]

How to pass the id of an element that triggers an `onclick` event to the event handling function

The element that triggered the event can be different than the one you bound the handler to because events bubble up the DOM tree.

So if you want to get the ID of the element the event handler is bound to, you can do this easily with this.id (this refers to the element).

But if you want to get the element where the event originated, then you have to access it with event.target in W3C compatible browsers and event.srcElement in IE 8 and below.

I would avoid writing a lot of JavaScript in the onXXXX HTML attributes. I would only pass the event object and put the code to extract the element in the handler (or in an extra function):

<div onlick="doWithThisElement(event)">

Then the handler would look like this:

function doWithThisElement(event) {
    event = event || window.event; // IE
    var target = event.target || event.srcElement; // IE

    var id = target.id;
    //...
}

I suggest to read the excellent articles about event handling at quirksmode.org.


Btw

<link onclick="doWithThisElement(id_of_this_element)" />

does hardly make sense (<link> is an element that can only appear in the <head>, binding an event handler (if even possible) will have no effect).

How can you get the Manifest Version number from the App's (Layout) XML variables?

You can use the versionName in XML resources, such as activity layouts. First create a string resource in the app/build.gradle with the following snippet in the android node:

applicationVariants.all { variant ->
    variant.resValue "string", "versionName", variant.versionName
}

So the whole build.gradle file contents may look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0 rc3'
    defaultConfig {
        applicationId 'com.example.myapplication'
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 17
        versionName '0.2.3'
        jackOptions {
            enabled true
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "versionName", variant.versionName
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
} 

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'com.android.support:support-v4:23.3.0'
}

Then you can use @string/versionName in the XML. Android Studio will mark it red, but the app will compile without issues. For example, this may be used like this in app/src/main/res/xml/preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="About"
        android:key="pref_key_about">

        <Preference
            android:key="pref_about_build"
            android:title="Build version"
            android:summary="@string/versionName" />

    </PreferenceCategory>


</PreferenceScreen>

How to resize an image to a specific size in OpenCV?

You can use cvResize. Or better use c++ interface (eg cv::Mat instead of IplImage and cv::imread instead of cvLoadImage) and then use cv::resize which handles memory allocation and deallocation itself.

Session TimeOut in web.xml

You should consider splitting the large file to chunks and rely on multi threading capabilities to process more than one file at a time OR let the whole process run as a background task using TimerTask and write another query to know the status of it form the browser including a progress bar can be shown if you can know the process time of a file or record.

how to use Spring Boot profiles

If you are using the Spring Boot Maven Plugin, run:

mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar

(https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-profiles.html)

Converting Float to Dollars and Cents

In python 3, you can use:

import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )

Output

'$1,234.50'

this.getClass().getClassLoader().getResource("...") and NullPointerException

When eclipse runs the test case it will look for the file in target/classes not src/test/resources. When the resource is saved eclipse should copy it from src/test/resources to target/classes if it has changed but if for some reason this has not happened then you will get this error. Check that the file exists in target/classes to see if this is the problem.