Programs & Examples On #Casing

No provider for HttpClient

You have not provided providers in your module:

<strike>import { HttpModule } from '@angular/http';</strike>
import { HttpClientModule, HttpClient } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule,
    BrowserAnimationsModule,
    FormsModule,
    AppRoutingModule
  ],
  providers: [ HttpClientModule, ... ]
  // ...
})
export class MyModule { /* ... */ }

Using HttpClient in Tests

You will need to add the HttpClientTestingModule to the TestBed configuration when running ng test and getting the "No provider for HttpClient" error:

// Http testing module and mocking controller
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

// Other imports
import { TestBed } from '@angular/core/testing';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

describe('HttpClient testing', () => {
  let httpClient: HttpClient;
  let httpTestingController: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ HttpClientTestingModule ]
    });

    // Inject the http service and test controller for each test
    httpClient = TestBed.get(HttpClient);
    httpTestingController = TestBed.get(HttpTestingController);
  });

  it('works', () => {
  });
});

CSS Border Not Working

Use this line of code in your css

border: 1px solid #000 !important;

or if you want border only in left and right side of container then use:

border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;

Case-Insensitive List Search

I realise this is an old post, but just in case anyone else is looking, you can use Contains by providing the case insensitive string equality comparer like so:

using System.Linq;

// ...

if (testList.Contains(keyword, StringComparer.OrdinalIgnoreCase))
{
    Console.WriteLine("Keyword Exists");
}

This has been available since .net 2.0 according to msdn.

event.preventDefault() vs. return false

I think

event.preventDefault()

is the w3c specified way of canceling events.

You can read this in the W3C spec on Event cancelation.

Also you can't use return false in every situation. When giving a javascript function in the href attribute and if you return false then the user will be redirected to a page with false string written.

Case insensitive 'Contains(string)'

You can use a string comparison parameter (available from .net 2.1 and above) String.Contains Method.

public bool Contains (string value, StringComparison comparisonType);

Example:

string title = "ASTRINGTOTEST";
title.Contains("string", StringComparison.InvariantCultureIgnoreCase);

How do I get Maven to use the correct repositories?

tl;dr

All maven POMs inherit from a base Super POM.
The snippet below is part of the Super POM for Maven 3.5.4.

  <repositories>
    <repository>
      <id>central</id>
      <name>Central Repository</name>
      <url>https://repo.maven.apache.org/maven2</url>
      <layout>default</layout>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>

Count number of lines in a git repository

I was playing around with cmder (http://gooseberrycreative.com/cmder/) and I wanted to count the lines of html,css,java and javascript. While some of the answers above worked, or pattern in grep didn't - I found here (https://unix.stackexchange.com/questions/37313/how-do-i-grep-for-multiple-patterns) that I had to escape it

So this is what I use now:

git ls-files | grep "\(.html\|.css\|.js\|.java\)$" | xargs wc -l

AngularJS : How to watch service variables?

I came to this question but it turned out my problem was that I was using setInterval when I should have been using the angular $interval provider. This is also the case for setTimeout (use $timeout instead). I know it's not the answer to the OP's question, but it might help some, as it helped me.

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

You should initialize yours recordings. You are passing to adapter null

ArrayList<String> recordings = null; //You are passing this null

call a static method inside a class?

Let's assume this is your class:

class Test
{
    private $baz = 1;

    public function foo() { ... }

    public function bar() 
    {
        printf("baz = %d\n", $this->baz);
    }

    public static function staticMethod() { echo "static method\n"; }
}

From within the foo() method, let's look at the different options:

$this->staticMethod();

So that calls staticMethod() as an instance method, right? It does not. This is because the method is declared as public static the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.

$this::staticMethod();

Since PHP 5.3 you can use $var::method() to mean <class-of-$var>::; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:

self::staticMethod();

Now, before you start thinking that the :: is the static call operator, let me give you another example:

self::bar();

This will print baz = 1, which means that $this->bar() and self::bar() do exactly the same thing; that's because :: is just a scope resolution operator. It's there to make parent::, self:: and static:: work and give you access to static variables; how a method is called depends on its signature and how the caller was called.

To see all of this in action, see this 3v4l.org output.

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

In case you are getting this in the eclipse IDE, even after setting the parameters --launcher.XXMaxPermSize, -XX:MaxPermSize, etc, still if you are getting the same error, it most likely is that the eclipse is using a buggy version of JRE which would have been installed by some third party applications and set to default. These buggy versions do not pick up the PermSize parameters and so no matter whatever you set, you still keep getting these memory errors. So, in your eclipse.ini add the following parameters:

-vm <path to the right JRE directory>/<name of javaw executable>

Also make sure you set the default JRE in the preferences in the eclipse to the correct version of java.

What does the 'b' character do in front of a string literal?

Here's an example where the absence of b would throw a TypeError exception in Python 3.x

>>> f=open("new", "wb")
>>> f.write("Hello Python!")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface

Adding a b prefix would fix the problem.

Adding a Method to an Existing Object Instance

Preface - a note on compatibility: other answers may only work in Python 2 - this answer should work perfectly well in Python 2 and 3. If writing Python 3 only, you might leave out explicitly inheriting from object, but otherwise the code should remain the same.

Adding a Method to an Existing Object Instance

I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python.

I understand that it's not always a good decision to do so. But, how might one do this?

Yes, it is possible - But not recommended

I don't recommend this. This is a bad idea. Don't do it.

Here's a couple of reasons:

  • You'll add a bound object to every instance you do this to. If you do this a lot, you'll probably waste a lot of memory. Bound methods are typically only created for the short duration of their call, and they then cease to exist when automatically garbage collected. If you do this manually, you'll have a name binding referencing the bound method - which will prevent its garbage collection on usage.
  • Object instances of a given type generally have its methods on all objects of that type. If you add methods elsewhere, some instances will have those methods and others will not. Programmers will not expect this, and you risk violating the rule of least surprise.
  • Since there are other really good reasons not to do this, you'll additionally give yourself a poor reputation if you do it.

Thus, I suggest that you not do this unless you have a really good reason. It is far better to define the correct method in the class definition or less preferably to monkey-patch the class directly, like this:

Foo.sample_method = sample_method

Since it's instructive, however, I'm going to show you some ways of doing this.

How it can be done

Here's some setup code. We need a class definition. It could be imported, but it really doesn't matter.

class Foo(object):
    '''An empty class to demonstrate adding a method to an instance'''

Create an instance:

foo = Foo()

Create a method to add to it:

def sample_method(self, bar, baz):
    print(bar + baz)

Method nought (0) - use the descriptor method, __get__

Dotted lookups on functions call the __get__ method of the function with the instance, binding the object to the method and thus creating a "bound method."

foo.sample_method = sample_method.__get__(foo)

and now:

>>> foo.sample_method(1,2)
3

Method one - types.MethodType

First, import types, from which we'll get the method constructor:

import types

Now we add the method to the instance. To do this, we require the MethodType constructor from the types module (which we imported above).

The argument signature for types.MethodType is (function, instance, class):

foo.sample_method = types.MethodType(sample_method, foo, Foo)

and usage:

>>> foo.sample_method(1,2)
3

Method two: lexical binding

First, we create a wrapper function that binds the method to the instance:

def bind(instance, method):
    def binding_scope_fn(*args, **kwargs): 
        return method(instance, *args, **kwargs)
    return binding_scope_fn

usage:

>>> foo.sample_method = bind(foo, sample_method)    
>>> foo.sample_method(1,2)
3

Method three: functools.partial

A partial function applies the first argument(s) to a function (and optionally keyword arguments), and can later be called with the remaining arguments (and overriding keyword arguments). Thus:

>>> from functools import partial
>>> foo.sample_method = partial(sample_method, foo)
>>> foo.sample_method(1,2)
3    

This makes sense when you consider that bound methods are partial functions of the instance.

Unbound function as an object attribute - why this doesn't work:

If we try to add the sample_method in the same way as we might add it to the class, it is unbound from the instance, and doesn't take the implicit self as the first argument.

>>> foo.sample_method = sample_method
>>> foo.sample_method(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sample_method() takes exactly 3 arguments (2 given)

We can make the unbound function work by explicitly passing the instance (or anything, since this method doesn't actually use the self argument variable), but it would not be consistent with the expected signature of other instances (if we're monkey-patching this instance):

>>> foo.sample_method(foo, 1, 2)
3

Conclusion

You now know several ways you could do this, but in all seriousness - don't do this.

Running shell command and capturing the output

The output can be redirected to a text file and then read it back.

import subprocess
import os
import tempfile

def execute_to_file(command):
    """
    This function execute the command
    and pass its output to a tempfile then read it back
    It is usefull for process that deploy child process
    """
    temp_file = tempfile.NamedTemporaryFile(delete=False)
    temp_file.close()
    path = temp_file.name
    command = command + " > " + path
    proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    if proc.stderr:
        # if command failed return
        os.unlink(path)
        return
    with open(path, 'r') as f:
        data = f.read()
    os.unlink(path)
    return data

if __name__ == "__main__":
    path = "Somepath"
    command = 'ecls.exe /files ' + path
    print(execute(command))

check if array is empty (vba excel)

this worked for me:

Private Function arrIsEmpty(arr as variant)
    On Error Resume Next
    arrIsEmpty = False
    arrIsEmpty = IsNumeric(UBound(arr))
End Function

How to get the path of src/test/resources directory in JUnit?

I have a Maven3 project using JUnit 4.12 and Java8. In order to get the path of a file called myxml.xml under src/test/resources, I do this from within the test case:

@Test
public void testApp()
{
    File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
    System.out.println(inputXmlFile.getAbsolutePath());
    ...
}

Tested on Ubuntu 14.04 with IntelliJ IDE. Reference here.

Plotting images side by side using matplotlib

The problem you face is that you try to assign the return of imshow (which is an matplotlib.image.AxesImage to an existing axes object.

The correct way of plotting image data to the different axes in axarr would be

f, axarr = plt.subplots(2,2)
axarr[0,0].imshow(image_datas[0])
axarr[0,1].imshow(image_datas[1])
axarr[1,0].imshow(image_datas[2])
axarr[1,1].imshow(image_datas[3])

The concept is the same for all subplots, and in most cases the axes instance provide the same methods than the pyplot (plt) interface. E.g. if ax is one of your subplot axes, for plotting a normal line plot you'd use ax.plot(..) instead of plt.plot(). This can actually be found exactly in the source from the page you link to.

Troubleshooting misplaced .git directory (nothing to commit)

Check the location whether it's the right location of the git project.

Get pixel's RGB using PIL

Not PIL, but imageio.imread might still be interesting:

import imageio
im = scipy.misc.imread('um_000000.png', flatten=False, mode='RGB')
im = imageio.imread('Figure_1.png', pilmode='RGB')
print(im.shape)

gives

(480, 640, 3)

so it is (height, width, channels). So the pixel at position (x, y) is

color = tuple(im[y][x])
r, g, b = color

Outdated

scipy.misc.imread is deprecated in SciPy 1.0.0 (thanks for the reminder, fbahr!)

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Starting from this @Kartik Patel example , I have changed a little maybe now is more clear about static variable

 public class Variable
    {
        public static string StaticName = "Sophia ";
        public string nonStName = "Jenna ";
        public void test()
        {
            StaticName = StaticName + " Lauren"; 
            Console.WriteLine("  static ={0}",StaticName);
            nonStName = nonStName + "Bean ";
            Console.WriteLine("  NeStatic neSt={0}", nonStName);

        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Variable var = new Variable();
            var.test();
            Variable var1 = new Variable();
            var1.test();
            Variable var2 = new Variable();
            var2.test();
            Console.ReadKey();

        }
    }

Output 
  static =Sophia  Lauren
  NeStatic neSt=Jenna Bean
  static =Sophia  Lauren Lauren
  NeStatic neSt=Jenna Bean
  static =Sophia  Lauren Lauren Lauren
  NeStatic neSt=Jenna Bean
  1. Class Variable VS Instance Variable in C#

    Static Class Members C# OR Class Variable

    class A
    {
        // Class variable or " static member variable"  are declared with 
        //the "static " keyword
    
        public static int i=20;
        public int j=10;         //Instance variable 
        public static string s1="static class variable"; //Class variable 
        public string s2="instance variable";        // instance variable 
    }
    class Program
    {
        static void Main(string[] args)
        {
            A obj1 = new A();
    
            // obj1 instance variables 
            Console.WriteLine("obj1 instance variables ");
            Console.WriteLine(A.i);
            Console.WriteLine(obj1.j);
            Console.WriteLine(obj1.s2);
            Console.WriteLine(A.s1);
    
            A obj2 = new A();
    
            // obj2 instance variables 
            Console.WriteLine("obj2 instance variables ");
            Console.WriteLine(A.i);
            Console.WriteLine(obj2.j);
            Console.WriteLine(obj2.s2);
            Console.WriteLine(A.s1);
    
            Console.ReadKey();
    
        }
    
    
    }
    

    }

enter image description here enter image description here enter image description here enter image description here

https://en.wikipedia.org/wiki/Class_variable

https://en.wikipedia.org/wiki/Instance_variable

https://en.wikipedia.org/wiki/Static_variable

https://javaconceptoftheday.com/class-variables-and-instance-variables-in-java/?fbclid=IwAR1_dtpHzg3bC5WlGQGdgewaTvuOI6cwVeFUtTV8IZuGTj1qH5PmKGwX0yM

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-classes-and-static-class-members

How to bundle vendor scripts separately and require them as needed with Webpack?

In case you're interested in bundling automatically your scripts separately from vendors ones:

var webpack = require('webpack'),
    pkg     = require('./package.json'),  //loads npm config file
    html    = require('html-webpack-plugin');

module.exports = {
  context : __dirname + '/app',
  entry   : {
    app     : __dirname + '/app/index.js',
    vendor  : Object.keys(pkg.dependencies) //get npm vendors deps from config
  },
  output  : {
    path      : __dirname + '/dist',
    filename  : 'app.min-[hash:6].js'
  },
  plugins: [
    //Finally add this line to bundle the vendor code separately
    new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.min-[hash:6].js'),
    new html({template : __dirname + '/app/index.html'})
  ]
};

You can read more about this feature in official documentation.

UIButton action in table view cell

in Swift 4

in cellForRowAt indexPath:

 cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)

function that run after user pressed button:

@objc func onClicked(sender: UIButton){
        let tag = sender.tag


    }

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.

var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];

update columns values with column of another table based on condition

Something like this should do it :

UPDATE table1 
   SET table1.Price = table2.price 
   FROM table1  INNER JOIN  table2 ON table1.id = table2.id

You can also try this:

UPDATE table1 
   SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);

How to apply style classes to td classes?

Simply create a Class Name and define your style there like this :

table.tdfont td {
  font-size: 0.9em;
}

this in equals method

this refers to the current instance of the class (object) your equals-method belongs to. When you test this against an object, the testing method (which is equals(Object obj) in your case) will check wether or not the object is equal to the current instance (referred to as this).

An example:

Object obj = this; this.equals(obj); //true   Object obj = this; new Object().equals(obj); //false 

Converting a pointer into an integer

Several answers have pointed at uintptr_t and #include <stdint.h> as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.

Consider this code and compilation:

$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
    unsigned long z = *(unsigned long *)p;
    printf("%d - %lu\n", n, z);
}

int main(void)
{
    function(1, 2);
    return(0);
}
$ rmk kk
        gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
            -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
            -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk 
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$

You will observe that there is a problem at the calling location (in main()) — converting an integer to a pointer without a cast. You are going to need to analyze your function() in all its usages to see how values are passed to it. The code inside my function() would work if the calls were written:

unsigned long i = 0x2341;
function(1, &i);

Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.

Also, if you are going to format the value of the void * parameter (as converted), look carefully at the <inttypes.h> header (instead of stdint.hinttypes.h provides the services of stdint.h, which is unusual, but the C99 standard says [t]he header <inttypes.h> includes the header <stdint.h> and extends it with additional facilities provided by hosted implementations) and use the PRIxxx macros in your format strings.

Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

How can I check if a checkbox is checked?

This should work

    function validate() {
        if ($('#remeber').is(':checked')) {
            alert("checked");
        } else {
            alert("You didn't check it! Let me check it for you.");
        }
    }

Find package name for Android apps to use Intent to launch Market app from web

Use aapt from the SDK like

aapt dump badging yourpkg.apk

This will print the package name together with other info.

the tools is located in
<sdk_home>/build-tools/android-<api_level>
or
<sdk_home>/platform-tools
or
<sdk_home>/platforms/android-<api_level>/tools

Updated according to geniusburger's comment. Thanks!

Process.start: how to get the output?

You can process your output synchronously or asynchronously.

1. Synchronous example

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

Note that it's better to process both output and errors: they must be handled separately.

(*) For some commands (here StartInfo.Arguments) you must add the /c directive, otherwise the process freezes in the WaitForExit().

2. Asynchronous example

static void runCommand() 
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Is it safe to expose Firebase apiKey to the public?

I believe once database rules are written accurately, it will be enough to protect your data. Moreover, there are guidelines that one can follow to structure your database accordingly. For example, making a UID node under users, and putting all under information under it. After that, you will need to implement a simple database rule as below

  "rules": {
    "users": {
      "$uid": {
        ".read": "auth != null && auth.uid == $uid",
        ".write": "auth != null && auth.uid == $uid"
      }
    }
  }
}

No other user will be able to read other users' data, moreover, domain policy will restrict requests coming from other domains. One can read more about it on Firebase Security rules

What is the difference between "INNER JOIN" and "OUTER JOIN"?

The General Idea

Please see the answer by Martin Smith for a better illustations and explanations of the different joins, including and especially differences between FULL OUTER JOIN, RIGHT OUTER JOIN and LEFT OUTER JOIN.

These two table form a basis for the representation of the JOINs below:

Basis

CROSS JOIN

CrossJoin

SELECT *
  FROM citizen
 CROSS JOIN postalcode

The result will be the Cartesian products of all combinations. No JOIN condition required:

CrossJoinResult

INNER JOIN

INNER JOIN is the same as simply: JOIN

InnerJoin

SELECT *
  FROM citizen    c
  JOIN postalcode p ON c.postal = p.postal

The result will be combinations that satisfies the required JOIN condition:

InnerJoinResult

LEFT OUTER JOIN

LEFT OUTER JOIN is the same as LEFT JOIN

LeftJoin

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal

The result will be everything from citizen even if there are no matches in postalcode. Again a JOIN condition is required:

LeftJoinResult

Data for playing

All examples have been run on an Oracle 18c. They're available at dbfiddle.uk which is also where screenshots of tables came from.

CREATE TABLE citizen (id      NUMBER,
                      name    VARCHAR2(20),
                      postal  NUMBER,  -- <-- could do with a redesign to postalcode.id instead.
                      leader  NUMBER);

CREATE TABLE postalcode (id      NUMBER,
                         postal  NUMBER,
                         city    VARCHAR2(20),
                         area    VARCHAR2(20));

INSERT INTO citizen (id, name, postal, leader)
              SELECT 1, 'Smith', 2200,  null FROM DUAL
        UNION SELECT 2, 'Green', 31006, 1    FROM DUAL
        UNION SELECT 3, 'Jensen', 623,  1    FROM DUAL;

INSERT INTO postalcode (id, postal, city, area)
                 SELECT 1, 2200,     'BigCity',         'Geancy'  FROM DUAL
           UNION SELECT 2, 31006,    'SmallTown',       'Snizkim' FROM DUAL
           UNION SELECT 3, 31006,    'Settlement',      'Moon'    FROM DUAL  -- <-- Uuh-uhh.
           UNION SELECT 4, 78567390, 'LookoutTowerX89', 'Space'   FROM DUAL;

Blurry boundaries when playing with JOIN and WHERE

CROSS JOIN

CROSS JOIN resulting in rows as The General Idea/INNER JOIN:

SELECT *
  FROM citizen          c
  CROSS JOIN postalcode p
 WHERE c.postal = p.postal -- < -- The WHERE condition is limiting the resulting rows

Using CROSS JOIN to get the result of a LEFT OUTER JOIN requires tricks like adding in a NULL row. It's omitted.

INNER JOIN

INNER JOIN becomes a cartesian products. It's the same as The General Idea/CROSS JOIN:

SELECT *
  FROM citizen    c
  JOIN postalcode p ON 1 = 1  -- < -- The ON condition makes it a CROSS JOIN

This is where the inner join can really be seen as the cross join with results not matching the condition removed. Here none of the resulting rows are removed.

Using INNER JOIN to get the result of a LEFT OUTER JOIN also requires tricks. It's omitted.

LEFT OUTER JOIN

LEFT JOIN results in rows as The General Idea/CROSS JOIN:

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON 1 = 1 -- < -- The ON condition makes it a CROSS JOIN

LEFT JOIN results in rows as The General Idea/INNER JOIN:

SELECT *
  FROM citizen         c
  LEFT JOIN postalcode p ON c.postal = p.postal
 WHERE p.postal IS NOT NULL -- < -- removed the row where there's no mathcing result from postalcode

The troubles with the Venn diagram

An image internet search on "sql join cross inner outer" will show a multitude of Venn diagrams. I used to have a printed copy of one on my desk. But there are issues with the representation.

Venn diagram are excellent for set theory, where an element can be in one or both sets. But for databases, an element in one "set" seem, to me, to be a row in a table, and therefore not also present in any other tables. There is no such thing as one row present in multiple tables. A row is unique to the table.

Self joins are a corner case where each element is in fact the same in both sets. But it's still not free of any of the issues below.

The set A represents the set on the left (the citizen table) and the set B is the set on the right (the postalcode table) in below discussion.

CROSS JOIN

Every element in both sets are matched with every element in the other set, meaning we need A amount of every B elements and B amount of every A elements to properly represent this Cartesian product. Set theory isn't made for multiple identical elements in a set, so I find Venn diagrams to properly represent it impractical/impossible. It doesn't seem that UNION fits at all.

The rows are distinct. The UNION is 7 rows in total. But they're incompatible for a common SQL results set. And this is not how a CROSS JOIN works at all:

CrossJoinUnion1

Trying to represent it like this:

CrossJoinUnion2Crossing

..but now it just looks like an INTERSECTION, which it's certainly not. Furthermore there's no element in the INTERSECTION that is actually in any of the two distinct sets. However, it looks very much like the searchable results similar to this:

CrossJoinUnionUnion3

For reference one searchable result for CROSS JOINs can be seen at Tutorialgateway. The INTERSECTION, just like this one, is empty.

INNER JOIN

The value of an element depends on the JOIN condition. It's possible to represent this under the condition that every row becomes unique to that condition. Meaning id=x is only true for one row. Once a row in table A (citizen) matches multiple rows in table B (postalcode) under the JOIN condition, the result has the same problems as the CROSS JOIN: The row needs to be represented multiple times, and the set theory isn't really made for that. Under the condition of uniqueness, the diagram could work though, but keep in mind that the JOIN condition determines the placement of an element in the diagram. Looking only at the values of the JOIN condition with the rest of the row just along for the ride:

InnerJoinIntersection - Filled

This representation falls completely apart when using an INNER JOIN with a ON 1 = 1 condition making it into a CROSS JOIN.

With a self-JOIN, the rows are in fact idential elements in both tables, but representing the tables as both A and B isn't very suitable. For example a common self-JOIN condition that makes an element in A to be matching a different element in B is ON A.parent = B.child, making the match from A to B on seperate elements. From the examples that would be a SQL like this:

SELECT *
  FROM citizen c1
  JOIN citizen c2 ON c1.id = c2.leader

SelfJoinResult

Meaning Smith is the leader of both Green and Jensen.

OUTER JOIN

Again the troubles begin when one row has multiple matches to rows in the other table. This is further complicated because the OUTER JOIN can be though of as to match the empty set. But in set theory the union of any set C and an empty set, is always just C. The empty set adds nothing. The representation of this LEFT OUTER JOIN is usually just showing all of A to illustrate that rows in A are selected regardless of whether there is a match or not from B. The "matching elements" however has the same problems as the illustration above. They depend on the condition. And the empty set seems to have wandered over to A:

LeftJoinIntersection - Filled

WHERE clause - making sense

Finding all rows from a CROSS JOIN with Smith and postalcode on the Moon:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
   AND p.area = 'Moon';

Where - result

Now the Venn diagram isn't used to reflect the JOIN. It's used only for the WHERE clause:

Where

..and that makes sense.

When INTERSECT and UNION makes sense

INTERSECT

As explained an INNER JOIN is not really an INTERSECT. However INTERSECTs can be used on results of seperate queries. Here a Venn diagram makes sense, because the elements from the seperate queries are in fact rows that either belonging to just one of the results or both. Intersect will obviously only return results where the row is present in both queries. This SQL will result in the same row as the one above WHERE, and the Venn diagram will also be the same:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
INTERSECT
SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';

UNION

An OUTER JOIN is not a UNION. However UNION work under the same conditions as INTERSECT, resulting in a return of all results combining both SELECTs:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
UNION
SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE p.area = 'Moon';

which is equivalent to:

SELECT *
  FROM citizen          c
 CROSS JOIN postalcode  p
 WHERE c.name = 'Smith'
   OR p.area = 'Moon';

..and gives the result:

Union - Result

Also here a Venn diagram makes sense:

UNION

When it doesn't apply

An important note is that these only work when the structure of the results from the two SELECT's are the same, enabling a comparison or union. The results of these two will not enable that:

SELECT *
  FROM citizen
 WHERE name = 'Smith'
SELECT *
  FROM postalcode
 WHERE area = 'Moon';

..trying to combine the results with UNION gives a

ORA-01790: expression must have same datatype as corresponding expression

For further interest read Say NO to Venn Diagrams When Explaining JOINs and sql joins as venn diagram. Both also cover EXCEPT.

JavaScript override methods

Since this is a top hit on Google, I'd like to give an updated answer.

Using ES6 classes makes inheritance and method overriding a lot easier:

'use strict';

class A {
    speak() {
        console.log("I'm A");
    }
}

class B extends A {
    speak() {
        super.speak();

        console.log("I'm B");
    }
}

var a = new A();
a.speak();
// Output:
// I'm A

var b = new B();
b.speak();
// Output:
// I'm A
// I'm B

The super keyword refers to the parent class when used in the inheriting class. Also, all methods on the parent class are bound to the instance of the child, so you don't have to write super.method.apply(this);.

As for compatibility: the ES6 compatibility table shows only the most recent versions of the major players support classes (mostly). V8 browsers have had them since January of this year (Chrome and Opera), and Firefox, using the SpiderMonkey JS engine, will see classes next month with their official Firefox 45 release. On the mobile side, Android still does not support this feature, while iOS 9, release five months ago, has partial support.

Fortunately, there is Babel, a JS library for re-compiling Harmony code into ES5 code. Classes, and a lot of other cool features in ES6 can make your Javascript code a lot more readable and maintainable.

What "wmic bios get serialnumber" actually retrieves?

wmic bios get serialnumber     

if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)

I had to do exactly that.:):)

How to dynamically set bootstrap-datepicker's date value?

You can use this simple method like :

qsFromDate = '2017-05-10';
$("#dtMinDate").datepicker("setDate", new Date(qsFromDate));
$('#dtMinDate').datepicker('update');

How can I find a specific file from a Linux terminal?

find /the_path_you_want_to_find -name index.html

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

What is Shelving in TFS?

That's right. If you create a shelf, other people doing a get latest won't see your code.

It puts your code changes onto the server, which is probably better backed up than your work PC.

It enables you to pick up your changes on another machine, should you feel the urge to work from home.

Others can see your shelves (though I think this may be optional) so they can review your code prior to a check-in.

What is the difference between “int” and “uint” / “long” and “ulong”?

It's been a while since I C++'d but these answers are off a bit.

As far as the size goes, 'int' isn't anything. It's a notional value of a standard integer; assumed to be fast for purposes of things like iteration. It doesn't have a preset size.

So, the answers are correct with respect to the differences between int and uint, but are incorrect when they talk about "how large they are" or what their range is. That size is undefined, or more accurately, it will change with the compiler and platform.

It's never polite to discuss the size of your bits in public.

When you compile a program, int does have a size, as you've taken the abstract C/C++ and turned it into concrete machine code.

So, TODAY, practically speaking with most common compilers, they are correct. But do not assume this.

Specifically: if you're writing a 32 bit program, int will be one thing, 64 bit, it can be different, and 16 bit is different. I've gone through all three and briefly looked at 6502 shudder

A brief google search shows this: https://www.tutorialspoint.com/cprogramming/c_data_types.htm This is also good info: https://docs.oracle.com/cd/E19620-01/805-3024/lp64-1/index.html

use int if you really don't care how large your bits are; it can change.

Use size_t and ssize_t if you want to know how large something is.

If you're reading or writing binary data, don't use int. Use a (usually platform/source dependent) specific keyword. WinSDK has plenty of good, maintainable examples of this. Other platforms do too.

I've spent a LOT of time going through code from people that "SMH" at the idea that this is all just academic/pedantic. These ate the people that write unmaintainable code. Sure, it's easy to use type 'int' and use it without all the extra darn typing. It's a lot of work to figure out what they really meant, and a bit mind-numbing.

It's crappy coding when you mix int.

use int and uint when you just want a fast integer and don't care about the range (other than signed/unsigned).

How can I call PHP functions by JavaScript?

I created this library JS PHP Import which you can download from github, and use whenever and wherever you want.

The library allows importing php functions and class methods into javascript browser environment thus they can be accessed as javascript functions and methods by using their actual names. The code uses javascript promises so you can chain functions returns.

I hope it may useful to you.

Example:

<script>
$scandir(PATH_TO_FOLDER).then(function(result) {
  resultObj.html(result.join('<br>'));
});

$system('ls -l').then(function(result) {
  resultObj.append(result);
});

$str_replace(' ').then(function(result) {
  resultObj.append(result);
});

// Chaining functions 
$testfn(34, 56).exec(function(result) { // first call
   return $testfn(34, result); // second call with the result of the first call as a parameter
}).exec(function(result) {
   resultObj.append('result: ' + result + '<br><br>');
});
</script>

Implicit type conversion rules in C++ operators

My solution to the problem got WA(wrong answer), then i changed one of int to long long int and it gave AC(accept). Previously, I was trying to do long long int += int * int, and after I rectify it to long long int += long long int * int. Googling I came up with,

1. Arithmetic Conversions

Conditions for Type Conversion:

Conditions Met ---> Conversion

  • Either operand is of type long double. ---> Other operand is converted to type long double.

  • Preceding condition not met and either operand is of type double. ---> Other operand is converted to type double.

  • Preceding conditions not met and either operand is of type float. ---> Other operand is converted to type float.

  • Preceding conditions not met (none of the operands are of floating types). ---> Integral promotions are performed on the operands as follows:

    • If either operand is of type unsigned long, the other operand is converted to type unsigned long.
    • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
    • If the preceding two conditions are not met, and if either operand is of type long, t he other operand is converted to type long.
    • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.
    • If none of the preceding conditions are met, both operands are converted to type int.

2 . Integer conversion rules

  • Integer Promotions:

Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int. Integer promotions are applied as part of the usual arithmetic conversions to certain argument expressions; operands of the unary +, -, and ~ operators; and operands of the shift operators.

  • Integer Conversion Rank:

    • No two signed integer types shall have the same rank, even if they have the same representation.
    • The rank of a signed integer type shall be greater than the rank of any signed integer type with less precision.
    • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
    • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.
    • The rank of any standard integer type shall be greater than the rank of any extended integer type with the same width.
    • The rank of char shall equal the rank of signed char and unsigned char.
    • The rank of any extended signed integer type relative to another extended signed integer type with the same precision is implementation-defined but still subject to the other rules for determining the integer conversion rank.
    • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 has greater rank than T3.
  • Usual Arithmetic Conversions:

    • If both operands have the same type, no further conversion is needed.
    • If both operands are of the same integer type (signed or unsigned), the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
    • If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.
    • If the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type is converted to the type of the operand with signed integer type.
    • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. Specific operations can add to or modify the semantics of the usual arithmetic operations.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

Accessing an array out of bounds gives no error, why?

A nice approach that i have seen often and I had been used actually is to inject some NULL type element (or a created one, like uint THIS_IS_INFINITY = 82862863263;) at end of the array.

Then at the loop condition check, TYPE *pagesWords is some kind of pointer array:

int pagesWordsLength = sizeof(pagesWords) / sizeof(pagesWords[0]);

realloc (pagesWords, sizeof(pagesWords[0]) * (pagesWordsLength + 1);

pagesWords[pagesWordsLength] = MY_NULL;

for (uint i = 0; i < 1000; i++)
{
  if (pagesWords[i] == MY_NULL)
  {
    break;
  }
}

This solution won't word if array is filled with struct types.

VBA code to set date format for a specific column as "yyyy-mm-dd"

It works, when you use both lines:

Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000") = Format(Date, "yyyy-mm-dd")
Application.ActiveWorkbook.Worksheets("data").Range("C1", "C20000").NumberFormat = "yyyy-mm-dd"

How do I change the figure size for a seaborn plot?

You can set the context to be poster or manually set fig_size.

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

np.random.seed(0)
n, p = 40, 8
d = np.random.normal(0, 2, (n, p))
d += np.log(np.arange(1, p + 1)) * -5 + 10


# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
# the size of A4 paper
fig.set_size_inches(11.7, 8.27)
sns.violinplot(data=d, inner="points", ax=ax)    
sns.despine()

fig.savefig('example.png')

enter image description here

How to discard local changes and pull latest from GitHub repository

git reset is what you want, but I'm going to add a couple extra things you might find useful that the other answers didn't mention.

git reset --hard HEAD resets your changes back to the last commit that your local repo has tracked. If you made a commit, did not push it to GitHub, and want to throw that away too, see @absiddiqueLive's answer.

git clean -df will discard any new files or directories that you may have added, in case you want to throw those away. If you haven't added any, you don't have to run this.

git pull (or if you are using git shell with the GitHub client) git sync will get the new changes from GitHub.

Edit from way in the future: I updated my git shell the other week and noticed that the git sync command is no longer defined by default. For the record, typing git sync was equivalent to git pull && git push in bash. I find it still helpful so it is in my bashrc.

jQuery AJAX Call to PHP Script with JSON Return

try to send content type header from server use this just before echoing

header('Content-Type: application/json');

JavaScript replace \n with <br />

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');

static files with express.js

If you have a complicated folder structure, such as

- Your application
     - assets
         - images
             - profile.jpg
     - web
     - server
        - index.js

If you want to serve assets/images from index.js

app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))

To view from your browser

http://localhost:4000/images/profile.jpg

If you need more clarification comment, I'll elaborate.

what does this mean ? image/png;base64?

That data:image/png;base64 URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.

Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

TL;DR

Set an environment variable called ASPNETCORE_ENVIRONMENT with the name of the environment (e.g. Production). Then do one of two things:

  • Inject IHostingEnvironment into Startup.cs, then use that (env here) to check: env.IsEnvironment("Production"). Do not check using env.EnvironmentName == "Production"!
  • Use either separate Startup classes or individual Configure/ConfigureServices functions. If a class or the functions match these formats, they will be used instead of the standard options on that environment.
    • Startup{EnvironmentName}() (entire class) || example: StartupProduction()
    • Configure{EnvironmentName}() || example: ConfigureProduction()
    • Configure{EnvironmentName}Services() || example: ConfigureProductionServices()

Full explanation

The .NET Core docs describe how to accomplish this. Use an environment variable called ASPNETCORE_ENVIRONMENT that's set to the environment you want, then you have two choices.

Check environment name

From the docs:

The IHostingEnvironment service provides the core abstraction for working with environments. This service is provided by the ASP.NET hosting layer, and can be injected into your startup logic via Dependency Injection. The ASP.NET Core web site template in Visual Studio uses this approach to load environment-specific configuration files (if present) and to customize the app’s error handling settings. In both cases, this behavior is achieved by referring to the currently specified environment by calling EnvironmentName or IsEnvironment on the instance of IHostingEnvironment passed into the appropriate method.

NOTE: Checking the actual value of env.EnvironmentName is not recommended!

If you need to check whether the application is running in a particular environment, use env.IsEnvironment("environmentname") since it will correctly ignore case (instead of checking if env.EnvironmentName == "Development" for example).

Use separate classes

From the docs:

When an ASP.NET Core application starts, the Startup class is used to bootstrap the application, load its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists named Startup{EnvironmentName} (for example StartupDevelopment), and the ASPNETCORE_ENVIRONMENT environment variable matches that name, then that Startup class is used instead. Thus, you could configure Startup for development, but have a separate StartupProduction that would be used when the app is run in production. Or vice versa.

In addition to using an entirely separate Startup class based on the current environment, you can also make adjustments to how the application is configured within a Startup class. The Configure() and ConfigureServices() methods support environment-specific versions similar to the Startup class itself, of the form Configure{EnvironmentName}() and Configure{EnvironmentName}Services(). If you define a method ConfigureDevelopment() it will be called instead of Configure() when the environment is set to development. Likewise, ConfigureDevelopmentServices() would be called instead of ConfigureServices() in the same environment.

Getting the difference between two sets

Yes:

test2.removeAll(test1)

Although this will mutate test2, so create a copy if you need to preserve it.

Also, you probably meant <Integer> instead of <int>.

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Use Fieldset Legend with bootstrap

I had a different approach , used bootstrap panel to show it little more rich. Just to help someone and improve the answer.

_x000D_
_x000D_
.text-on-pannel {_x000D_
  background: #fff none repeat scroll 0 0;_x000D_
  height: auto;_x000D_
  margin-left: 20px;_x000D_
  padding: 3px 5px;_x000D_
  position: absolute;_x000D_
  margin-top: -47px;_x000D_
  border: 1px solid #337ab7;_x000D_
  border-radius: 8px;_x000D_
}_x000D_
_x000D_
.panel {_x000D_
  /* for text on pannel */_x000D_
  margin-top: 27px !important;_x000D_
}_x000D_
_x000D_
.panel-body {_x000D_
  padding-top: 30px !important;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="container">_x000D_
  <div class="panel panel-primary">_x000D_
    <div class="panel-body">_x000D_
      <h3 class="text-on-pannel text-primary"><strong class="text-uppercase"> Title </strong></h3>_x000D_
      <p> Your Code </p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div>
_x000D_
_x000D_
_x000D_

This will give below look. enter image description here

Note: We need to change the styles in order to use different header size.

Selenium using Python - Geckodriver executable needs to be in PATH

If you want to add the driver paths on Windows 10:

  1. Right click on the "This PC" icon and select "Properties"

    Enter image description here

  2. Click on “Advanced System Settings”

  3. Click on “Environment Variables” at the bottom of the screen

  4. In the “User Variables” section highlight “Path” and click “Edit”

  5. Add the paths to your variables by clicking “New” and typing in the path for the driver you are adding and hitting enter.

  6. Once you done entering in the path, click “OK”

  7. Keep clicking “OK” until you have closed out all the screens

Easiest way to copy a single file from host to Vagrant guest?

As default, the first vagrant instance use ssh port as 2222, and its ip address is 127.0.0.1 (You may need adjust the port with real virtual host)

==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)

So you can run below command to copy your local file to vagrant instance. password is the same as username which is vagrant.

scp -P 2222 your_file [email protected]:.

You can also copy the file back to your local host.

scp -P 2222 [email protected]:/PATH/filename .

Adding a library/JAR to an Eclipse Android project

Now for the missing class problem.

I'm an Eclipse Java EE developer and have been in the habit for many years of adding third-party libraries via the "User Library" mechanism in Build Path. Of course, there are at least 3 ways to add a third-party library, the one I use is the most elegant, in my humble opinion.

This will not work, however, for Android, whose Dalvik "JVM" cannot handle an ordinary Java-compiled class, but must have it converted to a special format. This does not happen when you add a library in the way I'm wont to do it.

Instead, follow the (widely available) instructions for importing the third-party library, then adding it using Build Path (which makes it known to Eclipse for compilation purposes). Here is the step-by-step:

  1. Download the library to your host development system.
  2. Create a new folder, libs, in your Eclipse/Android project.
  3. Right-click libs and choose Import -> General -> File System, then Next, Browse in the filesystem to find the library's parent directory (i.e.: where you downloaded it to).
  4. Click OK, then click the directory name (not the checkbox) in the left pane, then check the relevant JAR in the right pane. This puts the library into your project (physically).
  5. Right-click on your project, choose Build Path -> Configure Build Path, then click the Libraries tab, then Add JARs..., navigate to your new JAR in the libs directory and add it. (This, incidentally, is the moment at which your new JAR is converted for use on Android.)

NOTE

Step 5 may not be needed, if the lib is already included in your build path. Just ensure that its existence first before adding it.

What you've done here accomplishes two things:

  1. Includes a Dalvik-converted JAR in your Android project.
  2. Makes Java definitions available to Eclipse in order to find the third-party classes when developing (that is, compiling) your project's source code.

Search for a string in Enum and return the Enum

I marked OregonGhost's answer +1, then I tried to use the iteration and realised it wasn't quite right because Enum.GetNames returns strings. You want Enum.GetValues:

public MyColours GetColours(string colour)
{  
   foreach (MyColours mc in Enum.GetValues(typeof(MyColours))) 
   if (mc.ToString() == surveySystem) 
      return mc;

   return MyColors.Default;
}

How to terminate a window in tmux?

While you asked how to kill a window resp. pane, I often wouldn't want to kill it but simply to get it back to a working state (the layout of panes is of importance to me, killing a pane destroys it so I must recreate it); tmux provides the respawn commands to that effect: respawn-pane resp. respawn-window. Just that people like me may find this solution here.

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

Generate an integer that is not among four billion given ones

If you don't assume the 32-bit constraint, just return a randomly generated 64-bit number (or 128-bit if you're a pessimist). The chance of collision is 1 in 2^64/(4*10^9) = 4611686018.4 (roughly 1 in 4 billion). You'd be right most of the time!

(Joking... kind of.)

MSBuild doesn't copy references (DLL files) if using project dependencies in solution

Including all referenced DLL files from your projectreferences in the Website project is not always a good idea, especially when you're using dependency injection: your web project just want to add a reference to the interface DLL file/project, not any concrete implementation DLL file.

Because if you add a reference directly to an implementation DLL file/project, you can't prevent your developer from calling a "new" on concrete classes of the implementation DLL file/project instead of via the interface. It's also you've stated a "hardcode" in your website to use the implementation.

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

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

IMHO returning a null is a bad solution because now you have the problem of sending and interpreting it at the (likely) front end client. I had the same error and I solved it by simply returning a List<FooObject>. I used JDBCTemplate.query().

At the front end (Angular web client), I simply examine the list and if it is empty (of zero length), treat it as no records found.

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

Finding the indices of matching elements in list in Python

>>> average =  [1,3,2,1,1,0,24,23,7,2,727,2,7,68,7,83,2]
>>> matches = [i for i in range(0,len(average)) if average[i]<2 or average[i]>4]
>>> matches
[0, 3, 4, 5, 6, 7, 8, 10, 12, 13, 14, 15]

A Simple AJAX with JSP example

You are doing mistake in "configuration_page.jsp" file. here in this file , function loadXMLDoc() 's line number 2 should be like this:

var config=document.getElementsByName('configselect').value;

because you have declared only the name attribute in your <select> tag. So you should get this element by name.

After correcting this, it will run without any JavaScript error

How to read file binary in C#?

Quick and dirty version:

byte[] fileBytes = File.ReadAllBytes(inputFilename);
StringBuilder sb = new StringBuilder();

foreach(byte b in fileBytes)
{
    sb.Append(Convert.ToString(b, 2).PadLeft(8, '0'));  
}

File.WriteAllText(outputFilename, sb.ToString());

How can I check that JButton is pressed? If the isEnable() is not work?

Just do System.out.println(e.getActionCommand()); inside actionPerformed(ActionEvent e) function. This will tell you which command is just performed.

or

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

Make child div stretch across width of page

You can use 100vw (viewport width). 100vw means 100% of the viewport. vw is supported by all major browsers, including IE9+.

<div id="container" style="width: 960px">
   <div id="help_panel" style="width: 100vw; margin: 0 auto;">
     Content goes here.
   </div> 
</div>

How to parse a JSON string to an array using Jackson

The other answer is correct, but for completeness, here are other ways:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

Is it possible to get the index you're sorting over in Underscore.js?

The iterator of _.each is called with 3 parameters (element, index, list). So yes, for _.each you cab get the index.

You can do the same in sortBy

String length in bytes in JavaScript

For simple UTF-8 encoding, with slightly better compatibility than TextEncoder, Blob does the trick. Won't work in very old browsers though.

new Blob([""]).size; // -> 4  

Can't ignore UserInterfaceState.xcuserstate

I think it would be better to write like this.

git rm --cache *//UserInterfaceState.xcuserstate**

Convert from List into IEnumerable format

You don't need to convert it. List<T> implements the IEnumerable<T> interface so it is already an enumerable.

This means that it is perfectly fine to have the following:

public IEnumerable<Book> GetBooks()
{
    List<Book> books = FetchEmFromSomewhere();    
    return books;
}

as well as:

public void ProcessBooks(IEnumerable<Book> books)
{
    // do something with those books
}

which could be invoked:

List<Book> books = FetchEmFromSomewhere();    
ProcessBooks(books);

Composer killed while updating

You can try setting preferred-install to "dist" in Composer config.

Is it possible to use global variables in Rust?

Heap allocations are possible for static variables if you use the lazy_static macro as seen in the docs

Using this macro, it is possible to have statics that require code to be executed at runtime in order to be initialized. This includes anything requiring heap allocations, like vectors or hash maps, as well as anything that requires function calls to be computed.

// Declares a lazily evaluated constant HashMap. The HashMap will be evaluated once and
// stored behind a global static reference.

use lazy_static::lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = {
        let mut map = HashMap::new();
        map.insert("James", vec!["user", "admin"]);
        map.insert("Jim", vec!["user"]);
        map
    };
}

fn show_access(name: &str) {
    let access = PRIVILEGES.get(name);
    println!("{}: {:?}", name, access);
}

fn main() {
    let access = PRIVILEGES.get("James");
    println!("James: {:?}", access);

    show_access("Jim");
}

How do you create a Swift Date object?

Swift doesn't have its own Date type, but you to use the existing Cocoa NSDate type, e.g:

class Date {

    class func from(year: Int, month: Int, day: Int) -> Date {
        let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!

        var dateComponents = DateComponents()
        dateComponents.year = year
        dateComponents.month = month
        dateComponents.day = day

        let date = gregorianCalendar.date(from: dateComponents)!
        return date
    }

    class func parse(_ string: String, format: String = "yyyy-MM-dd") -> Date {
        let dateFormatter = DateFormatter()
        dateFormatter.timeZone = NSTimeZone.default
        dateFormatter.dateFormat = format

        let date = dateFormatter.date(from: string)!
        return date
    }
}

Which you can use like:

var date = Date.parse("2014-05-20")
var date = Date.from(year: 2014, month: 05, day: 20)

pip install mysql-python fails with EnvironmentError: mysql_config not found

You should install the mysql first:

yum install python-devel mysql-community-devel -y

Then you can install mysqlclient:

pip install  mysqlclient

How to list all the available keyspaces in Cassandra?

Once logged in to cqlsh or cassandra-cli. run below commands

  • On cqlsh

desc keyspaces;

or

describe keyspaces;

or

select * from system_schema.keyspaces;

  • On cassandra-cli

show keyspaces;

add created_at and updated_at fields to mongoose schemas

Use the built-in timestamps option for your Schema.

var ItemSchema = new Schema({
    name: { type: String, required: true, trim: true }
},
{
    timestamps: true
});

This will automatically add createdAt and updatedAt fields to your schema.

http://mongoosejs.com/docs/guide.html#timestamps

How to use variables in SQL statement in Python?

http://www.amk.ca/python/writing/DB-API.html

Be careful when you simply append values of variables to your statements: Imagine a user naming himself ';DROP TABLE Users;' -- That's why you need to use sql escaping, which Python provides for you when you use the cursor.execute in a decent manner. Example in the url is:

cursor.execute("insert into Attendees values (?, ?, ?)", (name,
seminar, paid) )

Laravel migration table field's type change

First composer requires doctrine/dbal, then:

$table->longText('column_name')->change();

How to get controls in WPF to fill available space?

Well, I figured it out myself, right after posting, which is the most embarassing way. :)

It seems every member of a StackPanel will simply fill its minimum requested size.

In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.

I would love to see a more elegant method of handling this, but it will do.

How to check a string against null in java?

You can check with String == null

This works for me

    String foo = null;
    if(foo == null){
        System.out.println("String is null");
    }

DataSet panel (Report Data) in SSRS designer is gone

View -> Datasets (bottom of menu, above Refresh)

DISTINCT for only one column

The reason DISTINCT and GROUP BY work on entire rows is that your query returns entire rows.

To help you understand: Try to write out by hand what the query should return and you will see that it is ambiguous what to put in the non-duplicated columns.

If you literally don't care what is in the other columns, don't return them. Returning a random row for each e-mail address seems a little useless to me.

How to draw a filled triangle in android canvas?

Ok I've done it. I'm sharing this code in case someone else will need it:

super.draw(canvas, mapView, true);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);     
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);

Point point1_draw = new Point();        
Point point2_draw = new Point();    
Point point3_draw = new Point();

mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);

Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();

canvas.drawPath(path, paint);

//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);

return true;

Thanks for the hint Nicolas!

ResultSet exception - before start of result set

You have to do a result.next() before you can access the result. It's a very common idiom to do

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}

PHP error: Notice: Undefined index:

How I can get rid of it so it doesnt display it?

People here are trying to tell you that it's unprofessional (and it is), but in your case you should simply add following to the start of your application:

 error_reporting(E_ERROR|E_WARNING);

This will disable E_NOTICE reporting. E_NOTICES are not errors, but notices, as the name says. You'd better check this stuff out and proof that undefined variables don't lead to errors. But the common case is that they are just informal, and perfectly normal for handling form input with PHP.

Also, next time Google the error message first.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

The remote host closed the connection. The error code is 0x800704CD

I got this error when I dynamically read data from a WebRequest and never closed the Response.

    protected System.IO.Stream GetStream(string url)
    {
        try
        {
            System.IO.Stream stream = null;
            var request = System.Net.WebRequest.Create(url);
            var response = request.GetResponse();

            if (response != null) {
                stream = response.GetResponseStream();

                // I never closed the response thus resulting in the error
                response.Close(); 
            }
            response = null;
            request = null;

            return stream;
        }
        catch (Exception) { }
        return null;
    }

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

What is the difference between "::" "." and "->" in c++

You have a pointer to an object. Therefore, you need to access a field of an object that's pointed to by the pointer. To dereference the pointer you use *, and to access a field, you use ., so you can use:

cout << (*kwadrat).val1;

Note that the parentheses are necessary. This operation is common enough that long ago (when C was young) they decided to create a "shorthand" method of doing it:

cout << kwadrat->val1;

These are defined to be identical. As you can see, the -> basically just combines a * and a . into a single operation. If you were dealing directly with an object or a reference to an object, you'd be able to use the . without dereferencing a pointer first:

Kwadrat kwadrat2(2,3,4);

cout << kwadrat2.val1;

The :: is the scope resolution operator. It is used when you only need to qualify the name, but you're not dealing with an individual object at all. This would be primarily to access a static data member:

struct something { 
    static int x; // this only declares `something::x`. Often found in a header
};

int something::x;  // this defines `something::x`. Usually in .cpp/.cc/.C file.

In this case, since x is static, it's not associated with any particular instance of something. In fact, it will exist even if no instance of that type of object has been created. In this case, we can access it with the scope resolution operator:

something::x = 10;

std::cout << something::x;

Note, however, that it's also permitted to access a static member as if it was a member of a particular object:

something s;

s.x = 1;

At least if memory serves, early in the history of C++ this wasn't allowed, but the meaning is unambiguous, so they decided to allow it.

commons httpclient - Adding query string parameters to GET/POST request

Here is how you would add query string parameters using HttpClient 4.2 and later:

URIBuilder builder = new URIBuilder("http://example.com/");
builder.setParameter("parts", "all").setParameter("action", "finish");

HttpPost post = new HttpPost(builder.build());

The resulting URI would look like:

http://example.com/?parts=all&action=finish

Regular expression for checking if capital letters are found consecutively in a string?

If you want to get all Employee name in mysql which having at least one uppercase letter than apply this query.

SELECT * FROM registration WHERE `name` REGEXP BINARY '[A-Z]';

Use of def, val, and var in scala

Let's take this:

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
person.age=20
println(person.age)

and rewrite it with equivalent code

class Person(val name:String,var age:Int )
def person =new Person("Kumar",12)
(new Person("Kumar", 12)).age_=(20)
println((new Person("Kumar", 12)).age)

See, def is a method. It will execute each time it is called, and each time it will return (a) new Person("Kumar", 12). And these is no error in the "assignment" because it isn't really an assignment, but just a call to the age_= method (provided by var).

How to Detect if I'm Compiling Code with a particular Visual Studio version?

As a more general answer http://sourceforge.net/p/predef/wiki/Home/ maintains a list of macros for detecting specicic compilers, operating systems, architectures, standards and more.

How do I return multiple values from a function in C?

I don't know what your string is, but I'm going to assume that it manages its own memory.

You have two solutions:

1: Return a struct which contains all the types you need.

struct Tuple {
    int a;
    string b;
};

struct Tuple getPair() {
    Tuple r = { 1, getString() };
    return r;
}

void foo() {
    struct Tuple t = getPair();
}

2: Use pointers to pass out values.

void getPair(int* a, string* b) {
    // Check that these are not pointing to NULL
    assert(a);
    assert(b);
    *a = 1;
    *b = getString();
}

void foo() {
    int a, b;
    getPair(&a, &b);
}

Which one you choose to use depends largely on personal preference as to whatever semantics you like more.

Creating an index on a table variable

It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386

Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.

The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.

To avoid name clashes, something like this usually works:

declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);

This insures the name is always unique even between simultaneous executions of the same procedure.

Why does find -exec mv {} ./target/ + not work?

no, the difference between + and \; should be reversed. + appends the files to the end of the exec command then runs the exec command and \; runs the command for each file.

The problem is find . -type f -iname '*.cpp' -exec mv {} ./test/ \+ should be find . -type f -iname '*.cpp' -exec mv {} ./test/ + no need to escape it or terminate the +

xargs I haven't used in a long time but I think works like +.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Yes, i also I fixed it changing in the js libraries to the unminified.

For example, in the tag, change:

<script type="text/javascript" src="js/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.min.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.min.js"></script>

For:

<script type="text/javascript" src="js/jquery.ui.core.js"></script>
<script type="text/javascript" src="js/jquery.ui.widget.js"></script>
<script type="text/javascript" src="js/jquery.ui.rcarousel.js"></script>

Quiting the 'min' as unminified.

Thanks for the idea.

Javamail Could not convert socket to TLS GMail

This can also be if the application does not support the TLS version the SMTP host is using.

For example, trying to configure an SMTP server that uses TLSv1.2 without fallback, when your application(or java program using an older javax.mail JAR) supports only upto TLSv1.1.

C# cannot convert method to non delegate type

You need to add parentheses after a method call, else the compiler will think you're talking about the method itself (a delegate type), whereas you're actually talking about the return value of that method.

string t = obj.getTitle();

Extra Non-Essential Information

Also, have a look at properties. That way you could use title as if it were a variable, while, internally, it works like a function. That way you don't have to write the functions getTitle() and setTitle(string value), but you could do it like this:

public string Title // Note: public fields, methods and properties use PascalCasing
{
    get // This replaces your getTitle method
    {
        return _title; // Where _title is a field somewhere
    }
    set // And this replaces your setTitle method
    {
        _title = value; // value behaves like a method parameter
    }
}

Or you could use auto-implemented properties, which would use this by default:

public string Title { get; set; }

And you wouldn't have to create your own backing field (_title), the compiler would create it itself.

Also, you can change access levels for property accessors (getters and setters):

public string Title { get; private set; }

You use properties as if they were fields, i.e.:

this.Title = "Example";
string local = this.Title;

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3

Use encode() function along with hardcoded String value given in a single quote.

Ex:

file.write(answers[i] + '\n'.encode())

OR

line.split(' +++$+++ '.encode())

How to compare two dates in Objective-C

In Cocoa, to compare dates, use one of isEqualToDate, compare, laterDate, and earlierDate methods on NSDate objects, instantiated with the dates you need.

Documentation:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/isEqualToDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/earlierDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/laterDate:
http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDate/compare:

How to keep the spaces at the end and/or at the beginning of a String?

There is also the solution of using CDATA. Example:

<string name="test"><![CDATA[Hello          world]]></string>

But in general I think \u0020 is good enough.

When to use AtomicReference in Java?

Here's a very simple use case and has nothing to do with thread safety.

To share an object between lambda invocations, the AtomicReference is an option:

public void doSomethingUsingLambdas() {

    AtomicReference<YourObject> yourObjectRef = new AtomicReference<>();

    soSomethingThatTakesALambda(() -> {
        yourObjectRef.set(youObject);
    });

    soSomethingElseThatTakesALambda(() -> {
        YourObject yourObject = yourObjectRef.get();
    });
}

I'm not saying this is good design or anything (it's just a trivial example), but if you have have the case where you need to share an object between lambda invocations, the AtomicReference is an option.

In fact you can use any object that holds a reference, even a Collection that has only one item. However, the AtomicReference is a perfect fit.

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

Failed to load resource under Chrome

If the images are generated via an ASP Response.Write(), make sure you don't call Response.Close();. Chrome doesn't like it.

Find a value in DataTable

this question asked in 2009 but i want to share my codes:

    Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable

    Dim x As Integer
    Dim y As Integer

    Dim bln As Boolean

    Dim dttable2 As New DataTable
    For x = 0 To dttable.Columns.Count - 1
        dttable2.Columns.Add(dttable.Columns(x).ColumnName)
    Next

    For x = 0 To dttable.Rows.Count - 1
        For y = 0 To searchcolumns.Length - 1
            If String.IsNullOrEmpty(searchcolumns(y)) = False Then
                If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
                    bln = True
                Else
                    bln = False
                    Exit For
                End If
            End If
        Next
        If bln = True Then
            dttable2.Rows.Add(dttable.Rows(x).ItemArray)
        End If
    Next

    Return dttable2


End Function

Using reCAPTCHA on localhost

For me, it worked deleting my actual configuration and creating a new one, adding domains like this:

enter image description here

What languages are Windows, Mac OS X and Linux written in?

Windows c c++ 10% C# Perl Linux C MAC Obective c Android Java c++ Solaris c c++

I hope you get the answer.

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Spark DataFrame groupBy and sort in the descending order (pyspark)

Use orderBy:

df.orderBy('column_name', ascending=False)

Complete answer:

group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html

Get the value in an input text box

I think this function is missed here in previous answers:

.val( function(index, value) ) 

error LNK2005, already defined?

In the Project’s Settings, add /FORCE:MULTIPLE to the Linker’s Command Line options.

From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."

Java, How to implement a Shift Cipher (Caesar Cipher)

Hello...I have created a java client server application in swing for caesar cipher...I have created a new formula that can decrypt the text properly... sorry only for lower case..!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarserver extends JFrame implements ActionListener {
    static String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l5, l6;
    JTextField t1;
    JButton close, b1;
    static String en;
    int num = 0;
    JProgressBar progress;

    ceasarserver() {
        super("SERVER");
        JPanel p = new JPanel(new GridLayout(10, 1));
        l1 = new JLabel("");
        l2 = new JLabel("");
        l3 = new JLabel("");
        l5 = new JLabel("");
        l6 = new JLabel("Enter the Key...");
        t1 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        close = new JButton("Close");
        close.setMnemonic('C');
        close.setPreferredSize(new Dimension(300, 25));
        close.addActionListener(this);
        b1 = new JButton("Decrypt");
        b1.setMnemonic('D');
        b1.addActionListener(this);
        p.add(l1);
        p.add(l2);
        p.add(l3);
        p.add(l6);
        p.add(t1);
        p.add(b1);
        p.add(progress);
        p.add(l5);
        p.add(close);
        add(p);
        setVisible(true);
        pack();
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == close)
            System.exit(0);
        else if (e.getSource() == b1) {
            int key = Integer.parseInt(t1.getText());
            String d = "";
            int i = 0, j, k;
            while (i < en.length()) {
                j = cs.indexOf(en.charAt(i));
                k = (j + (26 - key)) % 26;
                d = d + cs.charAt(k);
                i++;
            }
            while (num < 21) {
                progress.setValue(num);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ex) {
                }
                progress.setValue(num);
                Rectangle progressRect = progress.getBounds();
                progressRect.x = 0;
                progressRect.y = 0;
                progress.paintImmediately(progressRect);
                num++;
            }
            l5.setText("Decrypted text: " + d);
        }
    }

    public static void main(String args[]) throws IOException {
        new ceasarserver();
        String strm = new String();
        ServerSocket ss = new ServerSocket(4321);
        l1.setText("Secure data transfer Server Started....");
        Socket s = ss.accept();
        l2.setText("Client Connected !");
        while (true) {
            Scanner br1 = new Scanner(s.getInputStream());
            en = br1.nextLine();
            l3.setText("Client:" + en);
        }
    }

The client class:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.util.*;

public class ceasarclient extends JFrame {
    String cs = "abcdefghijklmnopqrstuvwxyz";
    static JLabel l1, l2, l3, l4, l5;
    JButton b1, b2, b3;
    JTextField t1, t2;
    JProgressBar progress;
    int num = 0;
    String en = "";

    ceasarclient(final Socket s) {
        super("CLIENT");
        JPanel p = new JPanel(new GridLayout(10, 1));
        setSize(500, 500);
        t1 = new JTextField(30);
        b1 = new JButton("Send");
        b1.setMnemonic('S');
        b2 = new JButton("Close");
        b2.setMnemonic('C');
        l1 = new JLabel("Welcome to Secure Data transfer!");
        l2 = new JLabel("Enter the word here...");
        l3 = new JLabel("");
        l4 = new JLabel("Enter the Key:");
        b3 = new JButton("Encrypt");
        b3.setMnemonic('E');
        t2 = new JTextField(30);
        progress = new JProgressBar(0, 20);
        progress.setValue(0);
        progress.setStringPainted(true);
        p.add(l1);
        p.add(l2);
        p.add(t1);
        p.add(l4);
        p.add(t2);
        p.add(b3);
        p.add(progress);
        p.add(b1);
        p.add(l3);
        p.add(b2);
        add(p);
        setVisible(true);
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
                    pw.println(en);
                } catch (Exception ex) {
                }
                ;
                l3.setText("Encrypted Text Sent.");
            }
        });
        b3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String strw = t1.getText();
                int key = Integer.parseInt(t2.getText());
                int i = 0, j, k;
                while (i < strw.length()) {
                    j = cs.indexOf(strw.charAt(i));
                    k = (j + key) % 26;
                    en = en + cs.charAt(k);
                    i++;
                }
                while (num < 21) {
                    progress.setValue(num);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException exe) {
                    }
                    progress.setValue(num);
                    Rectangle progressRect = progress.getBounds();
                    progressRect.x = 0;
                    progressRect.y = 0;
                    progress.paintImmediately(progressRect);
                    num++;
                }
            }
        });
        b2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        pack();
    }

    public static void main(String args[]) throws IOException {
        final Socket s = new Socket(InetAddress.getLocalHost(), 4321);
        new ceasarclient(s);
    }
}

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

systemd

sudo systemctl stop mysqld.service && sudo yum remove -y mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

sysvinit

sudo service mysql stop && sudo apt-get remove mariadb mariadb-server && sudo rm -rf /var/lib/mysql /etc/my.cnf

How to check if a string starts with one of several prefixes?

When you say you tried to use OR, how exactly did you try and use it? In your case, what you will need to do would be something like so:

String newStr4 = strr.split("2012")[0];
if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues")...)
str4.add(newStr4);

cd into directory without having permission

I know this post is old, but what i had to do in the case of the above answers on Linux machine was:

sudo chmod +x directory

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

Import data.sql MySQL Docker Container

Mount your sql-dump under/docker-entrypoint-initdb.d/yourdump.sql utilizing a volume mount

mysql:
  image: mysql:latest
  container_name: mysql-container
  ports:
    - 3306:3306
  volumes:
    - ./dump.sql:/docker-entrypoint-initdb.d/dump.sql
  environment:
    MYSQL_ROOT_PASSWORD: secret
    MYSQL_DATABASE: name_db
    MYSQL_USER: user
    MYSQL_PASSWORD: password

This will trigger an import of the sql-dump during the start of the container, see https://hub.docker.com/_/mysql/ under "Initializing a fresh instance"

Strip all non-numeric characters from string in JavaScript

we are in 2017 now you can also use ES2016

var a = 'abc123.8<blah>';
console.log([...a].filter( e => isFinite(e)).join(''));

or

console.log([...'abc123.8<blah>'].filter( e => isFinite(e)).join(''));  

The result is

1238

Convert char array to single int?

If you are using C++11, you should probably use stoi because it can distinguish between an error and parsing "0".

try {
    int number = std::stoi("1234abc");
} catch (std::exception const &e) {
    // This could not be parsed into a number so an exception is thrown.
    // atoi() would return 0, which is less helpful if it could be a valid value.
}

It should be noted that "1234abc" is implicitly converted from a char[] to a std:string before being passed to stoi().

Extract specific columns from delimited file using Awk

Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.

csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv

Replacing 2 with the column number will effectively extract the column data you are looking for.

Calculate correlation with cor(), only for numerical columns

if you have a dataframe where some columns are numeric and some are other (character or factor) and you only want to do the correlations for the numeric columns, you could do the following:

set.seed(10)

x = as.data.frame(matrix(rnorm(100), ncol = 10))
x$L1 = letters[1:10]
x$L2 = letters[11:20]

cor(x)

Error in cor(x) : 'x' must be numeric

but

cor(x[sapply(x, is.numeric)])

             V1         V2          V3          V4          V5          V6          V7
V1   1.00000000  0.3025766 -0.22473884 -0.72468776  0.18890578  0.14466161  0.05325308
V2   0.30257657  1.0000000 -0.27871430 -0.29075170  0.16095258  0.10538468 -0.15008158
V3  -0.22473884 -0.2787143  1.00000000 -0.22644156  0.07276013 -0.35725182 -0.05859479
V4  -0.72468776 -0.2907517 -0.22644156  1.00000000 -0.19305921  0.16948333 -0.01025698
V5   0.18890578  0.1609526  0.07276013 -0.19305921  1.00000000  0.07339531 -0.31837954
V6   0.14466161  0.1053847 -0.35725182  0.16948333  0.07339531  1.00000000  0.02514081
V7   0.05325308 -0.1500816 -0.05859479 -0.01025698 -0.31837954  0.02514081  1.00000000
V8   0.44705527  0.1698571  0.39970105 -0.42461411  0.63951574  0.23065830 -0.28967977
V9   0.21006372 -0.4418132 -0.18623823 -0.25272860  0.15921890  0.36182579 -0.18437981
V10  0.02326108  0.4618036 -0.25205899 -0.05117037  0.02408278  0.47630138 -0.38592733
              V8           V9         V10
V1   0.447055266  0.210063724  0.02326108
V2   0.169857120 -0.441813231  0.46180357
V3   0.399701054 -0.186238233 -0.25205899
V4  -0.424614107 -0.252728595 -0.05117037
V5   0.639515737  0.159218895  0.02408278
V6   0.230658298  0.361825786  0.47630138
V7  -0.289679766 -0.184379813 -0.38592733
V8   1.000000000  0.001023392  0.11436143
V9   0.001023392  1.000000000  0.15301699
V10  0.114361431  0.153016985  1.00000000

Multiprocessing: How to use Pool.map on a function defined in a class?

This may not be a very good solution but in my case, I solve it like this.

from multiprocessing import Pool

def foo1(data):
    self = data.get('slf')
    lst = data.get('lst')
    return sum(lst) + self.foo2()

class Foo(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def foo2(self):
        return self.a**self.b   

    def foo(self):
        p = Pool(5)
        lst = [1, 2, 3]
        result = p.map(foo1, (dict(slf=self, lst=lst),))
        return result

if __name__ == '__main__':
    print(Foo(2, 4).foo())

I had to pass self to my function as I have to access attributes and functions of my class through that function. This is working for me. Corrections and suggestions are always welcome.

How to display raw html code in PRE or something like it but without escaping it

echo '<pre>' . htmlspecialchars("<div><b>raw HTML</b></div>") . '</pre>';

I think that's what you're looking for?

In other words, use htmlspecialchars() in PHP

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Also something that can go wrong: Make sure you exit Docker for Mac (possibly all other kind of docker installations as well).

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

I have eclipse JRE 8.112 , not sure if that matters but what i did was this:

  1. Right clicked on my projects folder
  2. went down to properties and clicked
  3. clicked on the java build path folder
  4. once inside, I was in the order and export
  5. I checked the JRE System Library [jre1.8.0_112]
  6. then moved it up above the one other JRE system library there (not sure if this mattered)
  7. then pressed ok

This solved my problem.

Sending POST data without form

You could use AJAX to send a POST request if you don't want forms.

Using jquery $.post method it is pretty simple:

$.post('/foo.php', { key1: 'value1', key2: 'value2' }, function(result) {
    alert('successfully posted key1=value1&key2=value2 to foo.php');
});

What does "xmlns" in XML mean?

xmlns - xml namespace. It's just a method to avoid element name conflicts. For example:

<config xmlns:rnc="URI1" xmlns:bsc="URI2">
  <rnc:node>
      <rnc:rncId>5</rnc:rncId>
  </rnc:node>

  <bsc:node>
      <bsc:cId>5</bsc:cId>
  </bsc:node>
</config>

Two different node elements in one xml file. Without namespaces this file would not be valid.

Difference between MongoDB and Mongoose

Mongodb and Mongoose are two completely different things!

Mongodb is the database itself, while Mongoose is an object modeling tool for Mongodb

EDIT: As pointed out MongoDB is the npm package, thanks!

How to solve maven 2.6 resource plugin dependency?

This fixed the same issue for me: My eclipse is installed in /usr/local/bin/eclipse

1) Changed permission for eclipse from root to owner: sudo chown -R $USER eclipse

2) Right click on project/Maven right click on Update Maven select Force update maven project

JavaScript closure inside loops – simple practical example

With new features of ES6 block level scoping is managed:

var funcs = [];
for (let i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = function() {            // and store them in funcs
        console.log("My value: " + i); // each should log its value.
    };
}
for (let j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

The code in OP's question is replaced with let instead of var.

What's the advantage of a Java enum versus a class with public static final fields?

example:

public class CurrencyDenom {
   public static final int PENNY = 1;
 public static final int NICKLE = 5;
 public static final int DIME = 10;
public static final int QUARTER = 25;}

Limitation of java Constants

1) No Type-Safety: First of all it’s not type-safe; you can assign any valid int value to int e.g. 99 though there is no coin to represent that value.

2) No Meaningful Printing: printing value of any of these constant will print its numeric value instead of meaningful name of coin e.g. when you print NICKLE it will print "5" instead of "NICKLE"

3) No namespace: to access the currencyDenom constant we need to prefix class name e.g. CurrencyDenom.PENNY instead of just using PENNY though this can also be achieved by using static import in JDK 1.5

Advantage of enum

1) Enums in Java are type-safe and has there own name-space. It means your enum will have a type for example "Currency" in below example and you can not assign any value other than specified in Enum Constants.

public enum Currency {PENNY, NICKLE, DIME, QUARTER};

Currency coin = Currency.PENNY; coin = 1; //compilation error

2) Enum in Java are reference type like class or interface and you can define constructor, methods and variables inside java Enum which makes it more powerful than Enum in C and C++ as shown in next example of Java Enum type.

3) You can specify values of enum constants at the creation time as shown in below example: public enum Currency {PENNY(1), NICKLE(5), DIME(10), QUARTER(25)}; But for this to work you need to define a member variable and a constructor because PENNY (1) is actually calling a constructor which accepts int value , see below example.

public enum Currency {
    PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
    private int value;

    private Currency(int value) {
            this.value = value;
    }
}; 

Reference: https://javarevisited.blogspot.com/2011/08/enum-in-java-example-tutorial.html

How can I take a screenshot/image of a website using Python?

Try this..

#!/usr/bin/env python

import gtk.gdk

import time

import random

while 1 :
    # generate a random time between 120 and 300 sec
    random_time = random.randrange(120,300)

    # wait between 120 and 300 seconds (or between 2 and 5 minutes)
    print "Next picture in: %.2f minutes" % (float(random_time) / 60)

    time.sleep(random_time)

    w = gtk.gdk.get_default_root_window()
    sz = w.get_size()

    print "The size of the window is %d x %d" % sz

    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
    pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])

    ts = time.time()
    filename = "screenshot"
    filename += str(ts)
    filename += ".png"

    if (pb != None):
        pb.save(filename,"png")
        print "Screenshot saved to "+filename
    else:
        print "Unable to get the screenshot."

How to get input type using jquery?

$("#yourobj").attr('type');

Convert SVG to PNG in Python

A little extension on the answer of jsbueno:

#!/usr/bin/env python

import cairo
import rsvg
from xml.dom import minidom


def convert_svg_to_png(svg_file, output_file):
    # Get the svg files content
    with open(svg_file) as f:
        svg_data = f.read()

    # Get the width / height inside of the SVG
    doc = minidom.parse(svg_file)
    width = int([path.getAttribute('width') for path
                 in doc.getElementsByTagName('svg')][0])
    height = int([path.getAttribute('height') for path
                  in doc.getElementsByTagName('svg')][0])
    doc.unlink()

    # create the png
    img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    ctx = cairo.Context(img)
    handler = rsvg.Handle(None, str(svg_data))
    handler.render_cairo(ctx)
    img.write_to_png(output_file)

if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()

    parser.add_argument("-f", "--file", dest="svg_file",
                        help="SVG input file", metavar="FILE")
    parser.add_argument("-o", "--output", dest="output", default="svg.png",
                        help="PNG output file", metavar="FILE")
    args = parser.parse_args()

    convert_svg_to_png(args.svg_file, args.output)

How can I print literal curly-brace characters in a string and also use .format on it?

Python 3.6+ (2017)

In the recent versions of Python one would use f-strings (see also PEP498).

With f-strings one should use double {{ or }}

n = 42  
print(f" {{Hello}} {n} ")

produces the desired

 {Hello} 42

If you need to resolve an expression in the brackets instead of using literal text you'll need three sets of brackets:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

produces

{hello}

Iterating a JavaScript object's properties using jQuery

Note: Most modern browsers will now allow you to navigate objects in the developer console. This answer is antiquated.

This method will walk through object properties and write them to the console with increasing indent:

function enumerate(o,s){

    //if s isn't defined, set it to an empty string
    s = typeof s !== 'undefined' ? s : "";

    //if o is null, we need to output and bail
    if(typeof o == "object" && o === null){

       console.log(s+k+": null");

    } else {    

        //iterate across o, passing keys as k and values as v
        $.each(o, function(k,v){

            //if v has nested depth
           if(typeof v == "object" && v !== null){

                //write the key to the console
                console.log(s+k+": ");

                //recursively call enumerate on the nested properties
                enumerate(v,s+"  ");

            } else {

                //log the key & value
                console.log(s+k+": "+String(v));
            }
        });
    }
}

Just pass it the object you want to iterate through:

    var response = $.ajax({
        url: myurl,
        dataType: "json"
    })
    .done(function(a){
       console.log("Returned values:");
       enumerate(a);
    })
    .fail(function(){ console.log("request failed");});

Android studio - Failed to find target android-18

I had the same problem when trying out Android Studio. I already had projects running on the ADT under SDK 18. No need to hack the manifest files.

Fixed by:

export ANDROID_HOME= pathtobundle/adt-bundle-linux-x86_64-20130729/sdk

If you don't have the ADT installed, and just want the SDK, it seems like a good solution is to install everything and then point Android Studio to the just the packaged SDK.

cd pathtobundle

wget http://dl.google.com/android/adt/adt-bundle-linux-x86_64-20130729.zip

unzip *.zip

As someone else said, you may need to run the SDK Manager to install the desired packages before running Studio.

How can I view live MySQL queries?

This is the easiest setup on a Linux Ubuntu machine I have come across. Crazy to see all the queries live.

Find and open your MySQL configuration file, usually /etc/mysql/my.cnf on Ubuntu. Look for the section that says “Logging and Replication”

#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.

log = /var/log/mysql/mysql.log

Just uncomment the “log” variable to turn on logging. Restart MySQL with this command:

sudo /etc/init.d/mysql restart

Now we’re ready to start monitoring the queries as they come in. Open up a new terminal and run this command to scroll the log file, adjusting the path if necessary.

tail -f /var/log/mysql/mysql.log

Now run your application. You’ll see the database queries start flying by in your terminal window. (make sure you have scrolling and history enabled on the terminal)

FROM http://www.howtogeek.com/howto/database/monitor-all-sql-queries-in-mysql/

Reading a file line by line in Go

You can also use ReadString with \n as a separator:

  f, err := os.Open(filename)
  if err != nil {
    fmt.Println("error opening file ", err)
    os.Exit(1)
  }
  defer f.Close()
  r := bufio.NewReader(f)
  for {
    path, err := r.ReadString(10) // 0x0A separator = newline
    if err == io.EOF {
      // do something here
      break
    } else if err != nil {
      return err // if you return error
    }
  }

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

swift How to remove optional String Character

print("imageURLString = " + imageURLString!)

just use !

jQuery Mobile: document ready vs. page events

While you use .on(), it's basically a live query that you are using.

On the other hand, .ready (as in your case) is a static query. While using it, you can dynamically update data and do not have to wait for the page to load. You can simply pass on the values into your database (if required) when a particular value is entered.

The use of live queries is common in forms where we enter data (account or posts or even comments).

Javascript get object key name

Change alert(buttons[i].text); to alert(i);

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

.remove() is deprecated. instead we can use deleteMany

DateTime.deleteMany({}, callback).

How do I merge my local uncommitted changes into another Git branch?

A shorter alternative to the previously mentioned stash approach would be:

Temporarily move the changes to a stash.

  1. git stash

Create and switch to a new branch and then pop the stash to it in just one step.

  1. git stash branch new_branch_name

Then just add and commit the changes to this new branch.

SoapFault exception: Could not connect to host

That most likely refers to a connection issue. It could be either that your internet connection was down, or the web service you are trying to use was down. I suggest using this service to see if the web service is online or not: http://downforeveryoneorjustme.com/

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

how to display toolbox on the left side of window of Visual Studio Express for windows phone 7 development?

I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!

(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)

You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View-> Edit in Visual Studio.... It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...

Unzip files programmatically in .net

Use the DotNetZip library at http://www.codeplex.com/DotNetZip

class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...

DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...

If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

Convert a list of characters into a string

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

a = ['a','b','c','d']

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn't a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.

Eclipse: All my projects disappeared from Project Explorer

I tried differently for the same issue and worked .

Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs

For full details check out bellow link

http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac

What do the result codes in SVN mean?

For additional details see the SVNBook: "Status of working copy files and directories".

The common statuses:

U: Working file was updated

G: Changes on the repo were automatically merged into the working copy

M: Working copy is modified

C: This file conflicts with the version in the repo

?: This file is not under version control

!: This file is under version control but is missing or incomplete

A: This file will be added to version control (after commit)

A+: This file will be moved (after commit)

D: This file will be deleted (after commit)

S: This signifies that the file or directory has been switched from the path of the rest of the working copy (using svn switch) to a branch

I: Ignored

X: External definition

~: Type changed

R: Item has been replaced in your working copy. This means the file was scheduled for deletion, and then a new file with the same name was scheduled for addition in its place.

L : Item is locked

E: Item existed, as it would have been created, by an svn update.

Serializing enums with Jackson

In Spring Boot 2, the easiest way is to declare in your application.properties:

spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true

and define the toString() method of your enums.

Valid characters of a hostname?

It depends on whether you process IDNs before or after the IDN toASCII algorithm (that is, do you see the domain name pa??de??µa.d???µ? in Greek or as xn--hxajbheg2az3al.xn--jxalpdlp?).

In the latter case—where you are handling IDNs through the punycode—the old RFC 1123 rules apply:

U+0041 through U+005A (A-Z), U+0061 through U+007A (a-z) case folded as each other, U+0030 through U+0039 (0-9) and U+002D (-).

and U+002E (.) of course; the rules for labels allow the others, with dots between labels.

If you are seeing it in IDN form, the allowed characters are much varied, see http://unicode.org/reports/tr36/idn-chars.html for a handy chart of all valid characters.

Chances are your network code will deal with the punycode, but your display code (or even just passing strings to and from other layers) with the more human-readable form as nobody running a server on the ????????. domain wants to see their server listed as being on .xn--mgberp4a5d4ar.

HTML how to clear input using javascript?

you can use attribute placeholder

<input type="text" name="email" placeholder="[email protected]" size="30" />

or try this for older browsers

<input type="text" name="email" value="[email protected]" size="30" onblur="if(this.value==''){this.value='[email protected]';}" onfocus="if(this.value=='[email protected]'){this.value='';}">

Resolve Javascript Promise outside function scope

I'm using a helper function to create what I call a "flat promise" -

function flatPromise() {

    let resolve, reject;

    const promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    });

    return { promise, resolve, reject };
}

And I'm using it like so -

function doSomethingAsync() {

    // Get your promise and callbacks
    const { resolve, reject, promise } = flatPromise();

    // Do something amazing...
    setTimeout(() => {
        resolve('done!');
    }, 500);

    // Pass your promise to the world
    return promise;

}

See full working example -

_x000D_
_x000D_
function flatPromise() {_x000D_
_x000D_
    let resolve, reject;_x000D_
_x000D_
    const promise = new Promise((res, rej) => {_x000D_
        resolve = res;_x000D_
        reject = rej;_x000D_
    });_x000D_
_x000D_
    return { promise, resolve, reject };_x000D_
}_x000D_
_x000D_
function doSomethingAsync() {_x000D_
    _x000D_
    // Get your promise and callbacks_x000D_
    const { resolve, reject, promise } = flatPromise();_x000D_
_x000D_
    // Do something amazing..._x000D_
    setTimeout(() => {_x000D_
        resolve('done!');_x000D_
    }, 500);_x000D_
_x000D_
    // Pass your promise to the world_x000D_
    return promise;_x000D_
}_x000D_
_x000D_
(async function run() {_x000D_
_x000D_
    const result = await doSomethingAsync()_x000D_
        .catch(err => console.error('rejected with', err));_x000D_
    console.log(result);_x000D_
_x000D_
})();
_x000D_
_x000D_
_x000D_

Edit: I have created an NPM package called flat-promise and the code is also available on GitHub.

Jenkins not executing jobs (pending - waiting for next executor)

I ran into a similar problem because my master was set to " # of executor (The maximum number of concurrent builds that Jenkins may perform on this agent).

Go to Jenkins --> Manage Jenkins --> Manage Nodes, and click on the configure button of your master node (increase the number of executor to run mutiple jobs at a time).

Object Dump JavaScript

In Chrome, click the 3 dots and click More tools and click developer. On the console, type console.dir(yourObject).Click this link to view an example image

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

I was Working with Elastic SQL plugin. Query is done with GET method using cURL as below:

curl -XGET http://localhost:9200/_sql/_explain -H 'Content-Type: application/json' \
-d 'SELECT city.keyword as city FROM routes group by city.keyword order by city'

I exposed a custom port at public server, doing a reverse proxy with Basic Auth set.

This code, works fine plus Basic Auth Header:

$host = 'http://myhost.com:9200';
$uri = "/_sql/_explain";
$auth = "john:doe";
$data = "SELECT city.keyword as city FROM routes group by city.keyword order by city";

function restCurl($host, $uri, $data = null, $auth = null, $method = 'DELETE'){
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $host.$uri);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if ($method == 'POST')
        curl_setopt($ch, CURLOPT_POST, 1);
    if ($auth)
        curl_setopt($ch, CURLOPT_USERPWD, $auth);
    if (strlen($data) > 0)
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

    $resp  = curl_exec($ch);
    if(!$resp){
        $resp = (json_encode(array(array("error" => curl_error($ch), "code" => curl_errno($ch)))));
    }   
    curl_close($ch);
    return $resp;
}

$resp = restCurl($host, $uri); //DELETE
$resp = restCurl($host, $uri, $data, $auth, 'GET'); //GET
$resp = restCurl($host, $uri, $data, $auth, 'POST'); //POST
$resp = restCurl($host, $uri, $data, $auth, 'PUT'); //PUT

How to remove and clear all localStorage data

If you want to remove/clean all the values from local storage than use

localStorage.clear();

And if you want to remove the specific item from local storage than use the following code

localStorage.removeItem(key);

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

SQL Server - boolean literal?

select * from SomeTable where 1=1

How to build a query string for a URL in C#?

I needed to solve the same problem for a portable class library (PCL) that I'm working on. In this case, I don't have access to System.Web so I can't use ParseQueryString.

Instead I used System.Net.Http.FormUrlEncodedContent like so:

var url = new UriBuilder("http://example.com");

url.Query = new FormUrlEncodedContent(new Dictionary<string,string>()
{
    {"param1", "val1"},
    {"param2", "val2"},
    {"param3", "val3"},
}).ReadAsStringAsync().Result;

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

How to set the part of the text view is clickable

Boom Check this for java Lovers :D We can modify it according to our need:

List<Pair<String, View.OnClickListener>> pairsList = new ArrayList<>();

        pairsList.add(new Pair<>("38,50", v -> {
            Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
            intent.putExtra("which", "tos");
            startActivity(intent);
        }));

        pairsList.add(new Pair<>("81,95", v -> {
            Intent intent = new Intent(SignUpActivity.this, WebActivity.class);
            intent.putExtra("which", "policy");
            startActivity(intent);
        }));

        makeLinks(pairsList); // Method calling


private void makeLinks(List<Pair<String, View.OnClickListener>> pairsList) {

        SpannableString ss = new SpannableString(By signing up, I’m agree to PAKRISM’s Terms of Use and confirms that I have read Privacy Policy);

        for (Pair<String, View.OnClickListener> pair : pairsList) {

            ClickableSpan clickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View textView) {
                    //Toast.makeText(MyApplication.getAppContext(), "Clicked!", Toast.LENGTH_SHORT).show();
                    pair.second.onClick(textView);
                }

                @Override
                public void updateDrawState(TextPaint ds) {

                    ds.linkColor = ContextCompat.getColor(SignUpActivity.this, R.color.primary_main);
                    ds.setUnderlineText(true);

                    super.updateDrawState(ds);
                }
            };

            String[] indexes = pair.first.split(",");
            ss.setSpan(clickableSpan, Integer.parseInt(indexes[0]), Integer.parseInt(indexes[1]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        
        TextView tv = findViewById(R.id.txtView);
        tv.setText(ss);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    }

Get List of connected USB Devices

  lstResult.Clear();
  foreach (ManagementObject drive in new ManagementObjectSearcher("select * from Win32_DiskDrive where InterfaceType='USB'").Get())
  {
       foreach (ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + drive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
       {
            foreach (ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
            {
                  foreach (var item in disk.Properties)
                  {
                       object value = disk.GetPropertyValue(item.Name);
                  }
                  string valor = disk["Name"].ToString();
                  lstResult.Add(valor);
                  }
             }
        }
   }

Are complex expressions possible in ng-hide / ng-show?

I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide

Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

use request.getContextPath() instead of ${pageContext.request.contextPath} in JSP expression language.

<%
String contextPath = request.getContextPath();
%>
out.println(contextPath);

output: willPrintMyProjectcontextPath

When to use Interface and Model in TypeScript / Angular

As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.

iframe refuses to display

For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:

Content-Security-Policy: frame-ancestors 'self'

Or, add this to your web server's CSP configuration.

How to add elements of a string array to a string array list?

You already have built-in method for that: -

List<String> species = Arrays.asList(speciesArr);

NOTE: - You should use List<String> species not ArrayList<String> species.

Arrays.asList returns a different ArrayList -> java.util.Arrays.ArrayList which cannot be typecasted to java.util.ArrayList.

Then you would have to use addAll method, which is not so good. So just use List<String>

NOTE: - The list returned by Arrays.asList is a fixed size list. If you want to add something to the list, you would need to create another list, and use addAll to add elements to it. So, then you would better go with the 2nd way as below: -

    String[] arr = new String[1];
    arr[0] = "rohit";
    List<String> newList = Arrays.asList(arr);

    // Will throw `UnsupportedOperationException
    // newList.add("jain"); // Can't do this.

    ArrayList<String> updatableList = new ArrayList<String>();

    updatableList.addAll(newList); 

    updatableList.add("jain"); // OK this is fine. 

    System.out.println(newList);       // Prints [rohit]
    System.out.println(updatableList); //Prints [rohit, jain]

What is @RenderSection in asp.net MVC

Here the defination of Rendersection from MSDN

In layout pages, renders the content of a named section.MSDN

In _layout.cs page put

@RenderSection("Bottom",false)

Here render the content of bootom section and specifies false boolean property to specify whether the section is required or not.

@section Bottom{
       This message form bottom.
}

That meaning if you want to bottom section in all pages, then you must use false as the second parameter at Rendersection method.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

I had the same problem and I solved it as follows:

  1. check the node-sass version used in the current project

  2. go to node-sass release: "https://github.com/sass/node-sass/releases/tag/v@.@.@" (put your node-sass version here)

  3. check the Supported Environment table and see if your Node version exist in it

  4. if it is not, downgrade your node version to the latest version existing in the table

I know it's not the perfect solution but I didn't find anything else in my case.

How do I convert datetime.timedelta to minutes, hours in Python?

A datetime.timedelta corresponds to the difference between two dates, not a date itself. It's only expressed in terms of days, seconds, and microseconds, since larger time units like months and years don't decompose cleanly (is 30 days 1 month or 0.9677 months?).

If you want to convert a timedelta into hours and minutes, you can use the total_seconds() method to get the total number of seconds and then do some math:

x = datetime.timedelta(1, 5, 41038)  # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60

ERROR 2006 (HY000): MySQL server has gone away

If it's reconnecting and getting connection ID 2, the server has almost definitely just crashed.

Contact the server admin and get them to diagnose the problem. No non-malicious SQL should crash the server, and the output of mysqldump certainly should not.

It is probably the case that the server admin has made some big operational error such as assigning buffer sizes of greater than the architecture's address-space limits, or more than virtual memory capacity. The MySQL error-log will probably have some relevant information; they will be monitoring this if they are competent anyway.

How should I call 3 functions in order to execute them one after the other?

If method 1 has to be executed after method 2, 3, 4. The following code snippet can be the solution for this using Deferred object in JavaScript.

_x000D_
_x000D_
function method1(){_x000D_
  var dfd = new $.Deferred();_x000D_
     setTimeout(function(){_x000D_
     console.log("Inside Method - 1"); _x000D_
     method2(dfd);  _x000D_
    }, 5000);_x000D_
  return dfd.promise();_x000D_
}_x000D_
_x000D_
function method2(dfd){_x000D_
  setTimeout(function(){_x000D_
   console.log("Inside Method - 2"); _x000D_
   method3(dfd); _x000D_
  }, 3000);_x000D_
}_x000D_
_x000D_
function method3(dfd){_x000D_
  setTimeout(function(){_x000D_
   console.log("Inside Method - 3");  _x000D_
   dfd.resolve();_x000D_
  }, 3000);_x000D_
}_x000D_
_x000D_
function method4(){   _x000D_
   console.log("Inside Method - 4");  _x000D_
}_x000D_
_x000D_
var call = method1();_x000D_
_x000D_
$.when(call).then(function(cb){_x000D_
  method4();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to implement oauth2 server in ASP.NET MVC 5 and WEB API 2

Gmail: OAuth

  • Goto the link
  • Login with your gmail username password
  • Click on the google menu at the top left
  • Click API Manager
  • Click on Credentials
  • Click Create Credentials and select OAuth Client
  • Select Web Application as Application type and Enter the Name-> Enter Authorised Redirect URL (Eg: http://localhost:53922/signin-google) ->Click on Create button. This will create the credentials. Pls make a note of Client ID and Secret ID. Finally click OK to close the credentials pop up.
  • Next important step is to enable the Google API. Click on Overview in the left pane.
  • Click on the Google API under Social APIs section.
  • Click Enable.

That’s all from the Google part.

Come back to your application, open App_start/Startup.Auth.cs and uncomment the following snippet

        app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        {
            ClientId = "",
            ClientSecret = ""
        });

Update the ClientId and ClientSecret with the values from Google API credentials which you have created already.

  • Run your application
  • Click Login
  • You will see the Google button under ‘Use Another Section to log in’ section
  • Click on the Google button
  • Application will prompt you to enter the username and password
  • Enter the gmail username and password and click Sign In
  • This will perform the OAuth and come back to your application and prompting you to register with the Gmail id.
  • Click register to register the Gmail id into your application database.
  • You will see the Identity details appear in the top as normal registration
  • Try logout and login again thru Gmail. This will automatically logs you into the app.

Can't find bundle for base name

java.util.MissingResourceException: Can't find bundle for base name
    org.jfree.chart.LocalizationBundle, locale en_US

To the point, the exception message tells in detail that you need to have either of the following files in the classpath:

/org/jfree/chart/LocalizationBundle.properties

or

/org/jfree/chart/LocalizationBundle_en.properties

or

/org/jfree/chart/LocalizationBundle_en_US.properties

Also see the official Java tutorial about resourcebundles for more information.

But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.

When executing a JAR file, you can use the -cp argument to specify the classpath. E.g.:

java -jar -cp c:/path/to/jfreechart.jar yourfile.jar

Alternatively you can specify the classpath as class-path entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH% environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe without -cp, -classpath and -jar arguments.

How to check radio button is checked using JQuery?

Check this one out, too:

$(document).ready(function() { 
  if($("input:radio[name='yourRadioGroupName'][value='yourvalue']").is(":checked")) { 
      //its checked 
  } 
});