Programs & Examples On #Continuations

In computer science and programming, a continuation is an abstract representation of the control state. A continuation reifies an instance of a computational process at a given point in the process's execution. It contains information such as the process's current stack (including all data whose lifetime is within the process e.g. "local variables"), as well the process's point in the computation.

HttpClient.GetAsync(...) never returns when using await/async

Edit: Generally try to avoid doing the below except as a last ditch effort to avoid deadlocks. Read the first comment from Stephen Cleary.

Quick fix from here. Instead of writing:

Task tsk = AsyncOperation();
tsk.Wait();

Try:

Task.Run(() => AsyncOperation()).Wait();

Or if you need a result:

var result = Task.Run(() => AsyncOperation()).Result;

From the source (edited to match the above example):

AsyncOperation will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of AsyncOperation won’t be forced back to the invoking thread.

For me this looks like a useable option since I do not have the option of making it async all the way (which I would prefer).

From the source:

Ensure that the await in the FooAsync method doesn’t find a context to marshal back to. The simplest way to do that is to invoke the asynchronous work from the ThreadPool, such as by wrapping the invocation in a Task.Run, e.g.

int Sync() { return Task.Run(() => Library.FooAsync()).Result; }

FooAsync will now be invoked on the ThreadPool, where there won’t be a SynchronizationContext, and the continuations used inside of FooAsync won’t be forced back to the thread that’s invoking Sync().

What does Ruby have that Python doesn't, and vice versa?

"Variables that start with a capital letter becomes constants and can't be modified"

Wrong. They can.

You only get a warning if you do.

how to parse JSONArray in android

Here is a better way for doing it. Hope this helps

protected void onPostExecute(String result) {
                Log.v(TAG + " result);


                if (!result.equals("")) {

                    // Set up variables for API Call
                    ArrayList<String> list = new ArrayList<String>();

                    try {
                        JSONArray jsonArray = new JSONArray(result);

                        for (int i = 0; i < jsonArray.length(); i++) {

                            list.add(jsonArray.get(i).toString());

                        }//end for
                    } catch (JSONException e) {
                        Log.e(TAG, "onPostExecute > Try > JSONException => " + e);
                        e.printStackTrace();
                    }


                    adapter = new ArrayAdapter<String>(ListViewData.this, android.R.layout.simple_list_item_1, android.R.id.text1, list);
                    listView.setAdapter(adapter);
                    listView.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                            // ListView Clicked item index
                            int itemPosition = position;

                            // ListView Clicked item value
                            String itemValue = (String) listView.getItemAtPosition(position);

                            // Show Alert
                            Toast.makeText( ListViewData.this, "Position :" + itemPosition + "  ListItem : " + itemValue, Toast.LENGTH_LONG).show();
                        }
                    });

                    adapter.notifyDataSetChanged();
...

How do I add the Java API documentation to Eclipse?

For offline Javadoc from zip file rather than extracting it.

Why this approach?

This is already answered which uses extracted zip data but it consumes more memory than simple zip file.

Comparison of zip file and extracted data.

jdk-6u25-fcs-bin-b04-apidocs.zip  --->  ~57 MB
after extracting this zip file  --->  ~264 MB !

So this approach saves my approx. 200 MB.

How to use apidocs.zip?

1.Open Windows -> Preferences

enter image description here

2.Select jre from Installed JREs then Click Edit...

enter image description here

3.Select all .jar files from JRE system libraries then Click Javadoc Location...

enter image description here

4.Browse for apidocs.zip file for Archive path and set Path within archive as shown above. That's it.

5.Put cursor on any class name or method name and hit Shift + F2

COALESCE with Hive SQL

Hive supports bigint literal since 0.8 version. So, additional "L" is enough:

COALESCE(column, 0L)

No converter found capable of converting from type to type

You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.

Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation

import org.springframework.beans.factory.annotation.Value;

public interface DeadlineTypeProjection {
    String getId();

    // can get code and or change name of getter below
    String getCode();

    // Points to the code attribute of entity class
    @Value(value = "#{target.code}")
    String getText();
}

DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class DeadlineType {
    String id;

    // Use this annotation if you need to change the name of the property that is passed back from controller
    // Needs to be called code to be used in Repository
    @JsonProperty(value = "text")
    String code;

}

Entity class

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {

    @Id
    private String id;
    private String code;
}

Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>

import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {

    List<ABDeadlineType> findAll();

    List<DeadlineType> findAllDtoBy();

    List<DeadlineTypeProjection> findAllProjectionBy();

}

Example Controller - accesses the repository directly to simplify code

@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {

    private final ABDeadlineTypeRepository abDeadlineTypeRepository;

    @Autowired
    public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
        this.abDeadlineTypeRepository = abDeadlineTypeRepository;
    }

    @GetMapping(value = "/list")
    public ResponseEntity<List<ABDeadlineType>> list() {

        List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listdto")
    public ResponseEntity<List<DeadlineType>> listDto() {

        List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
        return ResponseEntity.ok(types);
    }

    @GetMapping(value = "/listprojection")
    public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {

        List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
        return ResponseEntity.ok(types);
    }
}

Hope that helps

Les

How can I disable the bootstrap hover color for links?

if anyone cares i ended up with:

a {
    color: inherit;
}

Python "SyntaxError: Non-ASCII character '\xe2' in file"

I had this exact issue running the simple .py code below:

import sys
print 'version is:', sys.version

DSM's code above provided the following:

1 'print \xe2\x80\x98version is\xe2\x80\x99, sys.version'

So the issue was that my text editor used SMART QUOTES, as John Y suggested. After changing the text editor settings and re-opening/saving the file, it works just fine.

How to JUnit test that two List<E> contain the same elements in the same order?

org.junit.Assert.assertEquals() and org.junit.Assert.assertArrayEquals() do the job.

To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))

If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet.

Yet another tip. The trick Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two)) works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet. You can use TreeSet with custom comparator.

How do you get the current time of day?

Get the current date and time, then just use the time portion of it. Look at the possibilities for formatting a date time string in the MSDN docs.

Remove the string on the beginning of an URL

Either manually, like

var str = "www.test.com",
    rmv = "www.";

str = str.slice( str.indexOf( rmv ) + rmv.length );

or just use .replace():

str = str.replace( rmv, '' );

How can I get phone serial number (IMEI)

Use below code for IMEI:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String imei= tm.getDeviceId();

Git Remote: Error: fatal: protocol error: bad line length character: Unab

Maybe you have a statement in the server's .bashrc that produces output. I, for example had this:

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm"
rvm use ruby-1.9.3-p194@rails32

In this case the output from the rvm use will be (wrongly) interpreted as coming from git. So replace it by:

rvm use ruby-1.9.3-p194@rails32 > /dev/null

How to echo (or print) to the js console with php

You can also try this way:

<?php
   echo "<script>console.log('$variableName')</script>";
?>

Git: See my last commit

As determined via comments, it appears that the OP is looking for

$ git log --name-status HEAD^..HEAD

This is also very close to the output you'd get from svn status or svn log -v, which many people coming from subversion to git are familiar with.

--name-status is the key here; as noted by other folks in this question, you can use git log -1, git show, and git diff to get the same sort of output. Personally, I tend to use git show <rev> when looking at individual revisions.

Easily measure elapsed time

In answer to OP's three specific questions.

"What I don't understand is why the values in the before and after are the same?"

The first question and sample code shows that time() has a resolution of 1 second, so the answer has to be that the two functions execute in less than 1 second. But occasionally it will (apparently illogically) inform 1 second if the two timer marks straddle a one second boundary.

The next example uses gettimeofday() which fills this struct

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

and the second question asks: "How do I read a result of **time taken = 0 26339? Does that mean 26,339 nanoseconds = 26.3 msec?"

My second answer is the time taken is 0 seconds and 26339 microseconds, that is 0.026339 seconds, which bears out the first example executing in less than 1 second.

The third question asks: "What about **time taken = 4 45025, does that mean 4 seconds and 25 msec?"

My third answer is the time taken is 4 seconds and 45025 microseconds, that is 4.045025 seconds, which shows that OP has altered the tasks performed by the two functions which he previously timed.

How do I read and parse an XML file in C#?

You could use a DataSet to read XML strings.

var xmlString = File.ReadAllText(FILE_PATH);
var stringReader = new StringReader(xmlString);
var dsSet = new DataSet();
dsSet.ReadXml(stringReader);

Posting this for the sake of information.

Modulo operation with negative numbers

C99 requires that when a/b is representable:

(a/b) * b + a%b shall equal a

This makes sense, logically. Right?

Let's see what this leads to:


Example A. 5/(-3) is -1

=> (-1) * (-3) + 5%(-3) = 5

This can only happen if 5%(-3) is 2.


Example B. (-5)/3 is -1

=> (-1) * 3 + (-5)%3 = -5

This can only happen if (-5)%3 is -2

How to clear APC cache entries?

If you want to monitor the results via json, you can use this kind of script:

<?php

$result1 = apc_clear_cache();
$result2 = apc_clear_cache('user');
$result3 = apc_clear_cache('opcode');
$infos = apc_cache_info();
$infos['apc_clear_cache'] = $result1;
$infos["apc_clear_cache('user')"] = $result2;
$infos["apc_clear_cache('opcode')"] = $result3;
$infos["success"] = $result1 && $result2 && $result3;
header('Content-type: application/json');
echo json_encode($infos);

As mentioned in other answers, this script will have to be called via http or curl and you will have to be secured if it is exposed in the web root of your application. (by ip, token...)

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

How can I create a small color box using html and css?

You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.

_x000D_
_x000D_
.foo {_x000D_
  float: left;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  margin: 5px;_x000D_
  border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
  background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
  background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
  background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
_x000D_
_x000D_

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

I was facing this same scaring error... :) Then I realized that I was forgetting to set a

@Html.HiddenFor(model => model.UserProfile.UserId)

for the primary key of the object being updated! I tend to forget this simple, but very important thingy!

By the way: HiddenFor is for ASP.NET MVC.

What represents a double in sql server?

It sounds like you can pick and choose. If you pick float, you may lose 11 digits of precision. If that's acceptable, go for it -- apparently the Linq designers thought this to be a good tradeoff.

However, if your application needs those extra digits, use decimal. Decimal (implemented correctly) is way more accurate than a float anyway -- no messy translation from base 10 to base 2 and back.

Sleep function in Windows, using C

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleep for this function is misleading, since the CPU will not be sleeping at all.

In Java, how can I determine if a char array contains a particular character?

Some other options if you do not want your own "Utils"-class:

Use Apache commons lang (ArrayUtils):

@Test
public void arrayCommonLang(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(ArrayUtils.contains(test, 'o'));
    Assert.assertFalse(ArrayUtils.contains(test, 'p'));
}

Or use the builtin Arrays:

@Test
public void arrayTest(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(Arrays.binarySearch(test, 'o') >= 0);
    Assert.assertTrue(Arrays.binarySearch(test, 'p') < 0);
}

Or use the Chars class from Google Guava:

@Test
public void testGuava(){
    char[] test = {'h', 'e', 'l', 'l', 'o'};
    Assert.assertTrue(Chars.contains(test, 'o'));
    Assert.assertFalse(Chars.contains(test, 'p'));
}

Slightly off-topic, the Chars class allows to find a subarray in an array.

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Another neat option is to use the Directive as an element and not as an attribute.

@Directive({
   selector: 'app-directive'
})
export class InformativeDirective implements AfterViewInit {

    @Input()
    public first: string;

    @Input()
    public second: string;

    ngAfterViewInit(): void {
       console.log(`Values: ${this.first}, ${this.second}`);
    }
}

And this directive can be used like that:

<app-someKindOfComponent>
    <app-directive [first]="'first 1'" [second]="'second 1'">A</app-directive>
    <app-directive [first]="'First 2'" [second]="'second 2'">B</app-directive>
    <app-directive [first]="'First 3'" [second]="'second 3'">C</app-directive>
</app-someKindOfComponent>`

Simple, neat and powerful.

Viewing my IIS hosted site on other machines on my network

It might be late, but for any other person who may get such an issue in future, for any connections you want to make to the server (in this case the machine that hosts the web application, regardless if it is iis or xampp) you need to allow connection or traffic through the specific port that will be used in the firewall

1. Go to Windows Firewall -> Advanced settings
2. Click Inbound Rules -> Then New Rule
3. Select Port -> Next
4. Specific local ports -> Add the Port you want to allow
5. Allow All Connections
6. Enter a name and a description for to help you remember later on

and you Done

Best way to call a JSON WebService from a .NET Console

I use HttpWebRequest to GET from the web service, which returns me a JSON string. It looks something like this for a GET:

// Returns JSON string
string GET(string url) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    try {
        WebResponse response = request.GetResponse();
        using (Stream responseStream = response.GetResponseStream()) {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
            return reader.ReadToEnd();
        }
    }
    catch (WebException ex) {
        WebResponse errorResponse = ex.Response;
        using (Stream responseStream = errorResponse.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
            String errorText = reader.ReadToEnd();
            // log errorText
        }
        throw;
    }
}

I then use JSON.Net to dynamically parse the string. Alternatively, you can generate the C# class statically from sample JSON output using this codeplex tool: http://jsonclassgenerator.codeplex.com/

POST looks like this:

// POST a JSON string
void POST(string url, string jsonContent) 
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream()) {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) {
            length = response.ContentLength;
        }
    }
    catch (WebException ex) {
        // Log exception and throw as for GET example above
    }
}

I use code like this in automated tests of our web service.

Find Number of CPUs and Cores per CPU using Command Prompt

In order to check the absence of physical sockets run:

wmic cpu get SocketDesignation

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

This is how you get rid of that notice and be able to open those grid cells for edit

1) click "STRUCTURE"

2) go to the field you want to be a primary key (and this usually is the 1st one ) and then click on the "PRIMARY" and "INDEX" fields for that field and accept the PHPMyadmin's pop-up question "OK".

3) pad yourself in the back.

Converting List<Integer> to List<String>

List<String> stringList = integerList.stream().map((Object s)->String.valueOf(s)).collect(Collectors.toList())

Cannot get to $rootScope

You can not ask for instance during configuration phase - you can ask only for providers.

var app = angular.module('modx', []);

// configure stuff
app.config(function($routeProvider, $locationProvider) {
  // you can inject any provider here
});

// run blocks
app.run(function($rootScope) {
  // you can inject any instance here
});

See http://docs.angularjs.org/guide/module for more info.

Java: Date from unix timestamp

Sometimes you need to work with adjustments.

Don't use cast to long! Use nanoadjustment.

For example, using Oanda Java API for trading you can get datetime as UNIX format.

For example: 1592523410.590566943

    System.out.println("instant with nano = " + Instant.ofEpochSecond(1592523410, 590566943));
    System.out.println("instant = " + Instant.ofEpochSecond(1592523410));

you get:

instant with nano = 2020-06-18T23:36:50.590566943Z
instant = 2020-06-18T23:36:50Z

Also, use:

 Date date = Date.from( Instant.ofEpochSecond(1592523410, 590566943) );

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

Deserialize a json string to an object in python

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

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

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

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

TL;DR: python -m pip install -U pip, then try again.


I was already using a venv (virtualenv) in PyCharm.

Creating it I clicked inherit global site packages checkbox, to allow packages installed via an installer to work. Now inside my venv there was no pip installed, so it would use the inherited global pip.

Here is how the error went:

(venv) D:\path\to\my\project> pip install certifi  # or any other package

Would fail with

PermissionError: [WinError 5] Access denied: 'c:\\program files\\python36\\Lib\\site-packages\\certifi'

Notice how that is the path of the system python, not the venv one. However we want it to execute in the right environment.

Here some more digging:

(venv) D:\path\to\my\project> which pip
/c/Program Files/Python36/Scripts/pip

(venv) D:\path\to\my\project> which python
/d/path/to/my/project/venv/Scripts/python

So python is using the correct path, but pip is not? Let's install pip here in the correct one as well:

(venv) D:\path\to\my\project> python -m pip install -U pip
... does stuff ...
Successfully installed pip

Now that's better. Running the original failing command again now works, as it is using the correct pip.

(venv) D:\path\to\my\project> pip install certifi  # or any other package
... install noise ...
Successfully installed certifi-2019.9.11 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.7

Adding Image to xCode by dragging it from File

Add the image to Your project by clicking File -> "Add Files to ...".

Then choose the image in ImageView properties (Utilities -> Attributes Inspector).

Redirecting a page using Javascript, like PHP's Header->Location

You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)

You can use window.location to change your current page.

$('.entry a:first').click(function() {
    window.location = "http://google.ca";
});

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

5 Jan 2021: link update thanks to @Sadap's comment.

Kind of a corollary answer: the people on this site have taken the time to make tables of macros defined for every OS/compiler pair.

For example, you can see that _WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).

Anyway, I found the tables quite informative and thought I'd share here.

Iterate keys in a C++ map

When no explicit begin and end is needed, ie for range-looping, the loop over keys (first example) or values (second example) can be obtained with

#include <boost/range/adaptors.hpp>

map<Key, Value> m;

for (auto k : boost::adaptors::keys(m))
  cout << k << endl;

for (auto v : boost::adaptors::values(m))
  cout << v << endl;

What is the maximum length of a table name in Oracle?

Oracle database object names maximum length is 30 bytes.

Object Name Rules: http://docs.oracle.com/database/121/SQLRF/sql_elements008.htm

Convert Char to String in C

Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn't seem right.

You could simply build this buffer on your own:

char buffer[MAX_SIZE_OF_MY_BUFFER];

int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
    buffer[i++] = ch;
}
buffer[i] = '\0';  // terminating character

Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters

How to load URL in UIWebView in Swift?

Try this:

  1. Add UIWebView to View.

  2. Connect UIWebview outlet using assistant editor and name your "webview".

  3. UIWebView Load URL.

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
       super.viewDidLoad()
        // Your webView code goes here
       let url = URL(string: "https://www.example.com")
       let requestObj = URLRequest(url: url! as URL)
       webView.load(requestObj)
    }
    

And run the app!!

How can I read inputs as numbers?

Solution

Since Python 3, input returns a string which you have to explicitly convert to ints, with int, like this

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

You can accept numbers of any base and convert them directly to base-10 with the int function, like this

>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365

The second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a ValueError.

>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'

For values that can have a fractional component, the type would be float rather than int:

x = float(input("Enter a number:"))

Differences between Python 2 and 3

Summary

  • Python 2's input function evaluated the received data, converting it to an integer implicitly (read the next section to understand the implication), but Python 3's input function does not do that anymore.
  • Python 2's equivalent of Python 3's input is the raw_input function.

Python 2.x

There were two functions to get user input, called input and raw_input. The difference between them is, raw_input doesn't evaluate the data and returns as it is, in string form. But, input will evaluate whatever you entered and the result of evaluation will be returned. For example,

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

The data 5 + 17 is evaluated and the result is 22. When it evaluates the expression 5 + 17, it detects that you are adding two numbers and so the result will also be of the same int type. So, the type conversion is done for free and 22 is returned as the result of input and stored in data variable. You can think of input as the raw_input composed with an eval call.

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

Note: you should be careful when you are using input in Python 2.x. I explained why one should be careful when using it, in this answer.

But, raw_input doesn't evaluate the input and returns as it is, as a string.

>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)

Python 3.x

Python 3.x's input and Python 2.x's raw_input are similar and raw_input is not available in Python 3.x.

>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)

Matplotlib (pyplot) savefig outputs blank image

First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists.

Second, after plt.show() is called, a new figure is created. To deal with this, you can

  1. Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show()

  2. Save the figure before you show() by calling plt.gcf() for "get current figure", then you can call savefig() on this Figure object at any time.

For example:

fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)

In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.

Convert Set to List without creating new List

Also from Guava Collect library, you can use newArrayList(Collection):

Lists.newArrayList([your_set])

This would be very similar to the previous answer from amit, except that you do not need to declare (or instanciate) any list object.

How to scroll to top of long ScrollView layout?

Had the same issue, probably some kind of bug.

Even the fullScroll(ScrollView.FOCUS_UP) from the other answer didn't work.
Only thing that worked for me was calling scroll_view.smoothScrollTo(0,0) right after the dialog is shown.

Capturing "Delete" Keypress with jQuery

$('html').keyup(function(e){
    if(e.keyCode == 46) {
        alert('Delete key released');
    }
});

Source: javascript char codes key codes from www.cambiaresearch.com

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

In Visual Studio and most other half decent IDEs you can simply do SHIFT+TAB. It does the opposite of just TAB.

I would think and hope that the IDEs you mention support this as well.

How do I convert an integer to binary in JavaScript?

we can also calculate the binary for positive or negative numbers as below:

_x000D_
_x000D_
function toBinary(n){
    let binary = "";
    if (n < 0) {
      n = n >>> 0;
    }
    while(Math.ceil(n/2) > 0){
        binary = n%2 + binary;
        n = Math.floor(n/2);
    }
    return binary;
}

console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
_x000D_
_x000D_

Given URL is not permitted by the application configuration

Sometimes this error occurs for old javascript sdk. If you save locally javascript file. Update it. I prefer to load it form the facebook server all the time.

Left align and right align within div in Bootstrap

bootstrap 5.0

_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">

<div class="row">
  <div class="col-sm-6"><p class="float-start">left</p></div>  
  <div class="col-sm-6"><p class="float-end">right</p></div>  
</div>
_x000D_
_x000D_
_x000D_

A whole column can accommodate 12, 6 (col-sm-6) is exactly half, and in this half, one to the left(float-start) and one to the right(float-end).

more example

  • fontawesome-button

    _x000D_
    _x000D_
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css" integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w==" crossorigin="anonymous" />
    
    <div class="row">
      <div class=col-sm-6>
        <p class="float-start text-center">  <!-- text-center can help you put the icon at the center -->
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-left fa-3x"></i><br>Left
          </a>
        </p>
      </div>
      <div class=col-sm-6>
        <p class="float-end text-center">
          <a class="text-decoration-none" href="https://www.google.com/"
          ><i class="fas fa-arrow-circle-right fa-3x"></i><br>Right
          </a>
        </p>
      </div>  
    _x000D_
    _x000D_
    _x000D_

UILabel with text of two different colors

There is a Swift 3.0 solution

extension UILabel{


    func setSubTextColor(pSubString : String, pColor : UIColor){
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self.text!);
        let range = attributedString.mutableString.range(of: pSubString, options:NSString.CompareOptions.caseInsensitive)
        if range.location != NSNotFound {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: pColor, range: range);
        }
        self.attributedText = attributedString

    }
}

And there is an example of call :

let colorString = " (string in red)"
self.mLabel.text = "classic color" + colorString
self.mLabel.setSubTextColor(pSubString: colorString, pColor: UIColor.red)

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

How to take a screenshot programmatically on iOS

Swift 4:

func makeImage(withView view: UIView) -> UIImage? {

    let rect = view.bounds

    UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)

    guard let context = UIGraphicsGetCurrentContext() else {
      assertionFailure()
      return nil
    }

    view.layer.render(in: context)

    guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
      assertionFailure()
      return nil
    }

    UIGraphicsEndImageContext()

    return image
}

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Combine several images horizontally with Python

If all image’s heights are same,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x)) for x in imgs],
    axis=1
  )
)

maybe you can resize images before the concatenation like this,

imgs = [‘a.jpg’, ‘b.jpg’, ‘c.jpg’]
concatenated = Image.fromarray(
  np.concatenate(
    [np.array(Image.open(x).resize((640,480)) for x in imgs],
    axis=1
  )
)

Spring Boot: Cannot access REST Controller on localhost (404)

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the application package.

How can I use a search engine to search for special characters?

Unfortunately, there doesn't appear to be a magic bullet. Bottom line up front: "context".

Google indeed ignores most punctuation, with the following exceptions:

  1. Punctuation in popular terms that have particular meanings, like [ C++ ] or [ C# ] (both are names of programming languages), are not ignored.
  2. The dollar sign ($) is used to indicate prices. [ nikon 400 ] and [ nikon $400 ] will give different results.
  3. The hyphen - is sometimes used as a signal that the two words around it are very strongly connected. (Unless there is no space after the - and a space before it, in which case it is a negative sign.)
  4. The underscore symbol _ is not ignored when it connects two words, e.g. [ quick_sort ].

As such, it is not well suited for these types of searchs. Google Code however does have syntax for searching through their code projects, that includes a robust language/syntax for dealing with "special characters". If looking at someone else's code could help solve a problem, this may be an option.

Unfortunately, this is not a limitation unique to google. You may find that your best successes hinge on providing as much 'context' to the problem as possible. If you are searching to find what $- means, providing information about the problem's domain may yield good results.

For example, searching "special perl variables" quickly yields your answer in the first entry on the results page.

Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<>

One reason can be that the IEnumerable may contain an unknown number of items. Some implementations produce the list of items as you iterate over it (see yield for samples). That does not work very well with accessing items using an index. which would require you to know that there are at least that many items in the list.

Passing a Bundle on startActivity()?

Write this is the activity you are in:

Intent intent = new Intent(CurrentActivity.this,NextActivity.class);
intent.putExtras("string_name","string_to_pass");
startActivity(intent);

In the NextActivity.java

Intent getIntent = getIntent();
//call a TextView object to set the string to
TextView text = (TextView)findViewById(R.id.textview_id);
text.setText(getIntent.getStringExtra("string_name"));

This works for me, you can try it.

Source:https://www.c-sharpcorner.com/article/how-to-send-the-data-one-activity-to-another-activity-in-android-application/

Why is my CSS bundling not working with a bin deployed MVC4 app?

Omitting runAllManagedModulesForAllRequests="true" also worked for me. Add the following configuration in web.config:

<modules>
  <remove name="BundleModule" />
  <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
</modules>

runAllManagedModulesForAllRequests will impose a performance hit on your website if not used appropriately. Check out this article.

How to convert an Image to base64 string in java?

The problem is that you are returning the toString() of the call to Base64.encodeBase64(bytes) which returns a byte array. So what you get in the end is the default string representation of a byte array, which corresponds to the output you get.

Instead, you should do:

encodedfile = new String(Base64.encodeBase64(bytes), "UTF-8");

Laravel Soft Delete posts

Just an update for Laravel 5:

In Laravel 4.2:

use Illuminate\Database\Eloquent\SoftDeletingTrait;    
class Post extends Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

becomes in Laravel 5:

use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model {

    use SoftDeletes;
    protected $dates = ['deleted_at'];

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).

If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.

There is an /etc/ImageMagick/policy.xml file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).

If you're getting a ReadImage error as above, you can change the line to:

<policy domain="coder" rights="read" pattern="LABEL" />

which should fix the issue.

The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:

<policy domain="coder" rights="read|write" pattern="LABEL" />

...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).

List<String> to ArrayList<String> conversion issue

Take a look at ArrayList#addAll(Collection)

Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)

So basically you could use

ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);

Cross domain POST request is not sending cookie Ajax Jquery

I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.

Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.

I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

Yet another solution to get timezone offset:

TimeZone tz = TimeZone.getDefault();
String current_Time_Zone = getGmtOffsetString(tz.getRawOffset());

public static String getGmtOffsetString(int offsetMillis) {
    int offsetMinutes = offsetMillis / 60000;
    char sign = '+';
    if (offsetMinutes < 0) {
        sign = '-';
        offsetMinutes = -offsetMinutes;
    }
    return String.format("GMT%c%02d:%02d", sign, offsetMinutes/60, offsetMinutes % 60);
}

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

If you show the file in a canvas anyway you can also convert the canvas content to a blob object.

canvas.toBlob(function(my_file){
  //.toBlob is only implemented in > FF18 but there is a polyfill 
  //for other browsers https://github.com/blueimp/JavaScript-Canvas-to-Blob
  var myBlob = (my_file);
})

SUM OVER PARTITION BY

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

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

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

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

scp via java

plug: sshj is the only sane choice! See these examples to get started: download, upload.

How do I extract part of a string in t-sql

substring(field, 1,3) will work on your examples.

select substring(field, 1,3) from table

Also, if the alphabetic part is of variable length, you can do this to extract the alphabetic part:

select substring(field, 1, PATINDEX('%[1234567890]%', field) -1) 
from table
where PATINDEX('%[1234567890]%', field) > 0

Mobile overflow:scroll and overflow-scrolling: touch // prevent viewport "bounce"

There's a great blog post on this here:

http://www.kylejlarson.com/blog/2011/fixed-elements-and-scrolling-divs-in-ios-5/

Along with a demo here:

http://www.kylejlarson.com/files/iosdemo/

In summary, you can use the following on a div containing your main content:

.scrollable {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
}

The problem I think you're describing is when you try to scroll up within a div that is already at the top - it then scrolls up the page instead of up the div and causes a bounce effect at the top of the page. I think your question is asking how to get rid of this?

In order to fix this, the author suggests that you use ScrollFix to auto increase the height of scrollable divs.

It's also worth noting that you can use the following to prevent the user from scrolling up e.g. in a navigation element:

document.addEventListener('touchmove', function(event) {
   if(event.target.parentNode.className.indexOf('noBounce') != -1 
|| event.target.className.indexOf('noBounce') != -1 ) {
    event.preventDefault(); }
}, false);

Unfortunately there are still some issues with ScrollFix (e.g. when using form fields), but the issues list on ScrollFix is a good place to look for alternatives. Some alternative approaches are discussed in this issue.

Other alternatives, also mentioned in the blog post, are Scrollability and iScroll

How to disable auto-play for local video in iframe

I've tried all the possible solutions but nothing worked for local video bindings. I believe best solution would be to fix using jQuery if you still wants to use iframes.

$(document).ready(function () {
    var ownVideos = $("iframe");
    $.each(ownVideos, function (i, video) {                
        var frameContent = $(video).contents().find('body').html();
        if (frameContent) {
            $(video).contents().find('body').html(frameContent.replace("autoplay", ""));
        }
    });
});

Note: It'll find all the iframes on document ready and loop through each iframe contents and replace/remove autoplay attribute. This solution can be use anywhere in your project. If you would like to do for specific element then use the code under $.each function and replace $(video) with your iframe element id like $("#myIFrameId").

Database design for a survey

Definitely option #2, also I think you might have an oversight in the current schema, you might want another table:

+-----------+
| tblSurvey |
|-----------|
| SurveyId  |
+-----------+

+--------------+
| tblQuestion  |
|--------------|
| QuestionID   |
| SurveyID     |
| QuestionType |
| Question     |
+--------------+

+--------------+
| tblAnswer    |
|--------------|
| AnswerID     |
| QuestionID   |
| Answer       |
+--------------+

+------------------+
| tblUsersAnswer   |
|------------------|
| UserAnswerID     |
| AnswerID         |
| UserID           |
| Response         |
+------------------+

+-----------+
| tblUser   |
|-----------|
| UserID    |
| UserName  |
+-----------+

Each question is going to probably have a set number of answers which the user can select from, then the actual responses are going to be tracked in another table.

Databases are designed to store a lot of data, and most scale very well. There is no real need to user a lesser normal form simply to save on space anymore.

kill -3 to get java thread dump

When using kill -3 one should see the thread dump in the standard output. Most of the application servers write the standard output to a separate file. You should find it there when using kill -3. There are multiple ways of getting thread dumps:

  • kill -3 <PID>: Gives output to standard output.
  • If one has access to the console window where server is running, one can use Ctrl+Break combination of keys to generate the stack trace on STDOUT.
  • For hotspot VM's we can also use jstack command to generate a thread dump. It’s a part of the JDK. Syntax is as follows:

    Usage:
    
    jstack [-l] <pid> (to connect to running process)
    jstack -F [-m] [-l] <pid>(to connect to a hung process)
    
     - For JRockit JVM we can use JRCMD command which comes with JDK Syntax: 
       jrcmd <jrockit pid> [<command> [<arguments>]] [-l] [-f file] [-p] -h]
    

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

For those out there who still couldn't fix this, I did so by changing my 'this' to '$(this)' when using jQuery.

E.G:

$('.icon').click(function() {
    this.fadeOut();
});

Fixed:

$('.icon').click(function() {
    $(this).fadeOut();
});

SQL QUERY replace NULL value in a row with a value from the previous known value

Try this:

update Projects
set KickOffStatus=2 
where KickOffStatus is null

Print text instead of value from C enum

The question is you want write the name just one times.
I have an ider like this:

#define __ENUM(situation,num) \
    int situation = num;        const char * __##situation##_name = #situation;

    const struct {
        __ENUM(get_other_string, -203);//using a __ENUM Mirco make it ease to write, 
        __ENUM(get_negative_to_unsigned, -204);
        __ENUM(overflow,-205);
//The following two line showing the expanding for __ENUM
        int get_no_num = -201;      const char * __get_no_num_name = "get_no_num";
        int get_float_to_int = -202;        const char * get_float_to_int_name = "float_to_int_name";

    }eRevJson;
#undef __ENUM
    struct sIntCharPtr { int value; const char * p_name; };
//This function transform it to string.
    inline const char * enumRevJsonGetString(int num) {
        sIntCharPtr * ptr = (sIntCharPtr *)(&eRevJson);
        for (int i = 0;i < sizeof(eRevJson) / sizeof(sIntCharPtr);i++) {
            if (ptr[i].value == num) {
                return ptr[i].p_name;
            }
        }
        return "bad_enum_value";
    }

it uses a struct to insert enum, so that a printer to string could follows each enum value define.

int main(int argc, char *argv[]) {  
    int enum_test = eRevJson.get_other_string;
    printf("error is %s, number is %d\n", enumRevJsonGetString(enum_test), enum_test);

>error is get_other_string, number is -203

The difference to enum is builder can not report error if the numbers are repeated. if you don't like write number, __LINE__ could replace it:

#define ____LINE__ __LINE__
#define __ENUM(situation) \
    int situation = (____LINE__ - __BASELINE -2);       const char * __##situation##_name = #situation;
constexpr int __BASELINE = __LINE__;
constexpr struct {
    __ENUM(Sunday);
    __ENUM(Monday);
    __ENUM(Tuesday);
    __ENUM(Wednesday);
    __ENUM(Thursday);
    __ENUM(Friday);
    __ENUM(Saturday);
}eDays;
#undef __ENUM
inline const char * enumDaysGetString(int num) {
    sIntCharPtr * ptr = (sIntCharPtr *)(&eDays);
    for (int i = 0;i < sizeof(eDays) / sizeof(sIntCharPtr);i++) {
        if (ptr[i].value == num) {
            return ptr[i].p_name;
        }
    }
    return "bad_enum_value";
}
int main(int argc, char *argv[]) {  
    int d = eDays.Wednesday;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
    d = 1;
    printf("day %s, number is %d\n", enumDaysGetString(d), d);
}

>day Wednesday, number is 3 >day Monday, number is 1

Rails: Address already in use - bind(2) (Errno::EADDRINUSE)

Found the script below in this github issue. Works great for me.

#!/usr/bin/env ruby
port = ARGV.first || 3000
system("sudo echo kill-server-on #{port}")

pid = `sudo lsof -iTCP -sTCP:LISTEN -n -P | grep #{port} | awk '{ print $2 }' | head -n 1`.strip
puts "PID: #{pid}"
`kill -9 #{pid}` unless pid.empty?

You can either run it in irb or inside a ruby file.

For the latter, create server_killer.rb then run it with ruby server_killer.rb

SQL query return data from multiple tables

Part 1 - Joins and Unions

This answer covers:

  1. Part 1
    • Joining two or more tables using an inner join (See the wikipedia entry for additional info)
    • How to use a union query
    • Left and Right Outer Joins (this stackOverflow answer is excellent to describe types of joins)
    • Intersect queries (and how to reproduce them if your database doesn't support them) - this is a function of SQL-Server (see info) and part of the reason I wrote this whole thing in the first place.
  2. Part 2
    • Subqueries - what they are, where they can be used and what to watch out for
    • Cartesian joins AKA - Oh, the misery!

There are a number of ways to retrieve data from multiple tables in a database. In this answer, I will be using ANSI-92 join syntax. This may be different to a number of other tutorials out there which use the older ANSI-89 syntax (and if you are used to 89, may seem much less intuitive - but all I can say is to try it) as it is much easier to understand when the queries start getting more complex. Why use it? Is there a performance gain? The short answer is no, but it is easier to read once you get used to it. It is easier to read queries written by other folks using this syntax.

I am also going to use the concept of a small caryard which has a database to keep track of what cars it has available. The owner has hired you as his IT Computer guy and expects you to be able to drop him the data that he asks for at the drop of a hat.

I have made a number of lookup tables that will be used by the final table. This will give us a reasonable model to work from. To start off, I will be running my queries against an example database that has the following structure. I will try to think of common mistakes that are made when starting out and explain what goes wrong with them - as well as of course showing how to correct them.

The first table is simply a color listing so that we know what colors we have in the car yard.

mysql> create table colors(id int(3) not null auto_increment primary key, 
    -> color varchar(15), paint varchar(10));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from colors;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
3 rows in set (0.01 sec)

mysql> insert into colors (color, paint) values ('Red', 'Metallic'), 
    -> ('Green', 'Gloss'), ('Blue', 'Metallic'), 
    -> ('White' 'Gloss'), ('Black' 'Gloss');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from colors;
+----+-------+----------+
| id | color | paint    |
+----+-------+----------+
|  1 | Red   | Metallic |
|  2 | Green | Gloss    |
|  3 | Blue  | Metallic |
|  4 | White | Gloss    |
|  5 | Black | Gloss    |
+----+-------+----------+
5 rows in set (0.00 sec)

The brands table identifies the different brands of the cars out caryard could possibly sell.

mysql> create table brands (id int(3) not null auto_increment primary key, 
    -> brand varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from brands;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| brand | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.01 sec)

mysql> insert into brands (brand) values ('Ford'), ('Toyota'), 
    -> ('Nissan'), ('Smart'), ('BMW');
Query OK, 5 rows affected (0.00 sec)
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from brands;
+----+--------+
| id | brand  |
+----+--------+
|  1 | Ford   |
|  2 | Toyota |
|  3 | Nissan |
|  4 | Smart  |
|  5 | BMW    |
+----+--------+
5 rows in set (0.00 sec)

The model table will cover off different types of cars, it is going to be simpler for this to use different car types rather than actual car models.

mysql> create table models (id int(3) not null auto_increment primary key, 
    -> model varchar(15));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from models;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| model | varchar(15) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> insert into models (model) values ('Sports'), ('Sedan'), ('4WD'), ('Luxury');
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql> select * from models;
+----+--------+
| id | model  |
+----+--------+
|  1 | Sports |
|  2 | Sedan  |
|  3 | 4WD    |
|  4 | Luxury |
+----+--------+
4 rows in set (0.00 sec)

And finally, to tie up all these other tables, the table that ties everything together. The ID field is actually the unique lot number used to identify cars.

mysql> create table cars (id int(3) not null auto_increment primary key, 
    -> color int(3), brand int(3), model int(3));
Query OK, 0 rows affected (0.01 sec)

mysql> show columns from cars;
+-------+--------+------+-----+---------+----------------+
| Field | Type   | Null | Key | Default | Extra          |
+-------+--------+------+-----+---------+----------------+
| id    | int(3) | NO   | PRI | NULL    | auto_increment |
| color | int(3) | YES  |     | NULL    |                |
| brand | int(3) | YES  |     | NULL    |                |
| model | int(3) | YES  |     | NULL    |                |
+-------+--------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> insert into cars (color, brand, model) values (1,2,1), (3,1,2), (5,3,1), 
    -> (4,4,2), (2,2,3), (3,5,4), (4,1,3), (2,2,1), (5,2,3), (4,5,1);
Query OK, 10 rows affected (0.00 sec)
Records: 10  Duplicates: 0  Warnings: 0

mysql> select * from cars;
+----+-------+-------+-------+
| id | color | brand | model |
+----+-------+-------+-------+
|  1 |     1 |     2 |     1 |
|  2 |     3 |     1 |     2 |
|  3 |     5 |     3 |     1 |
|  4 |     4 |     4 |     2 |
|  5 |     2 |     2 |     3 |
|  6 |     3 |     5 |     4 |
|  7 |     4 |     1 |     3 |
|  8 |     2 |     2 |     1 |
|  9 |     5 |     2 |     3 |
| 10 |     4 |     5 |     1 |
+----+-------+-------+-------+
10 rows in set (0.00 sec)

This will give us enough data (I hope) to cover off the examples below of different types of joins and also give enough data to make them worthwhile.

So getting into the grit of it, the boss wants to know The IDs of all the sports cars he has.

This is a simple two table join. We have a table that identifies the model and the table with the available stock in it. As you can see, the data in the model column of the cars table relates to the models column of the cars table we have. Now, we know that the models table has an ID of 1 for Sports so lets write the join.

select
    ID,
    model
from
    cars
        join models
            on model=ID

So this query looks good right? We have identified the two tables and contain the information we need and use a join that correctly identifies what columns to join on.

ERROR 1052 (23000): Column 'ID' in field list is ambiguous

Oh noes! An error in our first query! Yes, and it is a plum. You see, the query has indeed got the right columns, but some of them exist in both tables, so the database gets confused about what actual column we mean and where. There are two solutions to solve this. The first is nice and simple, we can use tableName.columnName to tell the database exactly what we mean, like this:

select
    cars.ID,
    models.model
from
    cars
        join models
            on cars.model=models.ID

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
|  2 | Sedan  |
|  4 | Sedan  |
|  5 | 4WD    |
|  7 | 4WD    |
|  9 | 4WD    |
|  6 | Luxury |
+----+--------+
10 rows in set (0.00 sec)

The other is probably more often used and is called table aliasing. The tables in this example have nice and short simple names, but typing out something like KPI_DAILY_SALES_BY_DEPARTMENT would probably get old quickly, so a simple way is to nickname the table like this:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID

Now, back to the request. As you can see we have the information we need, but we also have information that wasn't asked for, so we need to include a where clause in the statement to only get the Sports cars as was asked. As I prefer the table alias method rather than using the table names over and over, I will stick to it from this point onwards.

Clearly, we need to add a where clause to our query. We can identify Sports cars either by ID=1 or model='Sports'. As the ID is indexed and the primary key (and it happens to be less typing), lets use that in our query.

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Bingo! The boss is happy. Of course, being a boss and never being happy with what he asked for, he looks at the information, then says I want the colors as well.

Okay, so we have a good part of our query already written, but we need to use a third table which is colors. Now, our main information table cars stores the car color ID and this links back to the colors ID column. So, in a similar manner to the original, we can join a third table:

select
    a.ID,
    b.model
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  3 | Sports |
|  8 | Sports |
| 10 | Sports |
+----+--------+
4 rows in set (0.00 sec)

Damn, although the table was correctly joined and the related columns were linked, we forgot to pull in the actual information from the new table that we just linked.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
where
    b.ID=1

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
+----+--------+-------+
4 rows in set (0.00 sec)

Right, that's the boss off our back for a moment. Now, to explain some of this in a little more detail. As you can see, the from clause in our statement links our main table (I often use a table that contains information rather than a lookup or dimension table. The query would work just as well with the tables all switched around, but make less sense when we come back to this query to read it in a few months time, so it is often best to try to write a query that will be nice and easy to understand - lay it out intuitively, use nice indenting so that everything is as clear as it can be. If you go on to teach others, try to instill these characteristics in their queries - especially if you will be troubleshooting them.

It is entirely possible to keep linking more and more tables in this manner.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

While I forgot to include a table where we might want to join more than one column in the join statement, here is an example. If the models table had brand-specific models and therefore also had a column called brand which linked back to the brands table on the ID field, it could be done as this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
            and b.brand=d.ID
where
    b.ID=1

You can see, the query above not only links the joined tables to the main cars table, but also specifies joins between the already joined tables. If this wasn't done, the result is called a cartesian join - which is dba speak for bad. A cartesian join is one where rows are returned because the information doesn't tell the database how to limit the results, so the query returns all the rows that fit the criteria.

So, to give an example of a cartesian join, lets run the following query:

select
    a.ID,
    b.model
from
    cars a
        join models b

+----+--------+
| ID | model  |
+----+--------+
|  1 | Sports |
|  1 | Sedan  |
|  1 | 4WD    |
|  1 | Luxury |
|  2 | Sports |
|  2 | Sedan  |
|  2 | 4WD    |
|  2 | Luxury |
|  3 | Sports |
|  3 | Sedan  |
|  3 | 4WD    |
|  3 | Luxury |
|  4 | Sports |
|  4 | Sedan  |
|  4 | 4WD    |
|  4 | Luxury |
|  5 | Sports |
|  5 | Sedan  |
|  5 | 4WD    |
|  5 | Luxury |
|  6 | Sports |
|  6 | Sedan  |
|  6 | 4WD    |
|  6 | Luxury |
|  7 | Sports |
|  7 | Sedan  |
|  7 | 4WD    |
|  7 | Luxury |
|  8 | Sports |
|  8 | Sedan  |
|  8 | 4WD    |
|  8 | Luxury |
|  9 | Sports |
|  9 | Sedan  |
|  9 | 4WD    |
|  9 | Luxury |
| 10 | Sports |
| 10 | Sedan  |
| 10 | 4WD    |
| 10 | Luxury |
+----+--------+
40 rows in set (0.00 sec)

Good god, that's ugly. However, as far as the database is concerned, it is exactly what was asked for. In the query, we asked for for the ID from cars and the model from models. However, because we didn't specify how to join the tables, the database has matched every row from the first table with every row from the second table.

Okay, so the boss is back, and he wants more information again. I want the same list, but also include 4WDs in it.

This however, gives us a great excuse to look at two different ways to accomplish this. We could add another condition to the where clause like this:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
    or b.ID=3

While the above will work perfectly well, lets look at it differently, this is a great excuse to show how a union query will work.

We know that the following will return all the Sports cars:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1

And the following would return all the 4WDs:

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

So by adding a union all clause between them, the results of the second query will be appended to the results of the first query.

select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=1
union all
select
    a.ID,
    b.model,
    c.color
from
    cars a
        join models b
            on a.model=b.ID
        join colors c
            on a.color=c.ID
        join brands d
            on a.brand=d.ID
where
    b.ID=3

+----+--------+-------+
| ID | model  | color |
+----+--------+-------+
|  1 | Sports | Red   |
|  8 | Sports | Green |
| 10 | Sports | White |
|  3 | Sports | Black |
|  5 | 4WD    | Green |
|  7 | 4WD    | White |
|  9 | 4WD    | Black |
+----+--------+-------+
7 rows in set (0.00 sec)

As you can see, the results of the first query are returned first, followed by the results of the second query.

In this example, it would of course have been much easier to simply use the first query, but union queries can be great for specific cases. They are a great way to return specific results from tables from tables that aren't easily joined together - or for that matter completely unrelated tables. There are a few rules to follow however.

  • The column types from the first query must match the column types from every other query below.
  • The names of the columns from the first query will be used to identify the entire set of results.
  • The number of columns in each query must be the same.

Now, you might be wondering what the difference is between using union and union all. A union query will remove duplicates, while a union all will not. This does mean that there is a small performance hit when using union over union all but the results may be worth it - I won't speculate on that sort of thing in this though.

On this note, it might be worth noting some additional notes here.

  • If we wanted to order the results, we can use an order by but you can't use the alias anymore. In the query above, appending an order by a.ID would result in an error - as far as the results are concerned, the column is called ID rather than a.ID - even though the same alias has been used in both queries.
  • We can only have one order by statement, and it must be as the last statement.

For the next examples, I am adding a few extra rows to our tables.

I have added Holden to the brands table. I have also added a row into cars that has the color value of 12 - which has no reference in the colors table.

Okay, the boss is back again, barking requests out - *I want a count of each brand we carry and the number of cars in it!` - Typical, we just get to an interesting section of our discussion and the boss wants more work.

Rightyo, so the first thing we need to do is get a complete listing of possible brands.

select
    a.brand
from
    brands a

+--------+
| brand  |
+--------+
| Ford   |
| Toyota |
| Nissan |
| Smart  |
| BMW    |
| Holden |
+--------+
6 rows in set (0.00 sec)

Now, when we join this to our cars table we get the following result:

select
    a.brand
from
    brands a
        join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Nissan |
| Smart  |
| Toyota |
+--------+
5 rows in set (0.00 sec)

Which is of course a problem - we aren't seeing any mention of the lovely Holden brand I added.

This is because a join looks for matching rows in both tables. As there is no data in cars that is of type Holden it isn't returned. This is where we can use an outer join. This will return all the results from one table whether they are matched in the other table or not:

select
    a.brand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+
| brand  |
+--------+
| BMW    |
| Ford   |
| Holden |
| Nissan |
| Smart  |
| Toyota |
+--------+
6 rows in set (0.00 sec)

Now that we have that, we can add a lovely aggregate function to get a count and get the boss off our backs for a moment.

select
    a.brand,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
group by
    a.brand

+--------+--------------+
| brand  | countOfBrand |
+--------+--------------+
| BMW    |            2 |
| Ford   |            2 |
| Holden |            0 |
| Nissan |            1 |
| Smart  |            1 |
| Toyota |            5 |
+--------+--------------+
6 rows in set (0.00 sec)

And with that, away the boss skulks.

Now, to explain this in some more detail, outer joins can be of the left or right type. The Left or Right defines which table is fully included. A left outer join will include all the rows from the table on the left, while (you guessed it) a right outer join brings all the results from the table on the right into the results.

Some databases will allow a full outer join which will bring back results (whether matched or not) from both tables, but this isn't supported in all databases.

Now, I probably figure at this point in time, you are wondering whether or not you can merge join types in a query - and the answer is yes, you absolutely can.

select
    b.brand,
    c.color,
    count(a.id) as countOfBrand
from
    cars a
        right outer join brands b
            on b.ID=a.brand
        join colors c
            on a.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
+--------+-------+--------------+
9 rows in set (0.00 sec)

So, why is that not the results that were expected? It is because although we have selected the outer join from cars to brands, it wasn't specified in the join to colors - so that particular join will only bring back results that match in both tables.

Here is the query that would work to get the results that we expected:

select
    a.brand,
    c.color,
    count(b.id) as countOfBrand
from
    brands a
        left outer join cars b
            on a.ID=b.brand
        left outer join colors c
            on b.color=c.ID
group by
    a.brand,
    c.color

+--------+-------+--------------+
| brand  | color | countOfBrand |
+--------+-------+--------------+
| BMW    | Blue  |            1 |
| BMW    | White |            1 |
| Ford   | Blue  |            1 |
| Ford   | White |            1 |
| Holden | NULL  |            0 |
| Nissan | Black |            1 |
| Smart  | White |            1 |
| Toyota | NULL  |            1 |
| Toyota | Black |            1 |
| Toyota | Green |            2 |
| Toyota | Red   |            1 |
+--------+-------+--------------+
11 rows in set (0.00 sec)

As we can see, we have two outer joins in the query and the results are coming through as expected.

Now, how about those other types of joins you ask? What about Intersections?

Well, not all databases support the intersection but pretty much all databases will allow you to create an intersection through a join (or a well structured where statement at the least).

An Intersection is a type of join somewhat similar to a union as described above - but the difference is that it only returns rows of data that are identical (and I do mean identical) between the various individual queries joined by the union. Only rows that are identical in every regard will be returned.

A simple example would be as such:

select
    *
from
    colors
where
    ID>2
intersect
select
    *
from
    colors
where
    id<4

While a normal union query would return all the rows of the table (the first query returning anything over ID>2 and the second anything having ID<4) which would result in a full set, an intersect query would only return the row matching id=3 as it meets both criteria.

Now, if your database doesn't support an intersect query, the above can be easily accomlished with the following query:

select
    a.ID,
    a.color,
    a.paint
from
    colors a
        join colors b
            on a.ID=b.ID
where
    a.ID>2
    and b.ID<4

+----+-------+----------+
| ID | color | paint    |
+----+-------+----------+
|  3 | Blue  | Metallic |
+----+-------+----------+
1 row in set (0.00 sec)

If you wish to perform an intersection across two different tables using a database that doesn't inherently support an intersection query, you will need to create a join on every column of the tables.

From io.Reader to string in Go

data, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(data))

AttributeError: Module Pip has no attribute 'main'

To verify whether is your pip installation problem, try using easy_install to install an earlier version of pip:

easy_install pip==9.0.1

If this succeed, pip should be working now. Then you can go ahead to install any other version of pip you want with:

pip install pip==10....

Or you can just stay with version 9.0.1, as your project requires version >= 9.0.

Try building your project again.

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

QLabel: set color of text and background

The best way to set any feature regarding the colors of any widget is to use QPalette.

And the easiest way to find what you are looking for is to open Qt Designer and set the palette of a QLabel and check the generated code.

Colorized grep -- viewing the entire file with highlighted matches

Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:

#! /bin/bash
awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2

Use it like so:

$ ./cgrep pattern [file]

Unfortunately, it doesn't have all the functionality of grep.

For more information , you can refer to an article "So You Like Color" in Linux Journal

Open an html page in default browser with VBA?

You can use the Windows API function ShellExecute to do so:

Option Explicit

Private Declare Function ShellExecute _
  Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal Operation As String, _
  ByVal Filename As String, _
  Optional ByVal Parameters As String, _
  Optional ByVal Directory As String, _
  Optional ByVal WindowStyle As Long = vbMinimizedFocus _
  ) As Long

Public Sub OpenUrl()

    Dim lSuccess As Long
    lSuccess = ShellExecute(0, "Open", "www.google.com")

End Sub

Just a short remark concerning security: If the URL comes from user input make sure to strictly validate that input as ShellExecute would execute any command with the user's permissions, also a format c: would be executed if the user is an administrator.

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

How to use WPF Background Worker

using System;  
using System.ComponentModel;   
using System.Threading;    
namespace BackGroundWorkerExample  
{   
    class Program  
    {  
        private static BackgroundWorker backgroundWorker;  

        static void Main(string[] args)  
        {  
            backgroundWorker = new BackgroundWorker  
            {  
                WorkerReportsProgress = true,  
                WorkerSupportsCancellation = true  
            };  

            backgroundWorker.DoWork += backgroundWorker_DoWork;  
            //For the display of operation progress to UI.    
            backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;  
            //After the completation of operation.    
            backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;  
            backgroundWorker.RunWorkerAsync("Press Enter in the next 5 seconds to Cancel operation:");  

            Console.ReadLine();  

            if (backgroundWorker.IsBusy)  
            { 
                backgroundWorker.CancelAsync();  
                Console.ReadLine();  
            }  
        }  

        static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)  
        {  
            for (int i = 0; i < 200; i++)  
            {  
                if (backgroundWorker.CancellationPending)  
                {  
                    e.Cancel = true;  
                    return;  
                }  

                backgroundWorker.ReportProgress(i);  
                Thread.Sleep(1000);  
                e.Result = 1000;  
            }  
        }  

        static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)  
        {  
            Console.WriteLine("Completed" + e.ProgressPercentage + "%");  
        }  

        static void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)  
        {  

            if (e.Cancelled)  
            {  
                Console.WriteLine("Operation Cancelled");  
            }  
            else if (e.Error != null)  
            {  
                Console.WriteLine("Error in Process :" + e.Error);  
            }  
            else  
            {  
                Console.WriteLine("Operation Completed :" + e.Result);  
            }  
        }  
    }  
} 

Also, referr the below link you will understand the concepts of Background:

http://www.c-sharpcorner.com/UploadFile/1c8574/threads-in-wpf/

creating batch script to unzip a file without additional zip tools

Here is a quick and simple solution using PowerShell:

powershell.exe -nologo -noprofile -command "& { $shell = New-Object -COM Shell.Application; $target = $shell.NameSpace('C:\extractToThisDirectory'); $zip = $shell.NameSpace('C:\extractThis.zip'); $target.CopyHere($zip.Items(), 16); }"

This uses the built-in extract functionality of the Explorer and will also show the typical extract progress window. The second parameter 16 to CopyHere answers all questions with yes.

Android studio 3.0: Unable to resolve dependency for :app@dexOptions/compileClasspath': Could not resolve project :animators

In my case, the problem I had was due to a dependency I was trying to import (BottomNavigationViewEx).

This dependency requires to be downloaded from jitpack.io and maven.google.com, and I was putting this config in buildscript section:

buildscript {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" } // this is incorrect
        maven { url "https://maven.google.com" } // this is incorrect
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.2'
    } 
}

which it was incorrect, I need to remove these two maven lines and include them in the right section, 'allprojects':

allprojects {
    repositories {
        google()
        jcenter()
        maven { url "https://jitpack.io" }
        maven { url "https://maven.google.com" }
    }
}

Hope it helps somebody as same for me.

How to make a ssh connection with python?

Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/

The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.

Setting Up a Custom SSH Server

The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.

You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.

How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.

Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.

To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.

Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.

Example 10-1. sshserver.py

from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os

class SSHDemoProtocol(recvline.HistoricRecvLine):
    def __init__(self, user):
        self.user = user

    def connectionMade(self) : 
     recvline.HistoricRecvLine.connectionMade(self)
        self.terminal.write("Welcome to my test SSH server.")
        self.terminal.nextLine() 
        self.do_help()
        self.showPrompt()

    def showPrompt(self): 
        self.terminal.write("$ ")

    def getCommandFunc(self, cmd):
        return getattr(self, ‘do_’ + cmd, None)

    def lineReceived(self, line):
        line = line.strip()
        if line: 
            cmdAndArgs = line.split()
            cmd = cmdAndArgs[0]
            args = cmdAndArgs[1:]
            func = self.getCommandFunc(cmd)
            if func: 
               try:
                   func(*args)
               except Exception, e: 
                   self.terminal.write("Error: %s" % e)
                   self.terminal.nextLine()
            else:
               self.terminal.write("No such command.")
               self.terminal.nextLine()
        self.showPrompt()

    def do_help(self, cmd=”):
        "Get help on a command. Usage: help command"
        if cmd: 
            func = self.getCommandFunc(cmd)
            if func:
                self.terminal.write(func.__doc__)
                self.terminal.nextLine()
                return

        publicMethods = filter(
            lambda funcname: funcname.startswith(‘do_’), dir(self)) 
        commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods] 
        self.terminal.write("Commands: " + " ".join(commands))
        self.terminal.nextLine()

    def do_echo(self, *args):
        "Echo a string. Usage: echo my line of text"
        self.terminal.write(" ".join(args)) 
        self.terminal.nextLine()

    def do_whoami(self):
        "Prints your user name. Usage: whoami"
        self.terminal.write(self.user.username)
        self.terminal.nextLine()

    def do_quit(self):
        "Ends your session. Usage: quit" 
        self.terminal.write("Thanks for playing!")
        self.terminal.nextLine() 
        self.terminal.loseConnection()

    def do_clear(self):
        "Clears the screen. Usage: clear" 
        self.terminal.reset()

class SSHDemoAvatar(avatar.ConchUser): 
    implements(conchinterfaces.ISession)

    def __init__(self, username): 
        avatar.ConchUser.__init__(self) 
        self.username = username 
        self.channelLookup.update({‘session’:session.SSHSession})

    def openShell(self, protocol): 
        serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
        serverProtocol.makeConnection(protocol)
        protocol.makeConnection(session.wrapProtocol(serverProtocol))

    def getPty(self, terminal, windowSize, attrs):
        return None

    def execCommand(self, protocol, cmd): 
        raise NotImplementedError

    def closed(self):
        pass

class SSHDemoRealm:
    implements(portal.IRealm)

    def requestAvatar(self, avatarId, mind, *interfaces):
        if conchinterfaces.IConchUser in interfaces:
            return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
        else:
            raise Exception, "No supported interfaces found."

def getRSAKeys():
    if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
        # generate a RSA keypair
        print "Generating RSA keypair…" 
        from Crypto.PublicKey import RSA 
        KEY_LENGTH = 1024
        rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
        publicKeyString = keys.makePublicKeyString(rsaKey) 
        privateKeyString = keys.makePrivateKeyString(rsaKey)
        # save keys for next time
        file(‘public.key’, ‘w+b’).write(publicKeyString)
        file(‘private.key’, ‘w+b’).write(privateKeyString)
        print "done."
    else:
        publicKeyString = file(‘public.key’).read()
        privateKeyString = file(‘private.key’).read() 
    return publicKeyString, privateKeyString

if __name__ == "__main__":
    sshFactory = factory.SSHFactory() 
    sshFactory.portal = portal.Portal(SSHDemoRealm())
    users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
    sshFactory.portal.registerChecker(
 checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))

    pubKeyString, privKeyString =
getRSAKeys()
    sshFactory.publicKeys = {
        ‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
    sshFactory.privateKeys = {
        ‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}

    from twisted.internet import reactor 
    reactor.listenTCP(2222, sshFactory) 
    reactor.run()

{mospagebreak title=Setting Up a Custom SSH Server continued}

sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:

$ ssh admin@localhost -p 2222 
admin@localhost’s password: aaa

>>> Welcome to my test SSH server.  
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit

Connection to localhost closed.

How to enable multidexing with the new Android Multidex support library

build.gradle

multiDexEnabled true
implementation 'androidx.multidex:multidex:2.0.1'

AndroidManifest.xml

<application
    android:name="androidx.multidex.MultiDexApplication"

Creating a mock HttpServletRequest out of a url string?

Here it is how to use MockHttpServletRequest:

// given
MockHttpServletRequest request = new MockHttpServletRequest();
request.setServerName("www.example.com");
request.setRequestURI("/foo");
request.setQueryString("param1=value1&param");

// when
String url = request.getRequestURL() + '?' + request.getQueryString(); // assuming there is always queryString.

// then
assertThat(url, is("http://www.example.com:80/foo?param1=value1&param"));

How to Decode Json object in laravel and apply foreach loop on that in laravel

you can use json_decode function

foreach (json_decode($response) as $area)
{
 print_r($area); // this is your area from json response
}

See this fiddle

Find objects between two dates MongoDB

Why not convert the string to an integer of the form YYYYMMDDHHMMSS? Each increment of time would then create a larger integer, and you can filter on the integers instead of worrying about converting to ISO time.

C++: Print out enum value as text

For this problem, I do a help function like this:

const char* name(Id id) {
    struct Entry {
        Id id;
        const char* name;
    };
    static const Entry entries[] = {
        { ErrorA, "ErrorA" },
        { ErrorB, "ErrorB" },
        { 0, 0 }
    }
    for (int it = 0; it < gui::SiCount; ++it) {
        if (entries[it].id == id) {
            return entries[it].name;
        }
    }
   return 0;
}

Linear search is usually more efficient than std::map for small collections like this.

Storing Images in DB - Yea or Nay?

If you are on Teradata, then Teradata Developer Exchange has a detailed article on loading and retrieving lobs and blobs..

http://developer.teradata.com/applications/articles/large-objects-part-1-loading

How can I create database tables from XSD files?

Commercial Product: Altova's XML Spy.

Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database.

While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well.

If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL.

Been there, done that. Work for hire -- no open source available.

Eclipse "Invalid Project Description" when creating new project from existing source

I have been banging my head against the wall with a similar problem. The only thing that helped is following the steps in this post.

builtins.TypeError: must be str, not bytes

Convert binary file to base64 & vice versa. Prove in python 3.5.2

import base64

read_file = open('/tmp/newgalax.png', 'rb')
data = read_file.read()

b64 = base64.b64encode(data)

print (b64)

# Save file
decode_b64 = base64.b64decode(b64)
out_file = open('/tmp/out_newgalax.png', 'wb')
out_file.write(decode_b64)

# Test in python 3.5.2

How to change theme for AlertDialog

Better way to do this use custom dialog and customize according your needs here is custom dialog example.....

enter image description here

public class CustomDialogUI {
Dialog dialog;
Vibrator vib;
RelativeLayout rl;

@SuppressWarnings("static-access")
public void dialog(final Context context, String title, String message,
        final Runnable task) {
    dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom);
    dialog.setCancelable(false);
    TextView m = (TextView) dialog.findViewById(R.id.message);
    TextView t = (TextView) dialog.findViewById(R.id.title);
    final Button n = (Button) dialog.findViewById(R.id.button2);
    final Button p = (Button) dialog.findViewById(R.id.next_button);
    rl = (RelativeLayout) dialog.findViewById(R.id.rlmain);
    t.setText(bold(title));
    m.setText(message);
    dialog.show();
    n.setText(bold("Close"));
    p.setText(bold("Ok"));
    // color(context,rl);
    vib = (Vibrator) context.getSystemService(context.VIBRATOR_SERVICE);
    n.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            vib.vibrate(15);
            dialog.dismiss();
        }
    });
    p.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            vib.vibrate(20);
            dialog.dismiss();
            task.run();
        }
    });
}
 //customize text style bold italic....
public SpannableString bold(String s) {
    SpannableString spanString = new SpannableString(s);
    spanString.setSpan(new StyleSpan(Typeface.BOLD), 0,
            spanString.length(), 0);
    spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
    // spanString.setSpan(new StyleSpan(Typeface.ITALIC), 0,
    // spanString.length(), 0);
    return spanString;
}

}

Here is xml layout

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
>

<RelativeLayout
    android:id="@+id/rlmain"
    android:layout_width="fill_parent"
    android:layout_height="150dip"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:background="#569CE3" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="25dip"
        android:layout_marginTop="10dip" >

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="Are you Sure?"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ffffff"
            android:textSize="13dip" />
    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/relativeLayout2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/relativeLayout1"
        android:layout_alignRight="@+id/relativeLayout1"
        android:layout_below="@+id/relativeLayout1"
        android:layout_marginTop="5dip" >
    </RelativeLayout>

    <ProgressBar
        android:id="@+id/process"
        style="?android:attr/progressBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="3dip"
        android:layout_marginTop="3dip" />

    <RelativeLayout
        android:id="@+id/relativeLayout3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/relativeLayout2"
        android:layout_below="@+id/relativeLayout2"
        android:layout_toLeftOf="@+id/process" >

        <TextView
            android:id="@+id/message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:text="Medium Text"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#ffffff"
            android:textSize="13dip"/>

    </RelativeLayout>

    <Button
        android:id="@+id/next_button"
        android:layout_width="90dip"
        android:layout_height="35dip"
        android:layout_alignParentBottom="true"
        android:textColor="@drawable/button_text_color"
         android:background="@drawable/blue_button"
         android:layout_marginBottom="5dp"
           android:textSize="10dp"

        android:layout_alignRight="@+id/relativeLayout3"
        android:text="Okay" />

    <Button
        android:id="@+id/button2"
        android:text="Cancel"
        android:textColor="@drawable/button_text_color"
        android:layout_width="90dip"
        android:layout_height="35dip"
        android:layout_marginBottom="5dp"
         android:background="@drawable/blue_button"
         android:layout_marginRight="7dp"
        android:textSize="10dp"
        android:layout_alignParentBottom="true"
        android:layout_toLeftOf="@+id/next_button"
         />

</RelativeLayout>

How to add buttons dynamically to my form?

You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity

How can I show current location on a Google Map on Android Marshmallow?

Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.

import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {


    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    private double latitudeVillageApartmets= 53.385952001750184;
    private double longitudeVillageApartments= -6.599087119102478;


    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
 }
    /*These methods all have to do with the map and wht happens if the activity is paused etc*/
    //contains lat and lon of another marker
    private void setUpMap() {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
    }

    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

}

There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.

show validation error messages on submit in angularjs

I can come up with 2 ways to achieve it.

The first one is to remove novalidate to enable the browser's validation.

Second, you can disable the save button when the form is not valid like this

<input ng-disabled="!frmRegister.$valid" type="submit" value="Save" />

Hope it helps.

Write to file, but overwrite it if it exists

Just noting that if you wish to redirect both stderr and stdout to a file while you have noclobber set (i.e. set -o noclobber), you can use the code:

cmd >| file.txt 2>&1

More information about this can be seen at https://stackoverflow.com/a/876242.

Also this answer's @TuBui's question on the answer @BrDaHa provided above at Aug 9 '18 at 9:34.

Laravel Eloquent compare date from datetime field

You can get the all record of the date '2016-07-14' by using it

 whereDate('date','=','2016-07-14')

Or use the another code for dynamic date

whereDate('date',$date)

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to read xls with explicit implementation poi classes for xlsx.

G:\Selenium Jar Files\TestData\Data.xls

Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like;

Change:

XSSFWorkbook workbook = new XSSFWorkbook(file);

To:

 org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file);

And Change:

XSSFSheet sheet = workbook.getSheetAt(0);

To:

org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);

How can I get selector from jQuery object

Are you trying to get the name of the current tag that was clicked?

If so, do this..

$("*").click(function(){
    alert($(this)[0].nodeName);
});

You can't really get the "selector", the "selector" in your case is *.

What does java.lang.Thread.interrupt() do?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

What's the difference between a temp table and table variable in SQL Server?

Just looking at the claim in the accepted answer that table variables don't participate in logging.

It seems generally untrue that there is any difference in quantity of logging (at least for insert/update/delete operations to the table itself though I have since found that there is some small difference in this respect for cached temporary objects in stored procedures due to additional system table updates).

I looked at the logging behaviour against both a @table_variable and a #temp table for the following operations.

  1. Successful Insert
  2. Multi Row Insert where statement rolled back due to constraint violation.
  3. Update
  4. Delete
  5. Deallocate

The transaction log records were almost identical for all operations.

The table variable version actually has a few extra log entries because it gets an entry added to (and later removed from) the sys.syssingleobjrefs base table but overall had a few less bytes logged purely as the internal name for table variables consumes 236 less bytes than for #temp tables (118 fewer nvarchar characters).

Full script to reproduce (best run on an instance started in single user mode and using sqlcmd mode)

:setvar tablename "@T" 
:setvar tablescript "DECLARE @T TABLE"

/*
 --Uncomment this section to test a #temp table
:setvar tablename "#T" 
:setvar tablescript "CREATE TABLE #T"
*/

USE tempdb 
GO    
CHECKPOINT

DECLARE @LSN NVARCHAR(25)

SELECT @LSN = MAX([Current LSN])
FROM fn_dblog(null, null) 


EXEC(N'BEGIN TRAN StartBatch
SAVE TRAN StartBatch
COMMIT

$(tablescript)
(
[4CA996AC-C7E1-48B5-B48A-E721E7A435F0] INT PRIMARY KEY DEFAULT 0,
InRowFiller char(7000) DEFAULT ''A'',
OffRowFiller varchar(8000) DEFAULT REPLICATE(''B'',8000),
LOBFiller varchar(max) DEFAULT REPLICATE(cast(''C'' as varchar(max)),10000)
)


BEGIN TRAN InsertFirstRow
SAVE TRAN InsertFirstRow
COMMIT

INSERT INTO $(tablename)
DEFAULT VALUES

BEGIN TRAN Insert9Rows
SAVE TRAN Insert9Rows
COMMIT


INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP 9 ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM sys.all_columns

BEGIN TRAN InsertFailure
SAVE TRAN InsertFailure
COMMIT


/*Try and Insert 10 rows, the 10th one will cause a constraint violation*/
BEGIN TRY
INSERT INTO $(tablename) ([4CA996AC-C7E1-48B5-B48A-E721E7A435F0])
SELECT TOP (10) (10 + ROW_NUMBER() OVER (ORDER BY (SELECT 0))) % 20
FROM sys.all_columns
END TRY
BEGIN CATCH
PRINT ERROR_MESSAGE()
END CATCH

BEGIN TRAN Update10Rows
SAVE TRAN Update10Rows
COMMIT

UPDATE $(tablename)
SET InRowFiller = LOWER(InRowFiller),
    OffRowFiller  =LOWER(OffRowFiller),
    LOBFiller  =LOWER(LOBFiller)


BEGIN TRAN Delete10Rows
SAVE TRAN Delete10Rows
COMMIT

DELETE FROM  $(tablename)
BEGIN TRAN AfterDelete
SAVE TRAN AfterDelete
COMMIT

BEGIN TRAN EndBatch
SAVE TRAN EndBatch
COMMIT')


DECLARE @LSN_HEX NVARCHAR(25) = 
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 1, 8),2) AS INT) AS VARCHAR) + ':' +
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 10, 8),2) AS INT) AS VARCHAR) + ':' +
        CAST(CAST(CONVERT(varbinary,SUBSTRING(@LSN, 19, 4),2) AS INT) AS VARCHAR)        

SELECT 
    [Operation],
    [Context],
    [AllocUnitName],
    [Transaction Name],
    [Description]
FROM   fn_dblog(@LSN_HEX, null) AS D
WHERE  [Current LSN] > @LSN  

SELECT CASE
         WHEN GROUPING(Operation) = 1 THEN 'Total'
         ELSE Operation
       END AS Operation,
       Context,
       AllocUnitName,
       COALESCE(SUM([Log Record Length]), 0) AS [Size in Bytes],
       COUNT(*)                              AS Cnt
FROM   fn_dblog(@LSN_HEX, null) AS D
WHERE  [Current LSN] > @LSN  
GROUP BY GROUPING SETS((Operation, Context, AllocUnitName),())

Results

+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
|                       |                    |                           |             @TV      |             #TV      |                  |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Operation             | Context            | AllocUnitName             | Size in Bytes | Cnt  | Size in Bytes | Cnt  | Difference Bytes |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| LOP_ABORT_XACT        | LCX_NULL           |                           | 52            | 1    | 52            | 1    |                  |
| LOP_BEGIN_XACT        | LCX_NULL           |                           | 6056          | 50   | 6056          | 50   |                  |
| LOP_COMMIT_XACT       | LCX_NULL           |                           | 2548          | 49   | 2548          | 49   |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 624           | 3    | 624           | 3    |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysrowsets.clust      | 208           | 1    | 208           | 1    |                  |
| LOP_COUNT_DELTA       | LCX_CLUSTERED      | sys.sysrscols.clst        | 832           | 4    | 832           | 4    |                  |
| LOP_CREATE_ALLOCCHAIN | LCX_NULL           |                           | 120           | 3    | 120           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 720           | 9    | 720           | 9    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysallocunits.clust   | 444           | 3    | 444           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysallocunits.nc      | 276           | 3    | 276           | 3    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syscolpars.clst       | 628           | 4    | 628           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syscolpars.nc         | 484           | 4    | 484           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysidxstats.clst      | 176           | 1    | 176           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysidxstats.nc        | 144           | 1    | 144           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysiscols.clst        | 100           | 1    | 100           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysiscols.nc1         | 88            | 1    | 88            | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysobjvalues.clst     | 596           | 5    | 596           | 5    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysrowsets.clust      | 132           | 1    | 132           | 1    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysrscols.clst        | 528           | 4    | 528           | 4    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.clst       | 1040          | 6    | 1276          | 6    | 236              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc1        | 820           | 6    | 1060          | 6    | 240              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc2        | 820           | 6    | 1060          | 6    | 240              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.sysschobjs.nc3        | 480           | 6    | 480           | 6    |                  |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syssingleobjrefs.clst | 96            | 1    |               |      | -96              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | sys.syssingleobjrefs.nc1  | 88            | 1    |               |      | -88              |
| LOP_DELETE_ROWS       | LCX_MARK_AS_GHOST  | Unknown Alloc Unit        | 72092         | 19   | 72092         | 19   |                  |
| LOP_DELETE_ROWS       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 16348         | 37   | 16348         | 37   |                  |
| LOP_FORMAT_PAGE       | LCX_HEAP           | Unknown Alloc Unit        | 1596          | 19   | 1596          | 19   |                  |
| LOP_FORMAT_PAGE       | LCX_IAM            | Unknown Alloc Unit        | 252           | 3    | 252           | 3    |                  |
| LOP_FORMAT_PAGE       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 84            | 1    | 84            | 1    |                  |
| LOP_FORMAT_PAGE       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 4788          | 57   | 4788          | 57   |                  |
| LOP_HOBT_DDL          | LCX_NULL           |                           | 108           | 3    | 108           | 3    |                  |
| LOP_HOBT_DELTA        | LCX_NULL           |                           | 9600          | 150  | 9600          | 150  |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 456           | 3    | 456           | 3    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.syscolpars.clst       | 644           | 4    | 644           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysidxstats.clst      | 180           | 1    | 180           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysiscols.clst        | 104           | 1    | 104           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysobjvalues.clst     | 616           | 5    | 616           | 5    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysrowsets.clust      | 136           | 1    | 136           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysrscols.clst        | 544           | 4    | 544           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.sysschobjs.clst       | 1064          | 6    | 1300          | 6    | 236              |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | sys.syssingleobjrefs.clst | 100           | 1    |               |      | -100             |
| LOP_INSERT_ROWS       | LCX_CLUSTERED      | Unknown Alloc Unit        | 135888        | 19   | 135888        | 19   |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_INTERIOR | Unknown Alloc Unit        | 1596          | 19   | 1596          | 19   |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysallocunits.nc      | 288           | 3    | 288           | 3    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.syscolpars.nc         | 500           | 4    | 500           | 4    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysidxstats.nc        | 148           | 1    | 148           | 1    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysiscols.nc1         | 92            | 1    | 92            | 1    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc1        | 844           | 6    | 1084          | 6    | 240              |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc2        | 844           | 6    | 1084          | 6    | 240              |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.sysschobjs.nc3        | 504           | 6    | 504           | 6    |                  |
| LOP_INSERT_ROWS       | LCX_INDEX_LEAF     | sys.syssingleobjrefs.nc1  | 92            | 1    |               |      | -92              |
| LOP_INSERT_ROWS       | LCX_TEXT_MIX       | Unknown Alloc Unit        | 5112          | 71   | 5112          | 71   |                  |
| LOP_MARK_SAVEPOINT    | LCX_NULL           |                           | 508           | 8    | 508           | 8    |                  |
| LOP_MODIFY_COLUMNS    | LCX_CLUSTERED      | Unknown Alloc Unit        | 1560          | 10   | 1560          | 10   |                  |
| LOP_MODIFY_HEADER     | LCX_HEAP           | Unknown Alloc Unit        | 3780          | 45   | 3780          | 45   |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.syscolpars.clst       | 384           | 4    | 384           | 4    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysidxstats.clst      | 100           | 1    | 100           | 1    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysrowsets.clust      | 92            | 1    | 92            | 1    |                  |
| LOP_MODIFY_ROW        | LCX_CLUSTERED      | sys.sysschobjs.clst       | 1144          | 13   | 1144          | 13   |                  |
| LOP_MODIFY_ROW        | LCX_IAM            | Unknown Alloc Unit        | 4224          | 48   | 4224          | 48   |                  |
| LOP_MODIFY_ROW        | LCX_PFS            | Unknown Alloc Unit        | 13632         | 169  | 13632         | 169  |                  |
| LOP_MODIFY_ROW        | LCX_TEXT_MIX       | Unknown Alloc Unit        | 108640        | 120  | 108640        | 120  |                  |
| LOP_ROOT_CHANGE       | LCX_CLUSTERED      | sys.sysallocunits.clust   | 960           | 10   | 960           | 10   |                  |
| LOP_SET_BITS          | LCX_GAM            | Unknown Alloc Unit        | 1200          | 20   | 1200          | 20   |                  |
| LOP_SET_BITS          | LCX_IAM            | Unknown Alloc Unit        | 1080          | 18   | 1080          | 18   |                  |
| LOP_SET_BITS          | LCX_SGAM           | Unknown Alloc Unit        | 120           | 2    | 120           | 2    |                  |
| LOP_SHRINK_NOOP       | LCX_NULL           |                           |               |      | 32            | 1    | 32               |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+
| Total                 |                    |                           | 410144        | 1095 | 411232        | 1092 | 1088             |
+-----------------------+--------------------+---------------------------+---------------+------+---------------+------+------------------+

Lint: How to ignore "<key> is not translated in <language>" errors?

This will cause Lint to ignore the missing translation error for ALL strings in the file, yet other string resource files can be verified if needed.

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools" 
    tools:ignore="MissingTranslation">

How to move the layout up when the soft keyboard is shown android

Accoding to this guide, the correct way to achieve this is by declaring in your manifest:

<activity name="EditContactActivity"
        android:windowSoftInputMode="stateVisible|adjustResize">

    </activity>

how to prevent css inherit

Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).

An example of its use:

li * {
   display: initial;
}

remove all special characters in java

Your problem is that the indices returned by match.start() correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c every time, these indices become incorrect.

The best approach to solve this is to use replaceAll, for example:

        System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

Can we have multiple <tbody> in same <table>?

Yes you can use them, for example I use them to more easily style groups of data, like this:

_x000D_
_x000D_
thead th { width: 100px; border-bottom: solid 1px #ddd; font-weight: bold; }_x000D_
tbody:nth-child(odd) { background: #f5f5f5;  border: solid 1px #ddd; }_x000D_
tbody:nth-child(even) { background: #e5e5e5;  border: solid 1px #ddd; }
_x000D_
<table>_x000D_
    <thead>_x000D_
        <tr><th>Customer</th><th>Order</th><th>Month</th></tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 1</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 1</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 2</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 2</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
    <tbody>_x000D_
        <tr><td>Customer 3</td><td>#1</td><td>January</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#2</td><td>April</td></tr>_x000D_
        <tr><td>Customer 3</td><td>#3</td><td>March</td></tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

You can view an example here. It'll only work in newer browsers, but that's what I'm supporting in my current application, you can use the grouping for JavaScript etc. The main thing is it's a convenient way to visually group the rows to make the data much more readable. There are other uses of course, but as far as applicable examples, this one is the most common one for me.

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
{
    public static void main(String[] args) throws InterruptedException
    {
        stopWatch();
        stopWatchGuava();
        stopWatchApacheCommons();
    }

    public static void stopWatch() throws InterruptedException
    {
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchGuava() throws InterruptedException
    {
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchApacheCommons() throws InterruptedException
    {
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }
}

How do you know a variable type in java?

If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:

boolean b = a instanceof String

How to make a machine trust a self-signed Java application

Just Go To *Startmenu >>Java >>Configure Java >> Security >> Edit site list >> copy and paste your Link with problem >> OK Problem fixed :)*

Directory Chooser in HTML page

Scripting is inevitable.

This isn't provided because of the security risk. <input type='file' /> is closest, but not what you are looking for.

Checkout this example that uses Javascript to achieve what you want.

If the OS is windows, you can use VB scripts to access the core control files to browse for a folder.

MongoDb shuts down with Code 100

To run Mongo DB demon with mongod command, you should have a database directory, probably you need to run:

mkdir C:\data\db

Also, MongoDB need to have a write permissions for that directory or it should be run with superuser permissions, like sudo mongod.

Test if executable exists in Python?

There is a which.py script in a standard Python distribution (e.g. on Windows '\PythonXX\Tools\Scripts\which.py').

EDIT: which.py depends on ls therefore it is not cross-platform.

PHP syntax question: What does the question mark and colon mean?

It's the ternary form of the if-else operator. The above statement basically reads like this:

if ($add_review) then {
    return FALSE; //$add_review evaluated as True
} else {
    return $arg //$add_review evaluated as False
}

See here for more details on ternary op in PHP: http://www.addedbytes.com/php/ternary-conditionals/

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

Simple jQuery, PHP and JSONP example?

Simple jQuery, PHP and JSONP example is below:

_x000D_
_x000D_
window.onload = function(){_x000D_
 $.ajax({_x000D_
  cache: false,_x000D_
  url: "https://jsonplaceholder.typicode.com/users/2",_x000D_
  dataType: 'jsonp',_x000D_
  type: 'GET',_x000D_
  success: function(data){_x000D_
   console.log('data', data)_x000D_
  },_x000D_
  error: function(data){_x000D_
   console.log(data);_x000D_
  }_x000D_
 });_x000D_
};
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Where is Maven Installed on Ubuntu

I would like to add that .m2 folder a lot of people say it is in your home folder. It is right. But if use maven from ready to go IDE like Spring STS then your .m2 folder is placed in root folder

To access root folder you need to switch to super user account

sudo su

Go to root folder

cd root/

You will find it by

cd -all

XmlSerializer giving FileNotFoundException at constructor

This exception can also be trapped by a managed debugging assistant (MDA) called BindingFailure.

This MDA is useful if your application is designed to ship with pre-build serialization assemblies. We do this to increase performance for our application. It allows us to make sure that the pre-built serialization assemblies are being properly built by our build process, and loaded by the application without being re-built on the fly.

It's really not useful except in this scenario, because as other posters have said, when a binding error is trapped by the Serializer constructor, the serialization assembly is re-built at runtime. So you can usually turn it off.

How do I add a border to an image in HTML?

as said above simple line of code will fix your problems

border: 1px solid #000;

There is another option to add border to your image and that with photoshop you can see how it's done with this tutorial below: http://bannercheapdesign.com/articles-and-tutorials/learn-how-to-add-border-to-your-banner-design-using-photoshop/

Setting new value for an attribute using jQuery

Works fine for me

See example here. http://jsfiddle.net/blowsie/c6VAy/

Make sure your jquery is inside $(document).ready function or similar.

Also you can improve your code by using jquery data

$('#amount').data('min','1000');

<div id="amount" data-min=""></div>

Update,

A working example of your full code (pretty much) here. http://jsfiddle.net/blowsie/c6VAy/3/

Can someone explain mappedBy in JPA and Hibernate?

Table relationship vs. entity relationship

In a relational database system, a one-to-many table relationship looks as follows:

one-to-many table relationship

Note that the relationship is based on the Foreign Key column (e.g., post_id) in the child table.

So, there is a single source of truth when it comes to managing a one-to-many table relationship.

Now, if you take a bidirectional entity relationship that maps on the one-to-many table relationship we saw previously:

Bidirectional One-To-Many entity association

If you take a look at the diagram above, you can see that there are two ways to manage this relationship.

In the Post entity, you have the comments collection:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

And, in the PostComment, the post association is mapped as follows:

@ManyToOne(
    fetch = FetchType.LAZY
)
@JoinColumn(name = "post_id")
private Post post;

Because there are two ways to represent the Foreign Key column, you must define which is the source of truth when it comes to translating the association state change into its equivalent Foreign Key column value modification.

MappedBy

The mappedBy attribute tells that the @ManyToOne side is in charge of managing the Foreign Key column, and the collection is used only to fetch the child entities and to cascade parent entity state changes to children (e.g., removing the parent should also remove the child entities).

Synchronize both sides of a bidirectional association

Now, even if you defined the mappedBy attribute and the child-side @ManyToOne association manages the Foreign Key column, you still need to synchronize both sides of the bidirectional association.

The best way to do that is to add these two utility methods:

public void addComment(PostComment comment) {
    comments.add(comment);
    comment.setPost(this);
}

public void removeComment(PostComment comment) {
    comments.remove(comment);
    comment.setPost(null);
}

The addComment and removeComment methods ensure that both sides are synchronized. So, if we add a child entity, the child entity needs to point to the parent and the parent entity should have the child contained in the child collection.

Iptables setting multiple multiports in one rule

As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.

Where is my .vimrc file?

The vimrc file in Ubuntu (12.04 (Precise Pangolin)): I tried :scriptnames in Vim, and it shows both /usr/share/vim/vimrc and ~/.vimrc.

But I had manually created ~/.vimrc.

How to restore default perspective settings in Eclipse IDE

If you still have the "open perspective" button in the top right, you can switch to a different perspective, go to Windows -> Preferences -> General -> Keys, and apply a key binding for "Reset Perspective". Then, switch back to the afflicted perspective and hit that key binding.

What JSON library to use in Scala?

@AlaxDean's #7 answer, Argonaut is the only one that I was able to get working quickly with sbt and intellij. Actually json4s also took little time but dealing with a raw AST is not what I wanted. I got argonaut to work by putting in a single line into my build.st:

libraryDependencies += "io.argonaut" %% "argonaut" % "6.0.1"

And then a simple test to see if it I could get JSON:

package mytest


import scalaz._, Scalaz._
import argonaut._, Argonaut._

object Mytest extends App {

  val requestJson  =
    """
    {
      "userid": "1"
    }
    """.stripMargin

  val updatedJson: Option[Json] = for {
    parsed <- requestJson.parseOption
  } yield ("name", jString("testuser")) ->: parsed

  val obj = updatedJson.get.obj
  printf("Updated user: %s\n", updatedJson.toString())
  printf("obj : %s\n", obj.toString())
  printf("userid: %s\n", obj.get.toMap("userid"))
}

And then

$ sbt
> run
Updated user: Some({"userid":"1","name":"testuser"})
obj : Some(object[("userid","1"),("name","testuser")])
userid: "1"

Make sure you are familiar with Option which is just a value that can also be null (null safe I guess). Argonaut makes use of Scalaz so if you see something you don't understand like the symbol \/ (an or operation) it's probably Scalaz.

Run Bash Command from PHP

Check if have not set a open_basedir in php.ini or .htaccess of domain what you use. That will jail you in directory of your domain and php will get only access to execute inside this directory.

Retrofit 2 - Dynamic URL

I wanted to replace only a part of the url, and with this solution, I don't have to pass the whole url, just the dynamic part:

public interface APIService {

  @GET("users/{user_id}/playlists")
  Call<List<Playlist> getUserPlaylists(@Path(value = "user_id", encoded = true) String userId);
}

Android Studio Image Asset Launcher Icon Background Color

You have two ways:

1) In Background Layer > Scaling, reduce the Resize to 1

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here


2) in Background Layer > Scaling > Source Asset, you can set an image as a 1x1 pixel (or any size) transparent.png image (you've already created).

enter image description here

and then in Legacy > Legacy Icon set Shape as None

enter image description here

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

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');

Angular bootstrap datepicker date format does not format ng-model value

Defining a new directive to work around a bug is not really ideal.

Because the datepicker displays later dates correctly, one simple workaround could be just setting the model variable to null first, and then to the current date after a while:

$scope.dt = null;
$timeout( function(){
    $scope.dt = new Date();
},100);

Converting from longitude\latitude to Cartesian coordinates

Why implement something which has already been implemented and test-proven?

C#, for one, has the NetTopologySuite which is the .NET port of the JTS Topology Suite.

Specifically, you have a severe flaw in your calculation. The earth is not a perfect sphere, and the approximation of the earth's radius might not cut it for precise measurements.

If in some cases it's acceptable to use homebrew functions, GIS is a good example of a field in which it is much preferred to use a reliable, test-proven library.

Setting Django up to use MySQL

Follow the given steps in order to setup it up to use MySQL database:

1) Install MySQL Database Connector :

    sudo apt-get install libmysqlclient-dev

2) Install the mysqlclient library :

    pip install mysqlclient

3) Install MySQL server, with the following command :

    sudo apt-get install mysql-server

4) Create the Database :

    i) Verify that the MySQL service is running:

        systemctl status mysql.service

    ii) Log in with your MySQL credentials using the following command where -u is the flag for declaring your username and -p is the flag that tells MySQL that this user requires a password :  

        mysql -u db_user -p


    iii) CREATE DATABASE db_name;

    iv) Exit MySQL server, press CTRL + D.

5) Add the MySQL Database Connection to your Application:

    i) Navigate to the settings.py file and replace the current DATABASES lines with the following:

        # Database
        # https://docs.djangoproject.com/en/2.0/ref/settings/#databases

        DATABASES = {
            'default': {
                'ENGINE': 'django.db.backends.mysql',
                'OPTIONS': {
                    'read_default_file': '/etc/mysql/my.cnf',
                },
            }
        }
        ...

    ii) Next, let’s edit the config file so that it has your MySQL credentials. Use vi as sudo to edit the file and add the following information:

        sudo vi /etc/mysql/my.cnf

        database = db_name
        user = db_user
        password = db_password
        default-character-set = utf8

6) Once the file has been edited, we need to restart MySQL for the changes to take effect :

    systemctl daemon-reload

    systemctl restart mysql

7) Test MySQL Connection to Application:

    python manage.py runserver your-server-ip:8000

SQL Query - Concatenating Results into One String

@AlexanderMP's answer is correct, but you can also consider handling nulls with coalesce:

declare @CodeNameString  nvarchar(max)
set @CodeNameString = null
SELECT @CodeNameString = Coalesce(@CodeNameString + ', ', '') + cast(CodeName as varchar) from AccountCodes  
select @CodeNameString

Rails select helper - Default selected value, how?

Alternatively, you could set the :project_id attribute in the controller, since the first argument of f.select pulls that particular attribute.

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

It sounds like installing the VS2017 update for that specific version didn't also install the .NET Core 2.0 SDK. You can download that here.

To check which version of the SDK you've already got installed, run

dotnet --info

from the command line. Note that if there's a global.json file in either your current working directory or any ancestor directory, that will override which version of the SDK is run. (That's useful if you want to enforce a particular version for a project, for example.)

Judging by comments, some versions of VS2017 updates do install the .NET Core SDK. I suspect it may vary somewhat over time.

How do I delay a function call for 5 seconds?

var rotator = function(){
  widget.Rotator.rotate();
  setTimeout(rotator,5000);
};
rotator();

Or:

setInterval(
  function(){ widget.Rotator.rotate() },
  5000
);

Or:

setInterval(
  widget.Rotator.rotate.bind(widget.Rotator),
  5000
);

regular expression for Indian mobile numbers

/(((^[\+,0][9][1])(((\s[0-9]{7,10})|(\S[0-9]{7,10}))|([-]\S[0-9]{7,10})))|((^[\+,0][2]{2,2})((\S[0-9]{7,8})|((([-])[0-9]{7,8})|(\s[0-9]{7,8})))))|(((^[6,7,8,9][0-9]{9,9}))|(^[0,\+](([9][1)|[6,7,8,9]))[0-9]{8,9}))/gm

I don't know if there is a simple expression for this but I have created this REGEX that validates all possible Indian numbers that contains (0 or +) then (91 or 22 (since I needed it for Maharashtra and second thing is that India have too many STD codes)) or directly searches for numbers starting with 6,7,8,9 that have/don't have a 0 in front of it .

(/[regex]/gm) is a trial for multi-line search you can remove it(//gm) if it fails to work/gives error.

Feel free to try it at regex101. My Project of this REGEX is here .

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

<!--[if !IE]> not working

In case you are working with IE 10 or above, as mentioned in http://tanalin.com/en/articles/ie-version-js/ the conditional comments are no longer supported. You might refer to https://gist.github.com/jasongaylord/5733469 as an alternative method, which the Trident version is checked as well from the navigator.userAgent. This also verified in case the browser is working in compatibility mode.

Why does instanceof return false for some literals?

Or you can just make your own function like so:

function isInstanceOf(obj, clazz){
  return (obj instanceof eval("("+clazz+")")) || (typeof obj == clazz.toLowerCase());
};

usage:

isInstanceOf('','String');
isInstanceOf(new String(), 'String');

These should both return true.

Ajax post request in laravel 5 return error 500 (Internal Server Error)

In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:

class VerifyCsrfToken extends BaseVerifier {

    private $openRoutes =
    [
        ...excluded routes
    ];

    public function handle($request, Closure $next)
    {
        foreach($this->openRoutes as $route)
        {
            if ($request->is($route))
            {
                return $next($request);
            }
        }

        return parent::handle($request, $next);
    }
};

This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.

Javascript change font color

Consider changing your markup to this:

<span id="someId">onlineff</span>

Then you can use this script:

var x = document.getElementById('someId');
x.style.color = '#00FF00';

see it here: http://jsfiddle.net/2ANmM/

SSH SCP Local file to Remote in Terminal Mac Os X

At first, you need to add : after the IP address to indicate the path is following:

scp magento.tar.gz [email protected]:/var/www

I don't think you need to sudo the scp. In this case it doesn't affect the remote machine, only the local command.

Then if your user@xx.x.x.xx doesn't have write access to /var/www then you need to do it in 2 times:

Copy to remote server in your home folder (: represents your remote home folder, use :subfolder/ if needed, or :/home/user/ for full path):

scp magento.tar.gz [email protected]:

Then SSH and move the file:

ssh [email protected]
sudo mv magento.tar.gz /var/www

How to add a Java Properties file to my Java Project in Eclipse

To create a property class please select your package where you wants to create your property file.

Right click on the package and select other. Now select File and type your file name with (.properties) suffix. For example: db.properties. Than click finish. Now you can write your code inside this property file.

Typescript empty object for a typed variable

Really depends on what you're trying to do. Types are documentation in typescript, so you want to show intention about how this thing is supposed to be used when you're creating the type.

Option 1: If Users might have some but not all of the attributes during their lifetime

Make all attributes optional

type User = {
  attr0?: number
  attr1?: string
}

Option 2: If variables containing Users may begin null

type User = {
...
}
let u1: User = null;

Though, really, here if the point is to declare the User object before it can be known what will be assigned to it, you probably want to do let u1:User without any assignment.

Option 3: What you probably want

Really, the premise of typescript is to make sure that you are conforming to the mental model you outline in types in order to avoid making mistakes. If you want to add things to an object one-by-one, this is a habit that TypeScript is trying to get you not to do.

More likely, you want to make some local variables, then assign to the User-containing variable when it's ready to be a full-on User. That way you'll never be left with a partially-formed User. Those things are gross.

let attr1: number = ...
let attr2: string = ...
let user1: User = {
  attr1: attr1,
  attr2: attr2
}

Java string to date conversion

String to Date conversion:

private Date StringtoDate(String date) throws Exception {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
            java.sql.Date sqlDate = null;
            if( !date.isEmpty()) {

                try {
                    java.util.Date normalDate = sdf1.parse(date);
                    sqlDate = new java.sql.Date(normalDate.getTime());
                } catch (ParseException e) {
                    throw new Exception("Not able to Parse the date", e);
                }
            }
            return sqlDate;
        }

How do you create a UIImage View Programmatically - Swift

In Swift 4.2 and Xcode 10.1

//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view

//Add image view properties like this(This is one of the way to add properties).  
extension UIImageView {
    //If you want only round corners
    func imgViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.masksToBounds = true
    }
}

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

How to change the background color of a UIButton while it's highlighted?

Try this if you have an image:

-(void)setBackgroundImage:(UIImage *)image forState:(UIControlState)state;

or see if showsTouchWhenHighlighted is enough for you.

Why is my xlabel cut off in my matplotlib plot?

for some reason sharex was set to True so I turned it back to False and it worked fine.

df.plot(........,sharex=False)

How to get city name from latitude and longitude coordinates in Google Maps?

I´m in Brazil. Because of the regional details sometimes the city cames in differents ways. I think its the same in India and other countries. So, to prevent errors I make this verification:

private fun getAddress(latLng: LatLng): String {
    // 1
    val geocoder = Geocoder(this)
    val addresses: List<Address>?
    var city = "no"

    try {

        addresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1)

        if (null != addresses && !addresses.isEmpty()) { //prevent from error
             //sometimes the city comes in locality, sometimes in subAdminArea.
            if (addresses[0].locality == null) {

                city = addresses[0].subAdminArea
            } else {
                city = addresses[0].locality
            }

            }
    } catch (e: IOException) {
        Log.e("MapsActivity", e.localizedMessage)
    }

    return city
    }

You can also check if city returns "no". If so, wasn´t possible to get the user location. Hope it helps.

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

How do you import classes in JSP?

In the page tag:

<%@ page import="java.util.List" %>

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I am using the python package psycopg2 and I got this error while querying. I kept running just the query and then the execute function, but when I reran the connection (shown below), it resolved the issue. So rerun what is above your script i.e the connection, because as someone said above, I think it lost the connection or was out of sync or something.

connection = psycopg2.connect(user = "##",
        password = "##",
        host = "##",
        port = "##",
        database = "##")
cursor = connection.cursor()

How to embed a SWF file in an HTML page?

What is the 'best' way? Words like 'most efficient,' 'fastest rendering,' etc. are more specific. Anyway, I am offering an alternative answer that helps me most of the time (whether or not is 'best' is irrelevant).

Alternate answer: Use an iframe.

That is, host the SWF file on the server. If you put the SWF file in the root or public_html folder then the SWF file will be located at www.YourDomain.com/YourFlashFile.swf.

Then, on your index.html or wherever, link the above location to your iframe and it will be displayed around your content wherever you put your iframe. If you can put an iframe there, you can put an SWF file there. Make the iframe dimensions the same as your SWF file. In the example below, the SWF file is 500 by 500.

Pseudo code:

<iframe src="//www.YourDomain.com/YourFlashFile.swf" width="500" height="500"></iframe>

The line of HTML code above will embed your SWF file. No other mess needed. Pros: W3C compliant, page design friendly, no speed issue, minimalist approach.
Cons: White space around your SWF file when launched in a browser.

That is an alternate answer. Whether it is the 'best' answer depends on your project.

Is there a function to copy an array in C/C++?

Since C++11, you can copy arrays directly with std::array:

std::array<int,4> A = {10,20,30,40};
std::array<int,4> B = A; //copy array A into array B

Here is the documentation about std::array

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

Truncate (not round off) decimal numbers in javascript

function toFixed(number, digits) {
    var reg_ex = new RegExp("(\\d+\\.\\d{" + digits + "})(\\d)")
    var array = number.toString().match(reg_ex);
    return array ? parseFloat(array[1]) : number.valueOf()
}

var test = 10.123456789
var __fixed = toFixed(test, 6)
console.log(__fixed)
// => 10.123456

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

How to use LogonUser properly to impersonate domain user from workgroup client

this works for me, full working example (I wish more people would do this):

//logon impersonation
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute

...

class Program {

    // obtains user token
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    // closes open handes returned by LogonUser
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public void DoWorkUnderImpersonation() {
        //elevate privileges before doing file copy to handle domain security
        WindowsImpersonationContext impersonationContext = null;
        IntPtr userHandle = IntPtr.Zero;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
        string user = ConfigurationManager.AppSettings["ImpersonationUser"];
        string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

        try {
            Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);

            // if domain name was blank, assume local machine
            if (domain == "")
                domain = System.Environment.MachineName;

            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user,
                                        domain,
                                        password,
                                        LOGON32_LOGON_INTERACTIVE,
                                        LOGON32_PROVIDER_DEFAULT,
                                        ref userHandle);

            if (!loggedOn) {
                Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
                return;
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);

            Console.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);

            //run the program with elevated privileges (like file copying from a domain server)
            DoWork();

        } catch (Exception ex) {
            Console.WriteLine("Exception impersonating user: " + ex.Message);
        } finally {
            // Clean up
            if (impersonationContext != null) {
                impersonationContext.Undo();
            }

            if (userHandle != IntPtr.Zero) {
                CloseHandle(userHandle);
            }
        }
    }


    private void DoWork() {
        //everything in here has elevated privileges

        //example access files on a network share through e$ 
        string[] files = System.IO.Directory.GetFiles(@"\\domainserver\e$\images", "*.jpg");
    }
}

What is Common Gateway Interface (CGI)?

You maybe want to know what is not CGI, and the answer is a MODULE for your web server (if I suppose you are runnig Apache). AND THAT'S THE BIG DIFERENCE, because CGI needs and external program, thread, whatever to instantiate a PERL, PHP, C app server where when you run as a MODULE that program is the web server (apache) per-se.

Because of all this there is a lot of performance, security, portability issues that come into play. But it's good to know what is not CGI first, to understand what it is.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

You can use Configuration to resolve this.

Ex (Startup.cs):

You can pass by DI to the controllers after this implementation.

public class Startup
{
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);

        Configuration = builder.Build();

    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        var microserviceName = Configuration["microserviceName"];

       services.AddSingleton(Configuration);

       ...
    }

Build error: You must add a reference to System.Runtime

For me helped only this code line:

Assembly.Load("System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

You need to add an event, before call your handleFunction like this:

function SingInContainer() {
..
..
handleClose = () => {
}

return (
    <SnackBar
        open={open}
        handleClose={() => handleClose}
        variant={variant}
        message={message}
        />
    <SignInForm/>
)

}

to remove first and last element in array

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

To remove first element from an array arr , use arr.shift()
To remove last element from an array arr , use arr.pop()

AngularJS does not send hidden field value

I use a classical javascript to set value to hidden input

$scope.SetPersonValue = function (PersonValue)
{
    document.getElementById('TypeOfPerson').value = PersonValue;
    if (PersonValue != 'person')
    {
        document.getElementById('Discount').checked = false;
        $scope.isCollapsed = true;
    }
    else
    {
        $scope.isCollapsed = false;
    }
}

Python date string to date object

you have a date string like this, "24052010" and you want date object for this,

from datetime import datetime
cus_date = datetime.strptime("24052010", "%d%m%Y").date()

this cus_date will give you date object.

you can retrieve date string from your date object using this,

cus_date.strftime("%d%m%Y")

Create nice column output in python

Wow, only 17 answers. The zen of python says "There should be one-- and preferably only one --obvious way to do it."

So here is an 18th way to do it: The tabulate package supports a bunch of data types that it can display as tables, here is a simple example adapted from their docs:

from tabulate import tabulate

table = [["Sun",696000,1989100000],
         ["Earth",6371,5973.6],
         ["Moon",1737,73.5],
         ["Mars",3390,641.85]]

print(tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"]))

which outputs

Planet      R (km)    mass (x 10^29 kg)
--------  --------  -------------------
Sun         696000           1.9891e+09
Earth         6371        5973.6
Moon          1737          73.5
Mars          3390         641.85

How to generate xsd from wsdl

You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.

SoapUI can do many things though!

Giving my function access to outside variable

$myArr = array();

function someFuntion(array $myArr) {
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;

    return $myArr;
}

$myArr = someFunction($myArr);

How add unique key to existing table (with non uniques rows)

You can do as yAnTar advised

ALTER TABLE TABLE_NAME ADD Id INT AUTO_INCREMENT PRIMARY KEY

OR

You can add a constraint

ALTER TABLE TABLE_NAME ADD CONSTRAINT constr_ID UNIQUE (user_id, game_id, date, time)

But I think to not lose your existing data, you can add an indentity column and then make a composite key.

What methods of ‘clearfix’ can I use?

It is so simple clearfix clears the issue by when we using the float properties inside the div element.If we use two div elements one as float:left; and other one as float:right; we can use clearfix for the parent of the two div element. If we refuse to use clearfix unnecessary spaces fill with contents below and site structure will be broken.

How do I import modules or install extensions in PostgreSQL 9.1+?

Postgrseql 9.1 provides for a new command CREATE EXTENSION. You should use it to install modules.

Modules provided in 9.1 can be found here.. The include,

adminpack , auth_delay , auto_explain , btree_gin , btree_gist
, chkpass , citext , cube , dblink , dict_int
, dict_xsyn , dummy_seclabel , earthdistance , file_fdw , fuzzystrmatch
, hstore , intagg , intarray , isn , lo
, ltree , oid2name , pageinspect , passwordcheck , pg_archivecleanup
, pgbench , pg_buffercache , pgcrypto , pg_freespacemap , pgrowlocks
, pg_standby , pg_stat_statements , pgstattuple , pg_test_fsync , pg_trgm
, pg_upgrade , seg , sepgsql , spi , sslinfo , tablefunc
, test_parser , tsearch2 , unaccent , uuid-ossp , vacuumlo
, xml2

If for instance you wanted to install earthdistance, simply use this command:

CREATE EXTENSION earthdistance;

If you wanted to install an extension with a hyphen in its name, like uuid-ossp, you need to enclose the extension name in double quotes:

CREATE EXTENSION "uuid-ossp";

How to set radio button checked as default in radiogroup?

There was same problem in my Colleague's code. This sounds as your Radio Group is not properly set with your Radio Buttons. This is the reason you can multi-select the radio buttons. I tried many things, finally i did a trick which is wrong actually, but works fine.

for ( int i = 0 ; i < myCount ; i++ )
{
    if ( i != k )
    {
        System.out.println ( "i = " + i );
        radio1[i].setChecked(false);
    }
}

Here I set one for loop, which checks for the available radio buttons and de-selects every one except the new clicked one. try it.

How to bind Events on Ajax loaded Content?

If your ajax response are containing html form inputs for instance, than this would be great:

$(document).on("change", 'input[type=radio][name=fieldLoadedFromAjax]', function(event) { 
if (this.value == 'Yes') {
  // do something here
} else if (this.value == 'No') {
  // do something else here.
} else {
   console.log('The new input field from an ajax response has this value: '+ this.value);
}

});

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

Converting byte array to String (Java)

The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:

String decoded = new String(bytes, "UTF-8");  // example for one encoding type

By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte is signed, it covers the range from -128 to 127.


-109 = 0x93: Control Code "Set Transmit State"

The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.

0x93 in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:

System.out.println(new String(new byte[]{-109}, "Cp1252")); 

How to set the authorization header using curl

If you don't have the token at the time of the call is made, You will have to make two calls, one to get the token and the other to extract the token form the response, pay attention to

grep token | cut -d, -f1 | cut -d\" -f4

as it is the part which is dealing with extracting the token from the response.

echo "Getting token response and extracting token"    
def token = sh (returnStdout: true, script: """
    curl -S -i -k -X POST https://www.example.com/getToken -H \"Content-Type: application/json\" -H \"Accept: application/json\" -d @requestFile.json | grep token | cut -d, -f1 | cut -d\\" -f4
""").split()

After extracting the token you can use the token to make subsequent calls as follows.

echo "Token : ${token[-1]}"       
echo "Making calls using token..."       
curl -S -i -k  -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer ${token[-1]}" https://www.example.com/api/resources 

What is the difference between null and System.DBNull.Value?

DataRow has a method that is called IsNull() that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.

DataRow["col"]==null will allways be false.

use

DataRow r;
if (r.IsNull("col")) ...

instead.

How do I set a ViewModel on a window in XAML using DataContext property?

You might want to try Catel. It allows you to define a DataWindow class (instead of Window), and that class automatically creates the view model for you. This way, you can use the declaration of the ViewModel as you did in your original post, and the view model will still be created and set as DataContext.

See this article for an example.

Effectively use async/await with ASP.NET Web API

I am not very sure whether it will make any difference in performance of my API.

Bear in mind that the primary benefit of asynchronous code on the server side is scalability. It won't magically make your requests run faster. I cover several "should I use async" considerations in my article on async ASP.NET.

I think your use case (calling other APIs) is well-suited for asynchronous code, just bear in mind that "asynchronous" does not mean "faster". The best approach is to first make your UI responsive and asynchronous; this will make your app feel faster even if it's slightly slower.

As far as the code goes, this is not asynchronous:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
  var response = _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
  return Task.FromResult(response);
}

You'd need a truly asynchronous implementation to get the scalability benefits of async:

public async Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return await _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Or (if your logic in this method really is just a pass-through):

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountriesAsync()
{
  return _service.ProcessAsync<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
}

Note that it's easier to work from the "inside out" rather than the "outside in" like this. In other words, don't start with an asynchronous controller action and then force downstream methods to be asynchronous. Instead, identify the naturally asynchronous operations (calling external APIs, database queries, etc), and make those asynchronous at the lowest level first (Service.ProcessAsync). Then let the async trickle up, making your controller actions asynchronous as the last step.

And under no circumstances should you use Task.Run in this scenario.

How to load a text file into a Hive table stored as sequence files

You cannot directly create a table stored as a sequence file and insert text into it. You must do this:

  1. Create a table stored as text
  2. Insert the text file into the text table
  3. Do a CTAS to create the table stored as a sequence file.
  4. Drop the text table if desired

Example:

CREATE TABLE test_txt(field1 int, field2 string)
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t';

LOAD DATA INPATH '/path/to/file.tsv' INTO TABLE test_txt;

CREATE TABLE test STORED AS SEQUENCEFILE
AS SELECT * FROM test_txt;

DROP TABLE test_txt;

How to bring a window to the front?

This simple method worked for me perfectly in Windows 7:

    private void BringToFront() {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                if(jFrame != null) {
                    jFrame.toFront();
                    jFrame.repaint();
                }
            }
        });
    }