Programs & Examples On #Iis metabase

Error - Unable to access the IIS metabase

Open visual studio command prompt and type below command and run

aspnet_regiis -ga machinename\ASPNET

After running the above command Reset the IIS and test the application that resolve your issue.

If above command doesn’t resolve your problem then try to run below command in visual studio command prompt:-

aspnet_regiis -i

Alternatively we can run above command from our windows command prompt also

Go to the Start menu and open Run and enter and click OK

%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe –I

After that Reset the IIS and test the application that resolves your issue

How to show row number in Access query like ROW_NUMBER in SQL

by VB function:

Dim m_RowNr(3) as Variant
'
Function RowNr(ByVal strQName As String, ByVal vUniqValue) As Long
' m_RowNr(3)
' 0 - Nr
' 1 - Query Name
' 2 - last date_time
' 3 - UniqValue

If Not m_RowNr(1) = strQName Then
  m_RowNr(0) = 1
  m_RowNr(1) = strQName
ElseIf DateDiff("s", m_RowNr(2), Now) > 9 Then
  m_RowNr(0) = 1
ElseIf Not m_RowNr(3) = vUniqValue Then
  m_RowNr(0) = m_RowNr(0) + 1
End If

m_RowNr(2) = Now
m_RowNr(3) = vUniqValue
RowNr = m_RowNr(0)

End Function

Usage(without sorting option):

SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
From table A
Order By A.id

if sorting required or multiple tables join then create intermediate table:

 SELECT RowNr('title_of_query_or_any_unique_text',A.id) as Nr,A.*
 INTO table_with_Nr
 From table A
 Order By A.id

Can you find all classes in a package using reflection?

You need to look up every class loader entry in the class path:

    String pkg = "org/apache/commons/lang";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    for (URL url : urls) {
        System.out.println(url.getFile());
        File jar = new File(url.getFile());
        // ....
    }   

If entry is directory, just look up in the right subdirectory:

if (jar.isDirectory()) {
    File subdir = new File(jar, pkg);
    if (!subdir.exists())
        continue;
    File[] files = subdir.listFiles();
    for (File file : files) {
        if (!file.isFile())
            continue;
        if (file.getName().endsWith(".class"))
            System.out.println("Found class: "
                    + file.getName().substring(0,
                            file.getName().length() - 6));
    }
}   

If the entry is the file, and it's jar, inspect the ZIP entries of it:

else {
    // try to open as ZIP
    try {
        ZipFile zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> entries = zip
                .entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith(pkg))
                continue;
            name = name.substring(pkg.length() + 1);
            if (name.indexOf('/') < 0 && name.endsWith(".class"))
                System.out.println("Found class: "
                        + name.substring(0, name.length() - 6));
        }
    } catch (ZipException e) {
        System.out.println("Not a ZIP: " + e.getMessage());
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

Now once you have all class names withing package, you can try loading them with reflection and analyze if they are classes or interfaces, etc.

What are the lesser known but useful data structures?

An interesting variant of the hash table is called Cuckoo Hashing. It uses multiple hash functions instead of just 1 in order to deal with hash collisions. Collisions are resolved by removing the old object from the location specified by the primary hash, and moving it to a location specified by an alternate hash function. Cuckoo Hashing allows for more efficient use of memory space because you can increase your load factor up to 91% with only 3 hash functions and still have good access time.

How to implement LIMIT with SQL Server?

This is a multi step approach that will work in SQL2000.

-- Create a temp table to hold the data
CREATE TABLE #foo(rowID int identity(1, 1), myOtherColumns)

INSERT INTO #foo (myColumns) SELECT myData order By MyCriteria

Select * FROM #foo where rowID > 10

How to make Google Fonts work in IE?

You can try fontsforweb.com where fonts are working for all browsers, because they are provided in TTF, WOFF and EOT formats together with CSS code ready to be pasted on your page i.e.

@font-face{ 
    font-family: "gothambold1";
    src: url('http://fontsforweb.com/public/fonts/5903/gothambold1.eot');
    src: local("Gotham-Bold"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.woff') format("woff"), url('http://fontsforweb.com/public/fonts/5903/gothambold1.ttf') format("truetype");
}
.fontsforweb_fontid_5903 {
    font-family: "gothambold1";
}

or you can download them zipped in a package with CSS file attached

then just add class to any element to apply that font i.e.

<h2 class="fontsforweb_fontid_5903">This will be written with Gotham Bold font and will work in all browsers</h2>

See it working: http://jsfiddle.net/SD4MP/

Count rows with not empty value

As far as I can see, most of the solutions here count the number of non empty cells, and not the number of rows with non empty cell inside.

One possible solution for the range B3:E29 is for example

=SUM(ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)))

Here ArrayFormula(IF(B3:B29&C3:C29&D3:D29&E3:E29="";0;1)) returns a column of 0 (if the row is empty) and 1 (else).

Another one is given in consideRatio's answer.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

This is how use SignarR in order to target a specific user (without using any provider):

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

Returning Month Name in SQL Server Query

Change:

CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth

To:

CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

Remove element should clear out such errors. The reason behind this is the inherited settings. Your application will inherit some settings from its parent's config file and machine's (server) config files.
You can either remove such duplicates with the remove tag before adding them or make these tags non-inheritable in the upper level config files.

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

How do I compute derivative using Numpy?

NumPy does not provide general functionality to compute derivatives. It can handles the simple special case of polynomials however:

>>> p = numpy.poly1d([1, 0, 1])
>>> print p
   2
1 x + 1
>>> q = p.deriv()
>>> print q
2 x
>>> q(5)
10

If you want to compute the derivative numerically, you can get away with using central difference quotients for the vast majority of applications. For the derivative in a single point, the formula would be something like

x = 5.0
eps = numpy.sqrt(numpy.finfo(float).eps) * (1.0 + x)
print (p(x + eps) - p(x - eps)) / (2.0 * eps * x)

if you have an array x of abscissae with a corresponding array y of function values, you can comput approximations of derivatives with

numpy.diff(y) / numpy.diff(x)

How to get current CPU and RAM usage in Python?

I don't believe that there is a well-supported multi-platform library available. Remember that Python itself is written in C so any library is simply going to make a smart decision about which OS-specific code snippet to run, as you suggested above.

Equivalent of shell 'cd' command to change the working directory?

If you use spyder and love GUI, you can simply click on the folder button on the upper right corner of your screen and navigate through folders/directories you want as current directory. After doing so you can go to the file explorer tab of the window in spyder IDE and you can see all the files/folders present there. to check your current working directory go to the console of spyder IDE and simply type

pwd

it will print the same path as you have selected before.

Regex Named Groups in Java

Yes but its messy hacking the sun classes. There is a simpler way:

http://code.google.com/p/named-regexp/

named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).

It can be used with Java 5 and 6 (generics are used).

Java 7 will handle named capturing groups , so this project is not meant to last.

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)

SimpleDateFormat parse loses timezone

OP's solution to his problem, as he says, has dubious output. That code still shows confusion about representations of time. To clear up this confusion, and make code that won't lead to wrong times, consider this extension of what he did:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat sdfGMT2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");
    sdfGMT2.setTimeZone(TimeZone.getTimeZone("GMT"));

    SimpleDateFormat sdfLocal1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    SimpleDateFormat sdfLocal2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z");

    try {
        Date d = new Date();
        String s1 = d.toString();
        String s2 = sdfLocal1.format(d);
        // Store s3 or s4 in database.
        String s3 = sdfGMT1.format(d);
        String s4 = sdfGMT2.format(d);
        // Retrieve s3 or s4 from database, using LOCAL sdf.
        String s5 = sdfLocal1.parse(s3).toString();
        //EXCEPTION String s6 = sdfLocal2.parse(s3).toString();
        String s7 = sdfLocal1.parse(s4).toString();
        String s8 = sdfLocal2.parse(s4).toString();
        // Retrieve s3 from database, using GMT sdf.
        // Note that this is the SAME sdf that created s3.
        Date d2 = sdfGMT1.parse(s3);
        String s9 = d2.toString();
        String s10 = sdfGMT1.format(d2);
        String s11 = sdfLocal2.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

examining values in a debugger:

s1  "Mon Sep 07 06:11:53 EDT 2015" (id=831698113128)    
s2  "2015.09.07 06:11:53" (id=831698114048) 
s3  "2015.09.07 10:11:53" (id=831698114968) 
s4  "2015.09.07 10:11:53 GMT+00:00" (id=831698116112)   
s5  "Mon Sep 07 10:11:53 EDT 2015" (id=831698116944)    
s6  -- omitted, gave parse exception    
s7  "Mon Sep 07 10:11:53 EDT 2015" (id=831698118680)    
s8  "Mon Sep 07 06:11:53 EDT 2015" (id=831698119584)    
s9  "Mon Sep 07 06:11:53 EDT 2015" (id=831698120392)    
s10 "2015.09.07 10:11:53" (id=831698121312) 
s11 "2015.09.07 06:11:53 EDT" (id=831698122256) 

sdf2 and sdfLocal2 include time zone, so we can see what is really going on. s1 & s2 are at 06:11:53 in zone EDT. s3 & s4 are at 10:11:53 in zone GMT -- equivalent to the original EDT time. Imagine we save s3 or s4 in a data base, where we are using GMT for consistency, so we can have times from anywhere in the world, without storing different time zones.

s5 parses the GMT time, but treats it as a local time. So it says "10:11:53" -- the GMT time -- but thinks it is 10:11:53 in local time. Not good.

s7 parses the GMT time, but ignores the GMT in the string, so still treats it as a local time.

s8 works, because now we include GMT in the string, and the local zone parser uses it to convert from one time zone to another.

Now suppose you don't want to store the zone, you want to be able to parse s3, but display it as a local time. The answer is to parse using the same time zone it was stored in -- so use the same sdf as it was created in, sdfGMT1. s9, s10, & s11 are all representations of the original time. They are all "correct". That is, d2 == d1. Then it is only a question of how you want to DISPLAY it. If you want to display what is stored in DB -- GMT time -- then you need to format it using a GMT sdf. Ths is s10.

So here is the final solution, if you don't want to explicitly store with " GMT" in the string, and want to display in GMT format:

public static void _testDateFormatting() {
    SimpleDateFormat sdfGMT1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    sdfGMT1.setTimeZone(TimeZone.getTimeZone("GMT"));

    try {
        Date d = new Date();
        String s3 = sdfGMT1.format(d);
        // Store s3 in DB.
        // ...
        // Retrieve s3 from database, using GMT sdf.
        Date d2 = sdfGMT1.parse(s3);
        String s10 = sdfGMT1.format(d2);
    } catch (Exception e) {
        e.printStackTrace();
    }       
}

How can I output leading zeros in Ruby?

Use String#next as the counter.

>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003

next is relatively 'clever', meaning you can even go for

>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

Check whether user has a Chrome extension installed

Here is how you can detect a specific Extension installed and show a warning message.

First you need to open the manifest file of the extension by going to chrome-extension://extension_id_here_hkdppipefbchgpohn/manifest.json and look for any file name within "web_accessible_resources" section.

<div class="chromewarning" style="display:none">
    <script type="text/javascript">
                            $.get("chrome-extension://extension_id_here_hkdppipefbchgpohn/filename_found_in_ web_accessible_resources.png").done(function () {
                              $(".chromewarning").show();
                            }).fail(function () {
                             //  alert("failed.");
                            });
                        </script>
                        <p>We have detected a browser extension that conflicts with learning modules in this course.</p>
            </div>

C++ String Declaring

Preferred string type in C++ is string, defined in namespace std, in header <string> and you can initialize it like this for example:

#include <string>

int main()
{
   std::string str1("Some text");
   std::string str2 = "Some text";
}

More about it you can find here and here.

Prevent direct access to a php include file

The easiest way for the generic "PHP app running on an Apache server that you may or may not fully control" situation is to put your includes in a directory and deny access to that directory in your .htaccess file. To save people the trouble of Googling, if you're using Apache, put this in a file called ".htaccess" in the directory you don't want to be accessible:

Deny from all

If you actually have full control of the server (more common these days even for little apps than when I first wrote this answer), the best approach is to stick the files you want to protect outside of the directory that your web server is serving from. So if your app is in /srv/YourApp/, set the server to serve files from /srv/YourApp/app/ and put the includes in /srv/YourApp/includes, so there literally isn't any URL that can access them.

replacing text in a file with Python

Reading from standard input, write 'code.py' as follows:

import sys

rep = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}

for line in sys.stdin:
    for k, v in rep.iteritems():
        line = line.replace(k, v)
    print line

Then, execute the script with redirection or piping (http://en.wikipedia.org/wiki/Redirection_(computing))

python code.py < infile > outfile

Hunk #1 FAILED at 1. What's that mean?

In my case, the patch was generated perfectly fine by IDEA, however, I edited the patch and saved it which changed CRLF to LF and then the patch stopped working. Curiously, converting it back to CRLF did not work. I noticed in VI editor, that even after setting to DOS format, the '^M' were not added to the end of lines. This forced me to only make changes in VI, so that the EOLs were preserved.

This may apply to you, if you make changes in a non-Windows environment to a patch covering changes between two versions both coming from Windows environment. You want to be careful how you edit such files.

BTW ignore-whitespace did not help.

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

How do I connect to my existing Git repository using Visual Studio Code?

  1. Use git clone to clone your repository into a folder (say work). You should see a new subfolder, work/.git.
  2. Open folder work in Visual Studio Code - everything should work fine!

PS: Blow away the temporary folder.

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

Among $_REQUEST, $_GET and $_POST which one is the fastest?

I'd suggest using $_POST and $_GET explicitly.

Using $_REQUEST should be unnecessary with proper site design anyway, and it comes with some downsides like leaving you open to easier CSRF/XSS attacks and other silliness that comes from storing data in the URL.

The speed difference should be minimal either way.

Trigger function when date is selected with jQuery UI datepicker

$(".datepicker").datepicker().on("changeDate", function(e) {
   console.log("Date changed: ", e.date);
});

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

How to get the size of the current screen in WPF?

I created a little wrapper around the Screen from System.Windows.Forms, currently everything works... Not sure about the "device independent pixels", though.

public class WpfScreen
{
    public static IEnumerable<WpfScreen> AllScreens()
    {
        foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
        {
            yield return new WpfScreen(screen);
        }
    }

    public static WpfScreen GetScreenFrom(Window window)
    {
        WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
        Screen screen = System.Windows.Forms.Screen.FromHandle(windowInteropHelper.Handle);
        WpfScreen wpfScreen = new WpfScreen(screen);
        return wpfScreen;
    }

    public static WpfScreen GetScreenFrom(Point point)
    {
        int x = (int) Math.Round(point.X);
        int y = (int) Math.Round(point.Y);

        // are x,y device-independent-pixels ??
        System.Drawing.Point drawingPoint = new System.Drawing.Point(x, y);
        Screen screen = System.Windows.Forms.Screen.FromPoint(drawingPoint);
        WpfScreen wpfScreen = new WpfScreen(screen);

        return wpfScreen;
    }

    public static WpfScreen Primary
    {
        get { return new WpfScreen(System.Windows.Forms.Screen.PrimaryScreen); }
    }

    private readonly Screen screen;

    internal WpfScreen(System.Windows.Forms.Screen screen)
    {
        this.screen = screen;
    }

    public Rect DeviceBounds
    {
        get { return this.GetRect(this.screen.Bounds); }
    }

    public Rect WorkingArea
    {
        get { return this.GetRect(this.screen.WorkingArea); }
    }

    private Rect GetRect(Rectangle value)
    {
        // should x, y, width, height be device-independent-pixels ??
        return new Rect
                   {
                       X = value.X,
                       Y = value.Y,
                       Width = value.Width,
                       Height = value.Height
                   };
    }

    public bool IsPrimary
    {
        get { return this.screen.Primary; }
    }

    public string DeviceName
    {
        get { return this.screen.DeviceName; }
    }
}

How to handle anchor hash linking in AngularJS

$anchorScroll works for this, but there's a much better way to use it in more recent versions of Angular.

Now, $anchorScroll accepts the hash as an optional argument, so you don't have to change $location.hash at all. (documentation)

This is the best solution because it doesn't affect the route at all. I couldn't get any of the other solutions to work because I'm using ngRoute and the route would reload as soon as I set $location.hash(id), before $anchorScroll could do its magic.

Here is how to use it... first, in the directive or controller:

$scope.scrollTo = function (id) {
  $anchorScroll(id);  
}

and then in the view:

<a href="" ng-click="scrollTo(id)">Text</a>

Also, if you need to account for a fixed navbar (or other UI), you can set the offset for $anchorScroll like this (in the main module's run function):

.run(function ($anchorScroll) {
   //this will make anchorScroll scroll to the div minus 50px
   $anchorScroll.yOffset = 50;
});

How to set Status Bar Style in Swift 3

This worked for me

Set View controller-based status bar appearance into NO in plist then In UIViewController viewDidAppear just added the following line

UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

CSS for grabbing cursors (drag & drop)

I may be late, but you can try the following code, which worked for me for Drag and Drop.

.dndclass{
    cursor: url('../images/grab1.png'), auto; 

}

.dndclass:active {
    cursor: url('../images/grabbing1.png'), auto;
}

You can use the images below in the URL above. Make sure it is a PNG transparent image. If not, download one from google.

enter image description here enter image description here

Regular expression matching a multiline block of text

This will work:

>>> import re
>>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE)
>>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines
>>> text="""Some varying text1
...
... AAABBBBBBCCCCCCDDDDDDD
... EEEEEEEFFFFFFFFGGGGGGG
... HHHHHHIIIIIJJJJJJJKKKK
...
... Some varying text 2
...
... LLLLLMMMMMMNNNNNNNOOOO
... PPPPPPPQQQQQQRRRRRRSSS
... TTTTTUUUUUVVVVVVWWWWWW
... """
>>> for match in rx_sequence.finditer(text):
...   title, sequence = match.groups()
...   title = title.strip()
...   sequence = rx_blanks.sub("",sequence)
...   print "Title:",title
...   print "Sequence:",sequence
...   print
...
Title: Some varying text1
Sequence: AAABBBBBBCCCCCCDDDDDDDEEEEEEEFFFFFFFFGGGGGGGHHHHHHIIIIIJJJJJJJKKKK

Title: Some varying text 2
Sequence: LLLLLMMMMMMNNNNNNNOOOOPPPPPPPQQQQQQRRRRRRSSSTTTTTUUUUUVVVVVVWWWWWW

Some explanation about this regular expression might be useful: ^(.+?)\n\n((?:[A-Z]+\n)+)

  • The first character (^) means "starting at the beginning of a line". Be aware that it does not match the newline itself (same for $: it means "just before a newline", but it does not match the newline itself).
  • Then (.+?)\n\n means "match as few characters as possible (all characters are allowed) until you reach two newlines". The result (without the newlines) is put in the first group.
  • [A-Z]+\n means "match as many upper case letters as possible until you reach a newline. This defines what I will call a textline.
  • ((?:textline)+) means match one or more textlines but do not put each line in a group. Instead, put all the textlines in one group.
  • You could add a final \n in the regular expression if you want to enforce a double newline at the end.
  • Also, if you are not sure about what type of newline you will get (\n or \r or \r\n) then just fix the regular expression by replacing every occurrence of \n by (?:\n|\r\n?).

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

Why do we use __init__ in Python classes?

It is just to initialize the instance's variables.

E.g. create a crawler instance with a specific database name (from your example above).

How to call another controller Action From a controller in Mvc

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext.

Instead, you should get an instance of your controller like this:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

pip3: command not found but python3-pip is already installed

I had a similar issue. In my case, I had to uninstall and then reinstall pip3:

sudo apt-get remove python3-pip
sudo apt-get install python3-pip

Android overlay a view ontop of everything?

I have tried the awnsers before but this did not work. Now I jsut used a LinearLayout instead of a TextureView, now it is working without any problem. Hope it helps some others who have the same problem. :)

    view = (LinearLayout) findViewById(R.id.view); //this is initialized in the constructor
    openWindowOnButtonClick();

public void openWindowOnButtonClick()
{
    view.setAlpha((float)0.5);
    FloatingActionButton fb = (FloatingActionButton) findViewById(R.id.floatingActionButton);
    final InputMethodManager keyboard = (InputMethodManager) getSystemService(getBaseContext().INPUT_METHOD_SERVICE);
    fb.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // check if the Overlay should be visible. If this value is false, it is not shown -> show it.
            if(view.getVisibility() == View.INVISIBLE)
            {
                view.setVisibility(View.VISIBLE);
                keyboard.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                Log.d("Overlay", "Klick");
            }
            else if(view.getVisibility() == View.VISIBLE)
            {
                view.setVisibility(View.INVISIBLE);
                keyboard.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
            }

Trigger an action after selection select2

It works for me:

$('#yourselect').on("change", function(e) { 
   // what you would like to happen
});

How to get images in Bootstrap's card to be the same height/width?

I solved with these:

.card-img-top {
    max-height: 20vh; /*not want to take all vertical space*/
    object-fit: contain;/*show all image, autosized, no cut, in available space*/
}

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Finding the index of an item in a list

A variant on the answer from FMc and user7177 will give a dict that can return all indices for any entry:

>>> a = ['foo','bar','baz','bar','any', 'foo', 'much']
>>> l = dict(zip(set(a), map(lambda y: [i for i,z in enumerate(a) if z is y ], set(a))))
>>> l['foo']
[0, 5]
>>> l ['much']
[6]
>>> l
{'baz': [2], 'foo': [0, 5], 'bar': [1, 3], 'any': [4], 'much': [6]}
>>> 

You could also use this as a one liner to get all indices for a single entry. There are no guarantees for efficiency, though I did use set(a) to reduce the number of times the lambda is called.

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

There is no magic fix. Itunes is just working bad. Lately is having more and more issues and it takes more and more to update and send an ipa to the store. I had this issue with AppLoader and Xcode organiser too and after trying multiple times it just went through.

Bootstrap 3 - disable navbar collapse

Another way is to simply remove collapse navbar-collapse from the markup. Example with Bootstrap 3.3.7

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<nav class="navbar navbar-atp">_x000D_
  <div class="container-fluid">_x000D_
    <div class="">_x000D_
      <ul class="nav navbar-nav nav-custom">_x000D_
        <li>_x000D_
          <a href="#" id="sidebar-btn"><span class="fa fa-bars">Toggle btn</span></a>_x000D_
        </li>_x000D_
      </ul>_x000D_
      <ul class="nav navbar-nav navbar-right">_x000D_
        <li>Nav item</li>_x000D_
      </ul>_x000D_
    </div>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

Best Practices: working with long, multiline strings in PHP?

The one who believes that

"abc\n" . "def\n"

is multiline string is wrong. That's two strings with concatenation operator, not a multiline string. Such concatenated strings cannot be used as keys of pre-defined arrays, for example. Unfortunately php does not offer real multiline strings in form of

"abc\n"
"def\n"

only HEREDOC and NOWDOC syntax, which is more suitable for templates, because nested code indent is broken by such syntax.

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

UL list style not applying

and you can also give a left-margin if the reset.css you are using make all margin null : that means :

li {
list-style: disc outside none;
display: list-item;
margin-left: 1em;
}

Assuming you apply this css after the reset, it should work !

Matthieu Ricaud

How do I get the base URL with PHP?

   $base_url="http://".$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"].'?').'/';

Usage:

print "<script src='{$base_url}js/jquery.min.js'/>";

How do I check in python if an element of a list is empty?

If you want to know if list element at index i is set or not, you can simply check the following:

if len(l)<=i:
    print ("empty")

If you are looking for something like what is a NULL-Pointer or a NULL-Reference in other languages, Python offers you None. That is you can write:

l[0] = None # here, list element at index 0 has to be set already
l.append(None) # here the list can be empty before
# checking
if l[i] == None:
    print ("list has actually an element at position i, which is None")

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

LINQ - Full Outer Join

Yet another full outer join

As was not that happy with the simplicity and the readability of the other propositions, I ended up with this :

It does not have the pretension to be fast ( about 800 ms to join 1000 * 1000 on a 2020m CPU : 2.4ghz / 2cores). To me, it is just a compact and casual full outer join.

It works the same as a SQL FULL OUTER JOIN (duplicates conservation)

Cheers ;-)

using System;
using System.Collections.Generic;
using System.Linq;
namespace NS
{
public static class DataReunion
{
    public static List<Tuple<T1, T2>> FullJoin<T1, T2, TKey>(List<T1> List1, Func<T1, TKey> KeyFunc1, List<T2> List2, Func<T2, TKey> KeyFunc2)
    {
        List<Tuple<T1, T2>> result = new List<Tuple<T1, T2>>();

        Tuple<TKey, T1>[] identifiedList1 = List1.Select(_ => Tuple.Create(KeyFunc1(_), _)).OrderBy(_ => _.Item1).ToArray();
        Tuple<TKey, T2>[] identifiedList2 = List2.Select(_ => Tuple.Create(KeyFunc2(_), _)).OrderBy(_ => _.Item1).ToArray();

        identifiedList1.Where(_ => !identifiedList2.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(_.Item2, default(T2)));
        });

        result.AddRange(
            identifiedList1.Join(identifiedList2, left => left.Item1, right => right.Item1, (left, right) => Tuple.Create<T1, T2>(left.Item2, right.Item2)).ToList()
        );

        identifiedList2.Where(_ => !identifiedList1.Select(__ => __.Item1).Contains(_.Item1)).ToList().ForEach(_ => {
            result.Add(Tuple.Create<T1, T2>(default(T1), _.Item2));
        });

        return result;
    }
}
}

The idea is to

  1. Build Ids based on provided key function builders
  2. Process left only items
  3. Process inner join
  4. Process right only items

Here is a succinct test that goes with it :

Place a break point at the end to manually verify that it behaves as expected

using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NS;

namespace Tests
{
[TestClass]
public class DataReunionTest
{
    [TestMethod]
    public void Test()
    {
        List<Tuple<Int32, Int32, String>> A = new List<Tuple<Int32, Int32, String>>();
        List<Tuple<Int32, Int32, String>> B = new List<Tuple<Int32, Int32, String>>();

        Random rnd = new Random();

        /* Comment the testing block you do not want to run
        /* Solution to test a wide range of keys*/

        for (int i = 0; i < 500; i += 1)
        {
            A.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "A"));
            B.Add(Tuple.Create(rnd.Next(1, 101), rnd.Next(1, 101), "B"));
        }

        /* Solution for essential testing*/

        A.Add(Tuple.Create(1, 2, "B11"));
        A.Add(Tuple.Create(1, 2, "B12"));
        A.Add(Tuple.Create(1, 3, "C11"));
        A.Add(Tuple.Create(1, 3, "C12"));
        A.Add(Tuple.Create(1, 3, "C13"));
        A.Add(Tuple.Create(1, 4, "D1"));

        B.Add(Tuple.Create(1, 1, "A21"));
        B.Add(Tuple.Create(1, 1, "A22"));
        B.Add(Tuple.Create(1, 1, "A23"));
        B.Add(Tuple.Create(1, 2, "B21"));
        B.Add(Tuple.Create(1, 2, "B22"));
        B.Add(Tuple.Create(1, 2, "B23"));
        B.Add(Tuple.Create(1, 3, "C2"));
        B.Add(Tuple.Create(1, 5, "E2"));

        Func<Tuple<Int32, Int32, String>, Tuple<Int32, Int32>> key = (_) => Tuple.Create(_.Item1, _.Item2);

        var watch = System.Diagnostics.Stopwatch.StartNew();
        var res = DataReunion.FullJoin(A, key, B, key);
        watch.Stop();
        var elapsedMs = watch.ElapsedMilliseconds;
        String aser = JToken.FromObject(res).ToString(Formatting.Indented);
        Console.Write(elapsedMs);
    }
}

}

How to generate .json file with PHP?

Insert your fetched values into an array instead of echoing.

Use file_put_contents() and insert json_encode($rows) into that file, if $rows is your data.

How do I tell if an object is a Promise?

If you are in an async method you can do this and avoid any ambiguity.

async myMethod(promiseOrNot){
  const theValue = await promiseOrNot()
}

If the function returns promise, it will await and return with the resolved value. If the function returns a value, it will be treated as resolved.

If the function does not return a promise today, but tomorrow returns one or is declared async, you will be future-proof.

How to prevent multiple definitions in C?

I had similar problem and i solved it following way.

Solve as follows:

Function prototype declarations and global variable should be in test.h file and you can not initialize global variable in header file.

Function definition and use of global variable in test.c file

if you initialize global variables in header it will have following error

multiple definition of `_ test'| obj\Debug\main.o:path\test.c|1|first defined here|

Just declarations of global variables in Header file no initialization should work.

Hope it helps

Cheers

I can't understand why this JAXB IllegalAnnotationException is thrown

This is happening be cause you have 2 classes with same name. For, example, I have 2 SOAP web-services named settings and settings2 both have the same class GetEmployee and this is ambiguous proving the error.

How do I set the selected item in a comboBox to match my string using C#?

I have created a Function which will return the Index of the Value

        public static int SelectByValue(ComboBox comboBox, string value)
        {
            int i = 0;
            for (i = 0; i <= comboBox.Items.Count - 1; i++)
            {
                DataRowView cb;
                cb = (DataRowView)comboBox.Items[i];
                if (cb.Row.ItemArray[0].ToString() == value)// Change the 0 index if your want to Select by Text as 1 Index
                {
                    return i;
                }
            }
            return -1;
        }

What is the difference between java and core java?

Core Java is Sun Microsystem's, used to refer to Java SE. And there are Java ME and Java EE (J2EE). So this is told in order to differentiate with the Java ME and J2EE. So I feel Core Java is only used to mention J2SE.

Java having 3 category:

J2SE(Java to Standard Edition) - Core Java

J2EE(Java to Enterprises Edition)- Advance Java + Framework

J2ME(Java to Micro Edition)

Thank You..

Android Studio Google JAR file causing GC overhead limit exceeded error

Add this to build.gradle file

dexOptions {
   javaMaxHeapSize "2g"
}

How to set Meld as git mergetool

It took a few permutations to get meld working on windows for me. This is my current .gitconfig:

[merge]
    conflictstyle = diff3
    tool = meld
[mergetool "meld"]
    cmd = \"C:\\Program Files (x86)\\Meld\\Meld.exe\" --auto-merge \"$LOCAL\" \"$BASE\" \"$REMOTE\" --output \"$MERGED\"

Linux:

[merge]
    conflictstyle = diff3
    tool = meld
[mergetool "meld"]
    cmd = meld --auto-merge $LOCAL $BASE $REMOTE --output=$MERGED --diff $BASE $LOCAL --diff $BASE $REMOTE

I believe adding conflictstyle = diff3 changes the inline text to include BASE contents in the output file before meld gets to it, which might give it a head start. Not sure.

Now, since I already noted Meld supports three-way merging, there is another option. When “diff3” git conflict style is set, Meld prints “(??)” on the line showing the content from BASE. source

A few meld command line features I really like:

  • --auto-merge does a great job at choosing the right thing for you (it's not bulletproof, but I consider the time saved to be worth any risk).

  • You can add extra diff windows in the same command. E.g.:

    --diff $BASE $LOCAL --diff $BASE $REMOTE

    will add two more tabs with the local and incoming patch diffs. These can be quite useful to see separately from the 3 way view to see separate diffs from the base in each branch. I could't get this working on windows though.

  • Some version of meld allow you to label tabs with --label. This was more important before git fixed the names of the files passed to meld to include local/base/remote.

  • The order of --diff can affect the tab order. I had trouble in some older versions that were putting the additional diffs first, when the main 3 way diff is far more frequently used.

How do I find out which keystore was used to sign an app?

Much easier way to view the signing certificate:

jarsigner.exe -verbose -verify -certs myapk.apk

This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.

What is console.log?

Quoting MDN Docs here

console — contains many methods that you can call to perform rudimentary debugging tasks, generally focused around logging various values to the browser's Web Console.

By far the most commonly-used method is console.log, which is used to log the current value contained inside a specific variable.

How to use in Javascript?

let myString = 'Hello World';
console.log(myString);

Also remember console is a part of global window object in the web browser. Thus the following is also technically correct but isn't used in practical scenario.

let myString = 'Hello World';
window.console.log(myString);

How to check if a date is in a given range?

Convert them into dates or timestamp integers and then just check of $date_from_user is <= $end_date and >= $start_date

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

In my case, it was related to the node version.

My project was using 12.18.3 but I was on 14.5.0

So npm rebuild node-sass didn't solve the issue on the wrong node version(14.5.0).

I switched to the correct version(12.18.3) so it worked.

What does "export" do in shell programming?

Exported variables such as $HOME and $PATH are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.

$ env | grep '^variable='
$                                 # No environment variable called variable
$ variable=Hello                  # Create local (non-exported) variable with value
$ env | grep '^variable='
$                                 # Still no environment variable called variable
$ export variable                 # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye   # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$

For more information, see the entry for the export builtin in the GNU Bash manual, and also the sections on command execution environment and environment.

Note that non-exported variables will be available to subshells run via ( ... ) and similar notations because those subshells are direct clones of the main shell:

$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$

The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.

Some information about subshells can be found under command grouping and command execution environment in the Bash manual.

VBA array sort function?

Take a look here:
Edit: The referenced source (allexperts.com) has since closed, but here are the relevant author comments:

There are many algorithms available on the web for sorting. The most versatile and usually the quickest is the Quicksort algorithm. Below is a function for it.

Call it simply by passing an array of values (string or numeric; it doesn't matter) with the Lower Array Boundary (usually 0) and the Upper Array Boundary (i.e. UBound(myArray).)

Example: Call QuickSort(myArray, 0, UBound(myArray))

When it's done, myArray will be sorted and you can do what you want with it.
(Source: archive.org)

Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub

Note that this only works with single-dimensional (aka "normal"?) arrays. (There's a working multi-dimensional array QuickSort here.)

Using isKindOfClass with Swift

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

Edit

As pointed out in @Kevin's answer, the correct way would be to use optional type cast operator as?. You can read more about it on the section Optional Chaining sub section Downcasting.

Edit 2

As pointed on the other answer by user @KPM, using the is operator is the right way to do it.

How do I get multiple subplots in matplotlib?

Iterating through all subplots sequentially:

fig, axes = plt.subplots(nrows, ncols)

for ax in axes.flatten():
    ax.plot(x,y)

Accessing a specific index:

for row in range(nrows):
    for col in range(ncols):
        axes[row,col].plot(x[row], y[col])

What is Ruby's double-colon `::`?

It is all about preventing definitions from clashing with other code linked in to your project. It means you can keep things separate.

For example you can have one method called "run" in your code and you will still be able to call your method rather than the "run" method that has been defined in some other library that you have linked in.

Configure apache to listen on port other than 80

If you are using Apache on Windows:

  1. Check the name of the Apache service with Win+R+services.msc+Enter (if it's not ApacheX.Y, it should have the name of the software you are using with apache, e.g.: "wampapache64");
  2. Start a command prompt as Administrator (using Win+R+cmd+Enter is not enough);
  3. Change to Apache's directory, e.g.: cd c:\wamp\bin\apache\apache2.4.9\bin;
  4. Check if the config file is OK with: httpd.exe -n "YourServiceName" -t (replace the service name by the one you found on step 1);
  5. Make sure that the service is stopped: httpd.exe -k stop -n "YourServiceName"
  6. Start it with: httpd.exe -k start -n "YourServiceName"
  7. If it starts alright, the problem is no longer there, but if you get:

    AH00072: make_sock: could not bind to address IP:PORT_NUMBER

    AH00451: no listening sockets available, shutting down

    If the port number is not the one you wanted to use, then open the Apache config file (e.g. C:\wamp\bin\apache\apache2.4.9\conf\httpd.conf open with a code editor or wordpad, but not notepad - it does not read new lines properly) and replace the number on the line that starts with Listen with the number of the port you want, save it and repeat step 6. If it is the one you wanted to use, then continue:

  8. Check the PID of the process that is using that port with Win+R+resmon+Enter, click on Network tab and then on Ports subtab;
  9. Kill it with: taskkill /pid NUMBER /f (/f forces it);
  10. Recheck resmon to confirm that the port is free now and repeat step 6.

This ensures that Apache's service was started properly, the configuration on virtual hosts config file as sarul mentioned (e.g.: C:\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf) is necessary if you are setting your files path in there and changing the port as well. If you change it again, remember to restart the service: httpd.exe -k restart -n "YourServiceName".

How to add an image to an svg container using D3.js

I do not know why, but the image should not be duplicated, tripled, etc ... should remove the previous one and load it again but with another rotation data. This is my code:

data.csv enter image description here

d3.csv("data/data.csv").then(function(data){
//console.log(data);
// Clean data
formattedData = data.map(function(id){
id.rot_1 = +id.rot_1;
        id.trans_1 = +id.trans_1;
        return id;
});
// First run of the visualization
update(formattedData[0]);})

$("#play-button")
.on("click", function(){
    var button = $(this);
    if (button.text() == "Play"){
        button.text("Pause");
        interval = setInterval(step, 1000);            
    }
    else {
        button.text("Play");
        clearInterval(interval);
    }})

function step(){
// At the end of our data, loop back
time = (time < 76) ? time+1 : 0
update(formattedData[time]); }

function update(data) {
// Standard transition time for the visualization
var t = d3.transition()
    .duration(1000);

//console.log(d3.selectAll(data));    
//console.log(data)

// original
var imgs1 = g.append("image") // en vez de g es svg
.attr("xlink:href", "img/picturetest.png");

// EXIT old elements not present in new data.
imgs1.exit()
    .attr("class", "exit")
    .selectAll("svg:image")
    .remove();

//console.log(data)

// ENTER new elements present in new data.
imgs1.enter()
    .append("svg:image") // svg:image
    //.attr("xlink:href", "img/picturetest.png")
    .attr("class", "enter")
    .merge(imgs1)
    .transition(t)
        .attr("x", 0) // 150
        .attr("y", 0) // 80
        .attr("width", 200)
        .attr("height", 200)
        .attr("transform", "rotate("+data.rot_1+") translate("+data.trans_1+")" ); }`

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

This is a improve code from @MiFi. This one order in abs but not excluding the negative values.

   def top_correlation (df,n):
    corr_matrix = df.corr()
    correlation = (corr_matrix.where(np.triu(np.ones(corr_matrix.shape), k=1).astype(np.bool))
                 .stack()
                 .sort_values(ascending=False))
    correlation = pd.DataFrame(correlation).reset_index()
    correlation.columns=["Variable_1","Variable_2","Correlacion"]
    correlation = correlation.reindex(correlation.Correlacion.abs().sort_values(ascending=False).index).reset_index().drop(["index"],axis=1)
    return correlation.head(n)

top_correlation(ANYDATA,10)

Returning JSON response from Servlet to Javascript/JSP page

I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?

If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON

Difference between core and processor

Let's clarify first what is a CPU and what is a core, a central processing unit CPU, can have multiple core units, those cores are a processor by itself, capable of execute a program but it is self contained on the same chip.

In the past one CPU was distributed among quite a few chips, but as Moore's Law progressed they made to have a complete CPU inside one chip (die), since the 90's the manufacturer's started to fit more cores in the same die, so that's the concept of Multi-core.

In these days is possible to have hundreds of cores on the same CPU (chip or die) GPUs, Intel Xeon. Other technique developed in the 90's was simultaneous multi-threading, basically they found that was possible to have another thread in the same single core CPU, since most of the resources were duplicated already like ALU, multiple registers.

So basically a CPU can have multiple cores each of them capable to run one thread or more at the same time, we may expect to have more cores in the future, but with more difficulty to be able to program efficiently.

Why am I getting Unknown error in line 1 of pom.xml?

Simply add below maven jar version in properties tag in pom.xml, <maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>

Then follow below steps,

Step 1: mvn clean

Step 2 : update project

Problem solved for me! You should also try this :)

anaconda/conda - install a specific package version

To install a specific package:

conda install <pkg>=<version>

eg:

conda install matplotlib=1.4.3

How can I clear the SQL Server query cache?

EXEC sys.sp_configure N'max server memory (MB)', N'2147483646'
GO
RECONFIGURE WITH OVERRIDE
GO

What value you specify for the server memory is not important, as long as it differs from the current one.

Btw, the thing that causes the speedup is not the query cache, but the data cache.

IE11 Document mode defaults to IE7. How to reset?

By default, IE displays webpages in the Intranet zone in compatibility view. To change this:

  • Press Alt to display the IE menu.
  • Choose Tools | Compatibility View settings
  • Remove the checkmark next to Display intranet sites in Compatibility View.
  • Choose Close.

At this point, IE should rely on the webpage itself (or any relevant group policies) to determine the compatibility settings for your Intranet webpages.

Note that certain sites may no longer function correctly after making this change. You can use the same dialog box to add specific sites to enable compatibility view when needed.

Rails raw SQL example

You can also mix raw SQL with ActiveRecord conditions, for example if you want to call a function in a condition:

my_instances = MyModel.where.not(attribute_a: nil) \
  .where('crc32(attribute_b) = ?', slot) \
  .select(:id)

How do check if a PHP session is empty?

if(isset($_SESSION))
{}
else
{}

Can two or more people edit an Excel document at the same time?

The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.

I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=

Here is a discussion

http://blogs.msdn.com/b/sharepoint/archive/2009/10/19/sharepoint-2010.aspx

string sanitizer for filename

Well, tempnam() will do it for you.

http://us2.php.net/manual/en/function.tempnam.php

but that creates an entirely new name.

To sanitize an existing string just restrict what your users can enter and make it letters, numbers, period, hyphen and underscore then sanitize with a simple regex. Check what characters need to be escaped or you could get false positives.

$sanitized = preg_replace('/[^a-zA-Z0-9\-\._]/','', $filename);

LaTeX: remove blank page after a \part or \chapter

I believe that in the book class all \part and \chapter are set to start on a recto page.

from book.cls:

\newcommand\part{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \null\vfil
  \secdef\@part\@spart}

you should be able to renew that command, and something similar for the \chapter.

HTML Agility pack - parsing tables

How about something like: Using HTML Agility Pack

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
}

Note that you can make it prettier with LINQ-to-Objects if you want:

var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
            from row in table.SelectNodes("tr").Cast<HtmlNode>()
            from cell in row.SelectNodes("th|td").Cast<HtmlNode>()
            select new {Table = table.Id, CellText = cell.InnerText};

foreach(var cell in query) {
    Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}

"string could not resolved" error in Eclipse for C++ (Eclipse can't resolve standard library)

I had the same problem. Adding include path does work for all except std::string.

I noticed in the mingw-Toolchain many system header files *.tcc

I added filetype *.tcc as "C++ Header File" in Preferences > C/C++/ File Types. Now std::string can be resolved from the internal index and Code Analyzer. Perhaps this is added to Eclipse CDT by default in feature.

I hope this helps to someone...

PS: I'm using Eclipse Mars, mingw gcc 4.8.1, Own Makefile, no Eclipse Makefilebuilder.

What is the proper way to check if a string is empty in Perl?

For string comparisons in Perl, use eq or ne:

if ($str eq "")
{
  // ...
}

The == and != operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.

See the perlop man page for more information.

What does 'low in coupling and high in cohesion' mean

An example might be helpful. Imagine a system which generates data and puts it into a data store, either a file on disk or a database.

High Cohesion can be achieved by separate the data store code from the data production code. (and in fact separating the disk storage from the database storage).

Low Coupling can be achieved by making sure that the data production doesn't have any unnecessary knowledge of the data store (e.g. doesn't ask the data store about filenames or db connections).

How to enable CORS in ASP.net Core WebAPI

.NET Core 3.1

Worked for me and how the docs say to do it:

in Startup class:

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins"; 

In ConfigureServices() method:

    services.AddCors(options =>
    {
        options.AddPolicy(MyAllowSpecificOrigins,
        builder =>
        {
            builder.WithOrigins("http://example.com",
                                "http://www.contoso.com");
        });
    });

In Configure() method:

    app.UseCors(MyAllowSpecificOrigins);  

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

Local Storage vs Cookies

It is also worth mentioning that localStorage cannot be used when users browse in "private" mode in some versions of mobile Safari.

Quoted from MDN (https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage):

Note: Starting with iOS 5.1, Safari Mobile stores localStorage data in the cache folder, which is subject to occasional clean up, at the behest of the OS, typically if space is short. Safari Mobile's Private Browsing mode also prevents writing to localStorage entirely.

Regex match text between tags

Try

str.match(/<b>(.*?)<\/b>/g);

How to add multiple classes to a ReactJS Component?

I use classnames when there is a fair amount of logic required for deciding the classes to (not) use. An overly simple example:

...
    var liClasses = classNames({
      'main-class': true,
      'activeClass': self.state.focused === index
    });

    return (<li className={liClasses}>{data.name}</li>);
...

That said, if you don't want to include a dependency then there are better answers below.

How do I concatenate two lists in Python?

Use a simple list comprehension:

joined_list = [item for list_ in [list_one, list_two] for item in list_]

It has all the advantages of the newest approach of using Additional Unpacking Generalizations - i.e. you can concatenate an arbitrary number of different iterables (for example, lists, tuples, ranges, and generators) that way - and it's not limited to Python 3.5 or later.

Receive JSON POST with PHP

Read the doc:

In general, php://input should be used instead of $HTTP_RAW_POST_DATA.

as in the php Manual

Get current URL path in PHP

You want $_SERVER['REQUEST_URI']. From the docs:

'REQUEST_URI'

The URI which was given in order to access this page; for instance, '/index.html'.

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Try to use the argument: -sysdir <Your_SDK_DIR> and then check whether the error message displayed.

See also: https://android.googlesource.com/platform/external/qemu/+/1a15692cded92d66dea1a51389a3c4b9e3b3631a/android/emulator/main-emulator.cpp

Check out these clip you will find out the reason:

// Sanity checks.
if (avdName) {
    if (!isCpuArchSupportedByRanchu(avdArch)) {
        APANIC("CPU Architecture '%s' is not supported by the QEMU2 emulator, (the classic engine is deprecated!)",
               avdArch);
    }
    std::string systemPath = getAvdSystemPath(avdName, sysDir);
    if (systemPath.empty()) {
        const char* env = getenv("ANDROID_SDK_ROOT");
        if (!env || !env[0]) {
            APANIC("Cannot find AVD system path. Please define "
                   "ANDROID_SDK_ROOT\n");
        } else {
            APANIC("Broken AVD system path. Check your ANDROID_SDK_ROOT "
                   "value [%s]!\n",
                   env);
        }
    }
}

Then if you see emulator: ERROR: can't find SDK installation directory, please check this solution. Android emulator errors with "emulator: ERROR: can't find SDK installation directory"

MVC 3: How to render a view without its layout page when loaded via ajax?

You don't have to create an empty view for this.

In the controller:

if (Request.IsAjaxRequest())
  return PartialView();
else
  return View();

returning a PartialViewResult will override the layout definition when rendering the respons.

Downloading and unzipping a .zip file without writing to disk

My suggestion would be to use a StringIO object. They emulate files, but reside in memory. So you could do something like this:

# get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo'

import zipfile
from StringIO import StringIO

zipdata = StringIO()
zipdata.write(get_zip_data())
myzipfile = zipfile.ZipFile(zipdata)
foofile = myzipfile.open('foo.txt')
print foofile.read()

# output: "hey, foo"

Or more simply (apologies to Vishal):

myzipfile = zipfile.ZipFile(StringIO(get_zip_data()))
for name in myzipfile.namelist():
    [ ... ]

In Python 3 use BytesIO instead of StringIO:

import zipfile
from io import BytesIO

filebytes = BytesIO(get_zip_data())
myzipfile = zipfile.ZipFile(filebytes)
for name in myzipfile.namelist():
    [ ... ]

Capture iOS Simulator video for App Preview

A tip for users who like to use ZSH functions. You can simplify things a little by adding a function that does the same thing as @Tikhonov Alexander's answer.

Start out by typing:

edit ~/.zshrc

into your terminal.

Then add this function someplace in the file.

function recsim() {
    echo -n "Use CTRL+C to stop recording";
    xcrun simctl io booted recordVideo --codec=h264 --mask=black "$1.mp4";
}

To use, type something like:

recsim appPreview

into your terminal window. Note: Terminal must be restarted after adding the function before it will work.

This function is adapted from Antoine Van Der Lee's blog post on how to do this in bash, which can be found here.

When to use Hadoop, HBase, Hive and Pig?

Short answer to this question is -

Hadoop - Is Framework which facilitates distributed file system and programming model which allow us to store humongous sized data and process data in distributed fashion very efficiently and with very less processing time compare to traditional approaches.

(HDFS - Hadoop Distributed File system) (Map Reduce - Programming Model for distributed processing)

Hive - Is query language which allows to read/write data from Hadoop distributed file system in a very popular SQL like fashion. This made life easier for many non-programming background people as they don't have to write Map-Reduce program anymore except for very complex scenarios where Hive is not supported.

Hbase - Is Columnar NoSQL Database. Underlying storage layer for Hbase is again HDFS. Most important use case for this database is to be able to store billion's of rows with million's of columns. Low latency feature of Hbase helps faster and random access of record over distributed data, is very important feature to make it useful for complex projects like Recommender Engines. Also it's record level versioning capability allow user to store transactional data very efficiently (this solves the problem of updating records we have with HDFS and Hive)

Hope this is helpful to quickly understand the above 3 features.

Jupyter/IPython Notebooks: Shortcut for "run all"?

There is a menu shortcut to run all cells under Cell > "Run All". This isn't bound to a keyboard shortcut by default- you'll have to define your own custom binding from within the notebook, as described here.

For example, to add a keyboard binding that lets you run all the cells in a notebook, you can insert this in a cell:

%%javascript

Jupyter.keyboard_manager.command_shortcuts.add_shortcut('r', {
    help : 'run all cells',
    help_index : 'zz',
    handler : function (event) {
        IPython.notebook.execute_all_cells();
        return false;
    }}
);

If you run this code from within iPython notebook, you should find that you now have a keyboard binding to run all cells (in this case, press ctrl-M followed by r)

Java enum with multiple value types

First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.

Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.

Here's how you should do it with all the suggestions above:

public enum States {
    ...
    MASSACHUSETTS("Massachusetts",  "MA",   true),
    MICHIGAN     ("Michigan",       "MI",   false),
    ...; // all 50 of those

    private final String full;
    private final String abbr;
    private final boolean originalColony;

    private States(String full, String abbr, boolean originalColony) {
        this.full = full;
        this.abbr = abbr;
        this.originalColony = originalColony;
    }

    public String getFullName() {
        return full;
    }

    public String getAbbreviatedName() {
        return abbr;
    }

    public boolean isOriginalColony(){
        return originalColony;
    }
}

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

How do I count occurrence of duplicate items in array

There is a magical function PHP is offering to you it called in_array().

Using parts of your code we will modify the loop as follows:

<?php
$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$arr2 = array();
$counter = 0;
for($arr = 0; $arr < count($array); $arr++){
    if (in_array($array[$arr], $arr2)) {
        ++$counter;
        continue;
    }
    else{
        $arr2[] = $array[$arr];
    }
}
echo 'number of duplicates: '.$counter;
print_r($arr2);
?>

The above code snippet will return the number total number of repeated items i.e. form the sample array 43 is repeated 5 times, 78 is repeated 1 time and 21 is repeated 1 time, then it returns an array without repeat.

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

another way is to use certutil.exe save your username and password in a file e.g. in.txt as username:password

certutil -encode in.txt out.txt

Now you should be able to use auth value from out.txt

$headers = @{ Authorization = "Basic $((get-content out.txt)[1])" }
Invoke-WebRequest -Uri 'https://whatever' -Headers $Headers

"Unmappable character for encoding UTF-8" error

The following compiles for me:

class E{
   String s = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~#;:?/@&!\"'%*=¼.,-])(?=[^\\s]+$).{8,24}$";
}

See:

enter image description here

inner join in linq to entities

var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

Using Extension methods:

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

Why can't I see the "Report Data" window when creating reports?

It is in visual studio. In the designer page, it is on in the menu bar, there is XTRAREPORTS field. You can show up panels using it

XmlSerializer: remove unnecessary xsi and xsd namespaces

I'm using:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        const string DEFAULT_NAMESPACE = "http://www.something.org/schema";
        var serializer = new XmlSerializer(typeof(Person), DEFAULT_NAMESPACE);
        var namespaces = new XmlSerializerNamespaces();
        namespaces.Add("", DEFAULT_NAMESPACE);

        using (var stream = new MemoryStream())
        {
            var someone = new Person
            {
                FirstName = "Donald",
                LastName = "Duck"
            };
            serializer.Serialize(stream, someone, namespaces);
            stream.Position = 0;
            using (var reader = new StreamReader(stream))
            {
                Console.WriteLine(reader.ReadToEnd());
            }
        }
    }
}

To get the following XML:

<?xml version="1.0"?>
<Person xmlns="http://www.something.org/schema">
  <FirstName>Donald</FirstName>
  <LastName>Duck</LastName>
</Person>

If you don't want the namespace, just set DEFAULT_NAMESPACE to "".

The specified child already has a parent. You must call removeView() on the child's parent first

frameLayout.addView(yourView); <----- if you are getting error on this line remove view from it's parent first

if (yourView.getParent() != null)

((ViewGroup) yourView.getParent()).removeView(yourView); frameLayout.addView(yourView); (Add view to layout)

java.math.BigInteger cannot be cast to java.lang.Long

Try to convert the BigInteger to a long like this

Long longNumber= bigIntegerNumber.longValue();

How to get object length

One more answer:

_x000D_
_x000D_
var j = '[{"uid":"1","name":"Bingo Boy", "profile_img":"funtimes.jpg"},{"uid":"2","name":"Johnny Apples", "profile_img":"badtime.jpg"}]';_x000D_
_x000D_
obj = Object.keys(j).length;_x000D_
console.log(obj)
_x000D_
_x000D_
_x000D_

Ignoring upper case and lower case in Java

use toUpperCase() or toLowerCase() method of String class.

Is there a way to take a screenshot using Java and save it to some sort of image?

If you'd like to capture all monitors, you can use the following code:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();

Rectangle allScreenBounds = new Rectangle();
for (GraphicsDevice screen : screens) {
    Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();

    allScreenBounds.width += screenBounds.width;
    allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);
}

Robot robot = new Robot();
BufferedImage screenShot = robot.createScreenCapture(allScreenBounds);

Fitting polynomial model to data in R

Which model is the "best fitting model" depends on what you mean by "best". R has tools to help, but you need to provide the definition for "best" to choose between them. Consider the following example data and code:

x <- 1:10
y <- x + c(-0.5,0.5)

plot(x,y, xlim=c(0,11), ylim=c(-1,12))

fit1 <- lm( y~offset(x) -1 )
fit2 <- lm( y~x )
fit3 <- lm( y~poly(x,3) )
fit4 <- lm( y~poly(x,9) )
library(splines)
fit5 <- lm( y~ns(x, 3) )
fit6 <- lm( y~ns(x, 9) )

fit7 <- lm( y ~ x + cos(x*pi) )

xx <- seq(0,11, length.out=250)
lines(xx, predict(fit1, data.frame(x=xx)), col='blue')
lines(xx, predict(fit2, data.frame(x=xx)), col='green')
lines(xx, predict(fit3, data.frame(x=xx)), col='red')
lines(xx, predict(fit4, data.frame(x=xx)), col='purple')
lines(xx, predict(fit5, data.frame(x=xx)), col='orange')
lines(xx, predict(fit6, data.frame(x=xx)), col='grey')
lines(xx, predict(fit7, data.frame(x=xx)), col='black')

Which of those models is the best? arguments could be made for any of them (but I for one would not want to use the purple one for interpolation).

Googlemaps API Key for Localhost

It didn't work for me when I used

http://localhost{port}/
http://localhost:{port}/something-else/here

However, removing the http did the trick for me. I just added localhost:8000 without prefixing it with the http.

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Proper way to initialize a C# dictionary with values?

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

Convert floats to ints in Pandas?

Use the pandas.DataFrame.astype(<type>) function to manipulate column dtypes.

>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

EDIT:

To handle missing values:

>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Value cannot be null. Parameter name: source

In my case, the problem popped up while configuring the web application on IIS, When the update command on any record was fired this error got generated.

It was a permission issue on App_Data which set to read-only. Right-click the folder, uncheck the Read-only checkbox and you are done. By the way, for testing purpose, I was using the localdb database which was in App_Data folder.

What's the best/easiest GUI Library for Ruby?

Ruby Shoes (by why) is intended to be a really simple GUI framework. I don't know how fully featured it is, though.

Some good code samples can be found in the tutorials.

Also, I think shoes powers hackety hack, a compelling programming learning environment for youngsters.

How to check if a particular service is running on Ubuntu

For centos, below command worked for me (:

locate postgres | grep service

Output:

/usr/lib/firewalld/services/postgresql.xml

/usr/lib/systemd/system/postgresql-9.3.service

sudo systemctl status postgresql-9.3.service

convert iso date to milliseconds in javascript

var date = new Date()
console.log(" Date in MS last three digit = "+  date.getMilliseconds())
console.log(" MS = "+ Date.now())

Using this we can get date in milliseconds

How do I activate a Spring Boot profile when running from IntelliJ?

I use the Intellij Community Edition. Go to the "Run/Debug Configurations" > Runner tab > Environment variables > click button "...". Add: SPRING_PROFILES_ACTIVE = local

spring.profiles.active

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table:

student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
                                                        # "link back" if you need

You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).

One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:

teachers: teacher_id, first_name, last_name # the "one" side
classes:  class_id, class_name, teacher_id  # the "many" side

Many-to-many: Use a junction table (example):

student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id     # the junction table

Example queries:

 -- Getting all students for a class:

    SELECT s.student_id, last_name
      FROM student_classes sc 
INNER JOIN students s ON s.student_id = sc.student_id
     WHERE sc.class_id = X

 -- Getting all classes for a student: 

    SELECT c.class_id, name
      FROM student_classes sc 
INNER JOIN classes c ON c.class_id = sc.class_id
     WHERE sc.student_id = Y

Angular 4: How to include Bootstrap?

Adding bootstrap current version 4 to angular:

1/ First you have to install those:

npm install jquery --save
npm install popper.js --save
npm install bootstrap --save

2/ Then add the needed script files to scripts in angular.json:

"scripts": [
  "node_modules/jquery/dist/jquery.slim.js",
  "node_modules/popper.js/dist/umd/popper.js",
  "node_modules/bootstrap/dist/js/bootstrap.js"
],

3/Finally add the Bootstrap CSS to the styles array in angular.json:

"styles": [
  "node_modules/bootstrap/dist/css/bootstrap.css",
  "src/styles.css"
],`

check this link

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

Magento: Set LIMIT on collection

You can Implement this also:- setPage(1, n); where, n = any number.

$products = Mage::getResourceModel('catalog/product_collection')
                ->addAttributeToSelect('*')
                ->addAttributeToSelect(array('name', 'price', 'small_image'))
                ->addFieldToFilter('visibility', Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH) //visible only catalog & searchable product
                ->addAttributeToFilter('status', 1) // enabled
                ->setStoreId($storeId)
                ->setOrder('created_at', 'desc')
                ->setPage(1, 6);

How to Install Windows Phone 8 SDK on Windows 7

Here is a link from developer.nokia.com wiki pages, which explains how to install Windows Phone 8 SDK on a Virtual Machine with Working Emulator

And another link here

AFAIK, it is not possible to directly install WP8 SDK in Windows 7, because WP8 sdk is VS 2012 supported and also its emulator works on a Hyper-V (which is integrated into the Windows 8).

Reading specific XML elements from XML file

XDocument xdoc = XDocument.Load(path_to_xml);
var word = xdoc.Elements("word")
               .SingleOrDefault(w => (string)w.Element("category") == "verb");

This query will return whole word XElement. If there is more than one word element with category verb, than you will get an InvalidOperationException. If there is no elements with category verb, result will be null.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Create a data.frame with m columns and 2 rows

Does m really need to be a data.frame() or will a matrix() suffice?

m <- matrix(0, ncol = 30, nrow = 2)

You can wrap a data.frame() around that if you need to:

m <- data.frame(m)

or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))

cocoapods - 'pod install' takes forever

Sometimes happen to me too and I simply:

pod clean
pod update --verbose

VBA Date as integer

Just use CLng(Date).

Note that you need to use Long not Integer for this as the value for the current date is > 32767

What is a StackOverflowError?

Here is an example of a recursive algorithm for reversing a singly linked list. On a laptop with the following spec (4G memory, Intel Core i5 2.3GHz CPU, 64 bit Windows 7), this function will run into StackOverflow error for a linked list of size close to 10,000.

My point is that we should use recursion judiciously, always taking into account of the scale of the system. Often recursion can be converted to iterative program, which scales better. (One iterative version of the same algorithm is given at the bottom of the page, it reverses a singly linked list of size 1 million in 9 milliseconds.)

    private static LinkedListNode doReverseRecursively(LinkedListNode x, LinkedListNode first){

    LinkedListNode second = first.next;

    first.next = x;

    if(second != null){
        return doReverseRecursively(first, second);
    }else{
        return first;
    }
}

public static LinkedListNode reverseRecursively(LinkedListNode head){
    return doReverseRecursively(null, head);
}

Iterative Version of the Same Algorithm:

    public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);
}   

private static LinkedListNode doReverseIteratively(LinkedListNode x, LinkedListNode first) {

    while (first != null) {
        LinkedListNode second = first.next;
        first.next = x;
        x = first;

        if (second == null) {
            break;
        } else {
            first = second;
        }
    }
    return first;
}


public static LinkedListNode reverseIteratively(LinkedListNode head){
    return doReverseIteratively(null, head);
}

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

How to get the path of running java program

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

Highlight text similar to grep, but don't filter out text

You can make sure that all lines match but there is nothing to highlight on irrelevant matches

egrep --color 'apple|' test.txt 

Notes:

  • egrep may be spelled also grep -E
  • --color is usually default in most distributions
  • some variants of grep will "optimize" the empty match, so you might want to use "apple|$" instead (see: https://stackoverflow.com/a/13979036/939457)

How to specify credentials when connecting to boto3 S3?

I'd like expand on @JustAGuy's answer. The method I prefer is to use AWS CLI to create a config file. The reason is, with the config file, the CLI or the SDK will automatically look for credentials in the ~/.aws folder. And the good thing is that AWS CLI is written in python.

You can get cli from pypi if you don't have it already. Here are the steps to get cli set up from terminal

$> pip install awscli  #can add user flag 
$> aws configure
AWS Access Key ID [****************ABCD]:[enter your key here]
AWS Secret Access Key [****************xyz]:[enter your secret key here]
Default region name [us-west-2]:[enter your region here]
Default output format [None]:

After this you can access boto and any of the api without having to specify keys (unless you want to use a different credentials).

ASP.NET file download from server

Simple solution for downloading a file from the server:

protected void btnDownload_Click(object sender, EventArgs e)
        {
            string FileName = "Durgesh.jpg"; // It's a file name displayed on downloaded file on client side.

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "image/jpeg";
            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            response.TransmitFile(Server.MapPath("~/File/001.jpg"));
            response.Flush();
            response.End();
        }

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Binary Data in JSON String. Something better than Base64

Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.

A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.

And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.

Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.

Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.

Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).

How can I get the error message for the mail() function?

You can use the PEAR mailer, which has the same interface, but returns a PEAR_Error when there is problems.

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

npm command to uninstall or prune unused packages in Node.js

Note: Recent npm versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production flag.


Run npm prune to remove modules not listed in package.json.

From npm help prune:

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified, this command will remove the packages specified in your devDependencies.

How to write to a file in Scala?

Unfortunately for the top answer, Scala-IO is dead. If you don't mind using a third-party dependency, consider using my OS-Lib library. This makes working with files, paths and the filesystem very easy:

// Make sure working directory exists and is empty
val wd = os.pwd/"out"/"splash"
os.remove.all(wd)
os.makeDir.all(wd)

// Read/write files
os.write(wd/"file.txt", "hello")
os.read(wd/"file.txt") ==> "hello"

// Perform filesystem operations
os.copy(wd/"file.txt", wd/"copied.txt")
os.list(wd) ==> Seq(wd/"copied.txt", wd/"file.txt")

It has one-liners for writing to files, appending to files, overwriting files, and many other useful/common operations

"You may need an appropriate loader to handle this file type" with Webpack and Babel

In my case, I had such error since import path was wrong:

Wrong: import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)

Correct: import Select from "react-select";

Git update submodules recursively

The way I use is:

git submodule update --init --recursive
git submodule foreach --recursive git fetch
git submodule foreach git merge origin master

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

npm install gives error "can't find a package.json file"

>> For Visual Studio Users using Package Manager Console <<

If you are using the Package Manager Console in Visual Studio and you want to execute:

npm install and get:

ENOENT: no such file or directory, open 'C:\Users...\YourProject\package.json'

Verify that you are executing the command in the correct directory.

VS by default uses the solution folder when opening the Package Manager Console.

Execute dir then you can see in which folder you currently are. Most probably in the solution folder, that's why you get this error. Now you have to cd to your project folder.

cd YourWebProject

Now npm install should work now, if not, then you have another issue.

java.net.BindException: Address already in use: JVM_Bind <null>:80

I faced this problem while working in a spring project with tomcat:

Address already in use: JVM_Bind

screenshot of bin folder

To resolve the issue I ran a shutdown.bat file in tomcat/bin folder.

Adding an image to a PDF using iTextSharp and scale it properly

You can try something like this:

      Image logo = Image.GetInstance("pathToTheImage")
      logo.ScaleAbsolute(500, 300)

How do I test if a variable does not equal either of two values?

ECMA2016 Shortest answer, specially good when checking againt multiple values:

if (!["A","B", ...].includes(test)) {}

How to change the background color on a Java panel?

setBackground() is the right method to use. Did you repaint after you changed it? If you change it before you make the panel (or its containing frame) visible it should work

Is there a minlength validation attribute in HTML5?

minlength attribute is now widely supported in most of the browsers.

<input type="text" minlength="2" required>

But, as with other HTML5 features, IE11 is missing from this panorama. So, if you have a wide IE11 user base, consider using the pattern HTML5 attribute that is supported almost across the board in most browsers (including IE11).

To have a nice and uniform implementation and maybe extensible or dynamic (based on the framework that generate your HTML), I would vote for the pattern attribute:

<input type="text" pattern=".{2,}" required>

There is still a small usability catch when using pattern. The user will see a non-intuitive (very generic) error/warning message when using pattern. See this jsfiddle or below:

_x000D_
_x000D_
<h3>In each form type 1 character and press submit</h3>_x000D_
</h2>_x000D_
<form action="#">_x000D_
  Input with minlength: <input type="text" minlength="2" required name="i1">_x000D_
  <input type="submit" value="Submit">_x000D_
</form>_x000D_
<br>_x000D_
<form action="#">_x000D_
  Input with patern: <input type="text" pattern=".{2,}" required name="i1">_x000D_
  <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

For example, in Chrome (but similar in most browsers), you will get the following error messages:

Please lengthen this text to 2 characters or more (you are currently using 1 character)

by using minlength and

Please match the format requested

by using pattern.

jQuery Get Selected Option From Dropdown

You can select using exact selected option : Below will give innerText

$("select#aioConceptName > option:selected").text()

While below will give you value.

$("select#aioConceptName > option:selected").val()

How to round a number to significant figures in Python

Given a question so thoroughly answered why not add another

This suits my aesthetic a little better, though many of the above are comparable

import numpy as np

number=-456.789
significantFigures=4

roundingFactor=significantFigures - int(np.floor(np.log10(np.abs(number)))) - 1
rounded=np.round(number, roundingFactor)

string=rounded.astype(str)

print(string)

This works for individual numbers and numpy arrays, and should function fine for negative numbers.

There's one additional step we might add - np.round() returns a decimal number even if rounded is an integer (i.e. for significantFigures=2 we might expect to get back -460 but instead we get -460.0). We can add this step to correct for that:

if roundingFactor<=0:
    rounded=rounded.astype(int)

Unfortunately, this final step won't work for an array of numbers - I'll leave that to you dear reader to figure out if you need.

Are global variables bad?

In web applications within an enterprize can be used for holding session/window/thread/user specific data on the server for reasons of optimization and to preserve against loss of work where connection are unstable. As mentioned, race conditions need to be handled. We use a single instance of a class for this information and it is carefully managed.

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

Editor does not contain a main type

Try 'Update Project'. Once I did this, The Run as Java Application option appeared.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

you have to check your pip package to be updated to the latest version in your pycharm and then install numpy package. in settings -> project:progLangComp -> Project Interpreter there is a table of packages and their current version (just labelled as Version) and their latest version (labelled as Latest). Pip current version number should be the same as latest version. If you see a blue arrow in front of pip, you have to update it to the latest then trying to install numpy or any other packages that you couldn't install, for me it was pandas which I wanted to install.

enter image description here

Why can't I initialize non-const static member or static array in class?

Why I can't initialize static data members in class?

The C++ standard allows only static constant integral or enumeration types to be initialized inside the class. This is the reason a is allowed to be initialized while others are not.

Reference:
C++03 9.4.2 Static data members
§4

If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

What are integral types?

C++03 3.9.1 Fundamental types
§7

Types bool, char, wchar_t, and the signed and unsigned integer types are collectively called integral types.43) A synonym for integral type is integer type.

Footnote:

43) Therefore, enumerations (7.2) are not integral; however, enumerations can be promoted to int, unsigned int, long, or unsigned long, as specified in 4.5.

Workaround:

You could use the enum trick to initialize an array inside your class definition.

class A 
{
    static const int a = 3;
    enum { arrsize = 2 };

    static const int c[arrsize] = { 1, 2 };

};

Why does the Standard does not allow this?

Bjarne explains this aptly here:

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

Why are only static const integral types & enums allowed In-class Initialization?

The answer is hidden in Bjarne's quote read it closely,
"C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects."

Note that only static const integers can be treated as compile time constants. The compiler knows that the integer value will not change anytime and hence it can apply its own magic and apply optimizations, the compiler simply inlines such class members i.e, they are not stored in memory anymore, As the need of being stored in memory is removed, it gives such variables the exception to rule mentioned by Bjarne.

It is noteworthy to note here that even if static const integral values can have In-Class Initialization, taking address of such variables is not allowed. One can take the address of a static member if (and only if) it has an out-of-class definition.This further validates the reasoning above.

enums are allowed this because values of an enumerated type can be used where ints are expected.see citation above


How does this change in C++11?

C++11 relaxes the restriction to certain extent.

C++11 9.4.2 Static data members
§3

If a static data member is of const literal type, its declaration in the class definition can specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. [ Note: In both these cases, the member may appear in constant expressions. —end note ] The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Also, C++11 will allow(§12.6.2.8) a non-static data member to be initialized where it is declared(in its class). This will mean much easy user semantics.

Note that these features have not yet been implemented in latest gcc 4.7, So you might still get compilation errors.

How to drop all tables in a SQL Server database?

Short and sweet:

USE YOUR_DATABASE_NAME
-- Disable all referential integrity constraints
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

-- Drop all PKs and FKs
declare @sql nvarchar(max)
SELECT @sql = STUFF((SELECT '; ' + 'ALTER TABLE ' + Table_Name  +'  drop constraint ' + Constraint_Name  from Information_Schema.CONSTRAINT_TABLE_USAGE ORDER BY Constraint_Name FOR XML PATH('')),1,1,'')
EXECUTE (@sql)
GO

-- Drop all tables
EXEC sp_MSforeachtable 'DROP TABLE ?'
GO

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

How to split string using delimiter char using T-SQL?

You need a split function:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Create Function [dbo].[udf_Split]
(   
    @DelimitedList nvarchar(max)
    , @Delimiter nvarchar(2) = ','
)
RETURNS TABLE 
AS
RETURN 
    (
    With CorrectedList As
        (
        Select Case When Left(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            + @DelimitedList
            + Case When Right(@DelimitedList, Len(@Delimiter)) <> @Delimiter Then @Delimiter Else '' End
            As List
            , Len(@Delimiter) As DelimiterLen
        )
        , Numbers As 
        (
        Select TOP( Coalesce(DataLength(@DelimitedList)/2,0) ) Row_Number() Over ( Order By c1.object_id ) As Value
        From sys.columns As c1
            Cross Join sys.columns As c2
        )
    Select CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen As Position
        , Substring (
                    CL.List
                    , CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen     
                    , CharIndex(@Delimiter, CL.list, N.Value + 1)                           
                        - ( CharIndex(@Delimiter, CL.list, N.Value) + CL.DelimiterLen ) 
                    ) As Value
    From CorrectedList As CL
        Cross Join Numbers As N
    Where N.Value <= DataLength(CL.List) / 2
        And Substring(CL.List, N.Value, CL.DelimiterLen) = @Delimiter
    )

With your split function, you would then use Cross Apply to get the data:

Select T.Col1, T.Col2
    , Substring( Z.Value, 1, Charindex(' = ', Z.Value) - 1 ) As AttributeName
    , Substring( Z.Value, Charindex(' = ', Z.Value) + 1, Len(Z.Value) ) As Value
From Table01 As T
    Cross Apply dbo.udf_Split( T.Col3, '|' ) As Z

Using GSON to parse a JSON array

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

Seems to work fine. But there is an extra , Comma in your string.

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

Java: get greatest common divisor

Those GCD functions provided by Commons-Math and Guava have some differences.

  • Commons-Math throws an ArithematicException.class only for Integer.MIN_VALUE or Long.MIN_VALUE.
    • Otherwise, handles the value as an absolute value.
  • Guava throws an IllegalArgumentException.class for any negative values.

Animate scroll to ID on page load

Pure javascript solution with scrollIntoView() function:

_x000D_
_x000D_
document.getElementById('title1').scrollIntoView({block: 'start', behavior: 'smooth'});
_x000D_
<h2 id="title1">Some title</h2>
_x000D_
_x000D_
_x000D_

P.S. 'smooth' parameter now works from Chrome 61 as julien_c mentioned in the comments.

Advantages of std::for_each over for loop

Like many of the algorithm functions, an initial reaction is to think it's more unreadable to use foreach than a loop. It's been a topic of many flame wars.

Once you get used to the idiom you may find it useful. One obvious advantage is that it forces the coder to separate the inner contents of the loop from the actual iteration functionality. (OK, I think it's an advantage. Other's say you're just chopping up the code with no real benifit).

One other advantage is that when I see foreach, I know that either every item will be processed or an exception will be thrown.

A for loop allows several options for terminating the loop. You can let the loop run its full course, or you can use the break keyword to explicitly jump out of the loop, or use the return keyword to exit the entire function mid-loop. In contrast, foreach does not allow these options, and this makes it more readable. You can just glance at the function name and you know the full nature of the iteration.

Here's an example of a confusing for loop:

for(std::vector<widget>::iterator i = v.begin(); i != v.end(); ++i)
{
   /////////////////////////////////////////////////////////////////////
   // Imagine a page of code here by programmers who don't refactor
   ///////////////////////////////////////////////////////////////////////
   if(widget->Cost < calculatedAmountSofar)
   {
        break;
   }
   ////////////////////////////////////////////////////////////////////////
   // And then some more code added by a stressed out juniour developer
   // *#&$*)#$&#(#)$#(*$&#(&*^$#(*$#)($*#(&$^#($*&#)$(#&*$&#*$#*)$(#*
   /////////////////////////////////////////////////////////////////////////
   for(std::vector<widgetPart>::iterator ip = widget.GetParts().begin(); ip != widget.GetParts().end(); ++ip)
   {
      if(ip->IsBroken())
      {
         return false;
      }
   }
}

Clear text from textarea with selenium

In my experience, this turned out to be the most efficient

driver.find_element_by_css_selector('foo').send_keys(u'\ue009' + u'\ue003')

We are sending Ctrl + Backspace to delete all characters from the input, you can also replace backspace with delete.

EDIT: removed Keys dependency

Efficient way to determine number of digits in an integer

for integer 'X' you want to know the number of digits , alright without using any loop , this solution act in one formula in one line only so this is the most optimal solution i have ever seen to this problem .

 int x = 1000 ; 
 cout<<numberOfDigits = 1+floor(log10(x))<<endl ; 

ORA-00972 identifier is too long alias column name

If you have recently upgraded springboot to 1.4.3, you might need to make changes to yml file:

yml in 1.3 :

jpa: 
  hibernate: 
    namingStrategy: org.hibernate.cfg.EJB3NamingStrategy

yml in 1.4.3 :

jpa: 
  hibernate: 
    naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

How to dismiss keyboard for UITextView with return key?

I know this has been answered a lot of times, but here are my two cents to the issue.

I found the answers by samvermette and ribeto really useful, and also the comment by maxpower in the ribeto's answer. But there is a problem with those approaches. The problem that matt mentions in the samvermette's answer and it's that if the user wants to paste something with a line break inside it, the keyboard would hide without pasting anything.

So my approach is a mixture of the three above mentioned solutions and only checking if the string entered is a new line when the length of the string is 1 so we make sure the user is typing instead of pasting.

Here is what I have done:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    NSRange resultRange = [text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet] options:NSBackwardsSearch];
    if ([text length] == 1 && resultRange.location != NSNotFound) {
        [textView resignFirstResponder];
        return NO;
    }

    return YES;
}

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

If you are using Ubuntu, Python has already been downloaded on your PC. so, go to -> ctrl + alt + s -> search interpreter -> go to project interpreter than select Python 3.6 in the dropdown menu.

Edit: If there is no Python interpreter in drop-down menu, you should click the gear icon that on the right of the drop-down menu --> add --> select an interpreter.

(on PyCharm 2018.2.4 Community Edition)

How do I find the maximum of 2 numbers?

You could also achieve the same result by using a Conditional Expression:

maxnum = run if run > value else value

a bit more flexible than max but admittedly longer to type.

invalid types 'int[int]' for array subscript

You're trying to access a 3 dimensional array with 4 de-references

You only need 3 loops instead of 4, or int myArray[10][10][10][10];

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

I encountered a similar problem. I am using WinNMP. When I started it, MariaDB was also not running and prompts "Can't connect to MySQL server on '127.0.0.1' (10061) (2003)" whenever I try to connect to a database.

Just want to help. For WinNMP users like me, this worked for me:

  1. Run msyqld installer located at "C:\WinNMP\bin\MariaDB\bin".
  2. Restart your WinNMP.
  3. MariaDB should be running now.

Hope this helps someone! :D

How do I check how many options there are in a dropdown menu?

$("#mydropdown option").length

Or if you already got a reference to it,

$(myDropdown).find("option").length

How to change the URL from "localhost" to something else, on a local system using wampserver?

WINDOWS + WAMP solution

Step 1
Go to C:\wamp\bin\apache\Apache2.2.17\conf\
open httpd.conf file and change
#Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.

Step 2
Go to C:\wamp\bin\apache\Apache2.2.17\conf\extra
and open httpd-vhosts.conf file and add the following code

<VirtualHost myWebsite.local>
    DocumentRoot "C:/wamp/www/myWebsite/"
    ServerName myWebsite.local
    ServerAlias myWebsite.local
    <Directory "C:/wamp/www/myWebsite/">
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

change myWebsite.local and C:/wamp/www/myWebsite/ as per your requirements.

Step 3
Open hosts file in C:/Windows/System32/drivers/etc/ and add the following line ( Don't delete anything )

127.0.0.1 myWebsite.local

change myWebsite.local as per your name requirements

Step 4
restart your server. That's it


WINDOWS + XAMPP solution

Same steps as that of WAMP just change the paths according to XAMPP which corresponds to path in WAMP

How to update /etc/hosts file in Docker image during "docker build"

Tis is me Dockefile
FROM XXXXX
ENV DNS_1="10.0.0.1 TEST1.COM"
ENV DNS_1="10.0.0.1 TEST2.COM" 
CMD ["bash","change_hosts.sh"]`

#cat change_hosts.sh
su - root -c "env | grep DNS | akw -F "=" '{print $2}' >> /etc/hosts"
  • info
  • user must su

What is the meaning of <> in mysql query?

<> is standard ANSI SQL and stands for not equal or !=.

How do I generate random integers within a specific range in Java?

If you already use Commons Lang API 2.x or latest version then there is one class for random number generation RandomUtils.

public static int nextInt(int n)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), from the Math.random() sequence.

Parameters: n - the specified exclusive max-value

int random = RandomUtils.nextInt(1000000);

Note: In RandomUtils have many methods for random number generation

Footnotes for tables in LaTeX

If your table is already working with tabular, then easiest is to switch it to longtable, remembering to add

\usepackage{longtable}

For example:

\begin{longtable}{ll}
  2014--2015 & Something cool\footnote{first footnote} \\
  2016-- & Something cooler\footnote{second footnote}
\end{longtable}

Find unused code

The truth is that the tool can never give you a 100% certain answer, but coverage tool can give you a pretty good run for the money.

If you count with comprehensive unit test suite, than you can use test coverage tool to see exactly what lines of code were not executed during the test run. You will still need to analyze the code manually: either eliminate what you consider dead code or write test to improve test coverage.

One such tool is NCover, with open source precursor on Sourceforge. Another alternative is PartCover.

Check out this answer on stackoverflow.

How to read a value from the Windows registry

The pair RegOpenKey and RegQueryKeyEx will do the trick.

If you use MFC CRegKey class is even more easier solution.

Java web start - Unable to load resource

this also worked for me , thanks a lot

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

Run "Configure Java" as administrator.
Go to Advanced
Scroll to bottom
Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
Save

How do I embed a mp4 movie into my html?

You should look into Video For Everyone:

Video for Everybody is very simply a chunk of HTML code that embeds a video into a website using the HTML5 element which offers native playback in Firefox 3.5 and Safari 3 & 4 and an increasing number of other browsers.

The video is played by the browser itself. It loads quickly and doesn’t threaten to crash your browser.

In other browsers that do not support , it falls back to QuickTime.

If QuickTime is not installed, Adobe Flash is used. You can host locally or embed any Flash file, such as a YouTube video.

The only downside, is that you have to have 2/3 versions of the same video stored, but you can serve to every existing device/browser that supports video (i.e.: the iPhone).

<video width="640" height="360" poster="__POSTER__.jpg" controls="controls">
    <source src="__VIDEO__.mp4" type="video/mp4" />
    <source src="__VIDEO__.webm" type="video/webm" />
    <source src="__VIDEO__.ogv" type="video/ogg" /><!--[if gt IE 6]>
    <object width="640" height="375" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"><!
    [endif]--><!--[if !IE]><!-->
    <object width="640" height="375" type="video/quicktime" data="__VIDEO__.mp4"><!--<![endif]-->
    <param name="src" value="__VIDEO__.mp4" />
    <param name="autoplay" value="false" />
    <param name="showlogo" value="false" />
    <object width="640" height="380" type="application/x-shockwave-flash"
        data="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4">
        <param name="movie" value="__FLASH__.swf?image=__POSTER__.jpg&amp;file=__VIDEO__.mp4" />
        <img src="__POSTER__.jpg" width="640" height="360" />
        <p>
            <strong>No video playback capabilities detected.</strong>
            Why not try to download the file instead?<br />
            <a href="__VIDEO__.mp4">MPEG4 / H.264 “.mp4” (Windows / Mac)</a> |
            <a href="__VIDEO__.ogv">Ogg Theora &amp; Vorbis “.ogv” (Linux)</a>
        </p>
    </object><!--[if gt IE 6]><!-->
    </object><!--<![endif]-->
</video>

There is an updated version that is a bit more readable:

<!-- "Video For Everybody" v0.4.1 by Kroc Camen of Camen Design <camendesign.com/code/video_for_everybody>
     =================================================================================================================== -->
<!-- first try HTML5 playback: if serving as XML, expand `controls` to `controls="controls"` and autoplay likewise       -->
<!-- warning: playback does not work on iPad/iPhone if you include the poster attribute! fixed in iOS4.0                 -->
<video width="640" height="360" controls preload="none">
    <!-- MP4 must be first for iPad! -->
    <source src="__VIDEO__.MP4" type="video/mp4" /><!-- WebKit video    -->
    <source src="__VIDEO__.webm" type="video/webm" /><!-- Chrome / Newest versions of Firefox and Opera -->
    <source src="__VIDEO__.OGV" type="video/ogg" /><!-- Firefox / Opera -->
    <!-- fallback to Flash: -->
    <object width="640" height="384" type="application/x-shockwave-flash" data="__FLASH__.SWF">
        <!-- Firefox uses the `data` attribute above, IE/Safari uses the param below -->
        <param name="movie" value="__FLASH__.SWF" />
        <param name="flashvars" value="image=__POSTER__.JPG&amp;file=__VIDEO__.MP4" />
        <!-- fallback image. note the title field below, put the title of the video there -->
        <img src="__VIDEO__.JPG" width="640" height="360" alt="__TITLE__"
             title="No video playback capabilities, please download the video below" />
    </object>
</video>
<!-- you *must* offer a download link as they may be able to play the file locally. customise this bit all you want -->
<p> <strong>Download Video:</strong>
    Closed Format:  <a href="__VIDEO__.MP4">"MP4"</a>
    Open Format:    <a href="__VIDEO__.OGV">"OGG"</a>
</p>

typecast string to integer - Postgres

You can even go one further and restrict on this coalesced field such as, for example:-

SELECT CAST(coalesce(<column>, '0') AS integer) as new_field
from <table>
where CAST(coalesce(<column>, '0') AS integer) >= 10; 

How do I add an "Add to Favorites" button or link on my website?

This code is the corrected version of iambriansreed's answer:

<script type="text/javascript">
    $(function() {
        $("#bookmarkme").click(function() {
            // Mozilla Firefox Bookmark
            if ('sidebar' in window && 'addPanel' in window.sidebar) { 
                window.sidebar.addPanel(location.href,document.title,"");
            } else if( /*@cc_on!@*/false) { // IE Favorite
                window.external.AddFavorite(location.href,document.title); 
            } else { // webkit - safari/chrome
                alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');
            }
        });
    });
</script>

what is the differences between sql server authentication and windows authentication..?

When granting a user access to a database there are a few considerations to be made with advantages and disadvantages in terms of usability and security. Here we have two options for authenticating and granting permission to users. The first is by giving everyone the sa (systems admin) account access and then restricting the permissions manually by retaining a list of the users in which you can grant or deny permissions as needed. This is also known as the SQL authentication method. There are major security flaws in this method, as listed below. The second and better option is to have the Active Directory (AD) handle all the necessary authentication and authorization, also known as Windows authentication. Once the user logs in to their computer the application will connect to the database using those Windows login credentials on the operating system.

The major security issue with using the SQL option is that it violates the principle of least privilege (POLP) which is to only give the user the absolutely necessary permissions they need and no more. By using the sa account you present serious security flaws. The POLP is violated because when the application uses the sa account they have access to the entire database server. Windows authentication on the other hand follows the POLP by only granting access to one database on the server.

The second issue is that there is no need for every instance of the application to have the admin password. This means any application is a potential attack point for the entire server. Windows only uses the Windows credentials to login to the SQL Server. The Windows passwords are stored in a repository as opposed to the SQL database instance itself and the authentication takes place internally within Windows without having to store sa passwords on the application.

A third security issue arises by using the SQL method involves passwords. As presented on the Microsoft website and various security forums, the SQL method doesn’t’ enforce password changing or encryption, rather they are sent as clear text over the network. And the SQL method doesn’t lockout after failing attempts thus allowing a prolonged attempt to break in. Active Directory however, uses Kerberos protocol to encrypt passwords while employing as well a password change system and lockout after failing attempts.

There are efficiency disadvantages as well. Since you will be requiring the user to enter the credentials every time they want to access the database users may forget their credentials.

If a user being removed you would have to remove his credentials from every instance of the application. If you have to update the sa admin password you would have to update every instance of the SQL server. This is time consuming and unsafe, it leaves open the possibility of a dismissed user retaining access to the SQL Server. With the Windows method none of these concerns arise. Everything is centralized and handled by the AD.

The only advantages of using the SQL method lie in its flexibility. You are able to access it from any operating system and network, even remotely. Some older legacy systems as well as some web-based applications may only support sa access.

The AD method also provides time-saving tools such as groups to make it easier to add and remove users, and user tracking ability.

Even if you manage to correct these security flaws in the SQL method, you would be reinventing the wheel. When considering the security advantages provided by Windows authentication, including password policies and following the POLP, it is a much better choice over the SQL authentication. Therefore it is highly recommended to use the Windows authentication option.

How to store a large (10 digits) integer?

You could store by creating an object that hold a string value number to store in an array list. by example: BigInt objt = new BigInt("999999999999999999999999999999999999999999999999999");

objt is created by the constructor of BigInt class. Inside the class look like.

BigInt{

ArrayList<Integer> myNumber = new ArrayList <Integer>();        

public BigInt(){}

public BigInt(String number){ for(int i; i<number.length; i++){ myNumber.add(number.indexOf(i)); } }

}

Is there a way to change the spacing between legend items in ggplot2?

Looks like the best approach (in 2018) is to use legend.key.size under the theme object. (e.g., see here).

#Set-up:
    library(ggplot2)
    library(gridExtra)

    gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
        geom_point()

This is real easy if you are using theme_bw():

  gpbw <- gp + theme_bw()

#Change spacing size:

  g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
  g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
  g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1bw,g2bw,g3bw,nrow=3)

enter image description here

However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):

  g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
  g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
  g3 <- gp + theme(legend.key.size = unit(3, 'lines'))

  grid.arrange(g1,g2,g3,nrow=3)

#Notice that the legend symbol squares get bigger (that's what legend.key.size does). 

#Let's [indirectly] "control" that, too:
  gp2 <- g3
  g4 <- gp2 + theme(legend.key = element_rect(size = 1))
  g5 <- gp2 + theme(legend.key = element_rect(size = 3))
  g6 <- gp2 + theme(legend.key = element_rect(size = 10))

  grid.arrange(g4,g5,g6,nrow=3)   #see picture below, left

Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).

  #This shows you why:
    gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))

enter image description here

I haven't quite found a work-around for fixing the above problem... Let me know in the comments if you have an idea, and I'll update accordingly!

  • I wonder if there is some way to re-layer things using $layers...

Calculate relative time in C#

iPhone Objective-C Version

+ (NSString *)timeAgoString:(NSDate *)date {
    int delta = -(int)[date timeIntervalSinceNow];

    if (delta < 60)
    {
        return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta];
    }
    if (delta < 120)
    {
        return @"a minute ago";
    }
    if (delta < 2700)
    {
        return [NSString stringWithFormat:@"%i minutes ago", delta/60];
    }
    if (delta < 5400)
    {
        return @"an hour ago";
    }
    if (delta < 24 * 3600)
    {
        return [NSString stringWithFormat:@"%i hours ago", delta/3600];
    }
    if (delta < 48 * 3600)
    {
        return @"yesterday";
    }
    if (delta < 30 * 24 * 3600)
    {
        return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)];
    }
    if (delta < 12 * 30 * 24 * 3600)
    {
        int months = delta/(30*24*3600);
        return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months];
    }
    else
    {
        int years = delta/(12*30*24*3600);
        return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years];
    }
}

Android studio: emulator is running but not showing up in Run App "choose a running device"

try to open the emulator and run it parallel with android studio/eclipse and the option will be displayed to select in the choose the device(emuator name, mine is Genymotion).

Algorithm for Determining Tic Tac Toe Game Over

If you have boarder field 5*5 for examle, I used next method of checking:

public static boolean checkWin(char symb) {
  int SIZE = 5;

        for (int i = 0; i < SIZE-1; i++) {
            for (int j = 0; j <SIZE-1 ; j++) {
                //vertical checking
            if (map[0][j] == symb && map[1][j] == symb && map[2][j] == symb && map[3][j] == symb && map[4][j] == symb) return true;      // j=0
            }
            //horisontal checking
            if(map[i][0] == symb && map[i][1] == symb && map[i][2] == symb && map[i][3] == symb && map[i][4] == symb) return true;  // i=0
        }
        //diagonal checking (5*5)
        if (map[0][0] == symb && map[1][1] == symb && map[2][2] == symb && map[3][3] == symb && map[4][4] == symb) return true;
        if (map[4][0] == symb && map[3][1] == symb && map[2][2] == symb && map[1][3] == symb && map[0][4] == symb) return true;

        return false; 
        }

I think, it's more clear, but probably is not the most optimal way.