Programs & Examples On #Google instant previews

How to bring view in front of everything?

You can use BindingAdapter like this:

@BindingAdapter("bringToFront")
public static void bringToFront(View view, Boolean flag) {
    if (flag) {
        view.bringToFront();
    }
}


  <ImageView
        ...
        app:bringToFront="@{true}"/>

How to save LogCat contents to file?

Use logcat tool with -d or -f switch and exec() method.

Saving to a file on the host computer:

exec( "adb logcat -d > logcat.log" ) // logcat is written to logcat.log file on the host.

If you are just saving to a file on the device itself, you can use:

exec( "adb logcat -f logcat.log" ) // logcat is written to logcat.log file on the device.

How to check whether a pandas DataFrame is empty?

You can use the attribute df.empty to check whether it's empty or not:

if df.empty:
    print('DataFrame is empty!')

Source: Pandas Documentation

How do I check if a variable is of a certain type (compare two types) in C?

Gnu GCC has a builtin function for comparing types __builtin_types_compatible_p.

https://gcc.gnu.org/onlinedocs/gcc-3.4.5/gcc/Other-Builtins.html

This built-in function returns 1 if the unqualified versions of the types type1 and type2 (which are types, not expressions) are compatible, 0 otherwise. The result of this built-in function can be used in integer constant expressions.

This built-in function ignores top level qualifiers (e.g., const, volatile). For example, int is equivalent to const int.

Used in your example:

double doubleVar;
if(__builtin_types_compatible_p(typeof(doubleVar), double)) {
    printf("doubleVar is of type double!");
}

How does the @property decorator work in Python?

A property can be declared in two ways.

  • Creating the getter, setter methods for an attribute and then passing these as argument to property function
  • Using the @property decorator.

You can have a look at few examples I have written about properties in python.

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

One tiny addition to JB Jansen's answer - in the main readdir() loop I'd add this:

  if (dir->d_type == DT_REG)
  {
     printf("%s\n", dir->d_name);
  }

Just checking if it's really file, not (sym)link, directory, or whatever.

NOTE: more about struct dirent in libc documentation.

mysqli or PDO - what are the pros and cons?

Here's something else to keep in mind: For now (PHP 5.2) the PDO library is buggy. It's full of strange bugs. For example: before storing a PDOStatement in a variable, the variable should be unset() to avoid a ton of bugs. Most of these have been fixed in PHP 5.3 and they will be released in early 2009 in PHP 5.3 which will probably have many other bugs. You should focus on using PDO for PHP 6.1 if you want a stable release and using PDO for PHP 5.3 if you want to help the community.

Can't append <script> element

Your script is executing , you just can't use document.write from it. Use an alert to test it and avoid using document.write. The statements of your js file with document.write will not be executed and the rest of the function will be executed.

Regular expression to match any character being repeated more than 10 times

In Python you can use (.)\1{9,}

  • (.) makes group from one char (any char)
  • \1{9,} matches nine or more characters from 1st group

example:

txt = """1. aaaaaaaaaaaaaaa
2. bb
3. cccccccccccccccccccc
4. dd
5. eeeeeeeeeeee"""
rx = re.compile(r'(.)\1{9,}')
lines = txt.split('\n')
for line in lines:
    rxx = rx.search(line)
    if rxx:
        print line

Output:

1. aaaaaaaaaaaaaaa
3. cccccccccccccccccccc
5. eeeeeeeeeeee

Passing enum or object through an intent (the best solution)

You can pass an enum through as a string.

public enum CountType {
    ONE,
    TWO,
    THREE
}

private CountType count;
count = ONE;

String countString = count.name();

CountType countToo = CountType.valueOf(countString);

Given strings are supported you should be able to pass the value of the enum around with no problem.

Get CPU Usage from Windows Command Prompt

typeperf gives me issues when it randomly doesn't work on some computers (Error: No valid counters.) or if the account has insufficient rights. Otherwise, here is a way to extract just the value from its output. It still needs rounding though:

@for /f "delims=, tokens=2" %p in ('typeperf "\Processor(_Total)\% Processor Time" -sc 3 ^| find ":"') do @echo %~p%

Powershell has two cmdlets to get the percent utilization for all CPUs: Get-Counter (preferred) or Get-WmiObject:

Powershell "Get-Counter '\Processor(*)\% Processor Time' | Select -Expand Countersamples | Select InstanceName, CookedValue"

Or,

Powershell "Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor | Select Name, PercentProcessorTime"


To get the overall CPU load with formatted output exactly like the question:

Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'"

Or,

 Powershell "gwmi Win32_PerfFormattedData_PerfOS_Processor | Select -First 1 | %{'{0}%' -f $_.PercentProcessorTime}"

Stop executing further code in Java

You can just use return to end the method's execution

Angles between two n-dimensional vectors in Python

For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1) geometrical lines, there is the below minimal solution (uses the shapely module, but can be easily modified not to):

from shapely.geometry import LineString
import numpy as np

ninety_degrees_rad = 90.0 * np.pi / 180.0

def angle_between(line1, line2):
    coords_1 = line1.coords
    coords_2 = line2.coords

    line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
    line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0

    # Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
    if line1_vertical and line2_vertical:
        # Perpendicular vertical lines
        return 0.0
    if line1_vertical or line2_vertical:
        # 90° - angle of non-vertical line
        non_vertical_line = line2 if line1_vertical else line1
        return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))

    m1 = slope(line1)
    m2 = slope(line2)

    return np.arctan((m1 - m2)/(1 + m1*m2))

def slope(line):
    # Assignments made purely for readability. One could opt to just one-line return them
    x0 = line.coords[0][0]
    y0 = line.coords[0][1]
    x1 = line.coords[1][0]
    y1 = line.coords[1][1]
    return (y1 - y0) / (x1 - x0)

And the use would be

>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

jQuery call function after load

$(window).bind("load", function() {

   // code here 
});

How to comment lines in rails html.erb files?

ruby on rails notes has a very nice blogpost about commenting in erb-files

the short version is

to comment a single line use

<%# commented line %>

to comment a whole block use a if false to surrond your code like this

<% if false %>
code to comment
<% end %>

What is the http-header "X-XSS-Protection"?

TL;DR: All well written web sites (/apps) must emit the header X-XSS-Protection: 0 and just forget about this feature. If you want to have extra security that better user agents can provide, use a strict Content-Security-Policy header.

Long answer:

HTTP header X-XSS-Protection is one of those things that Microsoft introduced in Internet Explorer 8.0 (MSIE 8) that was supposed to improve security of incorrectly written web sites.

The idea is to apply some kind of heuristics to try to detect reflection XSS attack and automatically neuter the attack.

The problematic part of this is "heuristics" and "neutering". The heuristics causes false positives and neutering cannot be safely done because it causes side-effects that can be used to implement XSS attacks and DoS attacks on perfectly safe web sites.

The bad part is that if a web site does not emit the header X-XSS-Protection then the browser will behave as if the header X-XSS-Protection: 1 had been emitted. The worst part is that this value is the least-safe value of all possible values for this header!

For a given secure web site (that is, the site does not have reflected XSS vulnerabilities) this "XSS protection" feature allows following attacks:

X-XSS-Protection: 1 allows attacker to selectively block parts of JavaScript and keep rest of the scripts running. This is possible because the heuristics of this feature are simply "if value of any GET parameter is found in the scripting part of the page source, the script will be automatically modified in user agent dependant way". In practice, the attacker can e.g. add parameter disablexss=<script src="framebuster.js" and the browser will automatically remove the string <script src="framebuster.js" from the actual page source. Note that the rest of the page continues run and the attacker just removed this part of page security. In practice, any JS in the page source can be modified. For some cases, a page without XSS vulnerability having reflected content can be used to run selected JavaScript on page due the neutering incorrectly turning plain text data into executable JavaScript code. (That is, turn textual data within a normal DOM text node into content of <script> tag and execute it!)

X-XSS-Protection: 1; mode=block allows attacker to leak data from the page source by using the behavior of the page as side-channel. For example, if the page contains JavaScript code along the lines of var csrf_secret="521231347843", the attacker simply adds an extra parameter e.g. leak=var%20csrf_secret="3 and if the page is NOT blocked, the 3 was incorrect first digit. The attacker tries again, this time leak=var%20csrf_secret="5 and the page loading will be aborted. This allows the attacker to know that the first digit of the secret is 5. The attacker then continues to guess the next digit. This allows easily brute-forcing of CSRF secrets or any other secret value in the <script> source.

In the end, if your site is full of XSS reflection attacks, using the default value of 1 will reduce the attack surface a little bit. However, if your site is secure and you don't emit X-XSS-Protection: 0, your site will be vulnerable with any browser that supports this feature. If you want defense in depth support from browsers against yet-unknown XSS vulnerabilities on your site, use a strict Content-Security-Policy header and keep sending 0 for this mis-feature. That doesn't open your site to any known vulnerabilities.

Currently this feature is enabled by default in MSIE, Safari and Google Chrome. This used to be enabled in Edge but Microsoft already removed this mis-feature from Edge. Mozilla Firefox never implemented this.

See also:

https://homakov.blogspot.com/2013/02/hacking-facebook-with-oauth2-and-chrome.html https://blog.innerht.ml/the-misunderstood-x-xss-protection/ http://p42.us/ie8xss/Abusing_IE8s_XSS_Filters.pdf https://www.slideshare.net/masatokinugawa/xxn-en https://bugs.chromium.org/p/chromium/issues/detail?id=396544 https://bugs.chromium.org/p/chromium/issues/detail?id=498982

Using "If cell contains" in VBA excel

This does the same, enhanced with CONTAINS:

Function SingleCellExtract(LookupValue As String, LookupRange As Range, ColumnNumber As Integer, Char As String)
Dim I As Long
Dim xRet As String
For I = 1 To LookupRange.Columns(1).Cells.Count
     If InStr(1, LookupRange.Cells(I, 1), LookupValue) > 0 Then
        If xRet = "" Then
            xRet = LookupRange.Cells(I, ColumnNumber) & Char
        Else
            xRet = xRet & "" & LookupRange.Cells(I, ColumnNumber) & Char
        End If
    End If
Next
SingleCellExtract = Left(xRet, Len(xRet) - 1)
End Function

jQuery ajax success callback function definition

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

Tkinter module not found on Ubuntu

requirement for tkinter:

python 3.6+

and go to shell write the test code like :

from tkinter import *

root = Tk()

root.mainloop()

enter image description here

Angular: Can't find Promise, Map, Set and Iterator

I managed to fix this issue without having to add any triple-slash reference to the TS bootstrap file, change to ES6 (which brings a bunch of issues, just as @DatBoi said) update VS2015's NodeJS and/or NPM bundled builds or install typings globally.

Here's what I did in few steps:

  • added typings in the project's package.json file.
  • added a script block in the package.json file to execute/update typings after each NPM action.
  • added a typings.json file in the project's root folder containing a reference to core-js, which is one of the best shim/polyfill packages out there at the moment to fix ES5/ES6 issues.

Here's how the package.json file should look like (relevant lines only):

{
  "version": "1.0.0",
  "name": "YourProject",
  "private": true,
  "dependencies": {
    ...
    "typings": "^1.3.2",
    ...
  },
  "devDependencies": {
    ...
  },
  "scripts": {
      "postinstall": "typings install"
  }
}

And here's the typings.json file:

{
  "globalDependencies": {
    "core-js": "registry:dt/core-js#0.0.0+20160602141332",
    "jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
    "node": "registry:dt/node#6.0.0+20160621231320"
  }
}

(Jasmine and Node are not required, but I suggest to keep them in case you'll need to in the future).

This fix is working fine with Angular2 RC1 to RC4, which is what I needed, but I think it will also fix similar issues with other ES6-enabled library packages as well.

AFAIK, I think this is the cleanest possible way of fixing it without messing up the VS2015 default settings.

For more info and a detailed analysis of the issue, I also suggest to read this post on my blog.

Python import csv to list

Updated for Python 3:

import csv

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    your_list = list(reader)

print(your_list)

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

How to update a record using sequelize for node?

I have used sequelize.js, node.js and transaction in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

How to set tint for an image view programmatically in android?

Better simplified extension function thanks to ADev

fun ImageView.setTint(@ColorRes colorRes: Int) {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}

Usage:-

imageView.setTint(R.color.tintColor)

How do I get an element to scroll into view, using jQuery?

There's a DOM method called scrollIntoView, which is supported by all major browsers, that will align an element with the top/left of the viewport (or as close as possible).

$("#myImage")[0].scrollIntoView();

On supported browsers, you can provide options:

$("#myImage")[0].scrollIntoView({
    behavior: "smooth", // or "auto" or "instant"
    block: "start" // or "end"
});

Alternatively, if all the elements have unique IDs, you can just change the hash property of the location object for back/forward button support:

$(document).delegate("img", function (e) {
    if (e.target.id)
        window.location.hash = e.target.id;
});

After that, just adjust the scrollTop/scrollLeft properties by -20:

document.body.scrollLeft -= 20;
document.body.scrollTop -= 20;

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

In simple words

$.ajax("info.txt").done(function(data) {
  alert(data);
}).fail(function(data){
  alert("Try again champ!");
});

if its get the info.text then it will alert and whatever function you add or if any how unable to retrieve info.text from the server then alert or error function.

Convert String array to ArrayList

new ArrayList( Arrays.asList( new String[]{"abc", "def"} ) );

How to center cards in bootstrap 4?

Update 2018

There is no need for extra CSS, and there are multiple centering methods in Bootstrap 4:

  • text-center for center display:inline elements
  • mx-auto for centering display:block elements inside display:flex (d-flex)
  • offset-* or mx-auto can be used to center grid columns
  • or justify-content-center on row to center grid columns

mx-auto (auto x-axis margins) will center inside display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various centering methods.

In your case, you can simply mx-auto to the cards.

Difference between drop table and truncate table?

DELETE

The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it.

TRUNCATE

TRUNCATE removes all rows from a table. The operation cannot be rolled back ... As such, TRUCATE is faster and doesn't use as much undo space as a DELETE.

From: http://www.orafaq.com/faq/difference_between_truncate_delete_and_drop_commands

Operation Not Permitted when on root - El Capitan (rootless disabled)

If after calling "csrutil disabled" still your command does not work, try with "sudo" in terminal, for example:

sudo mv geckodriver /usr/local/bin

And it should work.

Check synchronously if file/directory exists in Node.js

Using the currently recommended (as of 2015) APIs (per the Node docs), this is what I do:

var fs = require('fs');

function fileExists(filePath)
{
    try
    {
        return fs.statSync(filePath).isFile();
    }
    catch (err)
    {
        return false;
    }
}

In response to the EPERM issue raised by @broadband in the comments, that brings up a good point. fileExists() is probably not a good way to think about this in many cases, because fileExists() can't really promise a boolean return. You may be able to determine definitively that the file exists or doesn't exist, but you may also get a permissions error. The permissions error doesn't necessarily imply that the file exists, because you could lack permission to the directory containing the file on which you are checking. And of course there is the chance you could encounter some other error in checking for file existence.

So my code above is really doesFileExistAndDoIHaveAccessToIt(), but your question might be doesFileNotExistAndCouldICreateIt(), which would be completely different logic (that would need to account for an EPERM error, among other things).

While the fs.existsSync answer addresses the question asked here directly, that is often not going to be what you want (you don't just want to know if "something" exists at a path, you probably care about whether the "thing" that exists is a file or a directory).

The bottom line is that if you're checking to see if a file exists, you are probably doing that because you intend to take some action based on the result, and that logic (the check and/or subsequent action) should accommodate the idea that a thing found at that path may be a file or a directory, and that you may encounter EPERM or other errors in the process of checking.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I hit this error ("stat /bin/bash: no such file or directory") when running the command:

docker exec -it 80372bc2c41e /bin/bash

The solution was to identify the kind of terminal (or shell) that is available on the container. To do so, I ran:

docker inspect 80372bc2c41e

In the output from that command, I saw:

"Cmd": [
    "/bin/sh",
    "-c",
    "gunicorn -b 0.0.0.0:7082 server.app:app"
],

This tells me that there's a /bin/sh command available, and I was able to connect with:

docker exec -it 80372bc2c41e /bin/sh

Converting a JS object to an array using jQuery

The solving is very simple

var my_obj = {1:[Array-Data], 2:[Array-Data]}
Object.keys(my_obj).map(function(property_name){ 
    return my_obj[property_name]; 
});

Failed to resolve: com.android.support:cardview-v7:26.0.0 android

Simply change the build-version from compile 'com.android.support:appcompat-v7:26.0.0'

to

compile 'com.android.support:appcompat-v7:26.0.0-alpha1'

This will solve your problem.

SQL Inner join more than two tables

A possible solution:

SELECT Company.Company_Id,Company.Company_Name,
    Invoice_Details.Invoice_No, Product_Details.Price
  FROM Company inner join Invoice_Details
    ON Company.Company_Id=Invoice_Details.Company_Id
 INNER JOIN Product_Details
        ON Invoice_Details.Invoice_No= Product_Details.Invoice_No
 WHERE Price='60000';

-- tets changes

How can I find the length of a number?

Well without converting the integer to a string you could make a funky loop:

var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
     ++length;
     i = Math.floor(i/10);
}

alert(length);?

Demo: http://jsfiddle.net/maniator/G8tQE/

Concatenate multiple node values in xpath

I used concat method and works well.

concat(//SomeElement/text(),'_',//OtherElement/text())

Server.Mappath in C# classlibrary

Maybe you could abstract this as a dependency and create an IVirtualPathResolver. This way your service classes wouldn't be bound to System.Web and you could create another implementation if you wanted to reuse your logic in a different UI technology.

Using port number in Windows host file

Using netsh with connectaddress=127.0.0.1 did not work for me.

Despite looking everywhere on the internet I could not find the solution which solved this for me, which was to use connectaddress=127.x.x.x (i.e. any 127. ipv4 address, just not 127.0.0.1) as this appears to link back to localhost just the same but without the restriction, so that the loopback works in netsh.

MyISAM versus InnoDB

I have briefly discussed this question in a table so you can conclude whether to go with InnoDB or MyISAM.

Here is a small overview of which db storage engine you should use in which situation:

                                                 MyISAM   InnoDB
----------------------------------------------------------------
Required full-text search                        Yes      5.6.4
----------------------------------------------------------------
Require transactions                                      Yes
----------------------------------------------------------------
Frequent select queries                          Yes      
----------------------------------------------------------------
Frequent insert, update, delete                           Yes
----------------------------------------------------------------
Row locking (multi processing on single table)            Yes
----------------------------------------------------------------
Relational base design                                    Yes

Summary

  • In almost all circumstances, InnoDB is the best way to go
  • But, frequent reading, almost no writing, use MyISAM
  • Full-text search in MySQL <= 5.5, use MyISAM

What is &amp used for

My Source: http://htmlhelp.com/tools/validator/problems.html#amp

Another common error occurs when including a URL which contains an ampersand ("&"):

This is invalid:

a href="foo.cgi?chapter=1&section=2&copy=3&lang=en"

Explanation:

This example generates an error for "unknown entity section" because the "&" is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert &copy=3 to ©=3, which may cause the link to fail. Since ⟨ is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting &section=2 to §ion=2.

So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &amp; when writing a URL in your markup.

Note that replacing & with &amp; is only done when writing the URL in HTML, where "&" is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use "&" and not "&amp;". With HTML, the browser translates "&amp;" to "&" so the Web server would only see "&" and not "&amp;" in the query string of the request.

Hope this helps : )

remove white space from the end of line in linux

Try this:

sed -i 's/\s*$//' youfile.txt

Quotation marks inside a string

You can do this using Escape Sequence.

\"

So you will have to write something like this :

String name = "\"john\"";

You can learn about Escape Sequences from here.

In c# what does 'where T : class' mean?

It is a generic type constraint. In this case it means that the generic type T has to be a reference type (class, interface, delegate, or array type).

Best way to strip punctuation from a string

I usually use something like this:

>>> s = "string. With. Punctuation?" # Sample string
>>> import string
>>> for c in string.punctuation:
...     s= s.replace(c,"")
...
>>> s
'string With Punctuation'

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

update q
set q.QuestionID = a.QuestionID
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want

I recommend to check what the result set to update is before running the update (same query, just with a select):

select *
from QuestionTrackings q
inner join QuestionAnswers a
on q.AnswerID = a.AnswerID
where q.QuestionID is null -- and other conditions you might want

Particularly whether each answer id has definitely only 1 associated question id.

Change event on select with knockout binding, how can I know if it is a real change?

I use this custom binding (based on this fiddle by RP Niemeyer, see his answer to this question), which makes sure the numeric value is properly converted from string to number (as suggested by the solution of Michael Best):

Javascript:

ko.bindingHandlers.valueAsNumber = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var observable = valueAccessor(),
            interceptor = ko.computed({
                read: function () {
                    var val = ko.utils.unwrapObservable(observable);
                    return (observable() ? observable().toString() : observable());
                },
                write: function (newValue) {
                    observable(newValue ? parseInt(newValue, 10) : newValue);
                },
                owner: this
            });
        ko.applyBindingsToNode(element, { value: interceptor });
    }
};

Example HTML:

<select data-bind="valueAsNumber: level, event:{ change: $parent.permissionChanged }">
    <option value="0"></option>
    <option value="1">R</option>
    <option value="2">RW</option>
</select>

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

How to convert int to string on Arduino?

This is speed-optimized solution for converting int (signed 16-bit integer) into string.

This implementation avoids using division since 8-bit AVR used for Arduino has no hardware DIV instruction, the compiler translate division into time-consuming repetitive subtractions. Thus the fastest solution is using conditional branches to build the string.

A fixed 7 bytes buffer prepared from beginning in RAM to avoid dynamic allocation. Since it's only 7 bytes, the cost of fixed RAM usage is considered minimum. To assist compiler, we add register modifier into variable declaration to speed-up execution.

char _int2str[7];
char* int2str( register int i ) {
  register unsigned char L = 1;
  register char c;
  register boolean m = false;
  register char b;  // lower-byte of i
  // negative
  if ( i < 0 ) {
    _int2str[ 0 ] = '-';
    i = -i;
  }
  else L = 0;
  // ten-thousands
  if( i > 9999 ) {
    c = i < 20000 ? 1
      : i < 30000 ? 2
      : 3;
    _int2str[ L++ ] = c + 48;
    i -= c * 10000;
    m = true;
  }
  // thousands
  if( i > 999 ) {
    c = i < 5000
      ? ( i < 3000
          ? ( i < 2000 ? 1 : 2 )
          :   i < 4000 ? 3 : 4
        )
      : i < 8000
        ? ( i < 6000
            ? 5
            : i < 7000 ? 6 : 7
          )
        : i < 9000 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 1000;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // hundreds
  if( i > 99 ) {
    c = i < 500
      ? ( i < 300
          ? ( i < 200 ? 1 : 2 )
          :   i < 400 ? 3 : 4
        )
      : i < 800
        ? ( i < 600
            ? 5
            : i < 700 ? 6 : 7
          )
        : i < 900 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    i -= c * 100;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // decades (check on lower byte to optimize code)
  b = char( i );
  if( b > 9 ) {
    c = b < 50
      ? ( b < 30
          ? ( b < 20 ? 1 : 2 )
          :   b < 40 ? 3 : 4
        )
      : b < 80
        ? ( i < 60
            ? 5
            : i < 70 ? 6 : 7
          )
        : i < 90 ? 8 : 9;
    _int2str[ L++ ] = c + 48;
    b -= c * 10;
    m = true;
  }
  else if( m ) _int2str[ L++ ] = '0';
  // last digit
  _int2str[ L++ ] = b + 48;
  // null terminator
  _int2str[ L ] = 0;  
  return _int2str;
}

// Usage example:
int i = -12345;
char* s;
void setup() {
  s = int2str( i );
}
void loop() {}

This sketch is compiled to 1,082 bytes of code using avr-gcc which bundled with Arduino v1.0.5 (size of int2str function itself is 594 bytes). Compared with solution using String object which compiled into 2,398 bytes, this implementation can reduce your code size by 1.2 Kb (assumed that you need no other String's object method, and your number is strict to signed int type).

This function can be optimized further by writing it in proper assembler code.

How to match letters only using java regex, matches method?

"[a-zA-Z]" matches only one character. To match multiple characters, use "[a-zA-Z]+".

Since a dot is a joker for any character, you have to mask it: "abc\." To make the dot optional, you need a question mark: "abc\.?"

If you write the Pattern as literal constant in your code, you have to mask the backslash:

System.out.println ("abc".matches ("abc\\.?"));
System.out.println ("abc.".matches ("abc\\.?"));
System.out.println ("abc..".matches ("abc\\.?"));

Combining both patterns:

System.out.println ("abc.".matches ("[a-zA-Z]+\\.?"));

Instead of a-zA-Z, \w is often more appropriate, since it captures foreign characters like äöüßø and so on:

System.out.println ("abc.".matches ("\\w+\\.?"));   

How to convert a Datetime string to a current culture datetime string

DateTime dateValue;
CultureInfo culture = CultureInfo.CurrentCulture;
DateTimeStyles styles = DateTimeStyles.None;
DateTime.TryParse(datetimestring,culture, styles, out dateValue);

Multi column forms with fieldsets

There are a couple of things that need to be adjusted in your layout:

  1. You are nesting col elements within form-group elements. This should be the other way around (the form-group should be within the col-sm-xx element).

  2. You should always use a row div for each new "row" in your design. In your case, you would need at least 5 rows (Username, Password and co, Title/First/Last name, email, Language). Otherwise, your problematic .col-sm-12 is still on the same row with the above 3 .col-sm-4 resulting in a total of columns greater than 12, and causing the overlap problem.

Here is a fixed demo.

And an excerpt of what the problematic section HTML should become:

<fieldset>
    <legend>Personal Information</legend>
    <div class='row'>
        <div class='col-sm-4'>    
            <div class='form-group'>
                <label for="user_title">Title</label>
                <input class="form-control" id="user_title" name="user[title]" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_firstname">First name</label>
                <input class="form-control" id="user_firstname" name="user[firstname]" required="true" size="30" type="text" />
            </div>
        </div>
        <div class='col-sm-4'>
            <div class='form-group'>
                <label for="user_lastname">Last name</label>
                <input class="form-control" id="user_lastname" name="user[lastname]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
    <div class='row'>
        <div class='col-sm-12'>
            <div class='form-group'>

                <label for="user_email">Email</label>
                <input class="form-control required email" id="user_email" name="user[email]" required="true" size="30" type="text" />
            </div>
        </div>
    </div>
</fieldset>

How to update Xcode from command line

I had the same issue and I solved by doing the following:

  1. removing the old tools ($ sudo rm -rf /Library/Developer/CommandLineTools)
  2. install xcode command line tools again ($ xcode-select --install).

After these steps you will see a pop to install the new version of the tools.

get specific row from spark dataframe

Following is a Java-Spark way to do it , 1) add a sequentially increment columns. 2) Select Row number using Id. 3) Drop the Column

import static org.apache.spark.sql.functions.*;
..

ds = ds.withColumn("rownum", functions.monotonically_increasing_id());
ds = ds.filter(col("rownum").equalTo(99));
ds = ds.drop("rownum");

N.B. monotonically_increasing_id starts from 0;

preg_match in JavaScript?

This should work:

var matches = text.match(/\[(\d+)\][(\d+)\]/);
var productId = matches[1];
var shopId = matches[2];

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I just want to add what solved this problem for me, as it is different to all of the above answers.

The ajax calls that were causing the problem were trying to pass an empty data object. It seems IE does not like this, but other browsers don't mind.

To fix it I simply removed data: {}, from the ajax call.

How do you use colspan and rowspan in HTML tables?

It is similar to your table

  <table border=1 width=50%>
<tr>
    <td rowspan="2">x</td> 
    <td colspan="4">y</td>
</tr>
<tr>
    <td bgcolor=#FFFF00 >I</td>
    <td>II</td>
    <td bgcolor=#FFFF00>III</td>
    <td>IV</td>
</tr>
<tr>
    <td>empty</td>
    <td bgcolor=#FFFF00>1</td>
    <td>2</td>
    <td bgcolor=#FFFF00>3</td>
    <td>4</td>
</tr>

Printing result of mysql query from variable

well you are returning an array of items from the database. so you need something like this.

   $dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, 
    SUM(total_order_amount) as test FROM `orders` 
    WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") 
    or  die(mysql_error());


while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}

Strip out HTML and Special Characters

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

Scroll back to the top of scrollable div

As per François Noël's answer "For those who still can't make this work, make sure that the overflowed element is displayed before using the jQuery function."

I had been working in a bootstrap modal that I repeatedly bring up with account permissions in a div that overflows on the y dimension. My problem was, I was trying to use the jquery .scrollTop(0) function and it would not work no matter how I tried to do it. I had to setup an event for the modal that didn't reset the scrollbar until the modal had stopped animating. The code that finally worked for me is here:

    $('#add-modal').on('shown.bs.modal', function (e) {
        $('div.border').scrollTop(0);
    });

What is tail call optimization?

Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.

Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:

(define (fact x)
  (if (= x 0) 1
      (* x (fact (- x 1)))))

(define (fact x)
  (define (fact-tail x accum)
    (if (= x 0) accum
        (fact-tail (- x 1) (* x accum))))
  (fact-tail x 1))

The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:

(fact 3)
(* 3 (fact 2))
(* 3 (* 2 (fact 1)))
(* 3 (* 2 (* 1 (fact 0))))
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))
(* 3 2)
6

In contrast, the stack trace for the tail recursive factorial looks as follows:

(fact 3)
(fact-tail 3 1)
(fact-tail 2 3)
(fact-tail 1 6)
(fact-tail 0 6)
6

As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.

How (and why) to use display: table-cell (CSS)

The display:table family of CSS properties is mostly there so that HTML tables can be defined in terms of them. Because they're so intimately linked to a specific tag structure, they don't see much use beyond that.

If you were going to use these properties in your page, you would need a tag structure that closely mimicked that of tables, even though you weren't actually using the <table> family of tags. A minimal version would be a single container element (display:table), with direct children that can all be represented as rows (display:table-row), which themselves have direct children that can all be represented as cells (display:table-cell). There are other properties that let you mimic other tags in the table family, but they require analogous structures in the HTML. Without this, it's going to be very hard (if not impossible) to make good use of these properties.

Mocking python function based on input arguments

Although side_effect can achieve the goal, it is not so convenient to setup side_effect function for each test case.

I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:

from nextmock import Mock

m = Mock()

m.with_args(1, 2, 3).returns(123)

assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123

It also supports argument matcher:

from nextmock import Arg, Mock

m = Mock()

m.with_args(1, 2, Arg.Any).returns(123)

assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123

Hope this package could make testing more pleasant. Feel free to give any feedback.

How to use makefiles in Visual Studio?

I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:

debug: coratools_debug
    devenv coralib.vcproj /build debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

You can also use the msbuild tool to do the same thing:

debug: coratools_debug
    msbuild coralib.vcxproj /p:Configuration=debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.

Extract a substring according to a pattern

Another method to extract a substring

library(stringr)
substring <- str_extract(string, regex("(?<=:).*"))
#[1] "E001" "E002" "E003
  • (?<=:): look behind the colon (:)

Change font size of UISegmentedControl

Another option is to apply a transform to the control. However, it will scale down everything including the control borders.

segmentedControl.transform = CGAffineTransformMakeScale(.6f, .6f);

Read response headers from API response - Angular 5 + TypeScript

As Hrishikesh Kale has explained we need to pass the Access-Control-Expose-Headers.

Here how we can do it in the WebAPI/MVC environment:

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

Another way is we can add code as below in the webApiconfig.cs file.

config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

**We can add custom headers in the web.config file as below. *

<httpProtocol>
   <customHeaders>
      <add name="Access-Control-Expose-Headers" value="TestHeaderToExpose" />
   </customHeaders>
</httpProtocol>

we can create an attribute and decore the method with the attribute.

Happy Coding !!

How do I pass environment variables to Docker containers?

If you have the environment variables in an env.sh locally and want to set it up when the container starts, you could try

COPY env.sh /env.sh
COPY <filename>.jar /<filename>.jar
ENTRYPOINT ["/bin/bash" , "-c", "source /env.sh && printenv && java -jar /<filename>.jar"]

This command would start the container with a bash shell (I want a bash shell since source is a bash command), sources the env.sh file(which sets the environment variables) and executes the jar file.

The env.sh looks like this,

#!/bin/bash
export FOO="BAR"
export DB_NAME="DATABASE_NAME"

I added the printenv command only to test that actual source command works. You should probably remove it when you confirm the source command works fine or the environment variables would appear in your docker logs.

Convert array values from string to int?

Use this code with a closure (introduced in PHP 5.3), it's a bit faster than the accepted answer and for me, the intention to cast it to an integer, is clearer:

// if you have your values in the format '1,2,3,4', use this before:
// $stringArray = explode(',', '1,2,3,4');

$stringArray = ['1', '2', '3', '4'];

$intArray = array_map(
    function($value) { return (int)$value; },
    $stringArray
);

var_dump($intArray);

Output will be:

array(4) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
  [3]=>
  int(4)
}

Reusing output from last command in Bash

One way of doing that is by using trap DEBUG:

f() { bash -c "$BASH_COMMAND" >& /tmp/out.log; }
trap 'f' DEBUG

Now most recently executed command's stdout and stderr will be available in /tmp/out.log

Only downside is that it will execute a command twice: once to redirect output and error to /tmp/out.log and once normally. Probably there is some way to prevent this behavior as well.

Max parallel http connections in a browser?

The 2 concurrent requests is an intentional part of the design of many browsers. There is a standard out there that "good http clients" adhere to on purpose. Check out this RFC to see why.

Set environment variables on Mac OS X Lion

Unfortunately none of these answers solved the specific problem I had.

Here's a simple solution without having to mess with bash. In my case, it was getting gradle to work (for Android Studio).

Btw, These steps relate to OSX (Mountain Lion 10.8.5)

  • Open up Terminal.
  • Run the following command:

    sudo nano /etc/paths (or sudo vim /etc/paths for vim)

    nano

  • Go to the bottom of the file, and enter the path you wish to add.
  • Hit control-x to quit.
  • Enter 'Y' to save the modified buffer.
  • Open a new terminal window then type:

    echo $PATH

You should see the new path appended to the end of the PATH

I got these details from this post:

http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q

I hope that can help someone else

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

TypeError: no implicit conversion of Symbol into Integer

Your item variable holds Array instance (in [hash_key, hash_value] format), so it doesn't expect Symbol in [] method.

This is how you could do it using Hash#each:

def format(hash)
  output = Hash.new
  hash.each do |key, value|
    output[key] = cleanup(value)
  end
  output
end

or, without this:

def format(hash)
  output = hash.dup
  output[:company_name] = cleanup(output[:company_name])
  output[:street] = cleanup(output[:street])
  output
end

how to output every line in a file python

Firstly, as @l33tnerd said, f.close should be outside the for loop.

Secondly, you are only calling readline once, before the loop. That only reads the first line. The trick is that in Python, files act as iterators, so you can iterate over the file without having to call any methods on it, and that will give you one line per iteration:

 if data.find('!masters') != -1:
     f = open('masters.txt')
     for line in f:
           print line,
           sck.send('PRIVMSG ' + chan + " " + line)
     f.close()

Finally, you were referring to the variable lines inside the loop; I assume you meant to refer to line.

Edit: Oh and you need to indent the contents of the if statement.

How do I change a PictureBox's image?

You can use the ImageLocation property of pictureBox1:

pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";

How can I remove an element from a list?

You can use which.

x<-c(1:5)
x
#[1] 1 2 3 4 5
x<-x[-which(x==4)]
x
#[1] 1 2 3 5

using href links inside <option> tag

The <select> tag creates a dropdown list. You can't put html links inside a dropdown.

However, there are JavaScript libraries that provide similar functionality. Here is one example: http://www.dynamicdrive.com/dynamicindex1/dropmenuindex.htm

What is the best way to auto-generate INSERT statements for a SQL Server table?

There are many good scripts above for generating insert statements, but I attempted one of my own to make it as user friendly as possible and to also be able to do UPDATE statements. + package the result ready for .sql files that can be stored by date.

It takes as input your normal SELECT statement with WHERE clause, then outputs a list of Insert statements and update statements. Together they form a sort of IF NOT EXISTS () INSERT ELSE UPDATE It is handy too when there are non-updatable columns that need exclusion from the final INSERT/UPDATE statement.

Another thing that below script can do is: it can even handle INNER JOINs with other tables as input statement for the stored proc. It can be handy as a poor man's Release management tool that sits right at your finger tips where you are typing the sql SELECT statements all day.

original post : Generate UPDATE statement in SQL Server for specific table

CREATE PROCEDURE [dbo].[sp_generate_updates] (
    @fullquery              nvarchar(max) = '',
    @ignore_field_input     nvarchar(MAX) = '',
    @PK_COLUMN_NAME         nvarchar(MAX) = ''
)
AS

SET NOCOUNT ON
SET QUOTED_IDENTIFIER ON
/*
-- For Standard USAGE: (where clause is mandatory)
                EXEC [sp_generate_updates] 'select * from dbo.mytable where mytext=''1''  ' 
        OR
                SET QUOTED_IDENTIFIER OFF 
                EXEC [sp_generate_updates] "select * from dbo.mytable where mytext='1'    "

-- For ignoring specific columns  (to ignore in the UPDATE and INSERT SQL statement) 
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  ' , 'Column01,Column02'

-- For just updates without insert statement (replace the * )
                EXEC [sp_generate_updates] 'select Column01, Column02 from dbo.mytable where 1=1  ' 

-- For tables without a primary key: construct the key in the third variable
                EXEC [sp_generate_updates] 'select * from dbo.mytable where 1=1  '  ,'','your_chosen_primary_key_Col1,key_Col2'

-- For complex updates with JOINED tables 
                EXEC [sp_generate_updates] 'select o1.Name,  o1.category, o2.name+ '_hello_world' as #name 
                                            from overnightsetting o1 
                                            inner join overnightsetting o2  on o1.name=o2.name  
                                            where o1.name like '%appserver%' 
                (REMARK about above:   the use of # in front of a column name (so #abc) can do an update of that columname (abc) with any column from an inner joined table where you use the alias #abc )


-------------README for the deeper interested person:
            Goal of the Stored PROCEDURE is to get updates from simple SQL SELECT statements. It is made ot be simple but fast and powerfull. As always => power is nothing without control, so check before you execute.
            Its power sits also in the fact that you can make insert statements, so combined gives you a  "IF NOT EXISTS()  INSERT "   capability. 

            The scripts work were there are primary keys or identity columns on table you want to update (/ or make inserts for).
            It will also works when no primary keys / identity column exist(s) and you define them yourselve. But then be carefull (duplicate hits can occur). When the table has a primary key it will always be used.
            The script works with a real  temporary table, made on the fly   (APPROPRIATE RIGHTS needed), to put the values inside from the script, then add 3 columns for constructing the "insert into tableX (...) values ()" ,  and the 2 update statement.
            We work with temporary structures like   "where columnname = {Columnname}" and then later do the update on that temptable for the columns values found on that same line.
                    example  "where columnname = {Columnname}"  for birthdate becomes   "where birthdate = {birthdate}" an then we find the birthdate value on that line inside the temp table.
            So then the statement becomes  "where birthdate = {19800417}"
            Enjoy releasing scripts as of now...                                        by  Pieter van Nederkassel  - freeware "CC BY-SA" (+use at own risk)
*/
IF OBJECT_ID('tempdb..#ignore','U') IS NOT NULL     DROP TABLE #ignore
DECLARE @stringsplit_table               TABLE (col nvarchar(255), dtype  nvarchar(255)) -- table to store the primary keys or identity key
DECLARE @PK_condition                    nvarchar(512), -- placeholder for WHERE pk_field1 = pk_value1 AND pk_field2 = pk_value2 AND ...
        @pkstring                        NVARCHAR(512),  -- sting to store the primary keys or the idendity key
        @table_name                      nvarchar(512), -- (left) table name, including schema
        @table_N_where_clause            nvarchar(max), -- tablename 
        @table_alias                     nvarchar(512), -- holds the (left) table alias if one available, else @table_name
        @table_schema                    NVARCHAR(30),  -- schema of @table_name
        @update_list1                    NVARCHAR(MAX), -- placeholder for SET fields section of update
        @update_list2                    NVARCHAR(MAX), -- placeholder for SET fields section of update value comming from other tables in the join, other than the main table to update => updateof base table possible with inner join
        @list_all_cols                   BIT = 0,       -- placeholder for values for the insert into table VALUES command
        @select_list                     NVARCHAR(MAX), -- placeholder for SELECT fields of (left) table
        @COLUMN_NAME                     NVARCHAR(255), -- will hold column names of the (left) table
        @sql                             NVARCHAR(MAX), -- sql statement variable
        @getdate                         NVARCHAR(17),  -- transform getdate() to YYYYMMDDHHMMSSMMM
        @tmp_table                       NVARCHAR(255), -- will hold the name of a physical temp table
        @pk_separator                    NVARCHAR(1),   -- separator used in @PK_COLUMN_NAME if provided (only checking obvious ones ,;|-)
        @COLUMN_NAME_DATA_TYPE           NVARCHAR(100), -- needed for insert statements to convert to right text string
        @own_pk                          BIT = 0        -- check if table has PK (0) or if provided PK will be used (1)




set @ignore_field_input=replace(replace(replace(@ignore_field_input,' ',''),'[',''),']','')
set @PK_COLUMN_NAME=    replace(replace(replace(@PK_COLUMN_NAME,    ' ',''),'[',''),']','')

-- first we remove all linefeeds from the user query
set @fullquery=replace(replace(replace(@fullquery,char(10),''),char(13),' '),'  ',' ')
set @table_N_where_clause=@fullquery
if charindex ('order by' , @table_N_where_clause) > 0
    print ' WARNING:        ORDER BY NOT ALLOWED IN UPDATE ...'
if @PK_COLUMN_NAME <> ''
    select ' WARNING:        IF you select your own primary keys, make double sure before doing the update statements below!! '
--print @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) = 0
    set @table_N_where_clause= 'select * from ' + @table_N_where_clause
if charindex ('select ' , @table_N_where_clause) > 0
    exec (@table_N_where_clause)

set @table_N_where_clause=rtrim(ltrim(substring(@table_N_where_clause,CHARINDEX(' from ', @table_N_where_clause )+6, 4000)))
--print @table_N_where_clause 
set @table_name=left(@table_N_where_clause,CHARINDEX(' ', @table_N_where_clause )-1)


IF CHARINDEX('where ', @table_N_where_clause) > 0             SELECT @table_alias = LTRIM(RTRIM(REPLACE(REPLACE(SUBSTRING(@table_N_where_clause,1, CHARINDEX('where ', @table_N_where_clause )-1),'(nolock)',''),@table_name,'')))
IF CHARINDEX('join ',  @table_alias) > 0                      SELECT @table_alias = SUBSTRING(@table_alias, 1, CHARINDEX(' ', @table_alias)-1) -- until next space
IF LEN(@table_alias) = 0                                      SELECT @table_alias = @table_name
IF (charindex (' *' , @fullquery) > 0 or charindex (@table_alias+'.*' , @fullquery) > 0 )     set @list_all_cols=1
/*       
       print @fullquery     
       print @table_alias
       print @table_N_where_clause
       print @table_name
*/


-- Prepare PK condition
        SELECT @table_schema = CASE WHEN CHARINDEX('.',@table_name) > 0 THEN LEFT(@table_name, CHARINDEX('.',@table_name)-1) ELSE 'dbo' END

        SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
        WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + QUOTENAME(CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND TABLE_SCHEMA = @table_schema

        SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

            -- if no primary keys exist then we try for identity columns
                IF @PK_condition is null SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME('pk_'+COLUMN_NAME) + ' = ' + QUOTENAME('pk_'+COLUMN_NAME,'{')
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema

                IF @pkstring is null SELECT @pkstring = ISNULL(@pkstring + ', ', '') + @table_alias + '.' + QUOTENAME(COLUMN_NAME) + ' AS pk_' + COLUMN_NAME
                FROM  INFORMATION_SCHEMA.COLUMNS
                WHERE COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 
                AND TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND TABLE_SCHEMA = @table_schema
-- Same but in form of a table

        INSERT INTO @stringsplit_table
        SELECT 'pk_'+i1.COLUMN_NAME as col, i2.DATA_TYPE as dtype
        FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE i1
        inner join INFORMATION_SCHEMA.COLUMNS i2
        on  i1.TABLE_NAME = i2.TABLE_NAME AND i1.TABLE_SCHEMA =  i2.TABLE_SCHEMA
        WHERE OBJECTPROPERTY(OBJECT_ID(i1.CONSTRAINT_SCHEMA + '.' + QUOTENAME(i1.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1
        AND i1.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
        AND i1.TABLE_SCHEMA = @table_schema

                -- if no primary keys exist then we try for identity columns
                IF 0=(select count(*) from @stringsplit_table) INSERT INTO @stringsplit_table
                SELECT 'pk_'+i2.COLUMN_NAME as col, i2.DATA_TYPE as dtype
                FROM INFORMATION_SCHEMA.COLUMNS i2
                WHERE COLUMNPROPERTY(object_id(i2.TABLE_SCHEMA+'.'+i2.TABLE_NAME), i2.COLUMN_NAME, 'IsIdentity') = 1 
                AND i2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
                AND i2.TABLE_SCHEMA = @table_schema

-- NOW handling the primary key given as parameter to the main batch

SELECT @pk_separator = ',' -- take this as default, we'll check lower if it's a different one
IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME <> ''
BEGIN
    IF CHARINDEX(';', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = ';'
    ELSE IF CHARINDEX('|', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '|'
    ELSE IF CHARINDEX('-', @PK_COLUMN_NAME) > 0
        SELECT @pk_separator = '-'

    SELECT @PK_condition = NULL -- make sure to make it NULL, in case it was ''
    INSERT INTO @stringsplit_table
    SELECT LTRIM(RTRIM(x.value)) , 'datetime'  FROM STRING_SPLIT(@PK_COLUMN_NAME, @pk_separator) x  
    SELECT @PK_condition = ISNULL(@PK_condition + ' AND ', '') + QUOTENAME(x.col) + ' = ' + replace(QUOTENAME(x.col,'{'),'{','{pk_')
      FROM @stringsplit_table x

    SELECT @PK_COLUMN_NAME = NULL -- make sure to make it NULL, in case it was ''
    SELECT @PK_COLUMN_NAME = ISNULL(@PK_COLUMN_NAME + ', ', '') + QUOTENAME(x.col) + ' as pk_' + x.col
      FROM @stringsplit_table x
    --print 'pkcolumns  '+ isnull(@PK_COLUMN_NAME,'')
    update @stringsplit_table set col='pk_' + col
    SELECT @own_pk = 1
END
ELSE IF (@PK_condition IS NULL OR @PK_condition = '') AND @PK_COLUMN_NAME = ''
BEGIN
    RAISERROR('No Primary key or Identity column available on table. Add some columns as the third parameter when calling this SP to make your own temporary PK., also remove  [] from tablename',17,1)
END


-- IF there are no primary keys or an identity key in the table active, then use the given columns as a primary key


if isnull(@pkstring,'')   = ''  set    @pkstring  = @PK_COLUMN_NAME
IF ISNULL(@pkstring, '') <> ''  SELECT @fullquery = REPLACE(@fullquery, 'SELECT ','SELECT ' + @pkstring + ',' )
--print @pkstring




-- ignore fields for UPDATE STATEMENT (not ignored for the insert statement,  in iserts statement we ignore only identity Columns and the columns provided with the main stored proc )
-- Place here all fields that you know can not be converted to nvarchar() values correctly, an thus should not be scripted for updates)
-- for insert we will take these fields along, although they will be incorrectly represented!!!!!!!!!!!!!.
SELECT           ignore_field = 'uniqueidXXXX' INTO #ignore 
UNION ALL SELECT ignore_field = 'UPDATEMASKXXXX'
UNION ALL SELECT ignore_field = 'UIDXXXXX'
UNION ALL SELECT value FROM  string_split(@ignore_field_input,@pk_separator)




SELECT @getdate = REPLACE(REPLACE(REPLACE(REPLACE(CONVERT(NVARCHAR(30), GETDATE(), 121), '-', ''), ' ', ''), ':', ''), '.', '')
SELECT @tmp_table = 'Release_DATA__' + @getdate + '__' + REPLACE(@table_name,@table_schema+'.','') 

SET @sql = replace( @fullquery,  ' from ',  ' INTO ' + @tmp_table +' from ')
----print (@sql)
exec (@sql)



SELECT @sql = N'alter table ' + @tmp_table + N'  add update_stmt1  nvarchar(max), update_stmt2 nvarchar(max) , update_stmt3 nvarchar(max)'
EXEC (@sql)

-- Prepare update field list (only columns from the temp table are taken if they also exist in the base table to update)
SELECT @update_list1 = ISNULL(@update_list1 + ', ', '') + 
                      CASE WHEN C1.COLUMN_NAME = 'ModifiedBy' THEN '[ModifiedBy] = left(right(replace(CONVERT(VARCHAR(19),[Modified],121),''''-'''',''''''''),19) +''''-''''+right(SUSER_NAME(),30),50)'
                           WHEN C1.COLUMN_NAME = 'Modified' THEN '[Modified] = GETDATE()'
                           ELSE QUOTENAME(C1.COLUMN_NAME) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
                      END
FROM INFORMATION_SCHEMA.COLUMNS c1
inner join INFORMATION_SCHEMA.COLUMNS c2
on c1.COLUMN_NAME =c2.COLUMN_NAME and c2.TABLE_NAME = REPLACE(@table_name,@table_schema+'.','')  AND c2.TABLE_SCHEMA = @table_schema
WHERE c1.TABLE_NAME = @tmp_table --REPLACE(@table_name,@table_schema+'.','') 
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND COLUMNPROPERTY(object_id(c2.TABLE_SCHEMA+'.'+c2.TABLE_NAME), c2.COLUMN_NAME, 'IsIdentity') <> 1
AND NOT EXISTS (SELECT 1 
                  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE ku 
                 WHERE 1 = 1
                   AND ku.TABLE_NAME = c2.TABLE_NAME
                   AND ku.TABLE_SCHEMA = c2.TABLE_SCHEMA
                   AND ku.COLUMN_NAME = c2.COLUMN_NAME
                   AND OBJECTPROPERTY(OBJECT_ID(ku.CONSTRAINT_SCHEMA + '.' + QUOTENAME(ku.CONSTRAINT_NAME)), 'IsPrimaryKey') = 1)
AND NOT EXISTS (SELECT 1 FROM @stringsplit_table x WHERE x.col = c2.COLUMN_NAME AND @own_pk = 1)

-- Prepare update field list  (here we only take columns that commence with a #, as this is our queue for doing the update that comes from an inner joined table)
SELECT @update_list2 = ISNULL(@update_list2 + ', ', '') +  QUOTENAME(replace( C1.COLUMN_NAME,'#','')) + ' = ' + QUOTENAME(C1.COLUMN_NAME,'{')
FROM INFORMATION_SCHEMA.COLUMNS c1
WHERE c1.TABLE_NAME = @tmp_table --AND c1.TABLE_SCHEMA = @table_schema
AND QUOTENAME(c1.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here
AND c1.COLUMN_NAME like '#%'

-- similar for select list, but take all fields
SELECT @select_list = ISNULL(@select_list + ', ', '') + QUOTENAME(COLUMN_NAME)
FROM INFORMATION_SCHEMA.COLUMNS c
WHERE TABLE_NAME = REPLACE(@table_name,@table_schema+'.','') 
AND TABLE_SCHEMA = @table_schema
AND COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') <> 1  -- Identity columns are filled automatically by MSSQL, not needed at Insert statement
AND QUOTENAME(c.COLUMN_NAME) NOT IN (SELECT QUOTENAME(ignore_field) FROM #ignore) -- eliminate binary, image etc value here


SELECT @PK_condition = REPLACE(@PK_condition, '[pk_', '[')
set @select_list='if not exists (select * from '+  REPLACE(@table_name,@table_schema+'.','') +'  where '+  @PK_condition +')  INSERT INTO '+ REPLACE(@table_name,@table_schema+'.','')   + '('+ @select_list  + ') VALUES (' + replace(replace(@select_list,'[','{'),']','}') + ')'
SELECT @sql = N'UPDATE ' + @tmp_table + ' set update_stmt1 = ''' + @select_list + '''' 
if @list_all_cols=1 EXEC (@sql)



--print 'select==========  ' + @select_list
--print 'update==========  ' + @update_list1


SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt2 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list1 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql



SELECT @sql = N'UPDATE ' + @tmp_table + N'
set update_stmt3 = CONVERT(NVARCHAR(MAX),''UPDATE ' + @table_name + 
                                          N' SET ' + @update_list2 + N''' + ''' +
                                          N' WHERE ' + @PK_condition + N''') ' 

EXEC (@sql)
--print @sql


-- LOOPING OVER ALL base tables column for the INSERT INTO .... VALUES
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME, DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME = (CASE WHEN @list_all_cols=0 THEN @tmp_table ELSE REPLACE(@table_name,@table_schema+'.','') END )
    AND TABLE_SCHEMA = @table_schema
        UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
    ELSE  
                  N'UPDATE ' + @tmp_table + N' SET update_stmt1 = REPLACE(update_stmt1, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) '
    END
    ----PRINT @sql
    EXEC (@sql)
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

--SELECT col FROM @stringsplit_table -- these are the primary keys

-- LOOPING OVER ALL temp tables column for the Update values
DECLARE c_columns CURSOR FAST_FORWARD READ_ONLY FOR
    SELECT COLUMN_NAME,DATA_TYPE
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_NAME =  @tmp_table --    AND TABLE_SCHEMA = @table_schema
       UNION--pned
    SELECT col, 'datetime' FROM @stringsplit_table

OPEN c_columns
FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @sql = 
    CASE WHEN @COLUMN_NAME_DATA_TYPE IN ('char','varchar','nchar','nvarchar')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')) ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('float','real','money','smallmoney')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],126)),   '''''''','''''''''''') + '''''''', ''NULL'')) '
        WHEN @COLUMN_NAME_DATA_TYPE IN ('uniqueidentifier')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('text','ntext')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('xxxx','yyyy')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('binary','varbinary')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('XML','xml')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],0)),     '''''''','''''''''''') + '''''''', ''NULL''))  ' 
        WHEN @COLUMN_NAME_DATA_TYPE IN ('datetime','smalldatetime')
            THEN  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'],121)),   '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    ELSE    
                  N'UPDATE ' + @tmp_table + N' SET update_stmt2 = REPLACE(update_stmt2, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL'')), update_stmt3 = REPLACE(update_stmt3, ''{' + @COLUMN_NAME + N'}'', ISNULL('''''''' + REPLACE(RTRIM(CONVERT(NVARCHAR(MAX),[' + @COLUMN_NAME + N'])),       '''''''','''''''''''') + '''''''', ''NULL''))  ' 
    END
    EXEC (@sql)
    ----print @sql
    FETCH NEXT FROM c_columns INTO @COLUMN_NAME, @COLUMN_NAME_DATA_TYPE
END
CLOSE c_columns
DEALLOCATE c_columns

SET @sql = 'Select * from  ' + @tmp_table + ';'
--exec (@sql)

SELECT @sql = N'
IF OBJECT_ID(''' + @tmp_table + N''', ''U'') IS NOT NULL
BEGIN
       SELECT   ''USE ' + DB_NAME()  + '''  as executelist 
              UNION ALL
       SELECT   ''GO ''  as executelist 
              UNION ALL
       SELECT   '' /*PRESCRIPT CHECK  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT update_stmt1 as executelist FROM ' + @tmp_table + N' where update_stmt1 is not null
              UNION ALL
       SELECT update_stmt2 as executelist FROM ' + @tmp_table + N' where update_stmt2 is not null
              UNION ALL
       SELECT isnull(update_stmt3, '' add more columns inn query please'')  as executelist FROM ' + @tmp_table + N' where update_stmt3 is not null
              UNION ALL
       SELECT ''--EXEC usp_AddInstalledScript 5, 5, 1, 1, 1, ''''' + @tmp_table + '.sql'''', 2 ''  as executelist
              UNION ALL 
       SELECT   '' /*VERIFY WITH:  */              ' + replace(@fullquery,'''','''''')+''' as executelist 
              UNION ALL
       SELECT ''-- SCRIPT LOCATION:      F:\CopyPaste\++Distributionpoint++\Release_Management\' + @tmp_table + '.sql''  as executelist   
END'
exec (@sql)

SET @sql = 'DROP TABLE ' + @tmp_table + ';'
exec (@sql)

Why does overflow:hidden not work in a <td>?

Here is the same problem.

You need to set table-layout:fixed and a suitable width on the table element, as well as overflow:hidden and white-space: nowrap on the table cells.


Examples

Fixed width columns

The width of the table has to be the same (or smaller) than the fixed width cell(s).

With one fixed width column:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 100px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

With multiple fixed width columns:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
  max-width: 200px;
}
td {
  background: #F00;
  padding: 20px;
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
  border: solid 1px #000;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Fixed and fluid width columns

A width for the table must be set, but any extra width is simply taken by the fluid cell(s).

With multiple columns, fixed width and fluid width:

_x000D_
_x000D_
* {
  box-sizing: border-box;
}
table {
  table-layout: fixed;
  border-collapse: collapse;
  width: 100%;
}
td {
  background: #F00;
  padding: 20px;
  border: solid 1px #000;
}
tr td:first-child {
  overflow: hidden;
  white-space: nowrap;
  width: 100px;
}
_x000D_
<table>
  <tbody>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
    <tr>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
      <td>
        This_is_a_terrible_example_of_thinking_outside_the_box.
      </td>
    </tr>
  </tbody>
</table>
_x000D_
_x000D_
_x000D_

Replacing instances of a character in a string

I wrote this method to replace characters or replace strings at a specific instance. instances start at 0 (this can easily be changed to 1 if you change the optional inst argument to 1, and test_instance variable to 1.

def replace_instance(some_word, str_to_replace, new_str='', inst=0):
    return_word = ''
    char_index, test_instance = 0, 0
    while char_index < len(some_word):
        test_str = some_word[char_index: char_index + len(str_to_replace)]
        if test_str == str_to_replace:
            if test_instance == inst:
                return_word = some_word[:char_index] + new_str + some_word[char_index + len(str_to_replace):]
                break
            else:
                test_instance += 1
        char_index += 1
    return return_word

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

ng is not recognized as an internal or external command

Add the ng command path from the folder .bin under the node_modules to PATH variable in the system env settings.

e.g: add C:\testProject\node_modules\.bin\ to PATH

Restart your IDE.

How do I load a PHP file into a variable?

If you want to load the file without running it through the webserver, the following should work.

$string = eval(file_get_contents("file.php"));

This will load then evaluate the file contents. The PHP file will need to be fully formed with <?php and ?> tags for eval to evaluate it.

How to initialize private static members in C++?

If you want to initialize some compound type (f.e. string) you can do something like that:

class SomeClass {
  static std::list<string> _list;

  public:
    static const std::list<string>& getList() {
      struct Initializer {
         Initializer() {
           // Here you may want to put mutex
           _list.push_back("FIRST");
           _list.push_back("SECOND");
           ....
         }
      }
      static Initializer ListInitializationGuard;
      return _list;
    }
};

As the ListInitializationGuard is a static variable inside SomeClass::getList() method it will be constructed only once, which means that constructor is called once. This will initialize _list variable to value you need. Any subsequent call to getList will simply return already initialized _list object.

Of course you have to access _list object always by calling getList() method.

Response::json() - Laravel 5.1

After enough googling I found the answer from controller you need only a backslash like return \Response::json(['success' => 'hi, atiq']); . Or you can just return the array return array('success' => 'hi, atiq'); which will be rendered as json in Laravel version 5.2 .

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

How to sort an array in descending order in Ruby

It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:

#!/usr/bin/ruby

require 'benchmark'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

n = 500
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse!")   { n.times { ary.sort_by{ |a| a[:bar] }.reverse } }
end

                          user     system      total        real
sort                  3.960000   0.010000   3.970000 (  3.990886)
sort reverse          4.040000   0.000000   4.040000 (  4.038849)
sort_by -a[:bar]      0.690000   0.000000   0.690000 (  0.692080)
sort_by a[:bar]*-1    0.700000   0.000000   0.700000 (  0.699735)
sort_by.reverse!      0.650000   0.000000   0.650000 (  0.654447)

I think it's interesting that @Pablo's sort_by{...}.reverse! is fastest. Before running the test I thought it would be slower than "-a[:bar]" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.


Please note that these results are different in Ruby 1.9

Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:

                           user     system      total        real
sort                   1.340000   0.010000   1.350000 (  1.346331)
sort reverse           1.300000   0.000000   1.300000 (  1.310446)
sort_by -a[:bar]       0.430000   0.000000   0.430000 (  0.429606)
sort_by a[:bar]*-1     0.420000   0.000000   0.420000 (  0.414383)
sort_by.reverse!       0.400000   0.000000   0.400000 (  0.401275)

These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.


Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:

#!/usr/bin/ruby

require 'benchmark'

puts "Running Ruby #{RUBY_VERSION}"

ary = []
1000.times {
  ary << {:bar => rand(1000)}
}

n = 500

puts "n=#{n}"
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse")    { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
  x.report("sort_by.reverse!")   { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end

# >> Running Ruby 2.1.1
# >> n=500
# >>                            user     system      total        real
# >> sort                   0.670000   0.000000   0.670000 (  0.667754)
# >> sort reverse           0.650000   0.000000   0.650000 (  0.655582)
# >> sort_by -a[:bar]       0.260000   0.010000   0.270000 (  0.255919)
# >> sort_by a[:bar]*-1     0.250000   0.000000   0.250000 (  0.258924)
# >> sort_by.reverse        0.250000   0.000000   0.250000 (  0.245179)
# >> sort_by.reverse!       0.240000   0.000000   0.240000 (  0.242340)

New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:

Running Ruby 2.2.1
n=500
                           user     system      total        real
sort                   0.650000   0.000000   0.650000 (  0.653191)
sort reverse           0.650000   0.000000   0.650000 (  0.648761)
sort_by -a[:bar]       0.240000   0.010000   0.250000 (  0.245193)
sort_by a[:bar]*-1     0.240000   0.000000   0.240000 (  0.240541)
sort_by.reverse        0.230000   0.000000   0.230000 (  0.228571)
sort_by.reverse!       0.230000   0.000000   0.230000 (  0.230040)

Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:

Running Ruby 2.7.1
n=500     
                           user     system      total        real
sort                   0.494707   0.003662   0.498369 (  0.501064)
sort reverse           0.480181   0.005186   0.485367 (  0.487972)
sort_by -a[:bar]       0.121521   0.003781   0.125302 (  0.126557)
sort_by a[:bar]*-1     0.115097   0.003931   0.119028 (  0.122991)
sort_by.reverse        0.110459   0.003414   0.113873 (  0.114443)
sort_by.reverse!       0.108997   0.001631   0.110628 (  0.111532)

...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.

The source for Array#reverse is:

               static VALUE
rb_ary_reverse_m(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    VALUE dup = rb_ary_new2(len);

    if (len > 0) {
        const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
        VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
        do *p2-- = *p1++; while (--len > 0);
    }
    ARY_SET_LEN(dup, RARRAY_LEN(ary));
    return dup;
}

do *p2-- = *p1++; while (--len > 0); is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.

how do I make a single legend for many subplots with matplotlib?

figlegend may be what you're looking for: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend

Example here: http://matplotlib.org/examples/pylab_examples/figlegend_demo.html

Another example:

plt.figlegend( lines, labels, loc = 'lower center', ncol=5, labelspacing=0. )

or:

fig.legend( lines, labels, loc = (0.5, 0), ncol=5 )

Multiple actions were found that match the request in Web Api

After a lot of searching the web and trying to find the most suitable form for routing map if have found the following

config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id =RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");

These mapping applying to both action name mapping and basic http convention (GET,POST,PUT,DELETE)

Convert regular Python string to raw string

i believe what you're looking for is the str.encode("string-escape") function. For example, if you have a variable that you want to 'raw string':

a = '\x89'
a.encode('unicode_escape')
'\\x89'

Note: Use string-escape for python 2.x and older versions

I was searching for a similar solution and found the solution via: casting raw strings python

Parse a URI String into Name-Value Collection

If you are using Spring, add an argument of type @RequestParam Map<String,String> to your controller method, and Spring will construct the map for you!

Adding gif image in an ImageView in android

In your build.gradle(Module:app), add android-gif-drawable as a dependency by adding the following code:

allprojects {
    repositories {
       mavenCentral()
    }
}

dependencies {
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
}


UPDATE: As of Android Gradle Plugin 3.0.0, the new command for compiling is implementation, so the above line might have to be changed to:

dependencies {
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
}

Then sync your project. When synchronization ends, go to your layout file and add the following code:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/gif_file"
/>

And that's it, you can manage it with a simple ImageView.

Vagrant ssh authentication failure

Unable to run vagrant up because it gets stuck and times out? I recently had a "water in laptop incident" and had to migrate to a new one(on a MAC by the way). I successfully got all my projects up and running beside the one, which was using vagrant.

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Clearing any previously set forwarded ports...
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
    default: Adapter 2: hostonly
==> default: Forwarding ports...
    default: 8000 (guest) => 8877 (host) (adapter 1)
    default: 8001 (guest) => 8878 (host) (adapter 1)
    default: 8080 (guest) => 7777 (host) (adapter 1)
    default: 5432 (guest) => 2345 (host) (adapter 1)
    default: 5000 (guest) => 8855 (host) (adapter 1)
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Running 'pre-boot' VM customizations...
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...
    default: Warning: Authentication failure. Retrying...

It couldn't authenticate, retried again and again and eventually gave up.


This is how I got it back in shape in 3 steps:

1 - Find the IdentityFile used by Vagrant:

$ vagrant ssh-config

Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/ned/.vagrant.d/insecure_private_key
  IdentitiesOnly yes
  LogLevel FATAL

2 - Check the public key in the IdentityFile:

$ ssh-keygen -y -f <path-to-insecure_private_key>

It'd output something like this:

ssh-rsa AAAAB3Nyc2EAAA...9gE98OHlnVYCzRdK8jlqm8hQ==

3 - Log in to the Vagrant guest with the password vagrant:

ssh -p 2222 -o UserKnownHostsFile=/dev/null [email protected]
The authenticity of host '[127.0.0.1]:2222 ([127.0.0.1]:2222)' can't be established.
RSA key fingerprint is dc:48:73:c3:18:e4:9d:34:a2:7d:4b:20:6a:e7:3d:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[127.0.0.1]:2222' (RSA) to the list of known hosts.
[email protected]'s password: vagrant
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-31-generic x86_64)
...

NOTE: if vagrant guest is configured to disallow password authentication you need to open VBox' GUI, double click guest name, login as vagrant/vagrant, then sudo -s and edit /etc/ssh/sshd_config and look for PasswordAuthentication no line (usually at the end of the file), replace no with yes and restart sshd (i.e. systemctl reload sshd or /etc/init.d/sshd restart).

4 - Add the public key to the /home/vagrant/authorized_keys file.

$ echo "ssh-rsa AA2EAAA...9gEdK8jlqm8hQ== vagrant" > /home/vagrant/.ssh/authorized_keys

5 - Exit (CTRL+d) and stop the Vagrant guest and then bring it back up.

IMPORTANT if you use any provisioning tools (i.e. Ansible etc) disable it before restarting your guest as Vagrant will think your guest is not provisioned because of use of insecure private key. It will reinstall the key and then run your provisioner!

$ vagrant halt
$ vagrant up

Hopefully you will have your arms in the air now...

I got this, with just a minor amend, from Ned Batchelders article - Ned you are a champ!

HTML <input type='file'> File Selection Event

The Change event gets called even if you click on cancel..

Can media queries resize based on a div element instead of the screen?

The only way I can think that you can accomplish what you want purely with css, is to use a fluid container for your widget. If your container's width is a percentage of the screen then you can use media queries to style depending on your container's width, as you will now know for each screen's dimensions what is your container's dimensions. For example, let's say you decide to make your container's 50% of the screen width. Then for a screen width of 1200px you know that your container is 600px

.myContainer {
  width: 50%;
}

/* you know know that your container is 600px 
 * so you style accordingly
*/
@media (max-width: 1200px) { 
  /* your css for 600px container */
}

HTML/CSS font color vs span style

<span style="color:#ffffff; font-size:18px; line-height:35px; font-family: Calibri;">Our Activities </span>

This works for me well:) As it has been already mentioned above "The font tag has been deprecated, at least in XHTML. It always safe to use span tag. font may not give you desire results, at least in my case it didn't.

Best approach to real time http streaming to HTML5 video client

One way to live-stream a RTSP-based webcam to a HTML5 client (involves re-encoding, so expect quality loss and needs some CPU-power):

  • Set up an icecast server (could be on the same machine you web server is on or on the machine that receives the RTSP-stream from the cam)
  • On the machine receiving the stream from the camera, don't use FFMPEG but gstreamer. It is able to receive and decode the RTSP-stream, re-encode it and stream it to the icecast server. Example pipeline (only video, no audio):

    gst-launch-1.0 rtspsrc location=rtsp://192.168.1.234:554 user-id=admin user-pw=123456 ! rtph264depay ! avdec_h264 ! vp8enc threads=2 deadline=10000 ! webmmux streamable=true ! shout2send password=pass ip=<IP_OF_ICECAST_SERVER> port=12000 mount=cam.webm
    

=> You can then use the <video> tag with the URL of the icecast-stream (http://127.0.0.1:12000/cam.webm) and it will work in every browser and device that supports webm

Django: multiple models in one template using forms

I just was in about the same situation a day ago, and here are my 2 cents:

1) I found arguably the shortest and most concise demonstration of multiple model entry in single form here: http://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ .

In a nutshell: Make a form for each model, submit them both to template in a single <form>, using prefix keyarg and have the view handle validation. If there is dependency, just make sure you save the "parent" model before dependant, and use parent's ID for foreign key before commiting save of "child" model. The link has the demo.

2) Maybe formsets can be beaten into doing this, but as far as I delved in, formsets are primarily for entering multiples of the same model, which may be optionally tied to another model/models by foreign keys. However, there seem to be no default option for entering more than one model's data and that's not what formset seems to be meant for.

change type of input field with jQuery

A more cross-browser solution… I hope the gist of this helps someone out there.

This solution tries to set the type attribute, and if it fails, it simply creates a new <input> element, preserving element attributes and event handlers.

changeTypeAttr.js (GitHub Gist):

/* x is the <input/> element
   type is the type you want to change it to.
   jQuery is required and assumed to be the "$" variable */
function changeType(x, type) {
    x = $(x);
    if(x.prop('type') == type)
        return x; //That was easy.
    try {
        return x.prop('type', type); //Stupid IE security will not allow this
    } catch(e) {
        //Try re-creating the element (yep... this sucks)
        //jQuery has no html() method for the element, so we have to put into a div first
        var html = $("<div>").append(x.clone()).html();
        var regex = /type=(\")?([^\"\s]+)(\")?/; //matches type=text or type="text"
        //If no match, we add the type attribute to the end; otherwise, we replace
        var tmp = $(html.match(regex) == null ?
            html.replace(">", ' type="' + type + '">') :
            html.replace(regex, 'type="' + type + '"') );
        //Copy data from old element
        tmp.data('type', x.data('type') );
        var events = x.data('events');
        var cb = function(events) {
            return function() {
                //Bind all prior events
                for(i in events)
                {
                    var y = events[i];
                    for(j in y)
                        tmp.bind(i, y[j].handler);
                }
            }
        }(events);
        x.replaceWith(tmp);
        setTimeout(cb, 10); //Wait a bit to call function
        return tmp;
    }
}

What does void do in java?

Void doesn't return anything; it tells the compiler the method doesn't have a return value.

Creating a random string with A-Z and 0-9 in Java

RandomStringUtils from Apache commons-lang might help:

RandomStringUtils.randomAlphanumeric(17).toUpperCase()

2017 update: RandomStringUtils has been deprecated, you should now use RandomStringGenerator.

Bundler: Command not found

Step 1:Make sure you are on path actual workspace.For example, workspace/blog $: Step2:Enter the command: gem install bundler. Step 3: You should be all set to bundle install or bundle update by now

How to get Maven project version to the bash command line

Base on the question, I use this script below to automatic increase my version number in all maven parent/submodules:

#!/usr/bin/env bash  

# Advances the last number of the given version string by one.  
function advance\_version () {  
    local v=$1  
    \# Get the last number. First remove any suffixes (such as '-SNAPSHOT').  
  local cleaned=\`echo $v | sed \-e 's/\[^0-9\]\[^0-9\]\*$//'\`  
 local last\_num=\`echo $cleaned | sed \-e 's/\[0-9\]\*\\.//g'\`  
 local next\_num=$(($last\_num+1))  
  \# Finally replace the last number in version string with the new one.  
  echo $v | sed \-e "s/\[0-9\]\[0-9\]\*\\(\[^0-9\]\*\\)$/$next\_num/"  
}  

version=$(mvn org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate -Dexpression=project.version -q -DforceStdout)  

new\_version=$(advance\_version $version)  

mvn versions:set -DnewVersion=${new\_version} -DprocessAllModules -DgenerateBackupPoms=false

iconv - Detected an illegal character in input string

BE VERY CAREFUL, the problem may come from multibytes encoding and inappropriate PHP functions used...

It was the case for me and it took me a while to figure it out.

For example, I get the a string from MySQL using utf8mb4 (very common now to encode emojis):

$formattedString = strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WILL RETURN THE ERROR 'Detected an illegal character in input string'

The problem does not stand in iconv() but stands in strtolower() in this case.

The appropriate way is to use Multibyte String Functions mb_strtolower() instead of strtolower()

$formattedString = mb_strtolower($stringFromMysql);
$strCleaned = iconv('UTF-8', 'utf-8//TRANSLIT', $formattedString); // WORK FINE

MORE INFO

More examples of this issue are available at this SO answer

PHP Manual on the Multibyte String

How to get the current URL within a Django template?

The other answers were incorrect, at least in my case. request.path does not provide the full url, only the relative url, e.g. /paper/53. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path.

AngularJS : How to watch service variables?

Have a look at this plunker:: this is the simplest example i could think of

http://jsfiddle.net/HEdJF/

<div ng-app="myApp">
    <div ng-controller="FirstCtrl">
        <input type="text" ng-model="Data.FirstName"><!-- Input entered here -->
        <br>Input is : <strong>{{Data.FirstName}}</strong><!-- Successfully updates here -->
    </div>
    <hr>
    <div ng-controller="SecondCtrl">
        Input should also be here: {{Data.FirstName}}<!-- How do I automatically updated it here? -->
    </div>
</div>



// declare the app with no dependencies
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
   return { FirstName: '' };
});

myApp.controller('FirstCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

myApp.controller('SecondCtrl', function( $scope, Data ){
    $scope.Data = Data;
});

postgresql - add boolean column to table set default

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN DEFAULT FALSE;

you can also directly specify NOT NULL

ALTER TABLE users
  ADD COLUMN "priv_user" BOOLEAN NOT NULL DEFAULT FALSE;

UPDATE: following is only true for versions before postgresql 11.

As Craig mentioned on filled tables it is more efficient to split it into steps:

ALTER TABLE users ADD COLUMN priv_user BOOLEAN;
UPDATE users SET priv_user = 'f';
ALTER TABLE users ALTER COLUMN priv_user SET NOT NULL;
ALTER TABLE users ALTER COLUMN priv_user SET DEFAULT FALSE;

What is the Simplest Way to Reverse an ArrayList?

Solution without using extra ArrayList or combination of add() and remove() methods. Both can have negative impact if you have to reverse a huge list.

 public ArrayList<Object> reverse(ArrayList<Object> list) {

   for (int i = 0; i < list.size() / 2; i++) {
     Object temp = list.get(i);
     list.set(i, list.get(list.size() - i - 1));
     list.set(list.size() - i - 1, temp);
   }

   return list;
 }

How to write a PHP ternary operator

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer";
        case 2: return 'Druid';
        case 3: return 'Paladin';
        case 4: return 'Knight';
        case 5: return 'Master Sorcerer';
        case 6: return 'Elder Druid';
        case 7: return 'Royal Paladin';
        default: return 'Elite Knight';
    }
}

echo getVocationName($result->vocation);

Why use $_SERVER['PHP_SELF'] instead of ""

The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".

There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all (unless there is a submit event handler attached that handles the submission).

Is it possible to ping a server from Javascript?

just replace

file_get_contents

with

$ip = $_SERVER['xxx.xxx.xxx.xxx'];
exec("ping -n 4 $ip 2>&1", $output, $retval);
if ($retval != 0) { 
  echo "no!"; 
} 
else{ 
  echo "yes!"; 
}

Func delegate with no return type

All of the Func delegates take at least one parameter

That's not true. They all take at least one type argument, but that argument determines the return type.

So Func<T> accepts no parameters and returns a value. Use Action or Action<T> when you don't want to return a value.

PHP: Split string

$string_val = 'a.b';

$parts = explode('.', $string_val);

print_r($parts);

Docs: http://us.php.net/manual/en/function.explode.php

How do you run a single test/spec file in RSpec?

You can also use the actual text of the *e*xample test case with -e !

So for:

it "shows the plane arrival time"

you can use

rspec path/to/spec/file.rb -e 'shows the plane arrival time'
./scripts/spec path/to/spec/file.rb -e 'shows the plane arrival time'

no need for rake here.

How do I get an object's unqualified (short) class name?

You can do this with reflection. Specifically, you can use the ReflectionClass::getShortName method, which gets the name of the class without its namespace.

First, you need to build a ReflectionClass instance, and then call the getShortName method of that instance:

$reflect = new ReflectionClass($object);
if ($reflect->getShortName() === 'Name') {
    // do this
}

However, I can't imagine many circumstances where this would be desirable. If you want to require that the object is a member of a certain class, the way to test it is with instanceof. If you want a more flexible way to signal certain constraints, the way to do that is to write an interface and require that the code implement that interface. Again, the correct way to do this is with instanceof. (You can do it with ReflectionClass, but it would have much worse performance.)

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

How to convert HTML to PDF using iTextSharp

First, HTML and PDF are not related although they were created around the same time. HTML is intended to convey higher level information such as paragraphs and tables. Although there are methods to control it, it is ultimately up to the browser to draw these higher level concepts. PDF is intended to convey documents and the documents must "look" the same wherever they are rendered.

In an HTML document you might have a paragraph that's 100% wide and depending on the width of your monitor it might take 2 lines or 10 lines and when you print it it might be 7 lines and when you look at it on your phone it might take 20 lines. A PDF file, however, must be independent of the rendering device, so regardless of your screen size it must always render exactly the same.

Because of the musts above, PDF doesn't support abstract things like "tables" or "paragraphs". There are three basic things that PDF supports: text, lines/shapes and images. (There are other things like annotations and movies but I'm trying to keep it simple here.) In a PDF you don't say "here's a paragraph, browser do your thing!". Instead you say, "draw this text at this exact X,Y location using this exact font and don't worry, I've previously calculated the width of the text so I know it will all fit on this line". You also don't say "here's a table" but instead you say "draw this text at this exact location and then draw a rectangle at this other exact location that I've previously calculated so I know it will appear to be around the text".

Second, iText and iTextSharp parse HTML and CSS. That's it. ASP.Net, MVC, Razor, Struts, Spring, etc, are all HTML frameworks but iText/iTextSharp is 100% unaware of them. Same with DataGridViews, Repeaters, Templates, Views, etc. which are all framework-specific abstractions. It is your responsibility to get the HTML from your choice of framework, iText won't help you. If you get an exception saying The document has no pages or you think that "iText isn't parsing my HTML" it is almost definite that you don't actually have HTML, you only think you do.

Third, the built-in class that's been around for years is the HTMLWorker however this has been replaced with XMLWorker (Java / .Net). Zero work is being done on HTMLWorker which doesn't support CSS files and has only limited support for the most basic CSS properties and actually breaks on certain tags. If you do not see the HTML attribute or CSS property and value in this file then it probably isn't supported by HTMLWorker. XMLWorker can be more complicated sometimes but those complications also make it more extensible.

Below is C# code that shows how to parse HTML tags into iText abstractions that get automatically added to the document that you are working on. C# and Java are very similar so it should be relatively easy to convert this. Example #1 uses the built-in HTMLWorker to parse the HTML string. Since only inline styles are supported the class="headline" gets ignored but everything else should actually work. Example #2 is the same as the first except it uses XMLWorker instead. Example #3 also parses the simple CSS example.

//Create a byte array that will eventually hold our final PDF
Byte[] bytes;

//Boilerplate iTextSharp setup here
//Create a stream that we can write to, in this case a MemoryStream
using (var ms = new MemoryStream()) {

    //Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
    using (var doc = new Document()) {

        //Create a writer that's bound to our PDF abstraction and our stream
        using (var writer = PdfWriter.GetInstance(doc, ms)) {

            //Open the document for writing
            doc.Open();

            //Our sample HTML and CSS
            var example_html = @"<p>This <em>is </em><span class=""headline"" style=""text-decoration: underline;"">some</span> <strong>sample <em> text</em></strong><span style=""color: red;"">!!!</span></p>";
            var example_css = @".headline{font-size:200%}";

            /**************************************************
             * Example #1                                     *
             *                                                *
             * Use the built-in HTMLWorker to parse the HTML. *
             * Only inline CSS is supported.                  *
             * ************************************************/

            //Create a new HTMLWorker bound to our document
            using (var htmlWorker = new iTextSharp.text.html.simpleparser.HTMLWorker(doc)) {

                //HTMLWorker doesn't read a string directly but instead needs a TextReader (which StringReader subclasses)
                using (var sr = new StringReader(example_html)) {

                    //Parse the HTML
                    htmlWorker.Parse(sr);
                }
            }

            /**************************************************
             * Example #2                                     *
             *                                                *
             * Use the XMLWorker to parse the HTML.           *
             * Only inline CSS and absolutely linked          *
             * CSS is supported                               *
             * ************************************************/

            //XMLWorker also reads from a TextReader and not directly from a string
            using (var srHtml = new StringReader(example_html)) {

                //Parse the HTML
                iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
            }

            /**************************************************
             * Example #3                                     *
             *                                                *
             * Use the XMLWorker to parse HTML and CSS        *
             * ************************************************/

            //In order to read CSS as a string we need to switch to a different constructor
            //that takes Streams instead of TextReaders.
            //Below we convert the strings into UTF8 byte array and wrap those in MemoryStreams
            using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
                using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {

                    //Parse the HTML
                    iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
                }
            }


            doc.Close();
        }
    }

    //After all of the PDF "stuff" above is done and closed but **before** we
    //close the MemoryStream, grab all of the active bytes from the stream
    bytes = ms.ToArray();
}

//Now we just need to do something with those bytes.
//Here I'm writing them to disk but if you were in ASP.Net you might Response.BinaryWrite() them.
//You could also write the bytes to a database in a varbinary() column (but please don't) or you
//could pass them to another function for further PDF processing.
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);

2017's update

There are good news for HTML-to-PDF demands. As this answer showed, the W3C standard css-break-3 will solve the problem... It is a Candidate Recommendation with plan to turn into definitive Recommendation this year, after tests.

As not-so-standard there are solutions, with plugins for C#, as showed by print-css.rocks.

How to create a localhost server to run an AngularJS project

If you have used Visual Studio Community or any other edition for your angular project , then go to the project folder , first type

C:\Project Folder>npm install -g http-server You will see as follows: + [email protected] added 25 packages in 4.213s

Then type C:\Project Folder>http-server –o

You will see that your application automatically comes up at http://127.0.0.1:8080/

Defining Z order of views of RelativeLayout in Android

I encountered the same issues: In a relative layout parentView, I have 2 children childView1 and childView2. At first, I put childView1 above childView2 and I want childView1 to be on top of childView2. Changing the order of children views did not solve the problem for me. What worked for me is to set android:clipChildren="false" on parentView and in the code I set:

childView1.bringToFront();

parentView.invalidate();

std::vector versus std::array in C++

Using the std::vector<T> class:

  • ...is just as fast as using built-in arrays, assuming you are doing only the things built-in arrays allow you to do (read and write to existing elements).

  • ...automatically resizes when new elements are inserted.

  • ...allows you to insert new elements at the beginning or in the middle of the vector, automatically "shifting" the rest of the elements "up"( does that make sense?). It allows you to remove elements anywhere in the std::vector, too, automatically shifting the rest of the elements down.

  • ...allows you to perform a range-checked read with the at() method (you can always use the indexers [] if you don't want this check to be performed).

There are two three main caveats to using std::vector<T>:

  1. You don't have reliable access to the underlying pointer, which may be an issue if you are dealing with third-party functions that demand the address of an array.

  2. The std::vector<bool> class is silly. It's implemented as a condensed bitfield, not as an array. Avoid it if you want an array of bools!

  3. During usage, std::vector<T>s are going to be a bit larger than a C++ array with the same number of elements. This is because they need to keep track of a small amount of other information, such as their current size, and because whenever std::vector<T>s resize, they reserve more space then they need. This is to prevent them from having to resize every time a new element is inserted. This behavior can be changed by providing a custom allocator, but I never felt the need to do that!


Edit: After reading Zud's reply to the question, I felt I should add this:

The std::array<T> class is not the same as a C++ array. std::array<T> is a very thin wrapper around C++ arrays, with the primary purpose of hiding the pointer from the user of the class (in C++, arrays are implicitly cast as pointers, often to dismaying effect). The std::array<T> class also stores its size (length), which can be very useful.

Android ImageView Fixing Image Size

I had the same issue and this helped me.

<ImageView
    android:id="@+id/image"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:scaleType="fitXY"
    />

Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

Catch KeyError in Python

I am using Python 3.6 and using a comma between Exception and e does not work. I need to use the following syntax (just for anyone wondering)

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print(e.message)

Efficiently finding the last line in a text file

If you do know the maximal length of a line, you can do

def getLastLine(fname, maxLineLength=80):
    fp=file(fname, "rb")
    fp.seek(-maxLineLength-1, 2) # 2 means "from the end of the file"
    return fp.readlines()[-1]

This works on my windows machine. But I do not know what happens on other platforms if you open a text file in binary mode. The binary mode is needed if you want to use seek().

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

tl;dr

LocalDateTime.parse( 
    "2012-07-10 14:58:00.000000".replace( " " , "T" )  
)

Microseconds do not fit

You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.

Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).

Unzoned input does not fit a zoned type

You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.

Use an appropriate data type instead. Specifically, java.time.LocalDateTime.

Case-sensitive

Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM and mm have different effects.

Avoid legacy classes

The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.

ISO 8601

Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T to comply fully.

The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

Date-time objects have no "format"

and I need the resultant date object to be of the same format.

No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.

java.time

Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime objects which lacks those concepts.

String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

Generating strings

To generate a String representing the value of your LocalDateTime:

  • Call toString to get a String in standard ISO 8601 format.
  • Use DateTimeFormatter for producing strings in either custom formats or automatically-localized formats.

Search Stack Overflow for more info as these topics have been covered many many times already.

ZonedDateTime

A LocalDateTime does not represent an exact point on the timeline.

To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.

ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to programmatically click a button in WPF?

WPF takes a slightly different approach than WinForms here. Instead of having the automation of a object built into the API, they have a separate class for each object that is responsible for automating it. In this case you need the ButtonAutomationPeer to accomplish this task.

ButtonAutomationPeer peer = new ButtonAutomationPeer(someButton);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();

Here is a blog post on the subject.

Note: IInvokeProvider interface is defined in the UIAutomationProvider assembly.

Random row selection in Pandas dataframe

Actually this will give you repeated indices np.random.random_integers(0, len(df), N) where N is a large number.

How do I clear this setInterval inside a function?

Simplest way I could think of: add a class.

Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
_x000D_
_x000D_

Return the characters after Nth character in a string

Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4

=REPLACE(A1,1,4,"")

How to access the SMS storage on Android?

You are going to need to call the SmsManager class. You are probably going to need to use the STATUS_ON_ICC_READ constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through. BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.

Here is the link that goes into depth on the Sms Manager

Counting Number of Letters in a string variable

What is wrong with using string.Length?

// len will be 5
int len = "Hello".Length;

List all of the possible goals in Maven 2?

Strange nobody listed an actual command to do it:

mvn help:describe -e -Dplugin=site

If you want to list all goals of the site plugin. Output:

Name: Apache Maven Site Plugin Description: The Maven Site Plugin is a plugin that generates a site for the current project. Group Id: org.apache.maven.plugins Artifact Id: maven-site-plugin Version: 3.7.1 Goal Prefix: site

This plugin has 9 goals:

site:attach-descriptor Description: Adds the site descriptor (site.xml) to the list of files to be installed/deployed. For Maven-2.x this is enabled by default only when the project has pom packaging since it will be used by modules inheriting, but this can be enabled for other projects packaging if needed. This default execution has been removed from the built-in lifecycle of Maven 3.x for pom-projects. Users that actually use those projects to provide a common site descriptor for sub modules will need to explicitly define this goal execution to restore the intended behavior.

site:deploy Description: Deploys the generated site using wagon supported protocols to the site URL specified in the section of the POM. For scp protocol, the website files are packaged by wagon into zip archive, then the archive is transfered to the remote host, next it is un-archived which is much faster than making a file by file copy.

site:effective-site Description: Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of site.xml, for the first locale.

site:help Description: Display help information on maven-site-plugin. Call mvn site:help -Ddetail=true -Dgoal= to display parameter details.

site:jar Description: Bundles the site output into a JAR so that it can be deployed to a repository.

site:run Description: Starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.

site:site Description: Generates the site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn't match deployed site.

site:stage Description: Deploys the generated site to a local staging or mock directory based on the site URL specified in the section of the POM. It can be used to test that links between module sites in a multi-module build work.

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

site:stage-deploy Description: Deploys the generated site to a staging or mock URL to the site URL specified in the section of the POM, using wagon supported protocols

For more information, run 'mvn help:describe [...] -Ddetail'

More details on https://mkyong.com/maven/how-to-display-maven-plugin-goals-and-parameters/

Dynamic creation of table with DOM

In My example call add function from button click event and then get value from form control's and call function generateTable.
In generateTable Function check first Table is Generaed or not. If table is undefined then call generateHeader Funtion and Generate Header and then call addToRow function for adding new row in table.

<input type="button" class="custom-rounded-bttn bttn-save" value="Add" id="btnAdd" onclick="add()">


<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
        <div class="dataGridForItem">
        </div>
    </div>
</div>

//Call Function From Button click Event

var counts = 1;
function add(){ 
    var Weightage = $('#Weightage').val();
    var ItemName = $('#ItemName option:selected').text();  
    var ItemNamenum = $('#ItemName').val();
    generateTable(Weightage,ItemName,ItemNamenum);
     $('#Weightage').val('');
     $('#ItemName').val(-1);
     return true;
 } 


function generateTable(Weightage,ItemName,ItemNamenum){
    var tableHtml = '';
    if($("#rDataTable").html() == undefined){
        tableHtml = generateHeader();
    }else{
        tableHtml = $("#rDataTable");
    } 
    var temp = $("<div/>");
    var row = addToRow(Weightage,ItemName,ItemNamenum);
    $(temp).append($(row));
    $("#dataGridForItem").html($(tableHtml).append($(temp).html()));
}


//Generate Header


function generateHeader(){
        var html = "<table id='rDataTable' class='table table-striped'>";
        html+="<tr class=''>";
        html+="<td class='tb-heading ui-state-default'>"+'Sr.No'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Item Name'+"</td>";
        html+="<td class='tb-heading ui-state-default'>"+'Weightage'+"</td>";
        html+="</tr></table>";
        return html; 
}

//Add New Row


function addToRow(Weightage,ItemName,ItemNamenum){
    var html="<tr class='trObj'>";
    html+="<td>"+counts+"</td>";
    html+="<td>"+ItemName+"</td>";
    html+="<td>"+Weightage+"</td>";
    html+="</tr>";
    counts++;
    return html;
}

Calculate logarithm in python

If you use log without base it uses e.

From the comment

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

Therefor you have to use:

import math
print( math.log(1.5, 10))

Remove characters except digits from string using Python?

You can use filter:

filter(lambda x: x.isdigit(), "dasdasd2313dsa")

On python3.0 you have to join this (kinda ugly :( )

''.join(filter(lambda x: x.isdigit(), "dasdasd2313dsa"))

What is the difference between UTF-8 and ISO-8859-1?

ISO-8859-1 is a legacy standards from back in 1980s. It can only represent 256 characters so only suitable for some languages in western world. Even for many supported languages, some characters are missing. If you create a text file in this encoding and try copy/paste some Chinese characters, you will see weird results. So in other words, don't use it. Unicode has taken over the world and UTF-8 is pretty much the standards these days unless you have some legacy reasons (like HTTP headers which needs to compatible with everything).

How can I confirm a database is Oracle & what version it is using SQL?

There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check Oracle Version.

SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;
SQL> SELECT * FROM v$version;

Node Sass couldn't find a binding for your current environment

On linux ubuntu 20.04 I needed few steps,downgrade node first to apropriate version,remove node_modules,run yarn install and finally run sudo yarn add [email protected] --force.Node version 10.0.0. Only working way for me.

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

What is the difference between 'git pull' and 'git fetch'?

Git Fetch

Helps you to get known about the latest updates from a git repository. Let's say you working in a team using GitFlow, where team working on multiple branches ( features ). With git fetch --all command you can get known about all new branches within repository.

Mostly git fetch is used with git reset. For example you want to revert all your local changes to the current repository state.

git fetch --all // get known about latest updates
git reset --hard origin/[branch] // revert to current branch state

Git pull

This command update your branch with current repository branch state. Let's continue with GitFlow. Multiple feature branches was merged to develop branch and when you want to develop new features for the project you must go to the develop branch and do a git pull to get the current state of develop branch

Documentation for GitFlow https://gist.github.com/peterdeweese/4251497

Using sed, Insert a line above or below the pattern?

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

Can I do a max(count(*)) in SQL?

Using max with a limit will only give you the first row, but if there are two or more rows with the same number of maximum movies, then you are going to miss some data. Below is a way to do it if you have the rank() function available.

SELECT
    total_final.yr,
    total_final.num_movies
    FROM
    ( SELECT 
        total.yr, 
        total.num_movies, 
        RANK() OVER (ORDER BY num_movies desc) rnk
        FROM (
               SELECT 
                      m.yr, 
                      COUNT(*) AS num_movies
               FROM MOVIE m
               JOIN CASTING c ON c.movieid = m.id
               JOIN ACTOR a ON a.id = c.actorid
               WHERE a.name = 'John Travolta'
               GROUP BY m.yr
             ) AS total
    ) AS total_final 
   WHERE rnk = 1

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Use Capital letter for defining functional component name/ React hooks custom components. "const 'app' should be const 'App'.

App.js

import React, { useState } from 'react';
import { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Person from './Person/Person';

const App = props => {
  const [personState, setPersonState] = useState({
    persons : [
          {name: 'a', age: '1'},
          {name: 'b', age: '2'},
          {name: 'c', age: '3'}
    ]
  });

    return (
      <div>
     <Person name = {personState.persons[0].name} age={personState.persons[0].age}> First </Person>
     <Person name = {personState.persons[1].name} age={personState.persons[1].age}> Second </Person>
     <Person name = {personState.persons[2].name} age={personState.persons[2].age}> Third </Person>    
    );
};
export default App;

Person.js

import React from 'react';

const person = (props) => {
return (
        <div>
<p> My name is {props.name} and my age is {props.age}</p>
<p> My name is {props.name} and my age is {props.age} and {props.children}</p>
<p>{props.children}</p>
        </div>
)
};

[ReactHooks] [useState] [ReactJs]

How to compare two tables column by column in oracle

Using the minus operator was working but also it was taking more time to execute which was not acceptable. I have a similar kind of requirement for data migration and I used the NOT IN operator for that. The modified query is :

select * 
from A 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from B) 
   union all 
select * from B 
where (emp_id,emp_name) not in 
   (select emp_id,emp_name from A); 

This query executed fast. Also you can add any number of columns in the select query. Only catch is that both tables should have the exact same table structure for this to be executed.

Make an image follow mouse pointer

Ok, here's a simple box that follows the cursor

Doing the rest is a simple case of remembering the last cursor position and applying a formula to get the box to move other than exactly where the cursor is. A timeout would also be handy if the box has a limited acceleration and must catch up to the cursor after it stops moving. Replacing the box with an image is simple CSS (which can replace most of the setup code for the box). I think the actual thinking code in the example is about 8 lines.

Select the right image (use a sprite) to orientate the rocket.

Yeah, annoying as hell. :-)

_x000D_
_x000D_
function getMouseCoords(e) {
  var e = e || window.event;
  document.getElementById('container').innerHTML = e.clientX + ', ' +
    e.clientY + '<br>' + e.screenX + ', ' + e.screenY;
}


var followCursor = (function() {
  var s = document.createElement('div');
  s.style.position = 'absolute';
  s.style.margin = '0';
  s.style.padding = '5px';
  s.style.border = '1px solid red';
  s.textContent = ""

  return {
    init: function() {
      document.body.appendChild(s);
    },

    run: function(e) {
      var e = e || window.event;
      s.style.left = (e.clientX - 5) + 'px';
      s.style.top = (e.clientY - 5) + 'px';
      getMouseCoords(e);
    }
  };
}());

window.onload = function() {
  followCursor.init();
  document.body.onmousemove = followCursor.run;
}
_x000D_
#container {
  width: 1000px;
  height: 1000px;
  border: 1px solid blue;
}
_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

How to use wget in php?

lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission

Visit this file_get_contents vs cUrl

Basically file_get_contents for for you

$data = file_get_contents($file_url);

Iterate through pairs of items in a Python list

To do that you should do:

a =  [5, 7, 11, 4, 5]
for i in range(len(a)-1):
    print [a[i], a[i+1]]

Rename a dictionary key

Using a check for newkey!=oldkey, this way you can do:

if newkey!=oldkey:  
    dictionary[newkey] = dictionary[oldkey]
    del dictionary[oldkey]

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

Sending a get request with axios from a webpage, I needed (finally) to enable also Geocoding API.

I also have Places API, Maps Javascript API, and Geolocation API.

Thanks to these guys

MySQL CONCAT returns NULL if any field contain NULL

To have the same flexibility in CONCAT_WS as in CONCAT (if you don't want the same separator between every member for instance) use the following:

SELECT CONCAT_WS("",affiliate_name,':',model,'-',ip,... etc)

Select records from today, this week, this month php mysql

Nathan's answer will give you jokes from last 24, 168, and 744 hours, NOT the jokes from today, this week, this month. If that's what you want, great, but I think you might be looking for something different.

Using his code, at noon, you will get the jokes beginning yesterday at noon, and ending today at noon. If you really want today's jokes, try the following:

SELECT * FROM jokes WHERE date >= CURRENT_DATE() ORDER BY score DESC;  

You would have to do something a little different from current week, month, etc., but you get the idea.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

It's an indication that connection pooling is being used (which is a good thing).

Install MySQL on Ubuntu without a password prompt

This should do the trick

export DEBIAN_FRONTEND=noninteractive
sudo -E apt-get -q -y install mysql-server

Of course, it leaves you with a blank root password - so you'll want to run something like

mysqladmin -u root password mysecretpasswordgoeshere

Afterwards to add a password to the account.

WCF on IIS8; *.svc handler mapping doesn't work

using PowerShell you can install the required feature with:

Add-WindowsFeature 'NET-HTTP-Activation'

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Load dimension value from res/values/dimension.xml from source code

If you just want to change the size font dynamically then you can:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.tutorial_cross_marginTop))

As @achie's answer, you can get the dp from dimens.xml like this:

val dpValue = (resources.getDimension(R.dimen.tutorial_cross_marginTop)/ resources.displayMetrics.density).toInt()

or get sp like this

val spValue = (resources.getDimension(R.dimen.font_size)/ resources.displayMetrics.scaledDensity).toInt()

About Resources.java #{getDimension}

    /**
     * Retrieve a dimensional for a particular resource ID.  Unit 
     * conversions are based on the current {@link DisplayMetrics} associated
     * with the resources.
     * 
     * @param id The desired resource identifier, as generated by the aapt
     *           tool. This integer encodes the package, type, and resource
     *           entry. The value 0 is an invalid identifier.
     * 
     * @return Resource dimension value multiplied by the appropriate 
     * metric.
     * 
     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
     *
     * @see #getDimensionPixelOffset
     * @see #getDimensionPixelSize
     */

Resource dimension value multiplied by the appropriate

Add a column to a table, if it does not already exist

Another alternative. I prefer this approach because it is less writing but the two accomplish the same thing.

IF COLUMNPROPERTY(OBJECT_ID('dbo.Person'), 'ColumnName', 'ColumnId') IS NULL
BEGIN
    ALTER TABLE Person 
    ADD ColumnName VARCHAR(MAX) NOT NULL
END

I also noticed yours is looking for where table does exist that is obviously just this

 if COLUMNPROPERTY( OBJECT_ID('dbo.Person'),'ColumnName','ColumnId') is not null

Working with select using AngularJS's ng-options

For some reason AngularJS allows to get me confused. Their documentation is pretty horrible on this. More good examples of variations would be welcome.

Anyway, I have a slight variation on Ben Lesh's answer.

My data collections looks like this:

items =
[
   { key:"AD",value:"Andorra" }
,  { key:"AI",value:"Anguilla" }
,  { key:"AO",value:"Angola" }
 ...etc..
]

Now

<select ng-model="countries" ng-options="item.key as item.value for item in items"></select>

still resulted in the options value to be the index (0, 1, 2, etc.).

Adding Track By fixed it for me:

<select ng-model="blah" ng-options="item.value for item in items track by item.key"></select>

I reckon it happens more often that you want to add an array of objects into an select list, so I am going to remember this one!

Be aware that from AngularJS 1.4 you can't use ng-options any more, but you need to use ng-repeat on your option tag:

<select name="test">
   <option ng-repeat="item in items" value="{{item.key}}">{{item.value}}</option>
</select>

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

Here is the BESTEST way to send emails using PHPmailer library, this is the only method that works for me.

require_once 'mailer/class.phpmailer.php';
    $mail = new PHPMailer(); // create a new object
    $mail->IsSMTP(); // enable SMTP
    $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true; // authentication enabled
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 465; // or 587
    $mail->IsHTML(true);
    $mail->Username = "[email protected]";
    $mail->Password = "xxxxxxx";
    $mail->SetFrom("[email protected]");
    $mail->AddAddress($to);
    $logfile = dirname(dirname(__FILE__)) . '/mail.log';
    try {
        $mail->Body = $message;
        $mail->Subject = $subject;


        file_put_contents($logfile, "Content: \n", FILE_APPEND);
        file_put_contents($logfile, $message . "\n\n", FILE_APPEND);

        if(!$mail->Send()) {
            echo "Mailer Error: " . $mail->ErrorInfo;
        } else {
            echo "Email has been sent";
        }
    } catch (Exception $e) {
        #print_r($e->getMessage());
        file_put_contents($logfile, "Error: \n", FILE_APPEND);
        file_put_contents($logfile, $e->getMessage() . "\n", FILE_APPEND);
        file_put_contents($logfile, $e->getTraceAsString() . "\n\n", FILE_APPEND);
    }

How to convert all tables from MyISAM into InnoDB?

<?php

// Convert all MyISAM tables to INNODB tables in all non-special databases.
// Note: With MySQL less than 5.6, tables with a fulltext search index cannot be converted to INNODB and will be skipped.

if($argc < 4)
    exit("Usage: {$argv[0]} <host> <username> <password>\n");
$host = $argv[1];
$username = $argv[2];
$password = $argv[3];

// Connect to the database.
if(!mysql_connect($host, $username, $password))
    exit("Error opening database. " . mysql_error() . "\n");

// Get all databases except special ones that shouldn't be converted.
$databases = mysql_query("SHOW databases WHERE `Database` NOT IN ('mysql', 'information_schema', 'performance_schema')");
if($databases === false)
    exit("Error showing databases. " . mysql_error() . "\n");

while($db = mysql_fetch_array($databases))
{
    // Select the database.
    if(!mysql_select_db($db[0]))
        exit("Error selecting database: {$db[0]}. " . mysql_error() . "\n");
    printf("Database: %s\n", $db[0]);

    // Get all MyISAM tables in the database.
    $tables = mysql_query("SHOW table status WHERE Engine = 'MyISAM'");
    if($tables === false)
        exit("Error showing tables. " . mysql_error() . "\n");

    while($tbl = mysql_fetch_array($tables))
    {
        // Convert the table to INNODB.
        printf("--- Converting %s\n", $tbl[0]);
        if(mysql_query("ALTER TABLE `{$tbl[0]}` ENGINE = INNODB") === false)
            printf("--- --- Error altering table: {$tbl[0]}. " . mysql_error() . "\n");
    }
}

mysql_close();

?>

Should a RESTful 'PUT' operation return something

The HTTP specification (RFC 2616) has a number of recommendations that are applicable. Here is my interpretation:

  • HTTP status code 200 OK for a successful PUT of an update to an existing resource. No response body needed. (Per Section 9.6, 204 No Content is even more appropriate.)
  • HTTP status code 201 Created for a successful PUT of a new resource, with the most specific URI for the new resource returned in the Location header field and any other relevant URIs and metadata of the resource echoed in the response body. (RFC 2616 Section 10.2.2)
  • HTTP status code 409 Conflict for a PUT that is unsuccessful due to a 3rd-party modification, with a list of differences between the attempted update and the current resource in the response body. (RFC 2616 Section 10.4.10)
  • HTTP status code 400 Bad Request for an unsuccessful PUT, with natural-language text (such as English) in the response body that explains why the PUT failed. (RFC 2616 Section 10.4)

Use css gradient over background image

body {
    margin: 0;
    padding: 0;
    background: url('img/background.jpg') repeat;
}

body:before {
    content: " ";
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    background: -webkit-radial-gradient(top center, ellipse cover, rgba(255,255,255,0.2) 0%,rgba(0,0,0,0.5) 100%);
}

PLEASE NOTE: This only using webkit so it will only work in webkit browsers.

try :

-moz-linear-gradient = (Firefox)
-ms-linear-gradient = (IE)
-o-linear-gradient = (Opera)
-webkit-linear-gradient = (Chrome & safari)

You have not concluded your merge (MERGE_HEAD exists)

I think this is the right way :

git merge --abort

git fetch --all

Then, you have two options:

git reset --hard origin/master

OR If you are on some other branch:

git reset --hard origin/<branch_name>

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

I had a lot of headache with MySQLdb too.

Why not use the official MysQL Python Connector?

easy_install mysql-connector-python

Or you can download it from here: http://dev.mysql.com/downloads/connector/python/

Documentation: http://dev.mysql.com/doc/refman/5.5/en/connector-python.html

Converting SVG to PNG using C#

When I had to rasterize svgs on the server, I ended up using P/Invoke to call librsvg functions (you can get the dlls from a windows version of the GIMP image editing program).

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetDllDirectory(string pathname);

[DllImport("libgobject-2.0-0.dll", SetLastError = true)]
static extern void g_type_init(); 

[DllImport("librsvg-2-2.dll", SetLastError = true)]
static extern IntPtr rsvg_pixbuf_from_file_at_size(string file_name, int width, int height, out IntPtr error);

[DllImport("libgdk_pixbuf-2.0-0.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
static extern bool gdk_pixbuf_save(IntPtr pixbuf, string filename, string type, out IntPtr error, __arglist);

public static void RasterizeSvg(string inputFileName, string outputFileName)
{
    bool callSuccessful = SetDllDirectory("C:\\Program Files\\GIMP-2.0\\bin");
    if (!callSuccessful)
    {
        throw new Exception("Could not set DLL directory");
    }
    g_type_init();
    IntPtr error;
    IntPtr result = rsvg_pixbuf_from_file_at_size(inputFileName, -1, -1, out error);
    if (error != IntPtr.Zero)
    {
        throw new Exception(Marshal.ReadInt32(error).ToString());
    }
    callSuccessful = gdk_pixbuf_save(result, outputFileName, "png", out error, __arglist(null));
    if (!callSuccessful)
    {
        throw new Exception(error.ToInt32().ToString());
    }
}

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

#define GENERAL__GET_BITS_FROM_U8(source,lsb,msb) \
    ((uint8_t)((source) & \
        ((uint8_t)(((uint8_t)(0xFF >> ((uint8_t)(7-((uint8_t)(msb) & 7))))) & \
             ((uint8_t)(0xFF << ((uint8_t)(lsb) & 7)))))))

#define GENERAL__GET_BITS_FROM_U16(source,lsb,msb) \
    ((uint16_t)((source) & \
        ((uint16_t)(((uint16_t)(0xFFFF >> ((uint8_t)(15-((uint8_t)(msb) & 15))))) & \
            ((uint16_t)(0xFFFF << ((uint8_t)(lsb) & 15)))))))

#define GENERAL__GET_BITS_FROM_U32(source,lsb,msb) \
    ((uint32_t)((source) & \
        ((uint32_t)(((uint32_t)(0xFFFFFFFF >> ((uint8_t)(31-((uint8_t)(msb) & 31))))) & \
            ((uint32_t)(0xFFFFFFFF << ((uint8_t)(lsb) & 31)))))))

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

I got the same error because of a simple typo in vhost.conf. Remember to make sure you don't have any errors in the config files.

apachectl configtest

How do I use Docker environment variable in ENTRYPOINT array?

After much pain, and great assistance from @vitr et al above, i decided to try

  • standard bash substitution
  • shell form of ENTRYPOINT (great tip from above)

and that worked.

ENV LISTEN_PORT=""

ENTRYPOINT java -cp "app:app/lib/*" hello.Application --server.port=${LISTEN_PORT:-80}

e.g.

docker run --rm -p 8080:8080 -d --env LISTEN_PORT=8080 my-image

and

docker run --rm -p 8080:80 -d my-image

both set the port correctly in my container

Refs

see https://www.cyberciti.biz/tips/bash-shell-parameter-substitution-2.html

C++ preprocessor __VA_ARGS__ number of arguments

this works with 0 arguments with gcc/llvm. [links are dumb]

/*
 * we need a comma at the start for ##_VA_ARGS__ to consume then
 * the arguments are pushed out in such a way that 'cnt' ends up with
 * the right count.  
 */
#define COUNT_ARGS(...) COUNT_ARGS_(,##__VA_ARGS__,6,5,4,3,2,1,0)
#define COUNT_ARGS_(z,a,b,c,d,e,f,cnt,...) cnt

#define C_ASSERT(test) \
    switch(0) {\
      case 0:\
      case test:;\
    }

int main() {
   C_ASSERT(0 ==  COUNT_ARGS());
   C_ASSERT(1 ==  COUNT_ARGS(a));
   C_ASSERT(2 ==  COUNT_ARGS(a,b));
   C_ASSERT(3 ==  COUNT_ARGS(a,b,c));
   C_ASSERT(4 ==  COUNT_ARGS(a,b,c,d));
   C_ASSERT(5 ==  COUNT_ARGS(a,b,c,d,e));
   C_ASSERT(6 ==  COUNT_ARGS(a,b,c,d,e,f));
   return 0;
}

Visual Studio seems to be ignoring the ## operator used to consume the empty argument. You can probably get around that with something like

#define CNT_ COUNT_ARGS
#define PASTE(x,y) PASTE_(x,y)
#define PASTE_(x,y) x ## y
#define CNT(...) PASTE(ARGVS,PASTE(CNT_(__VA_ARGS__),CNT_(1,##__VA_ARGS__)))
//you know its 0 if its 11 or 01
#define ARGVS11 0
#define ARGVS01 0
#define ARGVS12 1
#define ARGVS23 2
#define ARGVS34 3

CSS text-overflow in a table cell?

It is worked for me

table {
    width: 100%;
    table-layout: fixed;
}

td {
   text-overflow: ellipsis;
   white-space: nowrap;
}

"Keep Me Logged In" - the best approach

OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong.

There. I said it. Now we can move on to the actual answer.

What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity.

Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5...

Let's also imagine for a second that they know the algorithm that you used. For example:

md5(salt+username+ip+salt)

Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle.

In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think.

But Wait!

All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG. That line of thinking has a name: Security Through Obscurity, which should NEVER be relied upon.

The Better Way

The better way is to never let a user's information leave the server, except for the id.

When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie.

What if the attacker guesses the random token of another user?

Well, let's do some math here. We're generating a 128 bit random token. That means that there are:

possibilities = 2^128
possibilities = 3.4 * 10^38

Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out.

guesses_per_second = servers * guesses
guesses_per_second = 50,000,000 * 1,000,000,000
guesses_per_second = 50,000,000,000,000,000

So 50 quadrillion guesses per second. That's fast! Right?

time_to_guess = possibilities / guesses_per_second
time_to_guess = 3.4e38 / 50,000,000,000,000,000
time_to_guess = 6,800,000,000,000,000,000,000

So 6.8 sextillion seconds...

Let's try to bring that down to more friendly numbers.

215,626,585,489,599 years

Or even better:

47917 times the age of the universe

Yes, that's 47917 times the age of the universe...

Basically, it's not going to be cracked.

So to sum up:

The better approach that I recommend is to store the cookie with three parts.

function onLogin($user) {
    $token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit
    storeTokenForUser($user, $token);
    $cookie = $user . ':' . $token;
    $mac = hash_hmac('sha256', $cookie, SECRET_KEY);
    $cookie .= ':' . $mac;
    setcookie('rememberme', $cookie);
}

Then, to validate:

function rememberMe() {
    $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : '';
    if ($cookie) {
        list ($user, $token, $mac) = explode(':', $cookie);
        if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) {
            return false;
        }
        $usertoken = fetchTokenByUserName($user);
        if (hash_equals($usertoken, $token)) {
            logUserIn($user);
        }
    }
}

Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks.

Now, it's very important that the SECRET_KEY be a cryptographic secret (generated by something like /dev/urandom and/or derived from a high-entropy input). Also, GenerateRandomToken() needs to be a strong random source (mt_rand() is not nearly strong enough. Use a library, such as RandomLib or random_compat, or mcrypt_create_iv() with DEV_URANDOM)...

The hash_equals() is to prevent timing attacks. If you use a PHP version below PHP 5.6 the function hash_equals() is not supported. In this case you can replace hash_equals() with the timingSafeCompare function:

/**
 * A timing safe equals comparison
 *
 * To prevent leaking length information, it is important
 * that user input is always used as the second parameter.
 *
 * @param string $safe The internal (safe) value to be checked
 * @param string $user The user submitted (unsafe) value
 *
 * @return boolean True if the two strings are identical.
 */
function timingSafeCompare($safe, $user) {
    if (function_exists('hash_equals')) {
        return hash_equals($safe, $user); // PHP 5.6
    }
    // Prevent issues if string length is 0
    $safe .= chr(0);
    $user .= chr(0);

    // mbstring.func_overload can make strlen() return invalid numbers
    // when operating on raw binary strings; force an 8bit charset here:
    if (function_exists('mb_strlen')) {
        $safeLen = mb_strlen($safe, '8bit');
        $userLen = mb_strlen($user, '8bit');
    } else {
        $safeLen = strlen($safe);
        $userLen = strlen($user);
    }

    // Set the result to the difference between the lengths
    $result = $safeLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return $result === 0;
}

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

CSS :not(:last-child):after selector

Remove the : before last-child and the :after and used

 ul li:not(last-child){
 content:' |';
}

Hopefully,it should work

How to save python screen output to a text file

Here's a really simple way in python 3+:

f = open('filename.txt', 'w')
print('something', file = f)

^ found that from this answer: https://stackoverflow.com/a/4110906/6794367

MySQLi prepared statements error reporting

Completeness

You need to check both $mysqli and $statement. If they are false, you need to output $mysqli->error or $statement->error respectively.

Efficiency

For simple scripts that may terminate, I use simple one-liners that trigger a PHP error with the message. For a more complex application, an error warning system should be activated instead, for example by throwing an exception.

Usage example 1: Simple script

# This is in a simple command line script
$mysqli = new mysqli('localhost', 'buzUser', 'buzPassword');
$q = "UPDATE foo SET bar=1";
($statement = $mysqli->prepare($q)) or trigger_error($mysqli->error, E_USER_ERROR);
$statement->execute() or trigger_error($statement->error, E_USER_ERROR);

Usage example 2: Application

# This is part of an application
class FuzDatabaseException extends Exception {
}

class Foo {
  public $mysqli;
  public function __construct(mysqli $mysqli) {
    $this->mysqli = $mysqli;
  }
  public function updateBar() {
    $q = "UPDATE foo SET bar=1";
    $statement = $this->mysqli->prepare($q);
    if (!$statement) {
      throw new FuzDatabaseException($mysqli->error);
    }

    if (!$statement->execute()) {
      throw new FuzDatabaseException($statement->error);
    }
  }
}

$foo = new Foo(new mysqli('localhost','buzUser','buzPassword'));
try {
  $foo->updateBar();
} catch (FuzDatabaseException $e)
  $msg = $e->getMessage();
  // Now send warning emails, write log
}

A failure occurred while executing com.android.build.gradle.internal.tasks

I know this might not be a complete or exact solution, but for those who are still facing issues even after doing what is given on this thread, check for your files in value folder. For me there was a typo and some missing values. Once i fixed them this error stopped.

Converting NSString to NSDate (and back again)

UPDATE 2019 (Swift 4):

Made a Date extension for that. It uses NSDataDetector instead of NSDateFormatter.

// Just throw at it without any format.
var date: Date? = Date.FromString("02-14-2019 17:05:05")

Pretty enjoyable, it even recognizes things like "Tomorrow at 5".

XCTAssertEqual(Date.FromString("2019-02-14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019.02.14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019/02/14"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14"),                   Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th"),                 Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("20190214"),                      Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02-14-2019"),                    Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("02.14.2019 5:00 PM"),            Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02/14/2019 17:00"),              Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("14 February 2019 at 5 hour"),    Date.FromCalendar(2019, 2, 14, 17))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05"),           Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("17:05, 14 February 2019 (UTC)"), Date.FromCalendar(2019, 2, 14, 17, 05))
XCTAssertEqual(Date.FromString("02-14-2019 17:05:05 GMT"),       Date.FromCalendar(2019, 2, 14, 17, 05, 05))
XCTAssertEqual(Date.FromString("02-13-2019 Tomorrow"),           Date.FromCalendar(2019, 2, 14))
XCTAssertEqual(Date.FromString("2019 Feb 14th Tomorrow at 5"),   Date.FromCalendar(2019, 2, 14, 17))

Goes like:

extension Date
{


    public static func FromString(_ dateString: String) -> Date?
    {
        // Date detector.
        let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.date.rawValue)

        // Enumerate matches.
        var matchedDate: Date?
        var matchedTimeZone: TimeZone?
        detector.enumerateMatches(
            in: dateString,
            options: [],
            range: NSRange(location: 0, length: dateString.utf16.count),
            using:
            {
                (eachResult, _, _) in

                // Lookup matches.
                matchedDate = eachResult?.date
                matchedTimeZone = eachResult?.timeZone

                // Convert to GMT (!) if no timezone detected.
                if matchedTimeZone == nil, let detectedDate = matchedDate
                { matchedDate = Calendar.current.date(byAdding: .second, value: TimeZone.current.secondsFromGMT(), to: detectedDate)! }
        })

        // Result.
        return matchedDate
    }
}

UPDATE 2014:

Made an NSString extension for that.

// Simple as this.   
date = dateString.dateValue;

Thanks to NSDataDetector, it recognizes a whole lot of format.

'2014-01-16' dateValue is <2014-01-16 11:00:00 +0000>
'2014.01.16' dateValue is <2014-01-16 11:00:00 +0000>
'2014/01/16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16' dateValue is <2014-01-16 11:00:00 +0000>
'2014 Jan 16th' dateValue is <2014-01-16 11:00:00 +0000>
'20140116' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014' dateValue is <2014-01-16 11:00:00 +0000>
'01.16.2014' dateValue is <2014-01-16 11:00:00 +0000>
'01/16/2014' dateValue is <2014-01-16 11:00:00 +0000>
'16 January 2014' dateValue is <2014-01-16 11:00:00 +0000>
'01-16-2014 17:05:05' dateValue is <2014-01-16 16:05:05 +0000>
'01-16-2014 T 17:05:05 UTC' dateValue is <2014-01-16 17:05:05 +0000>
'17:05, 1 January 2014 (UTC)' dateValue is <2014-01-01 16:05:00 +0000>

Part of eppz!kit, grab the category NSString+EPPZKit.h from GitHub.


ORIGINAL ANSWER 2013:

Whether you're not sure (or don't care) about the date format contained in the string, use NSDataDetector for parsing date.

//Role players.
NSString *dateString = @"Wed, 03 Jul 2013 02:16:02 -0700";
__block NSDate *detectedDate;

//Detect.
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingAllTypes error:nil];
[detector enumerateMatchesInString:dateString
                           options:kNilOptions
                             range:NSMakeRange(0, [dateString length])
                        usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop)
{ detectedDate = result.date; }];

jQuery slide left and show

And if you want to vary the speed and include callbacks simply add them like this :

        jQuery.fn.extend({
            slideRightShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftHide: function(speed,callback) {
                return this.each(function() {
                    $(this).hide('slide', {direction: 'left'}, speed, callback);
                });
            },
            slideRightHide: function(speed,callback) {
                return this.each(function() {  
                    $(this).hide('slide', {direction: 'right'}, speed, callback);
                });
            },
            slideLeftShow: function(speed,callback) {
                return this.each(function() {
                    $(this).show('slide', {direction: 'left'}, speed, callback);
                });
            }
        });

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

Pass mouse events through absolutely-positioned element

If you know the elements that need mouse events, and if your overlay is transparent, you can just set the z-index of them to something higher than the overlay. All events should of course work in that case on all browsers.

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

HTTP POST with Json on Body - Flutter/Dart

This would also work :

import 'package:http/http.dart' as http;

  sendRequest() async {

    Map data = {
       'apikey': '12345678901234567890'
    };

    var url = 'https://pae.ipportalegre.pt/testes2/wsjson/api/app/ws-authenticate';
    http.post(url, body: data)
        .then((response) {
      print("Response status: ${response.statusCode}");
      print("Response body: ${response.body}");
    });  
  }

DateTime.TryParseExact() rejecting valid formats

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

What is trunk, branch and tag in Subversion?

A good book on Subversion is Pragmatic Version Control using Subversion where your question is explained, and it gives a lot more information.

What is the MySQL JDBC driver connection string?

update for mySQL 8 :

String jdbcUrl="jdbc:mysql://localhost:3306/youdatabase?useSSL=false&serverTimezone=UTC";

Check whether your Jdbc configurations and URL correct or wrong using the following code snippet.

import java.sql.Connection;
import java.sql.DriverManager;

public class TestJdbc {

    public static void main(String[] args) {

        //db name:testdb_version001
        //useSSL=false (get rid of MySQL SSL warnings)

        String jdbcUrl = "jdbc:mysql://localhost:3306/testdb_version001?useSSL=false";
        String username="testdb";
        String password ="testdb";

        try{

            System.out.println("Connecting to database :" +jdbcUrl);
            Connection myConn =
                    DriverManager.getConnection(jdbcUrl,username,password);

            System.out.println("Connection Successful...!");


        }catch (Exception e){
            e.printStackTrace();
            //e.printStackTrace();
        }

    }


}

How to copy file from host to container using Dockerfile

For those who get this (terribly unclear) error:

COPY failed: stat /var/lib/docker/tmp/docker-builderXXXXXXX/abc.txt: no such file or directory

There could be loads of reasons, including:

  • For docker-compose users, remember that the docker-compose.yml context overwrites the context of the Dockerfile. Your COPY statements now need to navigate a path relative to what is defined in docker-compose.yml instead of relative to your Dockerfile.
  • Trailing comments or a semicolon on the COPY line: COPY abc.txt /app #This won't work
  • The file is in a directory ignored by .dockerignore or .gitignore files (be wary of wildcards)
  • You made a typo

Sometimes WORKDIR /abc followed by COPY . xyz/ works where COPY /abc xyz/ fails, but it's a bit ugly.

"Operation must use an updateable query" error in MS Access

You have to remove the IMEX=1 if you want to update. ;)

"IMEX=1; tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative." https://www.connectionstrings.com/excel/

What are the ways to make an html link open a folder

Do you want to open a shared folder in Windows Explorer? You need to use a file: link, but there are caveats:

  • Internet Explorer will work if the link is a converted UNC path (file://server/share/folder/).
  • Firefox will work if the link is in its own mangled form using five slashes (file://///server/share/folder) and the user has disabled the security restriction on file: links in a page served over HTTP. Thankfully IE also accepts the mangled link form.
  • Opera, Safari and Chrome can not be convinced to open a file: link in a page served over HTTP.

Calculate rolling / moving average in C++

You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.

List files recursively in Linux CLI with path relative to the current directory

If you want to preserve the details come with ls like file size etc in your output then this should work.

sed "s|<OLDPATH>|<NEWPATH>|g" input_file > output_file

How to get current user in asp.net core

In addition to existing answers I'd like to add that you can also have a class instance available app-wide which holds user-related data like UserID etc.

It may be useful for refactoring e.g. you don't want to fetch UserID in every controller action and declare an extra UserID parameter in every method related to Service Layer.

I've done a research and here's my post.

You just extend your class which you derive from DbContext by adding UserId property (or implement a custom Session class which has this property).

At filter level you can fetch your class instance and set UserId value.

After that wherever you inject your instance - it will have the necessary data (lifetime must be per request, so you register it using AddScoped method).

Working example:

public class AppInitializationFilter : IAsyncActionFilter
{
    private DBContextWithUserAuditing _dbContext;

    public AppInitializationFilter(
        DBContextWithUserAuditing dbContext
        )
    {
        _dbContext = dbContext;
    }

    public async Task OnActionExecutionAsync(
        ActionExecutingContext context,
        ActionExecutionDelegate next
        )
    {
        string userId = null;
        int? tenantId = null;

        var claimsIdentity = (ClaimsIdentity)context.HttpContext.User.Identity;

        var userIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
        if (userIdClaim != null)
        {
            userId = userIdClaim.Value;
        }

        var tenantIdClaim = claimsIdentity.Claims.SingleOrDefault(c => c.Type == CustomClaims.TenantId);
        if (tenantIdClaim != null)
        {
            tenantId = !string.IsNullOrEmpty(tenantIdClaim.Value) ? int.Parse(tenantIdClaim.Value) : (int?)null;
        }

        _dbContext.UserId = userId;
        _dbContext.TenantId = tenantId;

        var resultContext = await next();
    }
}

For more information see my answer.