Programs & Examples On #Acts as audited

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!

Where does R store packages?

This is documented in the 'R Installation and Administration' manual that came with your installation.

On my Linux box:

R> .libPaths()
[1] "/usr/local/lib/R/site-library" "/usr/lib/R/site-library"      
[3] "/usr/lib/R/library"           
R> 

meaning that the default path is the first of these. You can override that via an argument to both install.packages() (from inside R) or R CMD INSTALL (outside R).

You can also override by setting the R_LIBS_USER variable.

HTTP error 403 in Python 3 Web Scraping

You can try in two ways. The detail is in this link.

1) Via pip

pip install --upgrade certifi

2) If it doesn't work, try to run a Cerificates.command that comes bundled with Python 3.* for Mac:(Go to your python installation location and double click the file)

open /Applications/Python\ 3.*/Install\ Certificates.command

How to insert a new key value pair in array in php?

foreach($test_package_data as $key=>$data ) {

   $category_detail_arr = $test_package_data[$key]['category_detail'];

   foreach( $category_detail_arr as $i=>$value ) {
     $test_package_data[$key]['category_detail'][$i]['count'] = $some_value;////<----Here
   }

}

Reloading module giving NameError: name 'reload' is not defined

For python2 and python3 compatibility, you can use:

# Python 2 and 3
from imp import reload
reload(mymodule)

Delaying AngularJS route change until model loaded to prevent flicker

I worked from Misko's code above and this is what I've done with it. This is a more current solution since $defer has been changed to $timeout. Substituting $timeout however will wait for the timeout period (in Misko's code, 1 second), then return the data hoping it's resolved in time. With this way, it returns asap.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {

  phones: function($q, Phone) {
    var deferred = $q.defer();

    Phone.query(function(phones) {
        deferred.resolve(phones);
    });

    return deferred.promise;
  }
}

How to display svg icons(.svg files) in UI using React Component?

Hard to believe adding a custom icon is so complicated. I found a similar solution to those posted above, but for me, I could not get the icon to display until I added the viewBox info, which I got directly from opening the SVG in a text editor.

//customIcon.js

import React from "react";
import {ReactComponent as ImportedSVG} from "path/to/myIcon.svg";
import { SvgIcon } from '@material-ui/core';

function CustomIcon() {
 return(
  <SvgIcon component={ImportedSVG} viewBox="0 0 384 512"/>

)
}

export default CustomIcon;

I also ran into an error with namespaces and had to clean up the SVG before it would work, following advice from this post

Delete worksheet in Excel using VBA

Consider:

Sub SheetKiller()
    Dim s As Worksheet, t As String
    Dim i As Long, K As Long
    K = Sheets.Count

    For i = K To 1 Step -1
        t = Sheets(i).Name
        If t = "ID Sheet" Or t = "Summary" Then
            Application.DisplayAlerts = False
                Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Sub

NOTE:

Because we are deleting, we run the loop backwards.

If hasClass then addClass to parent

Alternatively you could use:

if ($('#navigation a').is(".active")) {
    $(this).parent().addClass("active");
}

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

Failed to add the host to the list of know hosts

I think the OP's question is solved by deleting the ~/.ssh/known_hosts (which was a folder, not a file). But for other's who might be having this issue, I noticed that one of my servers had weird permissions (400):

-r--------. 1 user user 396 Jan 7 11:12 /home/user/.ssh/known_hosts

So I solved this by adding owner/user PLUS write.

chmod u+w ~/.ssh/known_hosts

Thus. ~/.ssh/known_hosts needs to be a flat file, and must be owned by you, and you need to be able to read and write to it.

You could always declare known_hosts bankruptcy, delete it, and continue doing things as normal, and connecting to things (git / ssh) will regenerate a new known_hosts that should work just fine.

How to upgrade Angular CLI to the latest version

This command works fine:

npm upgrade -g @angular/cli

good postgresql client for windows?

EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.

Extract subset of key-value pairs from Python dictionary object?

Using map (halfdanrump's answer) is best for me, though haven't timed it...

But if you go for a dictionary, and if you have a big_dict:

  1. Make absolutely certain you loop through the the req. This is crucial, and affects the running time of the algorithm (big O, theta, you name it)
  2. Write it generic enough to avoid errors if keys are not there.

so e.g.:

big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']

{k:big_dict.get(k,None) for k in req )
# or 
{k:big_dict[k] for k in req if k in big_dict)

Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.

In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:

dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]

{k:dic[k] for k in set(req).intersection(dict.keys())}

It moves the critical operation inside python's c code and will work for all cases.

How to select a record and update it, with a single queryset in Django?

1st method

MyTable.objects.filter(pk=some_value).update(field1='some value')

2nd Method

q = MyModel.objects.get(pk=some_value)
q.field1 = 'some value'
q.save()

3rd method

By using get_object_or_404

q = get_object_or_404(MyModel,pk=some_value)
q.field1 = 'some value'
q.save()

4th Method

if you required if pk=some_value exist then update it other wise create new one by using update_or_create.

MyModel.objects.update_or_create(pk=some_value,defaults={'field1':'some value'})

Notepad++ - How can I replace blank lines

  1. Press Ctrl+H (Replace)

  2. Select Extended from SearchMode

  3. Put \r\n\r\n in Find What

  4. Put \r\n in ReplaceWith

  5. Click on Replace All

Replace multiple line breaks

Binary search (bisection) in Python

If you just want to see if it's present, try turning the list into a dict:

# Generate a list
l = [n*n for n in range(1000)]

# Convert to dict - doesn't matter what you map values to
d = dict((x, 1) for x in l)

count = 0
for n in range(1000000):
    # Compare with "if n in l"
    if n in d:
        count += 1

On my machine, "if n in l" took 37 seconds, while "if n in d" took 0.4 seconds.

How do I copy a folder from remote to local using scp?

Better to first compress catalog on remote server:

tar czfP backup.tar.gz /path/to/catalog

Secondly, download from remote:

scp [email protected]:/path/to/backup.tar.gz .

At the end, extract the files:

tar -xzvf backup.tar.gz

Make ABC Ordered List Items Have Bold Style

a bit of a cheat, but it works:

HTML:

<ol type="A" style="font-weight: bold;">
  <li><span>Text</span></li>
  <li><span>More text</span></li>
</ol>

CSS:

li span { font-weight: normal; }

How set the android:gravity to TextView from Java side in Android

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");

How can I remove a key from a Python dictionary?

Another way is by using items() + dict comprehension.

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}

# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}

# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))

Output:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

How to print like printf in Python3?

Simple printf() function from O'Reilly's Python Cookbook.

import sys
def printf(format, *args):
    sys.stdout.write(format % args)

Example output:

i = 7
pi = 3.14159265359
printf("hi there, i=%d, pi=%.2f\n", i, pi)
# hi there, i=7, pi=3.14

How to extract the year from a Python datetime object?

If you want the year from a (unknown) datetime-object:

tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)

>>> tijd.timetuple()
time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
>>> tijd.timetuple().tm_year
9999

How to get JQuery.trigger('click'); to initiate a mouse click

Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:

$('.next').click(function () {
    $('#primary li.active').next().find('.acf-tab-button')[0].click();
});

$('.prev').click(function () {
    $('#primary li.active').prev().find('.acf-tab-button')[0].click();
});

How to append text to an existing file in Java?

I just add small detail:

    new FileWriter("outfilename", true)

2.nd parameter (true) is a feature (or, interface) called appendable (http://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html). It is responsible for being able to add some content to the end of particular file/stream. This interface is implemented since Java 1.5. Each object (i.e. BufferedWriter, CharArrayWriter, CharBuffer, FileWriter, FilterWriter, LogStream, OutputStreamWriter, PipedWriter, PrintStream, PrintWriter, StringBuffer, StringBuilder, StringWriter, Writer) with this interface can be used for adding content

In other words, you can add some content to your gzipped file, or some http process

What's the difference between Docker Compose vs. Dockerfile

Imagine you are the manager of a software company and you just bought a brand new server. Just the hardware.

Think of Dockerfile as a set of instructions you would tell your system adminstrator what to install on this brand new server. For example:

  • We need a Debian linux
  • add an apache web server
  • we need postgresql as well
  • install midnight commander
  • when all done, copy all *.php, *.jpg, etc. files of our project into the webroot of the webserver (/var/www)

By contrast, think of docker-compose.yml as a set of instructions you would tell your system administrator how the server can interact with the rest of the world. For example,

  • it has access to a shared folder from another computer,
  • it's port 80 is the same as the port 8000 of the host computer,
  • and so on.

(This is not a precise explanation but good enough to start with.)

JSP : JSTL's <c:out> tag

c:out escapes HTML characters so that you can avoid cross-site scripting.

if person.name = <script>alert("Yo")</script>

the script will be executed in the second case, but not when using c:out

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

HTML Input Type Date, Open Calendar by default

This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.

<input type="date" data-date-inline-picker="true" />

Here is a small demo

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

At the end of the ~.profile file add::

export GOPATH="$HOME/go"
export PATH="$PATH:/usr/local/go/bin"
export PATH="$PATH:$GOPATH/bin"

How to show a running progress bar while page is loading

Take a look here,

html file

<div class='progress' id="progress_div">
   <div class='bar' id='bar1'></div>
   <div class='percent' id='percent1'></div>
</div>

<div id="wrapper">
   <div id="content">
     <h1>Display Progress Bar While Page Loads Using jQuery<p>TalkersCode.com</p></h1>
   </div>
</div>

js file

document.onreadystatechange = function(e) {
  if (document.readyState == "interactive") {
    var all = document.getElementsByTagName("*");
    for (var i = 0, max = all.length; i < max; i++) {
      set_ele(all[i]);
    }
  }
}

function check_element(ele) {
  var all = document.getElementsByTagName("*");
  var totalele = all.length;
  var per_inc = 100 / all.length;

  if ($(ele).on()) {
    var prog_width = per_inc + Number(document.getElementById("progress_width").value);
    document.getElementById("progress_width").value = prog_width;
    $("#bar1").animate({
      width: prog_width + "%"
    }, 10, function() {
      if (document.getElementById("bar1").style.width == "100%") {
        $(".progress").fadeOut("slow");
      }
    });
  } else {
    set_ele(ele);
  }
}

function set_ele(set_element) {
  check_element(set_element);
}

it definitely solve your problem for complete tutorial here is the link http://talkerscode.com/webtricks/display-progress-bar-while-page-loads-using-jquery.php

Is it better practice to use String.format over string Concatenation in Java?

Here's the same test as above with the modification of calling the toString() method on the StringBuilder. The results below show that the StringBuilder approach is just a bit slower than String concatenation using the + operator.

file: StringTest.java

class StringTest {

  public static void main(String[] args) {

    String formatString = "Hi %s; Hi to you %s";

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        String s = String.format(formatString, i, +i * 2);
    }

    long end = System.currentTimeMillis();
    System.out.println("Format = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        String s = "Hi " + i + "; Hi to you " + i * 2;
    }

    end = System.currentTimeMillis();

    System.out.println("Concatenation = " + ((end - start)) + " millisecond");

    start = System.currentTimeMillis();

    for (int i = 0; i < 1000000; i++) {
        StringBuilder bldString = new StringBuilder("Hi ");
        bldString.append(i).append("Hi to you ").append(i * 2).toString();
    }

    end = System.currentTimeMillis();

    System.out.println("String Builder = " + ((end - start)) + " millisecond");

  }
}

Shell Commands : (compile and run StringTest 5 times)

> javac StringTest.java
> sh -c "for i in \$(seq 1 5); do echo \"Run \${i}\"; java StringTest; done"

Results :

Run 1
Format = 1290 millisecond
Concatenation = 115 millisecond
String Builder = 130 millisecond

Run 2
Format = 1265 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

Run 3
Format = 1303 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 4
Format = 1297 millisecond
Concatenation = 114 millisecond
String Builder = 127 millisecond

Run 5
Format = 1270 millisecond
Concatenation = 114 millisecond
String Builder = 126 millisecond

How can I wait for set of asynchronous callback functions?

Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

function asyncAction(i) {
    return new Promise(function(resolve, reject) {
        var result = calculateResult();
        if (result.hasError()) {
            return reject(result.error);
        }
        return resolve(result);
    });
}

var promises = [];
for (var i=0; i < 10; i++) {
    promises.push(asyncAction(i));
}

Promise.all(promises).then(function AcceptHandler(results) {
    handleResults(results),
}, function ErrorHandler(error) {
    handleError(error);
});

nginx - read custom header from upstream server

Use $http_MY_CUSTOM_HEADER

You can write some-thing like

set my_header $http_MY_CUSTOM_HEADER;
if($my_header != 'some-value') {
#do some thing;
}

Python Pandas replicate rows in dataframe

df = df_try
for i in range(4):
   df = df.append(df_try)

# Here, we have df_try times 5

df = df.append(df)

# Here, we have df_try times 10

Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

What's a concise way to check that environment variables are set in a Unix shell script?

Try this:

[ -z "$STATE" ] && echo "Need to set STATE" && exit 1;

In Android, how do I set margins in dp programmatically?

In my example i am adding an ImageView to a LinearLayout programatically. I have set top and bottom margins to ImagerView. Then adding the ImageView to the LinearLayout.



        ImageView imageView = new ImageView(mContext);
        imageView.setImageBitmap(bitmap);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        params.setMargins(0, 20, 0, 40);
        imageView.setLayoutParams(params);
        linearLayout.addView(imageView);

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

View stored procedure/function definition in MySQL

You can use table proc in database mysql:

mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;

Note that you must have a grant for select to mysql.proc:

mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;

Difference between variable declaration syntaxes in Javascript (including global variables)?

Bassed on the excellent answer of T.J. Crowder: (Off-topic: Avoid cluttering window)

This is an example of his idea:

Html

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="init.js"></script>
    <script type="text/javascript">
      MYLIBRARY.init(["firstValue", 2, "thirdValue"]);
    </script>
    <script src="script.js"></script>
  </head>

  <body>
    <h1>Hello !</h1>
  </body>    
</html>

init.js (Based on this answer)

var MYLIBRARY = MYLIBRARY || (function(){
    var _args = {}; // private

    return {
        init : function(Args) {
            _args = Args;
            // some other initialising
        },
        helloWorld : function(i) {
            return _args[i];
        }
    };
}());

script.js

// Here you can use the values defined in the html as if it were a global variable
var a = "Hello World " + MYLIBRARY.helloWorld(2);

alert(a);

Here's the plnkr. Hope it help !

Remove an entire column from a data.frame in R

With this you can remove the column and store variable into another variable.

df = subset(data, select = -c(genome) )

How do you uninstall MySQL from Mac OS X?

Aside from the long list of remove commands in your question, which seems quite comprehensive in my recent experience of exactly this issue, I found mysql.sock running in /private/var and removed that. I used

find / -name mysql -print 2> /dev/null

...to find anything that looked like a mysql directory or file and removed most of what came up (aside from Perl/Python access modules). You may also need to check that the daemon is not still running using Activity Monitor (or at the command line using ps -A). I found that mysqld was still running even after deleting the files.

Python: how can I check whether an object is of type datetime.date?

import datetime
d = datetime.date(2012, 9, 1)
print type(d) is datetime.date

> True

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

I'm not sure you have gotten past this yet, but I had to work on something very similar today and I got your fiddle working like you are asking, basically what I did was make another table row under it, and then used the accordion control. I tried using just collapse but could not get it working and saw an example somewhere on SO that used accordion.

Here's your updated fiddle: http://jsfiddle.net/whytheday/2Dj7Y/11/

Since I need to post code here is what each collapsible "section" should look like ->

<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
    <td>1</td>
    <td>05 May 2013</td>
    <td>Credit Account</td>
    <td class="text-success">$150.00</td>
    <td class="text-error"></td>
    <td class="text-success">$150.00</td>
</tr>

<tr>
    <td colspan="6" class="hiddenRow">
        <div class="accordion-body collapse" id="demo1">Demo1</div>
    </td>
</tr>

Vagrant stuck connection timeout retrying

FWIW-- My problem was due to using a really old config file instead of a newer one. Using the new configuration file (and thus tweaked/changed DSL) fixed my problems instantly.

SQLite table constraint - unique on multiple columns

Put the UNIQUE declaration within the column definition section; working example:

CREATE TABLE a (
    i INT,
    j INT,
    UNIQUE(i, j) ON CONFLICT REPLACE
);

How to concatenate text from multiple rows into a single text string in SQL server?

This can be useful too

create table #test (id int,name varchar(10))
--use separate inserts on older versions of SQL Server
insert into #test values (1,'Peter'), (1,'Paul'), (1,'Mary'), (2,'Alex'), (3,'Jack')

DECLARE @t VARCHAR(255)
SELECT @t = ISNULL(@t + ',' + name, name) FROM #test WHERE id = 1
select @t
drop table #test

returns

Peter,Paul,Mary

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

The best way to force the use of a number composed of digits only:

_x000D_
_x000D_
<input type="number" onkeydown="javascript: return event.keyCode === 8 ||_x000D_
event.keyCode === 46 ? true : !isNaN(Number(event.key))" />
_x000D_
_x000D_
_x000D_

this avoids 'e', '-', '+', '.' ... all characters that are not numbers !

To allow number keys only:

isNaN(Number(event.key))

but accept "Backspace" (keyCode: 8) and "Delete" (keyCode: 46) ...

How do I make a text input non-editable?

You can use readonly attribute, if you want your input only to be read. And you can use disabled attribute, if you want input to be shown, but totally disabled (even processing languages like PHP wont be able to read those).

Can't perform a React state update on an unmounted component

I had a similar issue thanks @ford04 helped me out.

However, another error occurred.

NB. I am using ReactJS hooks

ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

What causes the error?

import {useHistory} from 'react-router-dom'

const History = useHistory()
if (true) {
  history.push('/new-route');
}
return (
  <>
    <render component />
  </>
)

This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.

What solution I found

import {Redirect} from 'react-router-dom'

if (true) {
  return <redirect to="/new-route" />
}
return (
  <>
    <render component />
  </>
)

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

Very simple to solve this problem.

Just open RUN window(Window+R) and type services.msc:

Services.msc window

Find the SQL within name column and right click on that.

right click on SQL as in screenshot

enter image description here

You will get properties option, click on properties.

One new window will be open and there you have to click on Log On tab. And select the Local System Account. then apply and okay.

Select Local system Account

enter image description here

After that come again in services.msc window. and right click on sql and click start.

And finally, SQL Server services started successfully. enjoy and keep learning.

What is the opposite of :hover (on mouse leave)?

Put your duration time in the non-hover selection:

li a {
  background-color: #111;
  transition:1s;
}

li a:hover {
  padding:19px;
}

What is the difference between Left, Right, Outer and Inner Joins?

There are three basic types of join:

  • INNER join compares two tables and only returns results where a match exists. Records from the 1st table are duplicated when they match multiple results in the 2nd. INNER joins tend to make result sets smaller, but because records can be duplicated this isn't guaranteed.
  • CROSS join compares two tables and return every possible combination of rows from both tables. You can get a lot of results from this kind of join that might not even be meaningful, so use with caution.
  • OUTER join compares two tables and returns data when a match is available or NULL values otherwise. Like with INNER join, this will duplicate rows in the one table when it matches multiple records in the other table. OUTER joins tend to make result sets larger, because they won't by themselves remove any records from the set. You must also qualify an OUTER join to determine when and where to add the NULL values:
    • LEFT means keep all records from the 1st table no matter what and insert NULL values when the 2nd table doesn't match.
    • RIGHT means the opposite: keep all records from the 2nd table no matter what and insert NULL values whent he 1st table doesn't match.
    • FULL means keep all records from both tables, and insert a NULL value in either table if there is no match.

Often you see will the OUTER keyword omitted from the syntax. Instead it will just be "LEFT JOIN", "RIGHT JOIN", or "FULL JOIN". This is done because INNER and CROSS joins have no meaning with respect to LEFT, RIGHT, or FULL, and so these are sufficient by themselves to unambiguously indicate an OUTER join.

Here is an example of when you might want to use each type:

  • INNER: You want to return all records from the "Invoice" table, along with their corresponding "InvoiceLines". This assumes that every valid Invoice will have at least one line.
  • OUTER: You want to return all "InvoiceLines" records for a particular Invoice, along with their corresponding "InventoryItem" records. This is a business that also sells service, such that not all InvoiceLines will have an IventoryItem.
  • CROSS: You have a digits table with 10 rows, each holding values '0' through '9'. You want to create a date range table to join against, so that you end up with one record for each day within the range. By CROSS-joining this table with itself repeatedly you can create as many consecutive integers as you need (given you start at 10 to 1st power, each join adds 1 to the exponent). Then use the DATEADD() function to add those values to your base date for the range.

How to put multiple statements in one line?

if you want it without try and except then there is the solution

what you are trying to do is print 'hello' if 'harry' in a list then the solution is

'hello' if 'harry' in sam else ''

Declaring an enum within a class

In general, I always put my enums in a struct. I have seen several guidelines including "prefixing".

enum Color
{
  Clr_Red,
  Clr_Yellow,
  Clr_Blue,
};

Always thought this looked more like C guidelines than C++ ones (for one because of the abbreviation and also because of the namespaces in C++).

So to limit the scope we now have two alternatives:

  • namespaces
  • structs/classes

I personally tend to use a struct because it can be used as parameters for template programming while a namespace cannot be manipulated.

Examples of manipulation include:

template <class T>
size_t number() { /**/ }

which returns the number of elements of enum inside the struct T :)

How to get first and last day of the current week in JavaScript

You can also use following lines of code to get first and last date of the week:

var curr = new Date;
var firstday = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastday = new Date(curr.setDate(curr.getDate() - curr.getDay()+6));

Hope it will be useful..

How to Identify port number of SQL server

This query works for me:

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL 

What is the newline character in the C language: \r or \n?

What is the newline character in the C language: \r or \n?

The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

  1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

  2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

  3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
    Note: File I/O in binary mode makes no translation.

The '\r' in source code is the carriage return char.

(*1) A lone 13 and/or 10 may also translate into \n.

When do I need to use a semicolon vs a slash in Oracle SQL?

Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".

See

http://ss64.com/ora/syntax-sqlplus.html

Rule of thumb would be to use slash with things that do BEGIN .. END or where you can use CREATE OR REPLACE.

For inserts that need to be unique use

INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT 
                  FROM my_table
                  WHERE <identify data that you are trying to insert>)

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem to ec2-user@publicdns:/var/www/html, you can simply do:

scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/

Where:

  • -C - Compress data
  • -r - Recursive

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

From http://www.javaroots.com/2013/02/classnotfoundexception-vs.html:

ClassNotFoundException : occurs when class loader could not find the required class in class path. So, basically you should check your class path and add the class in the classpath.

NoClassDefFoundError : this is more difficult to debug and find the reason. This is thrown when at compile time the required classes are present, but at run time the classes are changed or removed or class's static initializes threw exceptions. It means the class which is getting loaded is present in classpath, but one of the classes which are required by this class are either removed or failed to load by compiler. So you should see the classes which are dependent on this class.

Example:

public class Test1
{
}


public class Test 
{
   public static void main(String[] args)
   {
        Test1 = new Test1();    
   }

}

Now after compiling both the classes, if you delete Test1.class file and run Test class, it will throw

Exception in thread "main" java.lang.NoClassDefFoundError: Test
    at Test1.main(Test1.java:5)
Caused by: java.lang.ClassNotFoundException: Test
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

ClassNotFoundException: thrown when an application tries to load in a class through its name, but no definition for the class with the specified name could be found.

NoClassDefFoundError: thrown if the Java Virtual Machine tries to load in the definition of a class and no definition of the class could be found.

In a bootstrap responsive page how to center a div

jsFiddle

HTML:

<div class="container" id="parent">
  <div class="row">
    <div class="col-lg-12">text
      <div class="row ">
        <div class="col-md-4 col-md-offset-4" id="child">TEXT</div>
      </div>
    </div>
  </div>
</div>

CSS:

#parent {    
    text-align: center;
}
#child {
    margin: 0 auto;
    display: inline-block;
    background: red;
    color: white;
}

Git Checkout warning: unable to unlink files, permission denied

I ran into this problem whenever running "git repack" or "git gc" on my OS X machines, even when running git with admin privileges, and I finally solved it after coming across this page: http://hints.macworld.com/comment.php?mode=view&cid=1734

The fix is to open a terminal, go to your git repo, cd into the .git folder, and then do:

chflags -R nouchg *

If that was the issue, then after that, your git commands will work as normal.

How do you get git to always pull from a specific branch?

If you prefer, you can set these options via the commmand line (instead of editing the config file) like so:

  $ git config branch.master.remote origin
  $ git config branch.master.merge refs/heads/master

Or, if you're like me, and want this to be the default across all of your projects, including those you might work on in the future, then add it as a global config setting:

  $ git config --global branch.master.remote origin
  $ git config --global branch.master.merge refs/heads/master

How to cast a double to an int in Java by rounding it down?

To cast a double to an int and have it be rounded to the nearest integer (i.e. unlike the typical (int)(1.8) and (int)(1.2), which will both "round down" towards 0 and return 1), simply add 0.5 to the double that you will typecast to an int.

For example, if we have

double a = 1.2;
double b = 1.8;

Then the following typecasting expressions for x and y and will return the rounded-down values (x = 1 and y = 1):

int x = (int)(a);   // This equals (int)(1.2) --> 1
int y = (int)(b);   // This equals (int)(1.8) --> 1

But by adding 0.5 to each, we will obtain the rounded-to-closest-integer result that we may desire in some cases (x = 1 and y = 2):

int x = (int)(a + 0.5);   // This equals (int)(1.8) --> 1
int y = (int)(b + 0.5);   // This equals (int)(2.3) --> 2

As a small note, this method also allows you to control the threshold at which the double is rounded up or down upon (int) typecasting.

(int)(a + 0.8);

to typecast. This will only round up to (int)a + 1 whenever the decimal values are greater than or equal to 0.2. That is, by adding 0.8 to the double immediately before typecasting, 10.15 and 10.03 will be rounded down to 10 upon (int) typecasting, but 10.23 and 10.7 will be rounded up to 11.

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

Why is the Android emulator so slow? How can we speed up the Android emulator?

On a 3.4 GHz quad core 6 GB of RAM, Windows 7, the emulator was unusably slow! I downloaded Launcher-Pro.apk through the emulator, installed it and set it as the default launcher. It doubled my emulation speed! The screens load much smoother and faster. It doesn't seem to download in 2.1 or 2.2, only in 2.0.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

How do I vertical center text next to an image in html/css?

One basic way that comes to mind would be to put the item into a table and have two cells, one with the text, the other with the image, and use style="valign:center" with the tags.

How to get a value from a cell of a dataframe?

I needed the value of one cell, selected by column and index names. This solution worked for me:

original_conversion_frequency.loc[1,:].values[0]

CardView Corner Radius

You need to do 2 things :

1) Call setPreventCornerOverlap(false) on your CardView.

2) Put rounded Imageview inside CardView

About rounding your imageview, I had the same problem so I made a library that you can set different radii on each corner. Finally I got the result what I wanted like below.

https://github.com/pungrue26/SelectableRoundedImageView

Rounded ImageView inside CardView

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

Effective way to find any file's Encoding

Check this.

UDE

This is a port of Mozilla Universal Charset Detector and you can use it like this...

public static void Main(String[] args)
{
    string filename = args[0];
    using (FileStream fs = File.OpenRead(filename)) {
        Ude.CharsetDetector cdet = new Ude.CharsetDetector();
        cdet.Feed(fs);
        cdet.DataEnd();
        if (cdet.Charset != null) {
            Console.WriteLine("Charset: {0}, confidence: {1}", 
                 cdet.Charset, cdet.Confidence);
        } else {
            Console.WriteLine("Detection failed.");
        }
    }
}

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

Can I set enum start value in Java?

The ordinal() function returns the relative position of the identifier in the enum. You can use this to obtain automatic indexing with an offset, as with a C-style enum.

Example:

public class TestEnum {
    enum ids {
        OPEN,
        CLOSE,
        OTHER;

        public final int value = 100 + ordinal();
    };

    public static void main(String arg[]) {
        System.out.println("OPEN:  " + ids.OPEN.value);
        System.out.println("CLOSE: " + ids.CLOSE.value);
        System.out.println("OTHER: " + ids.OTHER.value);
    }
};

Gives the output:

OPEN:  100
CLOSE: 101
OTHER: 102

Edit: just realized this is very similar to ggrandes' answer, but I will leave it here because it is very clean and about as close as you can get to a C style enum.

How to check the function's return value if true or false

Wrong syntax. You can't compare a Boolean to a string like "false" or "true". In your case, just test it's inverse:

if(!ValidateForm()) { ...

You could test against the constant false, but it's rather ugly and generally frowned upon:

if(ValidateForm() == false) { ...

Lost connection to MySQL server during query?

The easiest solution I found to this problem was to downgrade the MySql from MySQL Workbench to MySQL Version 1.2.17. I had browsed some MySQL Forums, where it was said that the timeout time in MySQL Workbech has been hard coded to 600 and some suggested methods to change it didn't work for me. If someone is facing the same problem with workbench you could try downgrading too.

Android + Pair devices via bluetooth programmatically

Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.

Try this to do pairing:

If you are able to search the devices then this would be your next step

ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;

I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:

BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);

Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
    Log.i("Log","Paired");
}
} catch (Exception e) 
{
    e.printStackTrace(); 
}

The createBond() method:

public boolean createBond(BluetoothDevice btDevice)  
    throws Exception  
    { 
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");  
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);  
        return returnValue.booleanValue();  
    }  

Add this line into your Receiver in the ACTION_FOUND

if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    arrayListBluetoothDevices.add(device);
                }

connecting to MySQL from the command line

After you run MySQL Shell and you have seen following:

mysql-js>

Firstly, you should:

mysql-js>\sql

Secondly:

 mysql-sql>\connect username@servername (root@localhost)

And finally:

Enter password:*********

Facebook Open Graph not clearing cache

It is a cache, ofc it refreshes, that's what cache is ment to do once in a while. So waiting will eventually work but sometimes you need to do that faster. Changing the filename works.

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Non-static variable cannot be referenced from a static context

Static fields and methods are connected to the class itself and not its instances. If you have a class A, a 'normal' method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.

The solution for you is that you either make your fields static or your methods non-static. You main could look like this then:

class Programm {

    public static void main(String[] args) {
        Programm programm = new Programm();
        programm.start();
    }

    public void start() {
        // can now access non-static fields
    }
}

How do I "select Android SDK" in Android Studio?

The simplest solution for this problem:

First make sure your sdk path is currect. Then Please close current project and in android startup menu click on import project and choose your project from explorer. This will always solve my problem

Cannot overwrite model once compiled Mongoose

The schema definition should be unique for a collection, it should not be more then one schema for a collection.

Troubleshooting BadImageFormatException

When building apps for 32-bit or 64-bit platform (My experience is with Visual Studio 2010), don't rely on the Configuration Manager to set the correct platform for the executable. Even if the CM has x86 selected for the application, check the project properties (Build tab): it might still say "Any CPU" there. And if you run an "Any CPU" executable on a 64-bit platform, it will run in 64-bit mode and refuse to load your accompanying DLLs that were built for the x86 platform.

Achieving white opacity effect in html/css

If you can't use rgba due to browser support, and you don't want to include a semi-transparent white PNG, you will have to create two positioned elements. One for the white box, with opacity, and one for the overlaid text, solid.

_x000D_
_x000D_
body { background: red; }_x000D_
_x000D_
.box { position: relative; z-index: 1; }_x000D_
.box .back {_x000D_
    position: absolute; z-index: 1;_x000D_
    top: 0; left: 0; width: 100%; height: 100%;_x000D_
    background: white; opacity: 0.75;_x000D_
}_x000D_
.box .text { position: relative; z-index: 2; }_x000D_
_x000D_
body.browser-ie8 .box .back { filter: alpha(opacity=75); }
_x000D_
<!--[if lt IE 9]><body class="browser-ie8"><![endif]-->_x000D_
<!--[if gte IE 9]><!--><body><!--<![endif]-->_x000D_
    <div class="box">_x000D_
        <div class="back"></div>_x000D_
        <div class="text">_x000D_
            Lorem ipsum dolor sit amet blah blah boogley woogley oo._x000D_
        </div>_x000D_
    </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Lollipop : draw behind statusBar with its color set to transparent

@Cody Toombs's answer lead to an issue that brings the layout behind the navigation bar. So what I found is using this solution given by @Kriti

here is the Kotlin code snippet for the same:

if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true)
}

if (Build.VERSION.SDK_INT >= 19) {
    window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
}

if (Build.VERSION.SDK_INT >= 21) {
    setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false)
    getWindow().setStatusBarColor(Color.TRANSPARENT)
}

private fun setWindowFlag(activity: Activity, bits: Int, on: Boolean) {

    val win: Window = activity.getWindow()

    val winParams: WindowManager.LayoutParams = win.getAttributes()
    if (on) {
        winParams.flags = winParams.flags or bits
    } else {
        winParams.flags = winParams.flags and bits.inv()
    }
    win.setAttributes(winParams)
}

You also need to add

android:fitsSystemWindows="false"

root view of your layout.

Download file of any type in Asp.Net MVC using FileResult?

You can just specify the generic octet-stream MIME type:

public FileResult Download()
{
    byte[] fileBytes = System.IO.File.ReadAllBytes(@"c:\folder\myfile.ext");
    string fileName = "myfile.ext";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

In the near future you may be able to use the ::marker psuedo-element to achieve the same result as other solutions in just one line of code.

Remember to check the Browser Compatibility Table as this is still an experimental technology. At the moment of writing only Firefox and Firefox for Android, starting from version 68, support this.

Here is a snippet that will render correctly if tried in a compatible browser:

_x000D_
_x000D_
::marker { content: counters(list-item,'.') ':' }_x000D_
li { padding-left: 0.5em }
_x000D_
<ol>_x000D_
  <li>li element_x000D_
    <ol>_x000D_
      <li>sub li element</li>_x000D_
      <li>sub li element</li>_x000D_
      <li>sub li element</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>li element</li>_x000D_
  <li>li element_x000D_
    <ol>_x000D_
      <li>sub li element</li>_x000D_
      <li>sub li element</li>_x000D_
      <li>sub li element</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

You may also want to check out this great article by smashingmagazine on the topic.

Cannot find pkg-config error

Answer to my question (after several Google searches) revealed the following:

$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install

from the following link: Link showing above

Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!

Doing this fixed my issues as mentioned above.

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Parse error: Syntax error, unexpected end of file in my PHP code

I had the same error, but I had it fixed by modifying the php.ini and / or editing the PHP file!

There are two different methods to get around the parse error syntax.

Method 1 (Your PHP file)

Avoid in your PHP file this:

<? } ?>

Make sure you put it like this

<?php ?>

Your code contains <? ?>

NOTE: The missing php after <?!

Method 2 (php.ini file)

There is also a simple way to solve your problem. Search for the short_open_tag property value (Use in your text editor with Ctrl + F!), and apply the following change:

; short_open_tag = Off

to

short_open_tag = On

According to the description of core php.ini directives, short_open_tag allows you to use the short open tag (<?) although this might cause issues when used with xml (<?xml will not work when this is enabled)!

NOTE: Reload your Server (like for example: Apache) and reload your PHP webpage in your browser.

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?

if you are using XDocument.Load(url); to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException

See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

Return a value if no rows are found in Microsoft tSQL

You can do something just like this.

IF EXISTS ( SELECT * FROM TableName WHERE Column=colval)
BEGIN
   select 
select name ,Id from TableName WHERE Column=colval
END
ELSE
  SELECT 'test' as name,0 as Id

How to manually trigger click event in ReactJS?

Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html

import React, { Component } from "react";
class AddImage extends Component {
  constructor(props) {
    super(props);
    this.fileUpload = React.createRef();
    this.showFileUpload = this.showFileUpload.bind(this);
  }
  showFileUpload() {
    this.fileUpload.current.click();
  }
  render() {
    return (
      <div className="AddImage">
        <input
          type="file"
          id="my_file"
          style={{ display: "none" }}
          ref={this.fileUpload}
        />
        <input
          type="image"
          src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
          width="30px"
          onClick={this.showFileUpload}
        />
      </div>
    );
  }
}
export default AddImage;

Where are shared preferences stored?

I just tried to get path of shared preferences below like this.This is work for me.

File f = getDatabasePath("MyPrefsFile.xml");

if (f != null)
    Log.i("TAG", f.getAbsolutePath());

Oracle error : ORA-00905: Missing keyword

Late answer, but I just came on this list today!

CREATE TABLE assignment_20101120 AS SELECT * FROM assignment;

Does the same.

ps1 cannot be loaded because running scripts is disabled on this system

The PowerShell execution policy is default set to Restricted. You can change the PowerShell execution policies with Set-ExecutionPolicy cmdlet. To run outside script set policy to RemoteSigned.

PS C:> Set-ExecutionPolicy RemoteSigned Below is the list of four different execution policies in PowerShell

Restricted – No scripts can be run. AllSigned – Only scripts signed by a trusted publisher can be run. RemoteSigned – Downloaded scripts must be signed by a trusted publisher. Unrestricted – All Windows PowerShell scripts can be run.

When would you use the different git merge strategies?

Actually the only two strategies you would want to choose are ours if you want to abandon changes brought by branch, but keep the branch in history, and subtree if you are merging independent project into subdirectory of superproject (like 'git-gui' in 'git' repository).

octopus merge is used automatically when merging more than two branches. resolve is here mainly for historical reasons, and for when you are hit by recursive merge strategy corner cases.

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

Random number between 0 and 1 in python

RTM

From the docs for the Python random module:

Functions for integers:

random.randrange(stop)
random.randrange(start, stop[, step])

    Return a randomly selected element from range(start, stop, step).
    This is equivalent to choice(range(start, stop, step)), but doesn’t
    actually build a range object.

That explains why it only gives you 0, doesn't it. range(0,1) is [0]. It is choosing from a list consisting of only that value.

Also from those docs:

random.random()    
    Return the next random floating point number in the range [0.0, 1.0).

But if your inclusion of the numpy tag is intentional, you can generate many random floats in that range with one call using a np.random function.

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

The problem

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

This means that you are trying to return multiple sibling JSX elements in an incorrect manner. Remember that you are not writing HTML, but JSX! Your code is transpiled from JSX into JavaScript. For example:

render() {
  return (<p>foo bar</p>);
}

will be transpiled into:

render() {
  return React.createElement("p", null, "foo bar");
}

Unless you are new to programming in general, you already know that functions/methods (of any language) take any number of parameters but always only return one value. Given that, you can probably see that a problem arises when trying to return multiple sibling components based on how createElement() works; it only takes parameters for one element and returns that. Hence we cannot return multiple elements from one function call.


So if you've ever wondered why this works...

render() {
  return (
    <div>
      <p>foo</p>
      <p>bar</p>
      <p>baz</p>
    </div>
  );
}

but not this...

render() {
  return (
    <p>foo</p>
    <p>bar</p>
    <p>baz</p>
  );
}

it's because in the first snippet, both <p>-elements are part of children of the <div>-element. When they are part of children then we can express an unlimited number of sibling elements. Take a look how this would transpile:

render() {
  return React.createElement(
    "div",
    null,
    React.createElement("p", null, "foo"),
    React.createElement("p", null, "bar"),
    React.createElement("p", null, "baz"),
  );
}

Solutions

Depending on which version of React you are running, you do have a few options to address this:

  • Use fragments (React v16.2+ only!)

    As of React v16.2, React has support for Fragments which is a node-less component that returns its children directly.

    Returning the children in an array (see below) has some drawbacks:

    • Children in an array must be separated by commas.
    • Children in an array must have a key to prevent React’s key warning.
    • Strings must be wrapped in quotes.

    These are eliminated from the use of fragments. Here's an example of children wrapped in a fragment:

    render() {
      return (
        <>
          <ChildA />
          <ChildB />
          <ChildC />
        </>
      );
    }
    

    which de-sugars into:

    render() {
      return (
        <React.Fragment>
          <ChildA />
          <ChildB />
          <ChildC />
        </React.Fragment>
      );
    }
    

    Note that the first snippet requires Babel v7.0 or above.


  • Return an array (React v16.0+ only!)

    As of React v16, React Components can return arrays. This is unlike earlier versions of React where you were forced to wrap all sibling components in a parent component.

    In other words, you can now do:

    render() {
      return [<p key={0}>foo</p>, <p key={1}>bar</p>];
    }
    

    this transpiles into:

    return [React.createElement("p", {key: 0}, "foo"), React.createElement("p", {key: 1}, "bar")];
    

    Note that the above returns an array. Arrays are valid React Elements since React version 16 and later. For earlier versions of React, arrays are not valid return objects!

    Also note that the following is invalid (you must return an array):

    render() {
      return (<p>foo</p> <p>bar</p>);
    }
    

  • Wrap the elements in a parent element

    The other solution involves creating a parent component which wraps the sibling components in its children. This is by far the most common way to address this issue, and works in all versions of React.

    render() {
      return (
        <div>
          <h1>foo</h1>
          <h2>bar</h2>
        </div>
      );
    }
    

    Note: Take a look again at the top of this answer for more details and how this transpiles.

npm install hangs

While your mileage may vary, running npm cache verify fixed the issue for me.

Display Back Arrow on Toolbar

Possibly a more reliable way to get the up icon from your theme (if not using the toolbar as your action bar):

toolbar.navigationIcon = context.getDrawableFromAttribute(R.attr.homeAsUpIndicator)

In order to turn the theme attribute into a drawable I used an extension function:

fun Context.getDrawableFromAttribute(attributeId: Int): Drawable {
    val typedValue = TypedValue().also { theme.resolveAttribute(attributeId, it, true) }
    return resources.getDrawable(typedValue.resourceId, theme)
}

Change fill color on vector asset in Android Studio

Go to you MainActivity.java and below this code
-> NavigationView navigationView = findViewById(R.id.nav_view);
Add single line of code -> navigationView.setItemIconTintList(null);
i.e. the last line of my code

I hope this might solve your problem.

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Java error: Comparison method violates its general contract

The exception message is actually pretty descriptive. The contract it mentions is transitivity: if A > B and B > C then for any A, B and C: A > C. I checked it with paper and pencil and your code seems to have few holes:

if (card1.getRarity() < card2.getRarity()) {
  return 1;

you do not return -1 if card1.getRarity() > card2.getRarity().


if (card1.getId() == card2.getId()) {
  //...
}
return -1;

You return -1 if ids aren't equal. You should return -1 or 1 depending on which id was bigger.


Take a look at this. Apart from being much more readable, I think it should actually work:

if (card1.getSet() > card2.getSet()) {
    return 1;
}
if (card1.getSet() < card2.getSet()) {
    return -1;
};
if (card1.getRarity() < card2.getRarity()) {
    return 1;
}
if (card1.getRarity() > card2.getRarity()) {
    return -1;
}
if (card1.getId() > card2.getId()) {
    return 1;
}
if (card1.getId() < card2.getId()) {
    return -1;
}
return cardType - item.getCardType();  //watch out for overflow!

PHP Remove elements from associative array

Try this:

$keys = array_keys($array, "Completed");

/edit As mentioned by JohnP, this method only works for non-nested arrays.

Change a Git remote HEAD to point to something besides master

First, create the new branch you would like to set as your default, for example:

$>git branch main

Next, push that branch to the origin:

$>git push origin main

Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."

Then, if you so choose, you can delete the master branch:

$>git push origin :master

How to make the web page height to fit screen height

A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.

<body style="overflow:hidden; margin:0">
    <form id="form1" runat="server">
        <div id="main" style="background-color:red">
            <div id="content">

            </div>
            <div id="footer">

            </div>
        </div>
    </form>
    <script language="javascript">
        function autoResizeDiv()
        {
            document.getElementById('main').style.height = window.innerHeight +'px';
        }
        window.onresize = autoResizeDiv;
        autoResizeDiv();
    </script>
</body>

Android - how do I investigate an ANR?

Whenever you're analyzing timing issues, debugging often does not help, as freezing the app at a breakpoint will make the problem go away.

Your best bet is to insert lots of logging calls (Log.XXX()) into the app's different threads and callbacks and see where the delay is at. If you need a stacktrace, create a new Exception (just instantiate one) and log it.

How can building a heap be O(n) time complexity?

Your analysis is correct. However, it is not tight.

It is not really easy to explain why building a heap is a linear operation, you should better read it.

A great analysis of the algorithm can be seen here.


The main idea is that in the build_heap algorithm the actual heapify cost is not O(log n)for all elements.

When heapify is called, the running time depends on how far an element might move down in tree before the process terminates. In other words, it depends on the height of the element in the heap. In the worst case, the element might go down all the way to the leaf level.

Let us count the work done level by level.

At the bottommost level, there are 2^(h)nodes, but we do not call heapify on any of these, so the work is 0. At the next to level there are 2^(h - 1) nodes, and each might move down by 1 level. At the 3rd level from the bottom, there are 2^(h - 2) nodes, and each might move down by 2 levels.

As you can see not all heapify operations are O(log n), this is why you are getting O(n).

C++ getters/setters coding style

Even though the name is immutable, you may still want to have the option of computing it rather than storing it in a field. (I realize this is unlikely for "name", but let's aim for the general case.) For that reason, even constant fields are best wrapped inside of getters:

class Foo {
    public:
        const std::string& getName() const {return name_;}
    private:
        const std::string& name_;
};

Note that if you were to change getName() to return a computed value, it couldn't return const ref. That's ok, because it won't require any changes to the callers (modulo recompilation.)

Display encoded html with razor

I store encoded HTML in the database.

Imho you should not store your data html-encoded in the database. Just store in plain text (not encoded) and just display your data like this and your html will be automatically encoded:

<div class='content'>
    @Model.Content
</div>

Can I access a form in the controller?

Bit late for an answer but came with following option. It is working for me but not sure if it is the correct way or not.

In my view I'm doing this:

<form name="formName">
    <div ng-init="setForm(formName);"></div>
</form>

And in the controller:

$scope.setForm = function (form) {
    $scope.myForm = form;
}

Now after doing this I have got my form in my controller variable which is $scope.myForm

how to check and set max_allowed_packet mysql variable

The following PHP worked for me (using mysqli extension but queries should be the same for other extensions):

$db = new mysqli( 'localhost', 'user', 'pass', 'dbname' );
// to get the max_allowed_packet
$maxp = $db->query( 'SELECT @@global.max_allowed_packet' )->fetch_array();
echo $maxp[ 0 ];
// to set the max_allowed_packet to 500MB
$db->query( 'SET @@global.max_allowed_packet = ' . 500 * 1024 * 1024 );

So if you've got a query you expect to be pretty long, you can make sure that mysql will accept it with something like:

$sql = "some really long sql query...";
$db->query( 'SET @@global.max_allowed_packet = ' . strlen( $sql ) + 1024 );
$db->query( $sql );

Notice that I added on an extra 1024 bytes to the length of the string because according to the manual,

The value should be a multiple of 1024; nonmultiples are rounded down to the nearest multiple.

That should hopefully set the max_allowed_packet size large enough to handle your query. I haven't tried this on a shared host, so the same caveat as @Glebushka applies.

Save a subplot in matplotlib

While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig takes a bbox_inches argument that can be used to selectively save only a portion of a figure to an image.

Here's a quick example:

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))

The full figure: Full Example Figure


Area inside the second subplot: Inside second subplot


Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction: Full second subplot

Is it not possible to define multiple constructors in Python?

If your signatures differ only in the number of arguments, using default arguments is the right way to do it. If you want to be able to pass in different kinds of argument, I would try to avoid the isinstance-based approach mentioned in another answer, and instead use keyword arguments.

If using just keyword arguments becomes unwieldy, you can combine it with classmethods (the bzrlib code likes this approach). This is just a silly example, but I hope you get the idea:

class C(object):

    def __init__(self, fd):
        # Assume fd is a file-like object.
        self.fd = fd

    @classmethod
    def fromfilename(cls, name):
        return cls(open(name, 'rb'))

# Now you can do:
c = C(fd)
# or:
c = C.fromfilename('a filename')

Notice all those classmethods still go through the same __init__, but using classmethods can be much more convenient than having to remember what combinations of keyword arguments to __init__ work.

isinstance is best avoided because Python's duck typing makes it hard to figure out what kind of object was actually passed in. For example: if you want to take either a filename or a file-like object you cannot use isinstance(arg, file), because there are many file-like objects that do not subclass file (like the ones returned from urllib, or StringIO, or...). It's usually a better idea to just have the caller tell you explicitly what kind of object was meant, by using different keyword arguments.

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

how can I display tooltip or item information on mouse over?

The title attribute works on most HTML tags and is widely supported by modern browsers.

Jquery UI datepicker. Disable array of Dates

For DD-MM-YY use this code:

var array = ["03-03-2017', '03-10-2017', '03-25-2017"]

$('#datepicker').datepicker({
    beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
    return [ array.indexOf(string) == -1 ]
    }
});

function highlightDays(date) {
    for (var i = 0; i < dates.length; i++) {
    if (new Date(dates[i]).toString() == date.toString()) {
        return [true, 'highlight'];
    }
}
return [true, ''];
}

manage.py runserver

in flask using flask.ext.script, you can do it like this:

python manage.py runserver -h 127.0.0.1 -p 8000

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

How to remove white space characters from a string in SQL Server

Using ASCII(RIGHT(ProductAlternateKey, 1)) you can see that the right most character in row 2 is a Line Feed or Ascii Character 10.

This can not be removed using the standard LTrim RTrim functions.

You could however use (REPLACE(ProductAlternateKey, CHAR(10), '')

You may also want to account for carriage returns and tabs. These three (Line feeds, carriage returns and tabs) are the usual culprits and can be removed with the following :

LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(ProductAlternateKey, CHAR(10), ''), CHAR(13), ''), CHAR(9), '')))

If you encounter any more "white space" characters that can't be removed with the above then try one or all of the below:

--NULL
Replace([YourString],CHAR(0),'');
--Horizontal Tab
Replace([YourString],CHAR(9),'');
--Line Feed
Replace([YourString],CHAR(10),'');
--Vertical Tab
Replace([YourString],CHAR(11),'');
--Form Feed
Replace([YourString],CHAR(12),'');
--Carriage Return
Replace([YourString],CHAR(13),'');
--Column Break
Replace([YourString],CHAR(14),'');
--Non-breaking space
Replace([YourString],CHAR(160),'');

This list of potential white space characters could be used to create a function such as :

Create Function [dbo].[CleanAndTrimString] 
(@MyString as varchar(Max))
Returns varchar(Max)
As
Begin
    --NULL
    Set @MyString = Replace(@MyString,CHAR(0),'');
    --Horizontal Tab
    Set @MyString = Replace(@MyString,CHAR(9),'');
    --Line Feed
    Set @MyString = Replace(@MyString,CHAR(10),'');
    --Vertical Tab
    Set @MyString = Replace(@MyString,CHAR(11),'');
    --Form Feed
    Set @MyString = Replace(@MyString,CHAR(12),'');
    --Carriage Return
    Set @MyString = Replace(@MyString,CHAR(13),'');
    --Column Break
    Set @MyString = Replace(@MyString,CHAR(14),'');
    --Non-breaking space
    Set @MyString = Replace(@MyString,CHAR(160),'');

    Set @MyString = LTRIM(RTRIM(@MyString));
    Return @MyString
End
Go

Which you could then use as follows:

Select 
    dbo.CleanAndTrimString(ProductAlternateKey) As ProductAlternateKey
from DimProducts

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Unfortunately, modules aren't supported by many browsers right now.

This feature is only just beginning to be implemented in browsers natively at this time. It is implemented in many transpilers, such as TypeScript and Babel, and bundlers such as Rollup and Webpack.

Found on MDN

How to list files in a directory in a C program?

Below code will only print files within directory and exclude directories within given directory while traversing.

#include <dirent.h>
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    char path[1000]="/home/joy/Downloads";
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Condition to check regular file.
            if(dir->d_type==DT_REG){
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("%s\n",full_path);
            }
        }
        closedir(d);
    }
    return(0);     
}

Setting environment variables in Linux using Bash

export VAR=value will set VAR to value. Enclose it in single quotes if you want spaces, like export VAR='my val'. If you want the variable to be interpolated, use double quotes, like export VAR="$MY_OTHER_VAR".

Is there a Python equivalent of the C# null-coalescing operator?

The two functions below I have found to be very useful when dealing with many variable testing cases.

def nz(value, none_value, strict=True):
    ''' This function is named after an old VBA function. It returns a default
        value if the passed in value is None. If strict is False it will
        treat an empty string as None as well.

        example:
        x = None
        nz(x,"hello")
        --> "hello"
        nz(x,"")
        --> ""
        y = ""   
        nz(y,"hello")
        --> ""
        nz(y,"hello", False)
        --> "hello" '''

    if value is None and strict:
        return_val = none_value
    elif strict and value is not None:
        return_val = value
    elif not strict and not is_not_null(value):
        return_val = none_value
    else:
        return_val = value
    return return_val 

def is_not_null(value):
    ''' test for None and empty string '''
    return value is not None and len(str(value)) > 0

RuntimeError: module compiled against API version a but this version of numpy is 9

You may also want to check your $PYTHONPATH. I had changed mine in ~/.bashrc in order to get another package to work.

To check your path:

    echo $PYTHONPATH

To change your path (I use nano but you could edit another way)

    nano ~/.bashrc

Look for the line with export PYTHONPATH ...

After making changes, don't forget to

   source ~/.bashrc

When to use "ON UPDATE CASCADE"

It's true that if your primary key is just a identity value auto incremented, you would have no real use for ON UPDATE CASCADE.

However, let's say that your primary key is a 10 digit UPC bar code and because of expansion, you need to change it to a 13-digit UPC bar code. In that case, ON UPDATE CASCADE would allow you to change the primary key value and any tables that have foreign key references to the value will be changed accordingly.

In reference to #4, if you change the child ID to something that doesn't exist in the parent table (and you have referential integrity), you should get a foreign key error.

How to dynamically create a class?

Based on @danijels's answer, dynamically create a class in VB.NET:

Imports System.Reflection
Imports System.Reflection.Emit

Public Class ObjectBuilder

Public Property myType As Object
Public Property myObject As Object

Public Sub New(fields As List(Of Field))
    myType = CompileResultType(fields)
    myObject = Activator.CreateInstance(myType)
End Sub

Public Shared Function CompileResultType(fields As List(Of Field)) As Type
    Dim tb As TypeBuilder = GetTypeBuilder()
    Dim constructor As ConstructorBuilder = tb.DefineDefaultConstructor(MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.RTSpecialName)

    For Each field In fields
        CreateProperty(tb, field.Name, field.Type)
    Next

    Dim objectType As Type = tb.CreateType()
    Return objectType
End Function

Private Shared Function GetTypeBuilder() As TypeBuilder
    Dim typeSignature = "MyDynamicType"
    Dim an = New AssemblyName(typeSignature)
    Dim assemblyBuilder As AssemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run)
    Dim moduleBuilder As ModuleBuilder = assemblyBuilder.DefineDynamicModule("MainModule")
    Dim tb As TypeBuilder = moduleBuilder.DefineType(typeSignature, TypeAttributes.[Public] Or TypeAttributes.[Class] Or TypeAttributes.AutoClass Or TypeAttributes.AnsiClass Or TypeAttributes.BeforeFieldInit Or TypeAttributes.AutoLayout, Nothing)
    Return tb
End Function

Private Shared Sub CreateProperty(tb As TypeBuilder, propertyName As String, propertyType As Type)
    Dim fieldBuilder As FieldBuilder = tb.DefineField("_" & propertyName, propertyType, FieldAttributes.[Private])

    Dim propertyBuilder As PropertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, Nothing)
    Dim getPropMthdBldr As MethodBuilder = tb.DefineMethod("get_" & propertyName, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, propertyType, Type.EmptyTypes)
    Dim getIl As ILGenerator = getPropMthdBldr.GetILGenerator()

    getIl.Emit(OpCodes.Ldarg_0)
    getIl.Emit(OpCodes.Ldfld, fieldBuilder)
    getIl.Emit(OpCodes.Ret)

    Dim setPropMthdBldr As MethodBuilder = tb.DefineMethod("set_" & propertyName, MethodAttributes.[Public] Or MethodAttributes.SpecialName Or MethodAttributes.HideBySig, Nothing, {propertyType})

    Dim setIl As ILGenerator = setPropMthdBldr.GetILGenerator()
    Dim modifyProperty As Label = setIl.DefineLabel()
    Dim exitSet As Label = setIl.DefineLabel()

    setIl.MarkLabel(modifyProperty)
    setIl.Emit(OpCodes.Ldarg_0)
    setIl.Emit(OpCodes.Ldarg_1)
    setIl.Emit(OpCodes.Stfld, fieldBuilder)

    setIl.Emit(OpCodes.Nop)
    setIl.MarkLabel(exitSet)
    setIl.Emit(OpCodes.Ret)

    propertyBuilder.SetGetMethod(getPropMthdBldr)
    propertyBuilder.SetSetMethod(setPropMthdBldr)
End Sub

End Class

How can I decrypt MySQL passwords

How can I decrypt MySQL passwords

You can't really because they are hashed and not encrypted.

Here's the essence of the PASSWORD function that current MySQL uses. You can execute it from the sql terminal:

mysql> SELECT SHA1(UNHEX(SHA1("password")));

+------------------------------------------+
| SHA1(UNHEX(SHA1("password")))            |
+------------------------------------------+
| 2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+------------------------------------------+
1 row in set (0.00 sec)

How can I change or retrieve these?

If you are having trouble logging in on a debian or ubuntu system, first try this (thanks to tohuwawohu at https://askubuntu.com/questions/120718/cant-log-to-mysql):

$ sudo cat /etc/mysql/debian.conf | grep -i password
...
password: QWERTY12345...

Then, log in with the debian maintenance user:

$ mysql -u debian-sys-maint -p
password:

Finally, change the user's password:

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

When I look in the PHPmyAdmin the passwords are encrypted

Related, if you need to dump the user database for the relevant information, try:

mysql> SELECT User,Host,Password FROM mysql.user;
+------------------+-----------+----------------------+
| User             | Host      | Password             |
+------------------+-----------+----------------------+
| root             | localhost | *0123456789ABCDEF... |
| root             | 127.0.0.1 | *0123456789ABCDEF... |
| root             | ::1       | *0123456789ABCDEF... |
| debian-sys-maint | localhost | *ABCDEF0123456789... |
+------------------+-----------+----------------------+

And yes, those passwords are NOT salted. So an attacker can prebuild the tables and apply them to all MySQL installations. In addition, the adversary can learn which users have the same passwords.

Needles to say, the folks at mySQL are not following best practices. John Steven did an excellent paper on Password Storage Best Practice at OWASP's Password Storage Cheat Sheet. In fairness to the MySQL folks, they may be doing it because of pain points in the architecture, design or implementation (I simply don't know).


If you use the PASSWORD and UPDATE commands and the change does not work, then see http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html. Even though the page is named "resetting permissions", its really about how to change a password. (Its befuddling the MySQL password change procedure is so broken that you have to jump through the hoops, but it is what it is).

Float a DIV on top of another DIV

Use this css

.close-image {
    cursor: pointer;
    z-index: 3;
    right: 5px;
    top: 5px;
    position: absolute;
}

How to export JavaScript array info to csv (on client side)?

The solution from @Default works perfect on Chrome (thanks a lot for that!) but I had a problem with IE.

Here's a solution (works on IE10):

var csvContent=data; //here we load our csv data 
var blob = new Blob([csvContent],{
    type: "text/csv;charset=utf-8;"
});

navigator.msSaveBlob(blob, "filename.csv")

Making a DateTime field in a database automatic?

Just right click on that column and select properties and write getdate()in Default value or binding.like image:

enter image description here

If you want do it in CodeFirst in EF you should add this attributes befor of your column definition:

[Databasegenerated(Databaseoption.computed)]

this attributes can found in System.ComponentModel.Dataannotion.Schema.

In my opinion first one is better:))

SQL query to get the deadlocks in SQL SERVER 2008

In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.

I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:

DBCC TRACEON(1222, -1);

A quick search yielded this tutorial:

http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/

Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.

Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:

enter image description here

Disclaimer: I work for SQL Sentry.

What does PHP keyword 'var' do?

The var keyword is used to declare variables in a class in PHP 4:

class Foo {
    var $bar;
}

With PHP 5 property and method visibility (public, protected and private) was introduced and thus var is deprecated.

MySQL: How to copy rows, but change a few fields?

This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)

How to copy some rows into the same table, with some fields having different values:

  1. Create a temporary table with all the rows you want to copy
  2. Update all the rows in the temporary table with the values you want
  3. If you have an auto increment field, you should set it to NULL in the temporary table
  4. Copy all the rows of the temporary table into your original table
  5. Delete the temporary table

Your code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";

UPDATE temporary_table SET Event_ID="120";

UPDATE temporary_table SET ID=NULL

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

General scenario code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

UPDATE temporary_table SET <auto_inc_field>=NULL;

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

Simplified/condensed code:

CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

INSERT INTO original_table SELECT * FROM temporary_table;

As creation of the temporary table uses the TEMPORARY keyword it will be dropped automatically when the session finishes (as @ar34z suggested).

How to change the date format from MM/DD/YYYY to YYYY-MM-DD in PL/SQL?

SELECT TO_DATE(TO_CHAR(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD')
FROM table;

Why does this code using random strings print "hello world"?

It is about "seed". Same seeds give the same result.

Thread-safe List<T> property

Here is the class you asked for:

namespace AI.Collections {
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Runtime.Serialization;
    using System.Threading.Tasks;
    using System.Threading.Tasks.Dataflow;

    /// <summary>
    ///     Just a simple thread safe collection.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <value>Version 1.5</value>
    /// <remarks>TODO replace locks with AsyncLocks</remarks>
    [DataContract( IsReference = true )]
    public class ThreadSafeList<T> : IList<T> {
        /// <summary>
        ///     TODO replace the locks with a ReaderWriterLockSlim
        /// </summary>
        [DataMember]
        private readonly List<T> _items = new List<T>();

        public ThreadSafeList( IEnumerable<T> items = null ) { this.Add( items ); }

        public long LongCount {
            get {
                lock ( this._items ) {
                    return this._items.LongCount();
                }
            }
        }

        public IEnumerator<T> GetEnumerator() { return this.Clone().GetEnumerator(); }

        IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }

        public void Add( T item ) {
            if ( Equals( default( T ), item ) ) {
                return;
            }
            lock ( this._items ) {
                this._items.Add( item );
            }
        }

        public Boolean TryAdd( T item ) {
            try {
                if ( Equals( default( T ), item ) ) {
                    return false;
                }
                lock ( this._items ) {
                    this._items.Add( item );
                    return true;
                }
            }
            catch ( NullReferenceException ) { }
            catch ( ObjectDisposedException ) { }
            catch ( ArgumentNullException ) { }
            catch ( ArgumentOutOfRangeException ) { }
            catch ( ArgumentException ) { }
            return false;
        }

        public void Clear() {
            lock ( this._items ) {
                this._items.Clear();
            }
        }

        public bool Contains( T item ) {
            lock ( this._items ) {
                return this._items.Contains( item );
            }
        }

        public void CopyTo( T[] array, int arrayIndex ) {
            lock ( this._items ) {
                this._items.CopyTo( array, arrayIndex );
            }
        }

        public bool Remove( T item ) {
            lock ( this._items ) {
                return this._items.Remove( item );
            }
        }

        public int Count {
            get {
                lock ( this._items ) {
                    return this._items.Count;
                }
            }
        }

        public bool IsReadOnly { get { return false; } }

        public int IndexOf( T item ) {
            lock ( this._items ) {
                return this._items.IndexOf( item );
            }
        }

        public void Insert( int index, T item ) {
            lock ( this._items ) {
                this._items.Insert( index, item );
            }
        }

        public void RemoveAt( int index ) {
            lock ( this._items ) {
                this._items.RemoveAt( index );
            }
        }

        public T this[ int index ] {
            get {
                lock ( this._items ) {
                    return this._items[ index ];
                }
            }
            set {
                lock ( this._items ) {
                    this._items[ index ] = value;
                }
            }
        }

        /// <summary>
        ///     Add in an enumerable of items.
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="asParallel"></param>
        public void Add( IEnumerable<T> collection, Boolean asParallel = true ) {
            if ( collection == null ) {
                return;
            }
            lock ( this._items ) {
                this._items.AddRange( asParallel
                                              ? collection.AsParallel().Where( arg => !Equals( default( T ), arg ) )
                                              : collection.Where( arg => !Equals( default( T ), arg ) ) );
            }
        }

        public Task AddAsync( T item ) {
            return Task.Factory.StartNew( () => { this.TryAdd( item ); } );
        }

        /// <summary>
        ///     Add in an enumerable of items.
        /// </summary>
        /// <param name="collection"></param>
        public Task AddAsync( IEnumerable<T> collection ) {
            if ( collection == null ) {
                throw new ArgumentNullException( "collection" );
            }

            var produce = new TransformBlock<T, T>( item => item, new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount } );

            var consume = new ActionBlock<T>( action: async obj => await this.AddAsync( obj ), dataflowBlockOptions: new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = Environment.ProcessorCount } );
            produce.LinkTo( consume );

            return Task.Factory.StartNew( async () => {
                collection.AsParallel().ForAll( item => produce.SendAsync( item ) );
                produce.Complete();
                await consume.Completion;
            } );
        }

        /// <summary>
        ///     Returns a new copy of all items in the <see cref="List{T}" />.
        /// </summary>
        /// <returns></returns>
        public List<T> Clone( Boolean asParallel = true ) {
            lock ( this._items ) {
                return asParallel
                               ? new List<T>( this._items.AsParallel() )
                               : new List<T>( this._items );
            }
        }

        /// <summary>
        ///     Perform the <paramref name="action" /> on each item in the list.
        /// </summary>
        /// <param name="action">
        ///     <paramref name="action" /> to perform on each item.
        /// </param>
        /// <param name="performActionOnClones">
        ///     If true, the <paramref name="action" /> will be performed on a <see cref="Clone" /> of the items.
        /// </param>
        /// <param name="asParallel">
        ///     Use the <see cref="ParallelQuery{TSource}" /> method.
        /// </param>
        /// <param name="inParallel">
        ///     Use the
        ///     <see
        ///         cref="Parallel.ForEach{TSource}(System.Collections.Generic.IEnumerable{TSource},System.Action{TSource})" />
        ///     method.
        /// </param>
        public void ForEach( Action<T> action, Boolean performActionOnClones = true, Boolean asParallel = true, Boolean inParallel = false ) {
            if ( action == null ) {
                throw new ArgumentNullException( "action" );
            }
            var wrapper = new Action<T>( obj => {
                try {
                    action( obj );
                }
                catch ( ArgumentNullException ) {
                    //if a null gets into the list then swallow an ArgumentNullException so we can continue adding
                }
            } );
            if ( performActionOnClones ) {
                var clones = this.Clone( asParallel: asParallel );
                if ( asParallel ) {
                    clones.AsParallel().ForAll( wrapper );
                }
                else if ( inParallel ) {
                    Parallel.ForEach( clones, wrapper );
                }
                else {
                    clones.ForEach( wrapper );
                }
            }
            else {
                lock ( this._items ) {
                    if ( asParallel ) {
                        this._items.AsParallel().ForAll( wrapper );
                    }
                    else if ( inParallel ) {
                        Parallel.ForEach( this._items, wrapper );
                    }
                    else {
                        this._items.ForEach( wrapper );
                    }
                }
            }
        }

        /// <summary>
        ///     Perform the <paramref name="action" /> on each item in the list.
        /// </summary>
        /// <param name="action">
        ///     <paramref name="action" /> to perform on each item.
        /// </param>
        /// <param name="performActionOnClones">
        ///     If true, the <paramref name="action" /> will be performed on a <see cref="Clone" /> of the items.
        /// </param>
        /// <param name="asParallel">
        ///     Use the <see cref="ParallelQuery{TSource}" /> method.
        /// </param>
        /// <param name="inParallel">
        ///     Use the
        ///     <see
        ///         cref="Parallel.ForEach{TSource}(System.Collections.Generic.IEnumerable{TSource},System.Action{TSource})" />
        ///     method.
        /// </param>
        public void ForAll( Action<T> action, Boolean performActionOnClones = true, Boolean asParallel = true, Boolean inParallel = false ) {
            if ( action == null ) {
                throw new ArgumentNullException( "action" );
            }
            var wrapper = new Action<T>( obj => {
                try {
                    action( obj );
                }
                catch ( ArgumentNullException ) {
                    //if a null gets into the list then swallow an ArgumentNullException so we can continue adding
                }
            } );
            if ( performActionOnClones ) {
                var clones = this.Clone( asParallel: asParallel );
                if ( asParallel ) {
                    clones.AsParallel().ForAll( wrapper );
                }
                else if ( inParallel ) {
                    Parallel.ForEach( clones, wrapper );
                }
                else {
                    clones.ForEach( wrapper );
                }
            }
            else {
                lock ( this._items ) {
                    if ( asParallel ) {
                        this._items.AsParallel().ForAll( wrapper );
                    }
                    else if ( inParallel ) {
                        Parallel.ForEach( this._items, wrapper );
                    }
                    else {
                        this._items.ForEach( wrapper );
                    }
                }
            }
        }
    }
}

Build query string for System.Net.HttpClient get

If I wish to submit a http get request using System.Net.HttpClient there seems to be no api to add parameters, is this correct?

Yes.

Is there any simple api available to build the query string that doesn't involve building a name value collection and url encoding those and then finally concatenating them?

Sure:

var query = HttpUtility.ParseQueryString(string.Empty);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
string queryString = query.ToString();

will give you the expected result:

foo=bar%3c%3e%26-baz&bar=bazinga

You might also find the UriBuilder class useful:

var builder = new UriBuilder("http://example.com");
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["foo"] = "bar<>&-baz";
query["bar"] = "bazinga";
builder.Query = query.ToString();
string url = builder.ToString();

will give you the expected result:

http://example.com/?foo=bar%3c%3e%26-baz&bar=bazinga

that you could more than safely feed to your HttpClient.GetAsync method.

How to fix java.net.SocketException: Broken pipe?

This is caused by:

  • most usually, writing to a connection when the other end has already closed it;
  • less usually, the peer closing the connection without reading all the data that is already pending at his end.

So in both cases you have a poorly defined or implemented application protocol.

There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.

Changing the text on a label

Use the config method to change the value of the label:

top = Tk()

l = Label(top)
l.pack()

l.config(text = "Hello World", width = "50")

CSS3 Transition not working

A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)

Event on a disabled input

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $("input:disabled").closest("div").click(function() {_x000D_
    $(this).find("input:disabled").attr("disabled", false).focus();_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <input type="text" disabled />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Convert a list of characters into a string

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

import io

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

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

prints:

abcd

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

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

Get clicked element using jQuery on event?

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});

htaccess redirect all pages to single page

Are you trying to get visitors to old.com/about.htm to go to new.com/about.htm? If so, you can do this with a mod_rewrite rule in .htaccess:

RewriteEngine on

RewriteRule ^(.*)$ http://www.thenewdomain.com/$1 [R=permanent,L]

How do I pull from a Git repository through an HTTP proxy?

For Windows

Goto --> C:/Users/user_name/gitconfig

Update gitconfig file with below details

[http]

[https]

proxy = https://your_proxy:your_port

[http]

proxy = http://your_proxy:your_port

How to check your proxy and port number?

Internet Explorer -> Settings -> Internet Options -> Connections -> LAN Settings

SQL comment header examples

-- [why did we write this?]
-- [auto-generated change control info]

How to schedule a function to run every hour on Flask?

A complete example using schedule and multiprocessing, with on and off control and parameter to run_job() the return codes are simplified and interval is set to 10sec, change to every(2).hour.do()for 2hours. Schedule is quite impressive it does not drift and I've never seen it more than 100ms off when scheduling. Using multiprocessing instead of threading because it has a termination method.

#!/usr/bin/env python3

import schedule
import time
import datetime
import uuid

from flask import Flask, request
from multiprocessing import Process

app = Flask(__name__)
t = None
job_timer = None

def run_job(id):
    """ sample job with parameter """
    global job_timer
    print("timer job id={}".format(id))
    print("timer: {:.4f}sec".format(time.time() - job_timer))
    job_timer = time.time()

def run_schedule():
    """ infinite loop for schedule """
    global job_timer
    job_timer = time.time()
    while 1:
        schedule.run_pending()
        time.sleep(1)

@app.route('/timer/<string:status>')
def mytimer(status, nsec=10):
    global t, job_timer
    if status=='on' and not t:
        schedule.every(nsec).seconds.do(run_job, str(uuid.uuid4()))
        t = Process(target=run_schedule)
        t.start()
        return "timer on with interval:{}sec\n".format(nsec)
    elif status=='off' and t:
        if t:
            t.terminate()
            t = None
            schedule.clear()
        return "timer off\n"
    return "timer status not changed\n"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

You test this by just issuing:

$ curl http://127.0.0.1:5000/timer/on
timer on with interval:10sec
$ curl http://127.0.0.1:5000/timer/on
timer status not changed
$ curl http://127.0.0.1:5000/timer/off
timer off
$ curl http://127.0.0.1:5000/timer/off
timer status not changed

Every 10sec the timer is on it will issue a timer message to console:

127.0.0.1 - - [18/Sep/2018 21:20:14] "GET /timer/on HTTP/1.1" 200 -
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0117sec
timer job id=b64ed165-911f-4b47-beed-0d023ead0a33
timer: 10.0102sec

TSQL Pivot without aggregate function

Here is a great way to build dynamic fields for a pivot query:

--summarize values to a tmp table

declare @STR varchar(1000)
SELECT  @STr =  COALESCE(@STr +', ', '') 
+ QUOTENAME(DateRange) 
from (select distinct DateRange, ID from ##pivot)d order by ID

---see the fields generated

print @STr

exec('  .... pivot code ...
pivot (avg(SalesAmt) for DateRange IN (' + @Str +')) AS P
order by Decile')

Can't access Eclipse marketplace

I was facing the same issue and found here useful steps which saved my time a lot. Hope so below attached image will help you a lot-

Window-> Preferences-> General-> Network Connection

Change Active Provider Native to Manual if problem is not resolved by using the steps mentioned in snapshot. Make sure HTTP/HTTPS should be checked and if any IP is required for your proxy settings then you should provide proxy IP in host and port number as well. enter image description here

Reverse HashMap keys and values in Java

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

Fast Linux file count for a large number of files

The first 10 directories with the highest number of files.

dir=/ ; for i in $(ls -1 ${dir} | sort -n) ; { echo "$(find ${dir}${i} \
    -type f | wc -l) => $i,"; } | sort -nr | head -10

How to align 3 divs (left/center/right) inside another div?

.processList
  text-align: center
  li
  .leftProcess
    float: left
  .centerProcess
    float: none
    display: inline-block
  .rightProcess
    float: right

html
ul.processList.clearfix
  li.leftProcess

li.centerProcess
li.rightProcess

Encrypt and decrypt a String in java

Whether encrypted be the same when plain text is encrypted with the same key depends of algorithm and protocol. In cryptography there is initialization vector IV: http://en.wikipedia.org/wiki/Initialization_vector that used with various ciphers makes that the same plain text encrypted with the same key gives various cipher texts.

I advice you to read more about cryptography on Wikipedia, Bruce Schneier http://www.schneier.com/books.html and "Beginning Cryptography with Java" by David Hook. The last book is full of examples of usage of http://www.bouncycastle.org library.

If you are interested in cryptography the there is CrypTool: http://www.cryptool.org/ CrypTool is a free, open-source e-learning application, used worldwide in the implementation and analysis of cryptographic algorithms.

Disabling submit button until all fields have values

Grave digging... I like a different approach:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)

Hibernate dialect for Oracle Database 11g?

At least in case of EclipseLink 10g and 11g differ. Since 11g it is not recommended to use first_rows hint for pagination queries.

See "Is it possible to disable jpa hints per particular query". Such a query should not be used in 11g.

SELECT * FROM (
  SELECT /*+ FIRST_ROWS */ a.*, ROWNUM rnum  FROM (
    SELECT * FROM TABLES INCLUDING JOINS, ORDERING, etc.) a
  WHERE ROWNUM <= 10 )
WHERE rnum > 0;

But there can be other nuances.

lodash: mapping array to object

Yep it is here, using _.reduce

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];

_.reduce(params , function(obj,param) {
 obj[param.name] = param.input
 return obj;
}, {});

How much does it cost to develop an iPhone application?

I'm one of the developers for Twitterrific and to be honest, I can't tell you how many hours have gone into the product. I can tell you everyone who upvoted the estimate of 160 hours for development and 40 hours for design is fricken' high. (I'd use another phrase, but this is my first post on Stack Overflow, so I'm being good.)

Twitterrific has had 4 major releases beginning with the iOS 1.0 (Jailbreak.) That's a lot of code, much of which is in the bit bucket (we refactor a lot with each major release.)

One thing that would be interesting to look at is the amount of time that we had to work on the iPad version. Apple set a product release date that gave us 60 days to do the development. (That was later extended by a week.)

We started the iPad development from scratch, but a lot of our underlying code (mostly models) was re-used. The development was done by two experienced iOS developers. One of them has even written a book: http://appdevmanual.com :-)

With such a short schedule, we worked some pretty long hours. Let's be conservative and say it's 10 hours per day for 6 days a week. That 60 hours for 9 weeks gives us 540 hours. With two developers, that's pretty close to 1,100 hours. Our rate for clients is $150 per hour giving $165,000 just for new code. Remember also that we were reusing a bunch existing code: I'm going to lowball the value of that code at $35,000 giving a total development cost of $200,000.

Anyone who's done serious iPhone development can tell you there's a lot of design work involved with any project. We had two designers working on that aspect of the product. They worked their asses off dealing with completely new interaction mechanics. Don't forget they didn't have any hardware to touch, either (LOTS of printouts!) Combined they spent at least 25 hours per week on the project. So 225 hours at $150/hr is about $34,000.

There are also other costs that many developer neglect to take into account: project management, testing, equipment. Again, if we lowball that figure at $16,000 we're at $250,000. This number falls in line with Jonathan Wight's (@schwa) $50-150K estimate with the 22 day Obama app.

Take another hit, dude.

Now if you want to build backend services for your app, that number's going to go up even more. Everyone seems surprised that Instagram chewed through $500K in venture funding to build a new frontend and backend. I'm not.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

First reset locally:

git reset 23b6772

To see if you're on the right position, verify with:

git status

You will see something like:

On branch master Your branch is behind 'origin/master' by 17 commits, and can be fast-forwarded.

Then rewrite history on your remote tracking branch to reflect the change:

git push --force-with-lease // a useful command @oktober mentions in comments

Using --force-with-lease instead of --force will raise an error if others have meanwhile committed to the remote branch, in which case you should fetch first. More info in this article.

Image, saved to sdcard, doesn't appear in Android's Gallery app

Try this one, it will broadcast about a new image created, so your image visible. inside a gallery. photoFile replace with actual file path of the newly created image

private void galleryAddPicBroadCast() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri contentUri = Uri.fromFile(photoFile);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

How to get an Array with jQuery, multiple <input> with the same name

To catch the names array, i use that:

$("input[name*='task']")

Converting rows into columns and columns into rows using R

Here is a tidyverse option that might work depending on the data, and some caveats on its usage:

library(tidyverse)

starting_df %>% 
  rownames_to_column() %>% 
  gather(variable, value, -rowname) %>% 
  spread(rowname, value)

rownames_to_column() is necessary if the original dataframe has meaningful row names, otherwise the new column names in the new transposed dataframe will be integers corresponding to the orignal row number. If there are no meaningful row names you can skip rownames_to_column() and replace rowname with the name of the first column in the dataframe, assuming those values are unique and meaningful. Using the tidyr::smiths sample data would be:

smiths %>% 
    gather(variable, value, -subject) %>% 
    spread(subject, value)

Using the example starting_df with the tidyverse approach will throw a warning message about dropping attributes. This is related to converting columns with different attribute types into a single character column. The smiths data will not give that warning because all columns except for subject are doubles.

The earlier answer using as.data.frame(t()) will convert everything to a factor if there are mixed column types unless stringsAsFactors = FALSE is added, whereas the tidyverse option converts everything to a character by default if there are mixed column types.

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Convert HTML5 into standalone Android App

Create an Android app using Eclipse.

Create a layout that has a <WebView> control.

Move your HTML code to /assets folder.

Load webview with your file:///android_asset/ file.

And you have an android app!

What is the equivalent of ngShow and ngHide in Angular 2+?

If you are using Bootstrap is as simple as this:

<div [class.hidden]="myBooleanValue"></div>

How to set Default Controller in asp.net MVC 4 & MVC 5

In case you have only one controller and you want to access every action on root you can skip controller name like this

routes.MapRoute(
        "Default", 
        "{action}/{id}", 
        new { controller = "Home", action = "Index", 
        id = UrlParameter.Optional }
);

Doing a cleanup action just before Node.js exits

In the case where the process was spawned by another node process, like:

var child = spawn('gulp', ['watch'], {
    stdio: 'inherit',
});

And you try to kill it later, via:

child.kill();

This is how you handle the event [on the child]:

process.on('SIGTERM', function() {
    console.log('Goodbye!');
});

What is the difference between localStorage, sessionStorage, session and cookies?

  1. LocalStorage

    Pros:

    1. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. If you look at the Mozilla source code we can see that 5120KB (5MB which equals 2.5 Million chars on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
    2. The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
    3. The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.

    Cons:

    1. It works on same-origin policy. So, data stored will only be available on the same origin.
  2. Cookies

    Pros:

    1. Compared to others, there's nothing AFAIK.

    Cons:

    1. The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
    2. The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.

      Typically, the following are allowed:

      • 300 cookies in total
      • 4096 bytes per cookie
      • 20 cookies per domain
      • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)
  3. sessionStorage

    Pros:

    1. It is similar to localStorage.
    2. The data is not persistent i.e. data is only available per window (or tab in browsers like Chrome and Firefox). Data is only available during the page session. Changes made are saved and available for the current page, as well as future visits to the site on the same window. Once the window is closed, the storage is deleted.

    Cons:

    1. The data is available only inside the window/tab in which it was set.
    2. Like localStorage, it works on same-origin policy. So, data stored will only be available on the same origin.

Checkout across-tabs - how to facilitate easy communication between cross-origin browser tabs.

What is the difference between class and instance methods?

CLASS METHODS


A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.


INSTANCE METHODS


An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.


INVOKE


To invoke an instance method, you send the message to an instance of the class.

To invoke a class method, you send the message to the class directly.


Source: IOS - Objective-C - Class Methods And Instance Methods

CSS image overlay with color and transparency

CSS Filter Effects

It's not fully cross-browsers solution, but must work well in most modern browser.

<img src="image.jpg" />
<style>
    img:hover {
        /* Ch 23+, Saf 6.0+, BB 10.0+ */
        -webkit-filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
        /* FF 35+ */
        filter: hue-rotate(240deg) saturate(3.3) grayscale(50%);
    }
</style>

EXTERNAL DEMO PLAYGROUND

IN-HOUSE DEMO SNIPPET (source:simpl.info)

_x000D_
_x000D_
#container {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.blur {_x000D_
  filter: blur(5px)_x000D_
}_x000D_
_x000D_
.grayscale {_x000D_
  filter: grayscale(1)_x000D_
}_x000D_
_x000D_
.saturate {_x000D_
  filter: saturate(5)_x000D_
}_x000D_
_x000D_
.sepia {_x000D_
  filter: sepia(1)_x000D_
}_x000D_
_x000D_
.multi {_x000D_
  filter: blur(4px) invert(1) opacity(0.5)_x000D_
}
_x000D_
<div id="container">_x000D_
_x000D_
  <h1><a href="https://simpl.info/cssfilters/" title="simpl.info home page">simpl.info</a> CSS filters</h1>_x000D_
_x000D_
  <img src="https://simpl.info/cssfilters/balham.jpg" alt="No filter: Balham High Road and a rainbow" />_x000D_
  <img class="blur" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur filter: Balham High Road and a rainbow" />_x000D_
  <img class="grayscale" src="https://simpl.info/cssfilters/balham.jpg" alt="Grayscale filter: Balham High Road and a rainbow" />_x000D_
  <img class="saturate" src="https://simpl.info/cssfilters/balham.jpg" alt="Saturate filter: Balham High Road and a rainbow" />_x000D_
  <img class="sepia" src="https://simpl.info/cssfilters/balham.jpg" alt="Sepia filter: Balham High Road and a rainbow" />_x000D_
  <img class="multi" src="https://simpl.info/cssfilters/balham.jpg" alt="Blur, invert and opacity filters: Balham High Road and a rainbow" />_x000D_
_x000D_
  <p><a href="https://github.com/samdutton/simpl/blob/gh-pages/cssfilters" title="View source for this page on GitHub" id="viewSource">View source on GitHub</a></p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

NOTES

  • This property is significantly different from and incompatible with Microsoft's older "filter" property
  • Edge, element or it's parent can't have negative z-index (see bug)
  • IE use old school way (link) thanks @Costa

RESOURCES:

Find methods calls in Eclipse project

select method > right click > References > Workspace/Project (your preferred context ) 

or

(Ctrl+Shift+G) 

This will show you a Search view containing the hierarchy of class and method which using this method.

What Vim command(s) can be used to quote/unquote words?

If you use the vim plugin https://github.com/tpope/vim-surround (or use VSCode Vim plugin, which comes with vim-surround pre-installed), its pretty convinient!

add

ysiw' // surround in word `'`

drop

ds' // drop surround `'`

change

cs'" // change surround from `'` to `"`

It even works for html tags!

cst<em> // change surround from current tag to `<em>`

check out the readme on github for better examples

Expand and collapse with angular js

You can solve this fully in the html:

<div>
  <input ng-model=collapse type=checkbox>Title
  <div ng-show=collapse>
     Only shown when checkbox is clicked
  </div>
</div>

This also works well with ng-repeat since it will create a local scope for each member.

<table>
  <tbody ng-repeat='m in members'>
    <tr>
       <td><input type=checkbox ng-model=collapse></td>
       <td>{{m.title}}</td>
    </tr>
    <tr ng-show=collapse>
      <td> </td>
      <td>{{ m.content }}</td>
    </tr>
  </tbody>
</table>

Be aware that even though a repeat has its own scope, initially it will inherit the value from collapse from super scopes. This allows you to set the initial value in one place but it can be surprising.

You can of course restyle the checkbox. See http://jsfiddle.net/azD5m/5/

Updated fiddle: http://jsfiddle.net/azD5m/374/ Original fiddle used closing </input> tags to add the HTML text label instead of using <label> tags.

ASP MVC href to a controller/view

You can modify with the following

<li><a href="./Index" class="elements"><span>Clients</span></a></li>

The extra dot means you are in the same controller. If you want change the controller to a different controller then you can write this

<li><a href="../newController/Index" class="elements"><span>Clients</span></a></li>

Jquery ajax call click event submit button

You did not add # before id of the button. You do not have right selector in your jquery code. So jquery is never execute in your button click. its submitted your form directly not passing any ajax request.

See documentation: http://api.jquery.com/category/selectors/
its your friend.

Try this:

It seems that id: $("#Shareitem").val() is wrong if you want to pass the value of

<input type="hidden" name="id" value="" id="id">

you need to change this line:

id: $("#Shareitem").val()

by

id: $("#id").val()

All together:

 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    <script>
    $(document).ready(function(){
      $("#Shareitem").click(function(e){
          e.preventDefault();
        $.ajax({type: "POST",
                url: "/imball-reagens/public/shareitem",
                data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() },
                success:function(result){
          $("#sharelink").html(result);
        }});
      });
    });
    </script>

How to create a laravel hashed password

Hashing A Password Using Bcrypt in Laravel:

$password = Hash::make('yourpassword');

This will create a hashed password. You may use it in your controller or even in a model, for example, if a user submits a password using a form to your controller using POST method then you may hash it using something like this:

$password = Input::get('passwordformfield'); // password is form field
$hashed = Hash::make($password);

Here, $hashed will contain the hashed password. Basically, you'll do it when creating/registering a new user, so, for example, if a user submits details such as, name, email, username and password etc using a form, then before you insert the data into database, you'll hash the password after validating the data. For more information, read the documentation.

Update:

$password = 'JohnDoe';
$hashedPassword = Hash::make($password);
echo $hashedPassword; // $2y$10$jSAr/RwmjhwioDlJErOk9OQEO7huLz9O6Iuf/udyGbHPiTNuB3Iuy

So, you'll insert the $hashedPassword into database. Hope, it's clear now and if still you are confused then i suggest you to read some tutorials, watch some screen casts on laracasts.com and tutsplus.com and also read a book on Laravel, this is a free ebook, you may download it.

Update: Since OP wants to manually encrypt password using Laravel Hash without any class or form so this is an alternative way using artisan tinker from command prompt:

  1. Go to your command prompt/terminal
  2. Navigate to the Laravel installation (your project's root directory)
  3. Use cd <directory name> and press enter from command prompt/terminal
  4. Then write php artisan tinker and press enter
  5. Then write echo Hash::make('somestring');
  6. You'll get a hashed password on the console, copy it and then do whatever you want to do.

Update (Laravel 5.x):

// Also one can use bcrypt
$password = bcrypt('JohnDoe');

How do I include a JavaScript file in another JavaScript file?

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.

For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.

ES6 Modules

ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use "type": "module" in package.json or give the files the extension .mjs. (Similarly, modules written with Node.js's previous CJS module can be named .cjs if your default is ESM.)

Using package.json:

{
    "type": "module"
}

Then module.js:

export function hello() {
  return "Hello";
}

Then main.js:

import { hello } from './module.js';
let val = hello();  // val is "Hello";

Using .mjs, you'd have module.mjs:

export function hello() {
  return "Hello";
}

Then main.mjs:

import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

ECMAScript modules in browsers

Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse. There is no need to use Node.js' .mjs extension; browsers completely ignore file extensions on modules/scripts.

<script type="module">
  import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
  hello('world');
</script>
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

Read more at https://jakearchibald.com/2017/es-modules-in-browsers/

Dynamic imports in browsers

Dynamic imports let the script load other scripts as needed:

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

Read more at https://developers.google.com/web/updates/2017/11/dynamic-import

Node.js require

The older CJS module style, still widely used in Node.js, is the module.exports/require system.

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.

AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

Fetch Loading

Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

Dynamic Script Loading

You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

Here is an example of how this could work:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL

    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

This function will add a new <script> tag to the end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode = function() {
   // Here, do whatever you want
};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There's a great article on Javascript loading in general which discusses this.

Source Code Merge/Preprocessing

As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.

How to dismiss AlertDialog in android

Actually there is no any cancel() or dismiss() method from AlertDialog.Builder Class.

So Instead of AlertDialog.Builder optionDialog use AlertDialog instance.

Like,

AlertDialog optionDialog = new AlertDialog.Builder(this).create();

Now, Just call optionDialog.dismiss();

background.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        SetBackground();
        // here I want to dismiss it after SetBackground() method 
        optionDialog.dismiss();
    }
});

text-overflow: ellipsis not working

You may try using ellipsis by adding the following in CSS:

.truncate {
  width: 250px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

But it seems like this code just applies to one-line trim. More ways to trim text and show ellipsis can be found in this website: http://blog.sanuker.com/?p=631

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

Just call array.ToObject<List<SelectableEnumItem>>() method. It will return what you need.

Documentation: Convert JSON to a Type

SQL Server - Return value after INSERT

@@IDENTITY Is a system function that returns the last-inserted identity value.

How do I debug Windows services in Visual Studio?

I'm using the /Console parameter in the Visual Studio project Debug ? Start Options ? Command line arguments:

public static class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
         var runMode = args.Contains(@"/Console")
             ? WindowsService.RunMode.Console
             : WindowsService.RunMode.WindowsService;
         new WinodwsService().Run(runMode);
    }
}


public class WindowsService : ServiceBase
{
    public enum RunMode
    {
        Console,
        WindowsService
    }

    public void Run(RunMode runMode)
    {
        if (runMode.Equals(RunMode.Console))
        {
            this.StartService();
            Console.WriteLine("Press <ENTER> to stop service...");
            Console.ReadLine();

            this.StopService();
            Console.WriteLine("Press <ENTER> to exit.");
            Console.ReadLine();
        }
        else if (runMode.Equals(RunMode.WindowsService))
        {
            ServiceBase.Run(new[] { this });
        }
    }

    protected override void OnStart(string[] args)
    {
        StartService(args);
    }

    protected override void OnStop()
    {
        StopService();
    }

    /// <summary>
    /// Logic to Start Service
    /// Public accessibility for running as a console application in Visual Studio debugging experience
    /// </summary>
    public virtual void StartService(params string[] args){ ... }

    /// <summary>
    /// Logic to Stop Service
    /// Public accessibility for running as a console application in Visual Studio debugging experience
    /// </summary>
    public virtual void StopService() {....}
}

MySQL: Error dropping database (errno 13; errno 17; errno 39)

in linux , Just go to "/var/lib/mysql" right click and (open as adminstrator), find the folder corresponding to your database name inside mysql folder and delete it. that's it. Database is dropped.

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

Replace forward slash "/ " character in JavaScript string?

First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\) in front of it.

someString.replace(/\//g, "-");

Live example

Find the smallest positive integer that does not occur in a given sequence

This solution is in c# but complete the test with 100% score

public int solution(int[] A) {
    // write your code in C# 6.0 with .NET 4.5 (Mono)
    var positives = A.Where(x => x > 0).Distinct().OrderBy(x => x).ToArray();
    if(positives.Count() == 0) return 1;
    int prev = 0;
    for(int i =0; i < positives.Count(); i++){

        if(positives[i] != prev + 1){
            return prev + 1;
        }
         prev = positives[i];
    }
    return positives.Last() + 1;
}

Git will not init/sync/update new submodules

The problem for me is that the repo's previous developer had committed the submodules/thing folder as just a regular folder, meaning when I tried to run git submodule add ..., it would fail with: 'submodules/thing' already exists in the index, yet trying to update the submodule would also fail because it saw that the path did not contain a submodule.

To fix, I had to delete the submodules/thing folder, commit the deletion, then run the git submodule add command to add it back correctly:

git submodule add --force --name thing https://github.com/person/thing.git submodules/thing

How to BULK INSERT a file into a *temporary* table where the filename is a variable?

Sorry to dig up an old question but in case someone stumbles onto this thread and wants a quicker solution.

Bulk inserting a unknown width file with \n row terminators into a temp table that is created outside of the EXEC statement.

DECLARE     @SQL VARCHAR(8000)

IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
    DROP TABLE #BulkInsert
END

CREATE TABLE #BulkInsert
(
    Line    VARCHAR(MAX)
)

SET @SQL = 'BULK INSERT #BulkInser FROM ''##FILEPATH##'' WITH (ROWTERMINATOR = ''\n'')'
EXEC (@SQL)

SELECT * FROM #BulkInsert

Further support that dynamic SQL within an EXEC statement has access to temp tables outside of the EXEC statement. http://sqlfiddle.com/#!3/d41d8/19343

DECLARE     @SQL VARCHAR(8000)

IF OBJECT_ID('TempDB..#BulkInsert') IS NOT NULL
BEGIN
    DROP TABLE #BulkInsert
END

CREATE TABLE #BulkInsert
(
    Line    VARCHAR(MAX)
)
INSERT INTO #BulkInsert
(
    Line
)
SELECT 1
UNION SELECT 2
UNION SELECT 3

SET @SQL = 'SELECT * FROM #BulkInsert'
EXEC (@SQL)

Further support, written for MSSQL2000 http://technet.microsoft.com/en-us/library/aa175921(v=sql.80).aspx

Example at the bottom of the link

DECLARE @cmd VARCHAR(1000), @ExecError INT
CREATE TABLE #ErrFile (ExecError INT)
SET @cmd = 'EXEC GetTableCount ' + 
'''pubs.dbo.authors''' + 
'INSERT #ErrFile VALUES(@@ERROR)'
EXEC(@cmd)
SET @ExecError = (SELECT * FROM #ErrFile)
SELECT @ExecError AS '@@ERROR'

keyword not supported data source

I know this is an old post but I got the same error recently so for what it's worth, here's another solution:

This is usually a connection string error, please check the format of your connection string, you can look up 'entity framework connectionstring' or follow the suggestions above.

However, in my case my connection string was fine and the error was caused by something completely different so I hope this helps someone:

  1. First I had an EDMX error: there was a new database table in the EDMX and the table did not exist in my database (funny thing is the error the error was not very obvious because it was not shown in my EDMX or output window, instead it was tucked away in visual studio in the 'Error List' window under the 'Warnings'). I resolved this error by adding the missing table to my database. But, I was actually busy trying to add a stored procedure and still getting the 'datasource' error so see below how i resolved it:

  2. Stored procedure error: I was trying to add a stored procedure and everytime I added it via the EDMX design window I got a 'datasource' error. The solution was to add the stored procedure as blank (I kept the stored proc name and declaration but deleted the contents of the stored proc and replaced it with 'select 1' and retried adding it to the EDMX). It worked! Presumably EF didn't like something inside my stored proc. Once I'd added the proc to EF I was then able to update the contents of the proc on my database to what I wanted it to be and it works, 'datasource' error resolved.

weirdness

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

This is solved in my case.

JS

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

This answer was inserted in this link

https://stackoverflow.com/questions/28322636/synchronous-xmlhttprequest-warning-and-script

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Batch files: How to read a file?

You can use the for command:

FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k

Type

for /?

at the command prompt. Also, you can parse ini files!