Programs & Examples On #Video gallery

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

if you think you followed everything good but still unlucky, just make sure you/capistrano run touch tmp/restart.txt or equivalent at the end. I was in the unlucky list but now :)

How to remove a TFS Workspace Mapping?

If the mentioned clues are not helping you then download Team Foundation Sidekick and using that you can delete the workspaces.

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

How to append contents of multiple files into one file

If you want to append contents of 3 files into one file, then the following command will be a good choice:

cat file1 file2 file3 | tee -a file4 > /dev/null

It will combine the contents of all files into file4, throwing console output to /dev/null.

What is the default access specifier in Java?

The default specifier depends upon context.

For classes, and interface declarations, the default is package private. This falls between protected and private, allowing only classes in the same package access. (protected is like this, but also allowing access to subclasses outside of the package.)

class MyClass   // package private
{
   int field;    // package private field

   void calc() {  // package private method

   }
}

For interface members (fields and methods), the default access is public. But note that the interface declaration itself defaults to package private.

interface MyInterface  // package private
{
   int field1;         // static final public

   void method1();     // public abstract
}

If we then have the declaration

public interface MyInterface2 extends MyInterface
{

}

Classes using MyInterface2 can then see field1 and method1 from the super interface, because they are public, even though they cannot see the declaration of MyInterface itself.

How can I clear the input text after clicking

$("input:text").focus(function(){$(this).val("")});

Powershell get ipv4 address into a variable

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DefaultIPGateway -ne $null}).IPAddress | select-object -first 1

How can I parse a JSON file with PHP?

$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);



foreach($json_a as $person => $value)
{
    foreach($value as $key => $personal)
    {
        echo $person. " with ".$key . " is ".$personal;
        echo "<br>";
    }

}

What is a predicate in c#?

The Predicate will always return a boolean, by definition.

Predicate<T> is basically identical to Func<T,bool>.

Predicates are very useful in programming. They are often used to allow you to provide logic at runtime, that can be as simple or as complicated as necessary.

For example, WPF uses a Predicate<T> as input for Filtering of a ListView's ICollectionView. This lets you write logic that can return a boolean determining whether a specific element should be included in the final view. The logic can be very simple (just return a boolean on the object) or very complex, all up to you.

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

<code> vs <pre> vs <samp> for inline and block code snippets

Use <code> for inline code that can wrap and <pre><code> for block code that must not wrap. <samp> is for sample output, so I would avoid using it to represent sample code (which the reader is to input). This is what Stack Overflow does.

(Better yet, if you want easy to maintain, let the users edit the articles as Markdown, then they don’t have to remember to use <pre><code>.)

HTML5 agrees with this in “the pre element”:

The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.

Some examples of cases where the pre element could be used:

  • Including fragments of computer code, with structure indicated according to the conventions of that language.

[…]

To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter.

In the following snippet, a sample of computer code is presented.

_x000D_
_x000D_
<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
      this.element = element;
      this.canClose = canClose;
      this.closeHandler = function () { if (closeHandler) closeHandler() };
    }</code></pre>
_x000D_
_x000D_
_x000D_

List columns with indexes in PostgreSQL

Similar to the accepted answer but having left join on pg_attribute as normal join or query with pg_attribute doesnt give indices which are like :
create unique index unique_user_name_index on users (lower(name))

select 
    row_number() over (order by c.relname),
    c.relname as index, 
    t.relname as table, 
    array_to_string(array_agg(a.attname), ', ') as column_names 
from pg_class c
join pg_index i on c.oid = i.indexrelid and c.relkind='i' and c.relname not like 'pg_%' 
join pg_class t on t.oid = i.indrelid
left join pg_attribute a on a.attrelid = t.oid and a.attnum = ANY(i.indkey) 
group by t.relname, c.relname order by c.relname;

FIX CSS <!--[if lt IE 8]> in IE

Also, the comment tag

<comment></comment> 

is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as

<!--[if lte IE 8]><![endif]-->

In which lte means "less than or equal to".

See: Conditional Comments.

How to modify existing, unpushed commit messages?

If the commit you want to fix isn’t the most recent one:

  1. git rebase --interactive $parent_of_flawed_commit

    If you want to fix several flawed commits, pass the parent of the oldest one of them.

  2. An editor will come up, with a list of all commits since the one you gave.

    1. Change pick to reword (or on old versions of Git, to edit) in front of any commits you want to fix.
    2. Once you save, Git will replay the listed commits.

  3. For each commit you want to reword, Git will drop you back into your editor. For each commit you want to edit, Git drops you into the shell. If you’re in the shell:

    1. Change the commit in any way you like.
    2. git commit --amend
    3. git rebase --continue

Most of this sequence will be explained to you by the output of the various commands as you go. It’s very easy; you don’t need to memorise it – just remember that git rebase --interactive lets you correct commits no matter how long ago they were.


Note that you will not want to change commits that you have already pushed. Or maybe you do, but in that case you will have to take great care to communicate with everyone who may have pulled your commits and done work on top of them. How do I recover/resynchronise after someone pushes a rebase or a reset to a published branch?

Change background colour for Visual Studio

You can also use the Visual Studio Theme Generator. I have only tried this with VS 2005, but the settings it generates may work with newer versions of VS as well.

In case the link goes dead in the future here is a dark theme I generated. Just put this text into a file named VS_2005_dark_theme.vssettings and import it using Tools -> Import and Export Settings:

<UserSettings>
    <ApplicationIdentity version="8.0"/>
    <ToolsOptions>
        <ToolsOptionsCategory name="Environment" RegisteredName="Environment"/>
    </ToolsOptions>
    <Category name="Environment_Group" RegisteredName="Environment_Group">
        <Category name="Environment_FontsAndColors" Category="{1EDA5DD4-927A-43a7-810E-7FD247D0DA1D}" Package="{DA9FB551-C724-11d0-AE1F-00A0C90FFFC3}" RegisteredName="Environment_FontsAndColors" PackageName="Visual Studio Environment Package">
            <PropertyValue name="Version">2</PropertyValue>
            <FontsAndColors Version="2.0">
                <Categories>
                    <Category GUID="{5C48B2CB-0366-4FBF-9786-0BB37E945687}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0000FF00" Background="0x00003700" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{9973EFDF-317D-431C-8BC1-5E88CBFD4F7F}" FontName="PalmOS" FontSize="8" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="0x0057C732" Background="0x0017340E" BoldFont="No"/>
                            <Item Name="Selected Text" Foreground="0x00003700" Background="0x0000FF00" BoldFont="No"/>
                            <Item Name="Inactive Selected Text" Foreground="0x00003700" Background="0x00009100" BoldFont="No"/>
                            <Item Name="Current list location" Foreground="0x00A3DBFF" Background="0x01000007" BoldFont="No"/>
                        </Items>
                    </Category>
                    <Category GUID="{A27B4E24-A735-4D1D-B8E7-9716E1E3D8E0}" FontName="Monaco" FontSize="9" CharSet="0" FontIsDefault="No">
                        <Items>
                            <Item Name="Plain Text" Foreground="00CFCFCF" Background="00383838" BoldFont="No"/>
                            <Item Name="Indicator Margin" Foreground="0x02000000" Background="00383838" BoldFont="No"/>
                            <Item Name="Line Numbers" Foreground="00828282" Background="00383838" BoldFont="No"/>
                            <Item Name="Visible White Space" Foreground="0x00808080" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Compiler Error" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Property Value" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS Selector" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="CSS String Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Element Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="HTML Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Identifier" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Number" Foreground="002FFE60" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Operator" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Preprocessor Keyword" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Stale Code" Foreground="0x00808080" Background="0x00C0C0C0" BoldFont="No"/>
                            <Item Name="String" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="String (C# Verbatim)" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Task List Shortcut" Foreground="0x00FFFFFF" Background="0x02C0C0C0" BoldFont="No"/>
                            <Item Name="User Keywords" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="User Types" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="Warning" Foreground="000000F0" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Class" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Name" Foreground="00F12FFE" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Markup Extension Parameter Value" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Processing Instruction" Foreground="00FE2F8C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XAML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>                            
                            <Item Name="XML @ Attribute" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Quotes" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Attribute Value" Foreground="0032FE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Delimiter" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Attribute" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Comment" Foreground="00828282" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Doc Tag" Foreground="00D64EDF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Name" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Processing Instruction" Foreground="0x0015496C" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XML Text" Foreground="00CFCFCF" Background="0x02000000" BoldFont="No"/>
                            <Item Name="XSLT Keyword" Foreground="00FECE2F" Background="0x02000000" BoldFont="No"/>                                                                 
                        </Items>
                    </Category>
                </Categories>
            </FontsAndColors>
        </Category>
    </Category>
</UserSettings>

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

  1. Download gecko driver from the seleniumhq website (Now it is on GitHub and you can download it from Here) .
    1. You will have a zip (or tar.gz) so extract it.
    2. After extraction you will have geckodriver.exe file (appropriate executable in linux).
    3. Create Folder in C: named SeleniumGecko (Or appropriate)
    4. Copy and Paste geckodriver.exe to SeleniumGecko
    5. Set the path for gecko driver as below

.

System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

Mocking a class: Mock() or patch()?

Key points which explain difference and provide guidance upon working with unittest.mock

  1. Use Mock if you want to replace some interface elements(passing args) of the object under test
  2. Use patch if you want to replace internal call to some objects and imported modules of the object under test
  3. Always provide spec from the object you are mocking
    • With patch you can always provide autospec
    • With Mock you can provide spec
    • Instead of Mock, you can use create_autospec, which intended to create Mock objects with specification.

In the question above the right answer would be to use Mock, or to be more precise create_autospec (because it will add spec to the mock methods of the class you are mocking), the defined spec on the mock will be helpful in case of an attempt to call method of the class which doesn't exists ( regardless signature), please see some

from unittest import TestCase
from unittest.mock import Mock, create_autospec, patch


class MyClass:
    
    @staticmethod
    def method(foo, bar):
        print(foo)


def something(some_class: MyClass):
    arg = 1
    # Would fail becuase of wrong parameters passed to methd.
    return some_class.method(arg)


def second(some_class: MyClass):
    arg = 1
    return some_class.unexisted_method(arg)


class TestSomethingTestCase(TestCase):
    def test_something_with_autospec(self):
        mock = create_autospec(MyClass)
        mock.method.return_value = True
        # Fails because of signature misuse.
        result = something(mock)
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
    
    def test_something(self):
        mock = Mock()  # Note that Mock(spec=MyClass) will also pass, because signatures of mock don't have spec.
        mock.method.return_value = True
        
        result = something(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.method.called)
        
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)


class TestSecondTestCase(TestCase):
    def test_second_with_autospec(self):
        mock = Mock(spec=MyClass)
        # Fails because of signature misuse.
        result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second_with_patch_autospec(self):
        with patch(f'{__name__}.MyClass', autospec=True) as mock:
            # Fails because of signature misuse.
            result = second(mock)
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)
    
    def test_second(self):
        mock = Mock()
        mock.unexisted_method.return_value = True
        
        result = second(mock)
        
        self.assertTrue(result)
        self.assertTrue(mock.unexisted_method.called)

The test cases with defined spec used fail because methods called from something and second functions aren't complaint with MyClass, which means - they catch bugs, whereas default Mock will display.

As a side note there is one more option: use patch.object to mock just the class method which is called with.

The good use cases for patch would be the case when the class is used as inner part of function:

def something():
    arg = 1
    return MyClass.method(arg)

Then you will want to use patch as a decorator to mock the MyClass.

How to center a (background) image within a div?

Use background-position:

background-position: 50% 50%;

GIT commit as different user without email / or only email

Format

A U Thor <[email protected]>

simply mean that you should specify

FirstName MiddleName LastName <[email protected]>

Looks like middle and last names are optional (maybe the part before email doesn't have a strict format at all). Try, for example, this:

git commit --author="John <[email protected]>" -m "some fix"

As the docs say:

  --author=<author>
       Override the commit author. Specify an explicit author using the standard 
       A U Thor <[email protected]> format. Otherwise <author> is assumed to 
       be a pattern and is used to search for an existing commit by that author 
       (i.e. rev-list --all -i --author=<author>); the commit author is then copied 
       from the first such commit found.

if you don't use this format, git treats provided string as a pattern and tries to find matching name among the authors of other commits.

Parsing arguments to a Java command line program

I like this one. Simple, and you can have more than one parameter for each argument:

final Map<String, List<String>> params = new HashMap<>();

List<String> options = null;
for (int i = 0; i < args.length; i++) {
    final String a = args[i];

    if (a.charAt(0) == '-') {
        if (a.length() < 2) {
            System.err.println("Error at argument " + a);
            return;
        }

        options = new ArrayList<>();
        params.put(a.substring(1), options);
    }
    else if (options != null) {
        options.add(a);
    }
    else {
        System.err.println("Illegal parameter usage");
        return;
    }
}

For example:

-arg1 1 2 --arg2 3 4

System.out.print(params.get("arg1").get(0)); // 1
System.out.print(params.get("arg1").get(1)); // 2
System.out.print(params.get("-arg2").get(0)); // 3
System.out.print(params.get("-arg2").get(1)); // 4

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

In Python, how do I read the exif data for an image?

Here's the one that may be little easier to read. Hope this is helpful.

from PIL import Image
from PIL import ExifTags

exifData = {}
img = Image.open(picture.jpg)
exifDataRaw = img._getexif()
for tag, value in exifDataRaw.items():
    decodedTag = ExifTags.TAGS.get(tag, tag)
    exifData[decodedTag] = value

The order of keys in dictionaries

From http://docs.python.org/tutorial/datastructures.html:

"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."

Rails: Adding an index after adding column

For those who are using postgresql db and facing error

StandardError: An error has occurred, this and all later migrations canceled:

=== Dangerous operation detected #strong_migrations ===

Adding an index non-concurrently blocks writes

please refer this article

example:

class AddAncestryToWasteCodes < ActiveRecord::Migration[6.0]
  disable_ddl_transaction!

  def change
    add_column :waste_codes, :ancestry, :string
    add_index :waste_codes, :ancestry, algorithm: :concurrently
  end
end

Converting camel case to underscore case in ruby

Short oneliner for CamelCases when you have spaces also included (doesn't work correctly if you have a word inbetween with small starting-letter):

a = "Test String"
a.gsub(' ', '').underscore

  => "test_string"

Count elements with jQuery

The best way would be to use .each()

var num = 0;

$('.className').each(function(){
    num++;
});

accessing a variable from another class

I hope I'm understanding the problem correctly, but it looks like you don't have a reference back to your DrawFrame object from DrawCircle.

Try this:

Change your constructor signature for DrawCircle to take in a DrawFrame object. Within the constructor, set the class variable "d" to the DrawFrame object you just took in. Now add the getWidth/getHeight methods to DrawFrame as mentioned in previous answers. See if that allows you to get what you're looking for.

Your DrawCircle constructor should be changed to something like:

public DrawCircle(DrawFrame frame)
{
    d = frame;
    w = 400;
    h = 400;
    diBig = 300;
    diSmall = 10;
    maxRad = (diBig/2) - diSmall;
    xSq = 50;
    ySq = 50;
    xPoint = 200;
    yPoint = 200;
}

The last line of code in DrawFrame should look something like:

contentPane.add(new DrawCircle(this));

Then, try using d.getheight(), d.getWidth() and so on within DrawCircle. This assumes you still have those methods available on DrawFrame to access them, of course.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

Make a borderless form movable?

WPF only


don't have the exact code to hand, but in a recent project I think I used MouseDown event and simply put this:

frmBorderless.DragMove();

Window.DragMove Method (MSDN)

How do I execute a *.dll file

While many people have pointed out that you can't execute dlls directly and should use rundll32.exe to execute exported functions instead, here is a screenshot of an actual dll file running just like an executable:

enter image description here

While you cannot run dll files directly, I suspect it is possible to run them from another process using a WinAPI function CreateProcess:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Matrix Transpose in Python

def transpose(matrix):
    listOfLists = []
    for row in range(len(matrix[0])):
        colList = []
        for col in range(len(matrix)):
            colList.append(matrix[col][row])
    listOfLists.append(colList)

    return listOfLists

How do I correctly setup and teardown for my pytest class with tests?

When you write "tests defined as class methods", do you really mean class methods (methods which receive its class as first parameter) or just regular methods (methods which receive an instance as first parameter)?

Since your example uses self for the test methods I'm assuming the latter, so you just need to use setup_method instead:

class Test:

    def setup_method(self, test_method):
        # configure self.attribute

    def teardown_method(self, test_method):
        # tear down self.attribute

    def test_buttons(self):
        # use self.attribute for test

The test method instance is passed to setup_method and teardown_method, but can be ignored if your setup/teardown code doesn't need to know the testing context. More information can be found here.

I also recommend that you familiarize yourself with py.test's fixtures, as they are a more powerful concept.

OS X Terminal UTF-8 issues

Go to Terminal -> Preferences -> Advanced (Tab) go down to International and select Unicode (UTF-8) as Character Encoding.

And tick Set locale environment variables on startup.

What does 'foo' really mean?

Among my colleagues, the meaning (or perhaps more accurately - the use) of the term "foo" has been to serve as a placeholder to represent an example for a name. Examples include, but not limited to, yourVariableName, yourObjectName, or yourColumnName.

Today, I avoid using "foo" and prefer using this type of named substitution for a couple of reasons.

  • In my earlier days, I originally found the use of "foo" as a placement in any example to represent something as f'd-up to be confusing. I wanted a working example, not something that was foobar.
  • Your results may vary, but I always, 100%, everytime, never-failed, got more follow-up questions about the meaning of the actual variable where "foo" was used.

How to clear a notification in Android

 Notification mNotification = new Notification.Builder(this)

                .setContentTitle("A message from: " + fromUser)
                .setContentText(msg)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.app_icon)
                .setContentIntent(pIntent)
                .build();

.setAutoCancel(true)

when you click on notification, open corresponding activity and remove notification from notification bar

Get parent directory of running script

Fugly, but this will do it:

substr($_SERVER['SCRIPT_NAME'], 0, strpos($_SERVER['SCRIPT_NAME'],basename($_SERVER['SCRIPT_NAME'])))

clientHeight/clientWidth returning different values on different browsers

The body element takes the available width, which is usually your browser viewport. As such, it will be different dimensions cross browser due to browser chrome borders, scrollbars, vertical space being take up by menus and whatnot...

The fact that the heights also vary, also tells me you set the body/html height to 100% through css since the height is usually dependant on elements inside the body..

Unless you set the width of the body element to a fixed value through css or it's style property, it's dimensions will as a rule, always vary cross browsers/versions and perhaps even depending on plugins you installed for the browser. Constant values in such a case is more an exception to the rule...

When you invoke .clientWidth on other elements that do not take the automatic width of the browser viewport, it will always return the elements 'width' + 'padding'. So a div with width 200 and a padding of 20 will have clientWidth = 240 (20 padding left and right).

The main reason however, why one would invoke clientWidth, is exactly due to possible expected discrepancies in results. If you know you will get a constant width and the value is known, then invoking clientWidth is redundant...

What exactly is a Maven Snapshot and why do we need it?

Maven versions can contain a string literal "SNAPSHOT" to signify that a project is currently under active development.

For example, if your project has a version of “1.0-SNAPSHOT” and you deploy this project’s artifacts to a Maven repository, Maven would expand this version to “1.0-20080207-230803-1” if you were to deploy a release at 11:08 PM on February 7th, 2008 UTC. In other words, when you deploy a snapshot, you are not making a release of a software component; you are releasing a snapshot of a component at a specific time.

So mainly snapshot versions are used for projects under active development. If your project depends on a software component that is under active development, you can depend on a snapshot release, and Maven will periodically attempt to download the latest snapshot from a repository when you run a build. Similarly, if the next release of your system is going to have a version “1.8,” your project would have a “1.8-SNAPSHOT” version until it was formally released.

For example , the following dependency would always download the latest 1.8 development JAR of spring:

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring</artifactId>
        <version>1.8-SNAPSHOT”</version>
    </dependency>

Maven

An example of maven release process

enter image description here

How to get the first element of the List or Set?

Set

set.toArray()[0];

List

list.get(0);

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

After much pulling out of hair I discovered that the foreach loops were the culprits. What needs to happen is to call EF but return it into an IList<T> of that target type then loop on the IList<T>.

Example:

IList<Client> clientList = from a in _dbFeed.Client.Include("Auto") select a;
foreach (RivWorks.Model.NegotiationAutos.Client client in clientList)
{
   var companyFeedDetailList = from a in _dbRiv.AutoNegotiationDetails where a.ClientID == client.ClientID select a;
    // ...
}

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

Using JAXB to unmarshal/marshal a List<String>

If you are using maven in the jersey project add below in pom.xml and update project dependencies so that Jaxb is able to detect model class and convert list to Media type application XML:

<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>2.2.11</version>
</dependency>

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

Space between two divs

You can try something like the following:

h1{
   margin-bottom:<x>px;
}
div{
   margin-bottom:<y>px;
}
div:last-of-type{
   margin-bottom:0;
}

or instead of the first h1 rule:

div:first-of-type{
   margin-top:<x>px;
}

or even better use the adjacent sibling selector. With the following selector, you could cover your case in one rule:

div + div{
   margin-bottom:<y>px;
}

Respectively, h1 + div would control the first div after your header, giving you additional styling options.

Finding element in XDocument?

You should use Root to refer to the root element:

xmlFile.Root.Elements("Band")

If you want to find elements anywhere in the document use Descendants instead:

xmlFile.Descendants("Band")

Convert double to string C++?

You can't do it directly. There are a number of ways to do it:

  1. Use a std::stringstream:

    std::ostringstream s;
    s << "(" << c1 << ", " << c2 << ")";
    storedCorrect[count] = s.str()
    
  2. Use boost::lexical_cast:

    storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
    
  3. Use std::snprintf:

    char buffer[256];  // make sure this is big enough!!!
    snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
    storedCorrect[count] = buffer;
    

There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.

Git push failed, "Non-fast forward updates were rejected"

Using the --rebase option worked for me.

  • git pull <remote> <branch> --rebase

Then push to the repo.

  • git push <remote> <branch>

E.g.

git pull origin master --rebase

git push origin master

Catch paste input

document.addEventListener('paste', function(e){
    if(e.clipboardData.types.indexOf('text/html') > -1){
        processDataFromClipboard(e.clipboardData.getData('text/html'));
        e.preventDefault();

        ...
    }
});

Further:

Disabling submit button until all fields have values

All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.

var $input = $('input:text'),
    $register = $('#register');    
$register.attr('disabled', true);

$input.keyup(function() {
    var trigger = false;
    $input.each(function() {
        if (!$(this).val()) {
            trigger = true;
        }
    });
    trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});

Check working example at http://jsfiddle.net/DKNhx/3/

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Swift_TransportException Connection could not be established with host smtp.gmail.com

In my case, I had trouble with GoDaddy and SSL encryption.

Setting the encryption to Null and Port to 80 (Or any supportive port) did the job.

C# Form.Close vs Form.Dispose

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Based on Teste's code .. I can confirm the following works. I can't say whether or not this is "good" code, but it certainly works and could get you back up and running quickly if you ended up with GCM to FCM server problems!

public AndroidFCMPushNotificationStatus SendNotification(string serverApiKey, string senderId, string deviceId, string message)
{
    AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();

    try
    {
        result.Successful = false;
        result.Error = null;

        var value = message;
        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));
        tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));

        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";

        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        using (Stream dataStream = tRequest.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);

            using (WebResponse tResponse = tRequest.GetResponse())
            {
                using (Stream dataStreamResponse = tResponse.GetResponseStream())
                {
                    using (StreamReader tReader = new StreamReader(dataStreamResponse))
                    {
                        String sResponseFromServer = tReader.ReadToEnd();
                        result.Response = sResponseFromServer;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        result.Successful = false;
        result.Response = null;
        result.Error = ex;
    }

    return result;
}


public class AndroidFCMPushNotificationStatus
{
    public bool Successful
    {
        get;
        set;
    }

    public string Response
    {
        get;
        set;
    }
    public Exception Error
    {
        get;
        set;
    }
}

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

Difference between spring @Controller and @RestController annotation

THE new @RestController annotation in Spring4+, which marks the class as a controller where every method returns a domain object instead of a view. It’s shorthand for @Controller and @ResponseBody rolled together.

How to push changes to github after jenkins build completes?

The git checkout master of the answer by Woland isn't needed. Instead use the "Checkout to specific local branch" in the "Additional Behaviors" section to set the "Branch name" to master.

The git commit -am "blah" is still needed.

Now you can use the "Git Publisher" under "Post-build Actions" to push the changes. Be sure to specify the "Branches" to push ("Branch to push" = master, "Target remote name" = origin).

"Merge Results" isn't needed.

What do multiple arrow functions mean in javascript?

That is a curried function

First, examine this function with two parameters …

const add = (x, y) => x + y
add(2, 3) //=> 5

Here it is again in curried form …

const add = x => y => x + y

Here is the same1 code without arrow functions …

const add = function (x) {
  return function (y) {
    return x + y
  }
}

Focus on return

It might help to visualize it another way. We know that arrow functions work like this – let's pay particular attention to the return value.

const f = someParam => returnValue

So our add function returns a function – we can use parentheses for added clarity. The bolded text is the return value of our function add

const add = x => (y => x + y)

In other words add of some number returns a function

add(2) // returns (y => 2 + y)

Calling curried functions

So in order to use our curried function, we have to call it a bit differently …

add(2)(3)  // returns 5

This is because the first (outer) function call returns a second (inner) function. Only after we call the second function do we actually get the result. This is more evident if we separate the calls on two lines …

const add2 = add(2) // returns function(y) { return 2 + y }
add2(3)             // returns 5

Applying our new understanding to your code

related: ”What’s the difference between binding, partial application, and currying?”

OK, now that we understand how that works, let's look at your code

handleChange = field => e => {
  e.preventDefault()
  /// Do something here
}

We'll start by representing it without using arrow functions …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  };
};

However, because arrow functions lexically bind this, it would actually look more like this …

handleChange = function(field) {
  return function(e) {
    e.preventDefault()
    // Do something here
    // return ...
  }.bind(this)
}.bind(this)

Maybe now we can see what this is doing more clearly. The handleChange function is creating a function for a specified field. This is a handy React technique because you're required to setup your own listeners on each input in order to update your applications state. By using the handleChange function, we can eliminate all the duplicated code that would result in setting up change listeners for each field. Cool!

1 Here I did not have to lexically bind this because the original add function does not use any context, so it is not important to preserve it in this case.


Even more arrows

More than two arrow functions can be sequenced, if necessary -

const three = a => b => c =>
  a + b + c

const four = a => b => c => d =>
  a + b + c + d

three (1) (2) (3) // 6

four (1) (2) (3) (4) // 10

Curried functions are capable of surprising things. Below we see $ defined as a curried function with two parameters, yet at the call site, it appears as though we can supply any number of arguments. Currying is the abstraction of arity -

_x000D_
_x000D_
const $ = x => k =>_x000D_
  $ (k (x))_x000D_
  _x000D_
const add = x => y =>_x000D_
  x + y_x000D_
_x000D_
const mult = x => y =>_x000D_
  x * y_x000D_
  _x000D_
$ (1)           // 1_x000D_
  (add (2))     // + 2 = 3_x000D_
  (mult (6))    // * 6 = 18_x000D_
  (console.log) // 18_x000D_
  _x000D_
$ (7)            // 7_x000D_
  (add (1))      // + 1 = 8_x000D_
  (mult (8))     // * 8 = 64_x000D_
  (mult (2))     // * 2 = 128_x000D_
  (mult (2))     // * 2 = 256_x000D_
  (console.log)  // 256
_x000D_
_x000D_
_x000D_

Partial application

Partial application is a related concept. It allows us to partially apply functions, similar to currying, except the function does not have to be defined in curried form -

const partial = (f, ...a) => (...b) =>
  f (...a, ...b)

const add3 = (x, y, z) =>
  x + y + z

partial (add3) (1, 2, 3)   // 6

partial (add3, 1) (2, 3)   // 6

partial (add3, 1, 2) (3)   // 6

partial (add3, 1, 2, 3) () // 6

partial (add3, 1, 1, 1, 1) (1, 1, 1, 1, 1) // 3

Here's a working demo of partial you can play with in your own browser -

_x000D_
_x000D_
const partial = (f, ...a) => (...b) =>_x000D_
  f (...a, ...b)_x000D_
  _x000D_
const preventDefault = (f, event) =>_x000D_
  ( event .preventDefault ()_x000D_
  , f (event)_x000D_
  )_x000D_
  _x000D_
const logKeypress = event =>_x000D_
  console .log (event.which)_x000D_
  _x000D_
document_x000D_
  .querySelector ('input[name=foo]')_x000D_
  .addEventListener ('keydown', partial (preventDefault, logKeypress))
_x000D_
<input name="foo" placeholder="type here to see ascii codes" size="50">
_x000D_
_x000D_
_x000D_

Limit Get-ChildItem recursion depth

@scanlegentil I like this.
A little improvement would be:

$Depth = 2
$Path = "."

$Levels = "\*" * $Depth
$Folder = Get-Item $Path
$FolderFullName = $Folder.FullName
Resolve-Path $FolderFullName$Levels | Get-Item | ? {$_.PsIsContainer} | Write-Host

As mentioned, this would only scan the specified depth, so this modification is an improvement:

$StartLevel = 1 # 0 = include base folder, 1 = sub-folders only, 2 = start at 2nd level
$Depth = 2      # How many levels deep to scan
$Path = "."     # starting path

For ($i=$StartLevel; $i -le $Depth; $i++) {
    $Levels = "\*" * $i
    (Resolve-Path $Path$Levels).ProviderPath | Get-Item | Where PsIsContainer |
    Select FullName
}

Installing cmake with home-brew

Typing brew install cmake as you did installs cmake. Now you can type cmake and use it.

If typing cmake doesn’t work make sure /usr/local/bin is your PATH. You can see it with echo $PATH. If you don’t see /usr/local/bin in it add the following to your ~/.bashrc:

export PATH="/usr/local/bin:$PATH"

Then reload your shell session and try again.


(all the above assumes Homebrew is installed in its default location, /usr/local. If not you’ll have to replace /usr/local with $(brew --prefix) in the export line)

What is the idiomatic Go equivalent of C's ternary operator?

func Ternary(statement bool, a, b interface{}) interface{} {
    if statement {
        return a
    }
    return b
}

func Abs(n int) int {
    return Ternary(n >= 0, n, -n).(int)
}

This will not outperform if/else and requires cast but works. FYI:

BenchmarkAbsTernary-8 100000000 18.8 ns/op

BenchmarkAbsIfElse-8 2000000000 0.27 ns/op

jQuery Ajax simple call

You could also make the ajax call more generic, reusable, so you can call it from different CRUD(create, read, update, delete) tasks for example and treat the success cases from those calls.

makePostCall = function (url, data) { // here the data and url are not hardcoded anymore
   var json_data = JSON.stringify(data);

    return $.ajax({
        type: "POST",
        url: url,
        data: json_data,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    });
}

// and here a call example
makePostCall("index.php?action=READUSERS", {'city' : 'Tokio'})
    .success(function(data){
               // treat the READUSERS data returned
   })
    .fail(function(sender, message, details){
           alert("Sorry, something went wrong!");
  });

" netsh wlan start hostednetwork " command not working no matter what I try

Same issue.

I solved the problem first activating (right click mouse and select activate) from control panel (network connections) and later changing to set mode to allow (by netsh command), to finally starting the hostednetwork with other netsh command, that is:

1.- Activate (Network Connections) by right click

2.- netsh wlan set hostednetwork mode=allow

3.- netsh wlan start hosted network

Good luck mate !!!

How to refresh page on back button click?

The hidden input solution wasn't working for me in Safari. The solution below works, and came from here.

window.onpageshow = function(event) {
if (event.persisted) {
    window.location.reload() 
}
};

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Replacing server=localhost with server=.\SQLEXPRESS might do the job.

How to dockerize maven project? and how many ways to accomplish it?

Working example.

This is not a spring boot tutorial. It's the updated answer to a question on how to run a Maven build within a Docker container.

Question originally posted 4 years ago.

1. Generate an application

Use the spring initializer to generate a demo app

https://start.spring.io/

enter image description here

Extract the zip archive locally

2. Create a Dockerfile

#
# Build stage
#
FROM maven:3.6.0-jdk-11-slim AS build
COPY src /home/app/src
COPY pom.xml /home/app
RUN mvn -f /home/app/pom.xml clean package

#
# Package stage
#
FROM openjdk:11-jre-slim
COPY --from=build /home/app/target/demo-0.0.1-SNAPSHOT.jar /usr/local/lib/demo.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","/usr/local/lib/demo.jar"]

Note

  • This example uses a multi-stage build. The first stage is used to build the code. The second stage only contains the built jar and a JRE to run it (note how jar is copied between stages).

3. Build the image

docker build -t demo .

4. Run the image

$ docker run --rm -it demo:latest

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)

2019-02-22 17:18:57.835  INFO 1 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication v0.0.1-SNAPSHOT on f4e67677c9a9 with PID 1 (/usr/local/bin/demo.jar started by root in /)
2019-02-22 17:18:57.837  INFO 1 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2019-02-22 17:18:58.294  INFO 1 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 0.711 seconds (JVM running for 1.035)

Misc

Read the Docker hub documentation on how the Maven build can be optimized to use a local repository to cache jars.

Update (2019-02-07)

This question is now 4 years old and in that time it's fair to say building application using Docker has undergone significant change.

Option 1: Multi-stage build

This new style enables you to create more light-weight images that don't encapsulate your build tools and source code.

The example here again uses the official maven base image to run first stage of the build using a desired version of Maven. The second part of the file defines how the built jar is assembled into the final output image.

FROM maven:3.5-jdk-8 AS build  
COPY src /usr/src/app/src  
COPY pom.xml /usr/src/app  
RUN mvn -f /usr/src/app/pom.xml clean package

FROM gcr.io/distroless/java  
COPY --from=build /usr/src/app/target/helloworld-1.0.0-SNAPSHOT.jar /usr/app/helloworld-1.0.0-SNAPSHOT.jar  
EXPOSE 8080  
ENTRYPOINT ["java","-jar","/usr/app/helloworld-1.0.0-SNAPSHOT.jar"]  

Note:

  • I'm using Google's distroless base image, which strives to provide just enough run-time for a java app.

Option 2: Jib

I haven't used this approach but seems worthy of investigation as it enables you to build images without having to create nasty things like Dockerfiles :-)

https://github.com/GoogleContainerTools/jib

The project has a Maven plugin which integrates the packaging of your code directly into your Maven workflow.


Original answer (Included for completeness, but written ages ago)

Try using the new official images, there's one for Maven

https://registry.hub.docker.com/_/maven/

The image can be used to run Maven at build time to create a compiled application or, as in the following examples, to run a Maven build within a container.

Example 1 - Maven running within a container

The following command runs your Maven build inside a container:

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       maven:3.2-jdk-7 \
       mvn clean install

Notes:

  • The neat thing about this approach is that all software is installed and running within the container. Only need docker on the host machine.
  • See Dockerfile for this version

Example 2 - Use Nexus to cache files

Run the Nexus container

docker run -d -p 8081:8081 --name nexus sonatype/nexus

Create a "settings.xml" file:

<settings>
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://nexus:8081/content/groups/public/</url>
    </mirror>
  </mirrors>
</settings>

Now run Maven linking to the nexus container, so that dependencies will be cached

docker run -it --rm \
       -v "$(pwd)":/opt/maven \
       -w /opt/maven \
       --link nexus:nexus \
       maven:3.2-jdk-7 \
       mvn -s settings.xml clean install

Notes:

  • An advantage of running Nexus in the background is that other 3rd party repositories can be managed via the admin URL transparently to the Maven builds running in local containers.

Switching users inside Docker image to a non-root user

As a different approach to the other answer, instead of indicating the user upon image creation on the Dockerfile, you can do so via command-line on a particular container as a per-command basis.

With docker exec, use --user to specify which user account the interactive terminal will use (the container should be running and the user has to exist in the containerized system):

docker exec -it --user [username] [container] bash

See https://docs.docker.com/engine/reference/commandline/exec/

Google Chrome Full Black Screen

I still experience occasional black screens with latest Chrome 60 with GPU acceleration enabled by default (probably caused by lack of free memory for numerous tabs).

Sometimes it helps to kill GPU process in builtin Task manager (Shift+Esc) as @amit suggests. But sometimes this forces more Chrome windows to become black while some others may remain normal.

I've noticed that tabs headers and address bar of black windows remain funtional and tabs can be fully repaired just by dragging them out of black windows. But it's too tedious to do this one by one when their number is huge.

So here is quick completely restartless solution inspired by Merging windows of Google Chrome:

  • Add a new empty tab to black window (Ctrl+T)
  • Left-click the first tab in the window
  • Then hold the Shift key and left-click the right most tab just before the empty one
  • Drag all the selected tabs at once out of the black window
  • Close the black window with remaining single empty tab

How can I split a JavaScript string by white space or comma?

String.split() can also accept a regular expression:

input.split(/[ ,]+/);

This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

How to write a simple Html.DropDownListFor()?

Avoid of lot of fat fingering by starting with a Dictionary in the Model

namespace EzPL8.Models
{
    public class MyEggs
    {
        public Dictionary<int, string> Egg { get; set; }

        public MyEggs()
        {
            Egg = new Dictionary<int, string>()
            {
                { 0, "No Preference"},
                { 1, "I hate eggs"},
                { 2, "Over Easy"},
                { 3, "Sunny Side Up"},
                { 4, "Scrambled"},
                { 5, "Hard Boiled"},
                { 6, "Eggs Benedict"}
            };

    }


    }

In the View convert it to a list for display

@Html.DropDownListFor(m => m.Egg.Keys,
                         new SelectList(
                             Model.Egg, 
                             "Key", 
                             "Value"))

How can I add to a List's first position?

Of course, Insert or AddFirst will do the trick, but you could always do:

myList.Reverse();
myList.Add(item);
myList.Reverse();

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

How can I see CakePHP's SQL dump in the controller?

If you're using CakePHP 1.3, you can put this in your views to output the SQL:

<?php echo $this->element('sql_dump'); ?>

So you could create a view called 'sql', containing only the line above, and then call this in your controller whenever you want to see it:

$this->render('sql');

(Also remember to set your debug level to at least 2 in app/config/core.php)

Source

What is the maximum size of a web browser's cookie's key?

Not completely entirely a direct answer to the original question, but relevant for the curious quickly trying to visually understand their cookie information storage planning without implementing a complex limiter algorithm, this string is 4096 ASCII character bytes:

"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmn"

Add column with constant value to pandas dataframe

Here is another one liner using lambdas (create column with constant value = 10)

df['newCol'] = df.apply(lambda x: 10, axis=1)

before

df
    A           B           C
1   1.764052    0.400157    0.978738
2   2.240893    1.867558    -0.977278
3   0.950088    -0.151357   -0.103219

after

df
        A           B           C           newCol
    1   1.764052    0.400157    0.978738    10
    2   2.240893    1.867558    -0.977278   10
    3   0.950088    -0.151357   -0.103219   10

How to convert password into md5 in jquery?

You need additional plugin for this.

take a look at this plugin

Detecting scroll direction

You can get the scrollbar position using document.documentElement.scrollTop. And then it is simply matter of comparing it to the previous position.

Java ElasticSearch None of the configured nodes are available

I know I'm a bit late, incase the above answers didn't work, I recommend checking the logs in elasticsearch terminal. I found out that the error message says that i need to update my version from 5.0.0-rc1 to 6.8.0, i resolved it by updating my maven dependencies to:

<dependency>
  <groupId>org.elasticsearch</groupId>
  <artifactId>elasticsearch</artifactId>
  <version>6.8.0</version>
</dependency>
  <dependency>
  <groupId>org.elasticsearch.client</groupId>
  <artifactId>transport</artifactId>
  <version>6.8.0</version>
</dependency>

This changes my code as well, since InetSocketTransportAddress is deprecated. I have to change it to TransportAddress

TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
               .addTransportAddress(new TransportAddress(InetAddress.getByName(host), port));

And you also need to add this to your config/elasticsearch.yml file (use your host address)

transport.host: localhost

How can I find the product GUID of an installed MSI setup?

If you have too many installers to find what you are looking for easily, here is some powershell to provide a filter and narrow it down a little by display name.

$filter = "*core*sdk*"; (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | % { $path = "Registry::$_"; Get-ItemProperty $path } | Where-Object { $_.DisplayName -like $filter } | Select-Object -Property DisplayName, PsChildName

How to Automatically Close Alerts using Twitter Bootstrap

I could not get it to work with alert.('close') either.

However I am using this and it works a treat! The alert will fade away after 5 seconds, and once gone, the content below it will slide up to its natural position.

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

SQL server stored procedure return a table

I had a similar situation and solved by using a temp table inside the procedure, with the same fields being returned by the original Stored Procedure:

CREATE PROCEDURE mynewstoredprocedure
AS 
BEGIN

INSERT INTO temptable (field1, field2)
EXEC mystoredprocedure @param1, @param2

select field1, field2 from temptable

-- (mystoredprocedure returns field1, field2)

END

sql server Get the FULL month name from a date

Most answers are a bit more complicated than necessary, or don't provide the exact format requested.

select Format(getdate(), 'MMMM dd yyyy') --returns 'October 01 2020', note the leading zero
select Format(getdate(), 'MMMM d yyyy') --returns the desired format with out the leading zero: 'October 1 2020'

If you want a comma, as you normally would, use:

select Format(getdate(), 'MMMM d, yyyy') --returns 'October 1, 2020'

Note: even though there is only one 'd' for the day, it will become a 2 digit day when needed.

iPhone 5 CSS media query

/* iPad */
@media screen and (min-device-width: 768px) {
    /* ipad-portrait */
    @media screen and (max-width: 896px) { 
        .logo{
            display: none !important;
        }
    }
    /* ipad-landscape */
    @media screen and (min-width: 897px) { 

    }
}
/* iPhone */
@media screen and (max-device-width: 480px) {
    /* iphone-portrait */
    @media screen and (max-width: 400px) { 

    }
    /* iphone-landscape */
    @media screen and (min-width: 401px) { 

    }
}

WebAPI Multiple Put/Post parameters

You can get the formdata as string:

    protected NameValueCollection GetFormData()
    {
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        Request.Content.ReadAsMultipartAsync(provider);

        return provider.FormData;
    }

    [HttpPost]
    public void test() 
    {
        var formData = GetFormData();
        var userId = formData["userId"];

        // todo json stuff
    }

https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

How to convert date format to DD-MM-YYYY in C#

var dateTimeString = "21?-?10?-?2014? ?15?:?40?:?30";
dateTimeString = Regex.Replace(dateTimeString, @"[^\u0000-\u007F]", string.Empty);

var inputFormat = "dd-MM-yyyy HH:mm:ss";
var outputFormat = "yyyy-MM-dd HH:mm:ss";
var dateTime = DateTime.ParseExact(dateTimeString, inputFormat, CultureInfo.InvariantCulture);
var output = dateTime.ToString(outputFormat);

Console.WriteLine(output);

Try this, it works for me.

Where does the iPhone Simulator store its data?

if anyone is still experiencing this problem in lion, there is a great article with 19 different tips to view your ~/Library dir. find the article by Dan Frakes here http://www.macworld.com/article/161156/2011/07/view_library_folder_in_lion.html

Remember the directory to the simulator is given below

~/Library/Application Support/iPhone Simulator/User/

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

Regex for checking if a string is strictly alphanumeric

Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$". Use this RegEx in String.matches(Regex), it will return true if the string is alphanumeric, else it will return false.

public boolean isAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    return s.matches(pattern);
}

If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html

Using LINQ to concatenate strings

I did the following quick and dirty when parsing an IIS log file using linq, it worked @ 1 million lines pretty well (15 seconds), although got an out of memory error when trying 2 millions lines.

    static void Main(string[] args)
    {

        Debug.WriteLine(DateTime.Now.ToString() + " entering main");

        // USED THIS DOS COMMAND TO GET ALL THE DAILY FILES INTO A SINGLE FILE: copy *.log target.log 
        string[] lines = File.ReadAllLines(@"C:\Log File Analysis\12-8 E5.log");

        Debug.WriteLine(lines.Count().ToString());

        string[] a = lines.Where(x => !x.StartsWith("#Software:") &&
                                      !x.StartsWith("#Version:") &&
                                      !x.StartsWith("#Date:") &&
                                      !x.StartsWith("#Fields:") &&
                                      !x.Contains("_vti_") &&
                                      !x.Contains("/c$") &&
                                      !x.Contains("/favicon.ico") &&
                                      !x.Contains("/ - 80")
                                 ).ToArray();

        Debug.WriteLine(a.Count().ToString());

        string[] b = a
                    .Select(l => l.Split(' '))
                    .Select(words => string.Join(",", words))
                    .ToArray()
                    ;

        System.IO.File.WriteAllLines(@"C:\Log File Analysis\12-8 E5.csv", b);

        Debug.WriteLine(DateTime.Now.ToString() + " leaving main");

    }

The real reason I used linq was for a Distinct() I neede previously:

string[] b = a
    .Select(l => l.Split(' '))
    .Where(l => l.Length > 11)
    .Select(words => string.Format("{0},{1}",
        words[6].ToUpper(), // virtual dir / service
        words[10]) // client ip
    ).Distinct().ToArray()
    ;

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

How to add an action to a UIAlertView button using Swift iOS

this is for swift 4.2, 5 and 5+

let alert = UIAlertController(title: "ooops!", message: "Unable to login", preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))

self.present(alert, animated: true)

What REALLY happens when you don't free after malloc?

I think that your two examples are actually only one: the free() should occur only at the end of the process, which as you point out is useless since the process is terminating.

In you second example though, the only difference is that you allow an undefined number of malloc(), which could lead to running out of memory. The only way to handle the situation is to check the return code of malloc() and act accordingly.

How to list running screen sessions?

In most cases a screen -RRx $username/ will suffice :)

If you still want to list all screens then put the following script in your path and call it screen or whatever you like:

#!/bin/bash
if [[ "$1" != "-ls-all" ]]; then
    exec /usr/bin/screen "$@"
else
    shopt -s nullglob
    screens=(/var/run/screen/S-*/*)
    if (( ${#screens[@]} == 0 )); then
        echo "no screen session found in /var/run/screen"
    else
        echo "${screens[@]#*S-}"
    fi
fi

It will behave exactly like screen except for showing all screen sessions, when giving the option -ls-all as first parameter.

What is the difference between application server and web server?

The main difference between Web server and application server is that web server is meant to serve static pages e.g. HTML and CSS, while Application Server is responsible for generating dynamic content by executing server side code e.g. JSP, Servlet or EJB.

Which one should i use?
Once you know the difference between web and application server and web containers, it's easy to figure out when to use them. You need a web server like Apache HTTPD if you are serving static web pages. If you have a Java application with just JSP and Servlet to generate dynamic content then you need web containers like Tomcat or Jetty. While, if you have Java EE application using EJB, distributed transaction, messaging and other fancy features than you need a full fledged application server like JBoss, WebSphere or Oracle's WebLogic.

Web container is a part of Web Server and the Web Server is a part of Application Server.

Application Server

Web Server is composed of web container, while Application Server is composed of web container as well as EJB container.

Git pull command from different user

Was looking for the solution of a similar problem. Thanks to the answer provided by Davlet and Cupcake I was able to solve my problem.

Posting this answer here since I think this is the intended question

So I guess generally the problem that people like me face is what to do when a repo is cloned by another user on a server and that user is no longer associated with the repo.

How to pull from the repo without using the credentials of the old user ?

You edit the .git/config file of your repo.

and change

url = https://<old-username>@github.com/abc/repo.git/

to

url = https://<new-username>@github.com/abc/repo.git/

After saving the changes, from now onwards git pull will pull data while using credentials of the new user.

I hope this helps anyone with a similar problem

nodejs npm global config missing on windows

There is a problem with upgrading npm under Windows. The inital install done as part of the nodejs install using an msi package will create an npmrc file:

C:\Program Files\nodejs\node_modules\npm\npmrc

when you update npm using:

npm install -g npm@latest

it will install the new version in:

C:\Users\Jack\AppData\Roaming\npm

assuming that your name is Jack, which is %APPDATA%\npm.

The new install does not include an npmrc file and without it the global root directory will be based on where node was run from, hence it is C:\Program Files\nodejs\node_modules

You can check this by running:

npm root -g

This will not work as npm does not have permission to write into the "Program Files" directory. You need to copy the npmrc file from the original install into the new install. By default the file only has the line below:

prefix=${APPDATA}\npm

How to get current page URL in MVC 3

I too was looking for this for Facebook reasons and none of the answers given so far worked as needed or are too complicated.

@Request.Url.GetLeftPart(UriPartial.Path)

Gets the full protocol, host and path "without" the querystring. Also includes the port if you are using something other than the default 80.

TSQL - Cast string to integer or return default value

As has been mentioned, you may run into several issues if you use ISNUMERIC:

-- Incorrectly gives 0:
SELECT CASE WHEN ISNUMERIC('-') = 1 THEN CAST('-' AS INT) END   

-- Error (conversion failure):
SELECT CASE WHEN ISNUMERIC('$') = 1 THEN CAST('$' AS INT) END
SELECT CASE WHEN ISNUMERIC('4.4') = 1 THEN CAST('4.4' AS INT) END
SELECT CASE WHEN ISNUMERIC('1,300') = 1 THEN CAST('1,300' AS INT) END

-- Error (overflow):
SELECT CASE WHEN ISNUMERIC('9999999999') = 1 THEN CAST('9999999999' AS INT) END

If you want a reliable conversion, you'll need to code one yourself.

Update: My new recommendation would be to use an intermediary test conversion to FLOAT to validate the number. This approach is based on adrianm's comment. The logic can be defined as an inline table-valued function:

CREATE FUNCTION TryConvertInt (@text NVARCHAR(MAX)) 
RETURNS TABLE
AS
RETURN
(
    SELECT
        CASE WHEN ISNUMERIC(@text + '.e0') = 1 THEN 
             CASE WHEN CONVERT(FLOAT, @text) BETWEEN -2147483648 AND 2147483647 
                  THEN CONVERT(INT, @text) 
             END 
         END AS [Result]
)

Some tests:

SELECT [Conversion].[Result]
FROM ( VALUES
     ( '1234'                     )   -- 1234
   , ( '1,234'                    )   -- NULL
   , ( '1234.0'                   )   -- NULL
   , ( '-1234'                    )   -- -1234
   , ( '$1234'                    )   -- NULL
   , ( '1234e10'                  )   -- NULL
   , ( '1234 5678'                )   -- NULL
   , ( '123-456'                  )   -- NULL
   , ( '1234.5'                   )   -- NULL
   , ( '123456789000000'          )   -- NULL
   , ( 'N/A'                      )   -- NULL
   , ( '-'                        )   -- NULL
   , ( '$'                        )   -- NULL
   , ( '4.4'                      )   -- NULL
   , ( '1,300'                    )   -- NULL
   , ( '9999999999'               )   -- NULL
   , ( '00000000000000001234'     )   -- 1234
   , ( '212110090000000235698741' )   -- NULL
) AS [Source] ([Text])
OUTER APPLY TryConvertInt ([Source].[Text]) AS [Conversion]

Results are similar to Joseph Sturtevant's answer, with the following main differences:

  • My logic does not tolerate occurrences of . or , in order to mimic the behaviour of native INT conversions. '1,234' and '1234.0' return NULL.
  • Since it does not use local variables, my function can be defined as an inline table-valued function, allowing for better query optimization.
  • Joseph's answer can lead to incorrect results due to silent truncations of the argument; '00000000000000001234' evaluates to 12. Increasing the parameter length would result in errors on numbers that overflow BIGINT, such as BBANs (basic bank account numbers) like '212110090000000235698741'.

Withdrawn: The approach below is no longer recommended, as is left just for reference.

The snippet below works on non-negative integers. It checks that your string does not contain any non-digit characters, is not empty, and does not overflow (by exceeding the maximum value for the int type). However, it also gives NULL for valid integers whose length exceeds 10 characters due to leading zeros.

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 
                OR LEN(@text) = 10 AND @text <= '2147483647' 
              THEN CAST (@text AS INT)
         END
    END 

If you want to support any number of leading zeros, use the below. The nested CASE statements, albeit unwieldy, are required to promote short-circuit evaluation and reduce the likelihood of errors (arising, for example, from passing a negative length to LEFT).

SELECT 
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
    END

If you want to support positive and negative integers with any number of leading zeros:

SELECT 
         -- Positive integers (or 0):
    CASE WHEN @text NOT LIKE '%[^0-9]%' THEN
         CASE WHEN LEN(@text) BETWEEN 1 AND 9 THEN CAST (@text AS INT)
              WHEN LEN(@text) >= 10 THEN
              CASE WHEN LEFT(@text, LEN(@text) - 10) NOT LIKE '%[^0]%'
                    AND RIGHT(@text, 10) <= '2147483647'
                   THEN CAST (@text AS INT)
              END
         END
         -- Negative integers:
         WHEN LEFT(@text, 1) = '-' THEN
         CASE WHEN RIGHT(@text, LEN(@text) - 1) NOT LIKE '%[^0-9]%' THEN
              CASE WHEN LEN(@text) BETWEEN 2 AND 10 THEN CAST (@text AS INT)
                   WHEN LEN(@text) >= 11 THEN
                   CASE WHEN SUBSTRING(@text, 2, LEN(@text) - 11) NOT LIKE '%[^0]%'
                         AND RIGHT(@text, 10) <= '2147483648'
                        THEN CAST (@text AS INT)
                   END
              END
         END
    END

How to get JSON from webpage into Python script

In Python 2, json.load() will work instead of json.loads()

import json
import urllib

url = 'https://api.github.com/users?since=100'
output = json.load(urllib.urlopen(url))
print(output)

Unfortunately, that doesn't work in Python 3. json.load is just a wrapper around json.loads that calls read() for a file-like object. json.loads requires a string object and the output of urllib.urlopen(url).read() is a bytes object. So one has to get the file encoding in order to make it work in Python 3.

In this example we query the headers for the encoding and fall back to utf-8 if we don't get one. The headers object is different between Python 2 and 3 so it has to be done different ways. Using requests would avoid all this, but sometimes you need to stick to the standard library.

import json
from six.moves.urllib.request import urlopen

DEFAULT_ENCODING = 'utf-8'
url = 'https://api.github.com/users?since=100'
urlResponse = urlopen(url)

if hasattr(urlResponse.headers, 'get_content_charset'):
    encoding = urlResponse.headers.get_content_charset(DEFAULT_ENCODING)
else:
    encoding = urlResponse.headers.getparam('charset') or DEFAULT_ENCODING

output = json.loads(urlResponse.read().decode(encoding))
print(output)

Why does flexbox stretch my image rather than retaining aspect ratio?

It is stretching because align-self default value is stretch. there is two solution for this case : 1. set img align-self : center OR 2. set parent align-items : center

img {

   align-self: center
}

OR

.parent {
  align-items: center
}

how to set background image in submit button?

i do it like this cover button and the middle image that

<button><img src="foldername/imagename" width="30px" height= "30px"></button>

How do you make div elements display inline?

<div class="cdiv">
<div class="inline"><p>para 1</p></div>
 <div class="inline">
     <p>para 1</p>
     <span>para 2</span>
     <h1>para 3</h1>
</div>
 <div class="inline"><p>para 1</p></div>

http://jsfiddle.net/f8L0y5wx/

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Context.startForegroundService() did not then call Service.startForeground()

Even after calling the startForeground in Service, It crashes on some devices if we call stopService just before onCreate is called. So, I fixed this issue by Starting the service with an additional flag:

Intent intent = new Intent(context, YourService.class);
intent.putExtra("request_stop", true);
context.startService(intent);

and added a check in onStartCommand to see if it was started to stop:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //call startForeground first
    if (intent != null) {
        boolean stopService = intent.getBooleanExtra("request_stop", false);
        if (stopService) {
            stopSelf();
        }
    }

    //Continue with the background task
    return START_STICKY;
}

P.S. If the service were not running, it would start the service first, which is an overhead.

POST data in JSON format

Another example is available here:

Sending a JSON to server and retrieving a JSON in return, without JQuery

Which is the same as jans answer, but also checks the servers response by setting a onreadystatechange callback on the XMLHttpRequest.

XAMPP installation on Win 8.1 with UAC Warning

You can solve this problem by installing xampp in different Drive .Instead of C Drive .

How does #include <bits/stdc++.h> work in C++?

#include <bits/stdc++.h> is an implementation file for a precompiled header.

From, software engineering perspective, it is a good idea to minimize the include. If you use it actually includes a lot of files, which your program may not need, thus increase both compile-time and program size unnecessarily. [edit: as pointed out by @Swordfish in the comments that the output program size remains unaffected. But still, it's good practice to include only the libraries you actually need, unless it's some competitive competition]

But in contests, using this file is a good idea, when you want to reduce the time wasted in doing chores; especially when your rank is time-sensitive.

It works in most online judges, programming contest environments, including ACM-ICPC (Sub-Regionals, Regionals, and World Finals) and many online judges.

The disadvantages of it are that it:

  • increases the compilation time.
  • uses an internal non-standard header file of the GNU C++ library, and so will not compile in MSVC, XCode, and many other compilers

How can I limit ngFor repeat to some number of items in Angular?

This seems simpler to me

<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>

Closer to your approach

<ng-container *ngFor="let item of list" let-i="index">
  <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>

Generic deep diff between two objects

Here is a JavaScript library which you can use for finding diff between two JavaScript objects:

Github URL: https://github.com/cosmicanant/recursive-diff

Npmjs url: https://www.npmjs.com/package/recursive-diff

You can use recursive-diff library in browser as well as Node.js. For browser, do the following:

<script type="text" src="https://unpkg.com/recursive-diff@latest/dist/recursive-diff.min.js"/>
<script type="text/javascript">
     const ob1 = {a:1, b: [2,3]};
     const ob2 = {a:2, b: [3,3,1]};
     const delta = recursiveDiff.getDiff(ob1,ob2); 
     /* console.log(delta) will dump following data 
     [
         {path: ['a'], op: 'update', val: 2}
         {path: ['b', '0'], op: 'update',val: 3},
         {path: ['b',2], op: 'add', val: 1 },
     ]
      */
     const ob3 = recursiveDiff.applyDiff(ob1, delta); //expect ob3 is deep equal to ob2
 </script>

Whereas in node.js you can require 'recursive-diff' module and use it like below:

const diff = require('recursive-diff');
const ob1 = {a: 1}, ob2: {b:2};
const diff = diff.getDiff(ob1, ob2);

How to import a new font into a project - Angular 5

You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:

@font-face {
  font-family: lato;
  src: url(assets/font/Lato.otf) format("opentype");
}

Once done, you can apply this font any where like:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: 'lato', 'arial', sans-serif;
}

You can put the @font-face definition in your global styles.css or styles.scss and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css or styles.scss is already defined in angular-cli.json. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css or styles.scss like:

"styles": [
  "styles.css",
  "fonts.css"
],

jQuery Ajax error handling, show custom exception messages

If someone is here as in 2016 for the answer, use .fail() for error handling as .error() is deprecated as of jQuery 3.0

$.ajax( "example.php" )
  .done(function() {
    alert( "success" );
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    //handle error here
  })

I hope it helps

What are the "spec.ts" files generated by Angular CLI for?

if you generate new angular project using "ng new", you may skip a generating of spec.ts files. For this you should apply --skip-tests option.

ng new ng-app-name --skip-tests

pop/remove items out of a python tuple

In Python 3 this is no longer an issue, and you really don't want to use list comprehension, coercion, filters, functions or lambdas for something like this.

Just use

popped = unpopped[:-1]

Remember that it's an immutable, so you will have to reassign the value if you want it to change

my_tuple = my_tuple[:-1]

Example

>>> foo= 3,5,2,4,78,2,1
>>> foo
(3, 5, 2, 4, 78, 2, 1)
foo[:-1]
(3, 5, 2, 4, 78, 2)

How to go from Blob to ArrayBuffer

This is an async method which first checks for the availability of arrayBuffer method. This function is backward compatible and future proof.

async function blobToArrayBuffer(blob) {
    if ('arrayBuffer' in blob) return await blob.arrayBuffer();
    
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject;
        reader.readAsArrayBuffer(blob);
    });
}

Easiest way to compare arrays in C#

Use Enumerable.SequenceEqual in LINQ.

int[] arr1 = new int[] { 1,2,3};
int[] arr2 = new int[] { 3,2,1 };

Console.WriteLine(arr1.SequenceEqual(arr2)); // false
Console.WriteLine(arr1.Reverse().SequenceEqual(arr2)); // true

What is the difference between 'protected' and 'protected internal'?

Think about protected internal as applying two access modifier (protected, and internal) on the same field, property or method.

In the real world, imagine we are issuing privilege for people to visit museum:

  1. Everyone inside the city are allowed to visit museum (internal).
  2. Everyone outside of the city that their parents live here are allowed to visit museum (protected).

And we can put them together in these way:

Everyone inside the city (internal) and everyone outside of city that their parents live here (protected) are allowed to visit the museum (protected internal).

Programming world:

internal: The field is available everywhere in the assembly (project). It is like saying it is public in its project scope (but can not being accessed outside of project scope even by those classes outside of assembly which inherit from that class). Every instance of that type can see it in that assembly (project scope).

protected: simply means that all derived classes can see it (inside or outside of assembly). For example derived classes can see the field or method inside its methods and constructors using: base.NameOfProtectedInternal.

So, putting these two access modifier together (protected internal), you have something that can being public inside the project, and can be seen by those which have inherited from that class inside their scope.

They can be written in the internal protected, and does not change the meaning, but it is convenient to write it protected internal.

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Omit rows containing specific column of NA

It is possible to use na.omit for data.table:

na.omit(data, cols = c("x", "z"))

How to Validate a DateTime in C#?

protected static bool CheckDate(DateTime date)
{
    if(new DateTime() == date)      
        return false;       
    else        
        return true;        
} 

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

Git error: "Host Key Verification Failed" when connecting to remote repository

This is happening because github is not currently in your known hosts.

You should be prompted to add github to your known hosts. If this hasn't happened, you can run ssh -T [email protected] to receive the prompt again.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

Here is the slightly different C# version:

driver.Navigate().Refresh();

C++: Converting Hexadecimal to Decimal

This should work as well.

#include <ctype.h>
#include <string.h>

template<typename T = unsigned int>
T Hex2Int(const char* const Hexstr, bool* Overflow)
{
    if (!Hexstr)
        return false;
    if (Overflow)
        *Overflow = false;

    auto between = [](char val, char c1, char c2) { return val >= c1 && val <= c2; };
    size_t len = strlen(Hexstr);
    T result = 0;

    for (size_t i = 0, offset = sizeof(T) << 3; i < len && (int)offset > 0; i++)
    {
        if (between(Hexstr[i], '0', '9'))
            result = result << 4 ^ Hexstr[i] - '0';
        else if (between(tolower(Hexstr[i]), 'a', 'f'))
            result = result << 4 ^ tolower(Hexstr[i]) - ('a' - 10); // Remove the decimal part;
        offset -= 4;
    }
    if (((len + ((len % 2) != 0)) << 2) > (sizeof(T) << 3) && Overflow)
        *Overflow = true;
    return result;
}

The 'Overflow' parameter is optional, so you can leave it NULL.

Example:

auto result = Hex2Int("C0ffee", NULL);
auto result2 = Hex2Int<long>("DeadC0ffe", NULL);

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

This seems to be a thread sync issue on certain Windows machines. If you're having this problem with Windows, try redirecting the output to a file: mvn clean install > output.txt

What's a Good Javascript Time Picker?

CSS Gallery has variety of Time Pickers. Have a look.

Perifer Design's time picker is similar to google one

How to install popper.js with Bootstrap 4?

Here is a work-around:

  1. Create a js directory in the same directory as your index.html
  2. Download popper.min.js from the following site into said js directory https://github.com/FezVrasta/popper.js#installation

e.g.: https://unpkg.com/popper.js/dist/umd/popper.min.js

  1. Change your the src of your script include to look like this:

    src="js/popper.min.js"

Note that you've removed Popper from npm version control, so you'll have to manually download updates.

How to make a <div> always full screen?

Change the body element into a flex container and the div into a flex item:

_x000D_
_x000D_
body {_x000D_
  display: flex;_x000D_
  height: 100vh;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
div {_x000D_
  flex: 1;_x000D_
  background: tan;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to retrieve Request Payload

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.

You can fetch this data with this snippet:

$request_body = file_get_contents('php://input');

If you are passing json, then you can do:

$data = json_decode($request_body);

$data then contains the json data is php array.

php://input is a so called wrapper.

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

How to position the form in the center screen?

Simply set location relative to null after calling pack on the JFrame, that's it.

e.g.,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)

I've just experienced this issue. For me it appeared when some erroneous code was trying to redirect to HTTPS on port 80.

e.g.

https://example.com:80/some/page

by removing the port 80 from the url, the redirect works.

HTTPS by default runs over port 443.

Javascript "Not a Constructor" Exception while creating objects

In my case I'd forgotten the open and close parantheses at the end of the definition of the function wrapping all of my code in the exported module. I.e. I had:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
);

Instead of:

(function () {
  'use strict';

  module.exports.MyClass = class{
  ...
)();

The compiler doesn't complain, but the require statement in the importing module doesn't set the variable it's being assigned to, so it's undefined at the point you try to construct it and it will give the TypeError: MyClass is not a constructor error.

Get Request and Session Parameters and Attributes from JSF pages

In the bean you can use session.getAttribute("attributeName");

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

How to call code behind server method from a client side JavaScript function?

// include jquery.js
//javascript function
var a1="aaa";
var b1="bbb";
                         **pagename/methodname**     *parameters*
CallServerFunction("Default.aspx/FunPubGetTasks", "{a:'" + a1+ "',b:'" + b1+ "'}",
            function(result)
            {

            }
);
function CallServerFunction(StrPriUrl,ObjPriData,CallBackFunction)
 {

    $.ajax({
        type: "post",
        url: StrPriUrl,
        contentType: "application/json; charset=utf-8",
        data: ObjPriData,
        dataType: "json",
        success: function(result) 
        {
            if(CallBackFunction!=null && typeof CallBackFunction !='undefined')
            {
                CallBackFunction(result);
            }

        },
        error: function(result) 
        {
            alert('error occured');
            alert(result.responseText);
            window.location.href="FrmError.aspx?Exception="+result.responseText;
        },
        async: true
    });
 }

//page name is Default.aspx & FunPubGetTasks method
///your code behind function
     [System.Web.Services.WebMethod()]
        public static object FunPubGetTasks(string a, string b)
        {
            //return Ienumerable or array   
        }

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I had this issue also, I solved it instantly with this answer from a similar thread

In my case, I didn't want to delete the dependent record on key deletion. If this is the case in your situation just simply change the Boolean value in the migration to false:

AddForeignKey("dbo.Stories", "StatusId", "dbo.Status", "StatusID", cascadeDelete: false);

Chances are, if you are creating relationships which throw this compiler error but DO want to maintain cascade delete; you have an issue with your relationships.

How to update a plot in matplotlib?

You can also do like the following: This will draw a 10x1 random matrix data on the plot for 50 cycles of the for loop.

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

Found the solution after some searching.

You need to add a <meta> tag in your <head> containing name="theme-color", with your HEX code as the content value. For example:

<meta name="theme-color" content="#999999" />

Update:

If the android device has native dark-mode enabled, then this meta tag is ignored.

Chrome for Android does not use the color on devices with native dark-mode enabled.

source: https://caniuse.com/#search=theme-color

Inserting created_at data with Laravel

Currently (Laravel 5.4) the way to achieve this is:

$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);

How do you convert an entire directory with ffmpeg?

I'm using this one-liner in linux to convert files (usually H265) into something I can play on Kodi without issues:

for f in *.mkv; do ffmpeg -i "$f" -c:v libx264 -crf 28 -c:a aac -b:a 128k output.mkv; mv -f output.mkv "$f"; done

This converts to a temporary file and then replaces the original so the names remain the same after conversion.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Paste this on your command line:

export LC_CTYPE="en_US.UTF-8" 

How to read an external local JSON file in JavaScript?

Using the Fetch API is the easiest solution:

fetch("test.json")
  .then(response => response.json())
  .then(json => console.log(json));

It works perfect in Firefox, but in Chrome you have to customize security setting.

HtmlSpecialChars equivalent in Javascript?

With jQuery it can be like this:

var escapedValue = $('<div/>').text(value).html();

From related question Escaping HTML strings with jQuery

As mentioned in comment double quotes and single quotes are left as-is for this implementation. That means this solution should not be used if you need to make element attribute as a raw html string.

How to start rails server?

in rails 2.3.X,just type following command to start rails server on linux

script/server

and for more help read "README" file which is already created in rails project folder

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

android edittext onchange listener

TextWatcher didn't work for me as it kept firing for every EditText and messing up each others values.

Here is my solution:

public class ConsultantTSView extends Activity {
    .....

    //Submit is called when I push submit button.
    //I wanted to retrieve all EditText(tsHours) values in my HoursList

    public void submit(View view){

        ListView TSDateListView = (ListView) findViewById(R.id.hoursList);
        String value = ((EditText) TSDateListView.getChildAt(0).findViewById(R.id.tsHours)).getText().toString();
    }
}

Hence by using the getChildAt(xx) method you can retrieve any item in the ListView and get the individual item using findViewById. And it will then give the most recent value.

two divs the same line, one dynamic width, one fixed

So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.

Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.

<div id="parent twocols">
  <div class="left"></div>
  <div class="right"></div>
</div>

or

<div id="parent">
  <div class="left"></div>
</div>

So right style is always :

.right {
    float: right;
    width: 200px; /* or whatever value you need */
    /* margin and padding at your discretion */
}

and left style is :

.parent.twocols .left {
    margin-right: 200px; /* according to right div width + margin + padding*/
}

How to subtract hours from a date in Oracle so it affects the day also

you should divide hours by 24 not 11
like this:
select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual

How to redraw DataTable with new data

I was having same issue, and the solution was working but with some alerts and warnings so here is full solution, the key was to check for existing DataTable object or not, if yes just clear the table and add jsonData, if not just create new.

            var table;
            if ($.fn.dataTable.isDataTable('#example')) {
                table = $('#example').DataTable();
                table.clear();
                table.rows.add(jsonData).draw();
            }
            else {
                table = $('#example').DataTable({
                    "data": jsonData,
                    "deferRender": true,
                    "pageLength": 25,
                    "retrieve": true,

Versions

  • JQuery: 3.3.1
  • DataTable: 1.10.20

How do I do a multi-line string in node.js?

Multiline strings are a current part of JavaScript (since ES6) and are supported in node.js v4.0.0 and newer.

var text = `Lorem ipsum dolor 
sit amet, consectetur 
adipisicing 
elit.  `;

console.log(text);

How can I recursively find all files in current and subfolders based on wildcard matching?

Use find for that:

find . -name "foo*"

find needs a starting point, and the . (dot) points to the current directory.

How to change current working directory using a batch file

Specify /D to change the drive also.

CD /D %root%

Cannot create PoolableConnectionFactory

I had the same problem with localhost in the source URL. I resolved with 127.0.0.1 instead of localhost.

jQuery - adding elements into an array

Try this, at the end of the each loop, ids array will contain all the hexcodes.

var ids = [];

    $(document).ready(function($) {
    var $div = $("<div id='hexCodes'></div>").appendTo(document.body), code;
    $(".color_cell").each(function() {
        code = $(this).attr('id');
        ids.push(code);
        $div.append(code + "<br />");
    });



});

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

What are public, private and protected in object oriented programming?

They aren't really concepts but rather specific keywords that tend to occur (with slightly different semantics) in popular languages like C++ and Java.

Essentially, they are meant to allow a class to restrict access to members (fields or functions). The idea is that the less one type is allowed to access in another type, the less dependency can be created. This allows the accessed object to be changed more easily without affecting objects that refer to it.

Broadly speaking, public means everyone is allowed to access, private means that only members of the same class are allowed to access, and protected means that members of subclasses are also allowed. However, each language adds its own things to this. For example, C++ allows you to inherit non-publicly. In Java, there is also a default (package) access level, and there are rules about internal classes, etc.

Can't install Scipy through pip

If you are using CentOS you need to install lapack-devel like so:

 $ yum install lapack-devel

How to add additional libraries to Visual Studio project?

For Visual Studio you'll want to right click on your project in the solution explorer and then click on Properties.

Next open Configuration Properties and then Linker.

Now you want to add the folder you have the Allegro libraries in to Additional Library Directories,

Linker -> Input you'll add the actual library files under Additional Dependencies.

For the Header Files you'll also want to include their directories under C/C++ -> Additional Include Directories.

If there is a dll have a copy of it in your main project folder, and done.

I would recommend putting the Allegro files in the your project folder and then using local references in for the library and header directories.

Doing this will allow you to run the application on other computers without having to install Allergo on the other computer.

This was written for Visual Studio 2008. For 2010 it should be roughly the same.

How to use JavaScript regex over multiple lines?

You do not specify your environment and version of Javascript (ECMAscript), and I realise this post was from 2009, but just for completeness, with the release of ECMA2018 we can now use the s flag to cause . to match '\n', see https://stackoverflow.com/a/36006948/141801

Thus:

let s = 'I am a string\nover several\nlines.';
console.log('String: "' + s + '".');

let r = /string.*several.*lines/s; // Note 's' modifier
console.log('Match? ' + r.test(s); // 'test' returns true

This is a recent addition and will not work in many current environments, for example Node v8.7.0 does not seem to recognise it, but it works in Chromium, and I'm using it in a Typescript test I'm writing and presumably it will become more mainstream as time goes by.

Split string into strings by length?

# spliting a string by the length of the string

def len_split(string,sub_string):
    n,sub,str1=list(string),len(sub_string),')/^0*/-'
    for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
        n.insert(i,str1)   
    n="".join(n)
    n=n.split(str1)
    return n

x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))

# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

How is a CRC32 checksum calculated?

In addition to the Wikipedia Cyclic redundancy check and Computation of CRC articles, I found a paper entitled Reversing CRC - Theory and Practice* to be a good reference.

There are essentially three approaches for computing a CRC: an algebraic approach, a bit-oriented approach, and a table-driven approach. In Reversing CRC - Theory and Practice*, each of these three algorithms/approaches is explained in theory accompanied in the APPENDIX by an implementation for the CRC32 in the C programming language.

* PDF Link
Reversing CRC – Theory and Practice.
HU Berlin Public Report
SAR-PR-2006-05
May 2006
Authors:
Martin Stigge, Henryk Plötz, Wolf Müller, Jens-Peter Redlich

How to put comments in Django templates

Multiline comment in django templates use as follows ex: for .html etc.

{% comment %} All inside this tags are treated as comment {% endcomment %}

How to configure Fiddler to listen to localhost?

This is easy. Just grab your computer's IP address with IPconfig at the command prompt. Then, hit the service using the IP address rather than localhost. You don't need to do anything to Fiddler to make this work, it will just work by itself.

How could I create a list in c++?

I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.

First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:

struct Node {
    int data;
    Node * next;
};

Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:

Node a={1}, b={20, &a}, c={35, &b} d={42, &c};

Now, you have have a linked list of nodes, all allocated on the stack:

d -> c -> b -> a
42   35   20   1

Next step is to write a wrapper class List that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):

class List {
    struct Node {
        int data;
        Node * next;
    };

    Node * head;

public:
    List() {
        head = NULL;
    }

    ~List() {
        while(head != NULL) {
            Node * n = head->next;
            delete head;
            head = n;
        }
    }

    void add(int value) {
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }

    // ...
};

Next step is to make the List a template, so that you can stuff other values (not only integers).

If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.

HTTP POST with URL query parameters -- good idea or not?

It would be fine to use query parameters on a POST endpoint, provided they refer to already existing resources.

For example:

POST /user_settings?user_id=4
{
  "use_safe_mode": 1
}

The POST above has a query parameter referring to an existing resource. The body parameter defines the new resource to be created.

(Granted, this may be more of a personal preference than a dogmatic principle.)

How to convert string to date to string in Swift iOS?

//String to Date Convert

var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)


//CONVERT FROM NSDate to String  

let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" 
var dateString = dateFormatter.stringFromDate(date)
println(dateString)  

PHP JSON String, escape Double Quotes for JS output

Error come on script not in HTML tags.

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<pre><?php print_r($_POST??'') ?></pre>

<form method="POST">
    <input type="text" name="name"><br>
    <input type="email" name="email"><br>
    <input type="time" name="time"><br>
    <input type="date" name="date"><br>
    <input type="hidden" name="id"><br>
    <textarea name="detail"></textarea>
    <input type="submit" value="Submit"><br>
</form>
<?php 
/* data */
$data = [
            'name'=>'loKESH"'."'\\\\",
            'email'=>'[email protected]',
            'time'=>date('H:i:00'),
            'date'=>date('Y-m-d'),
            'detail'=>'Try this var_dump(0=="ZERO") \\ \\"'." ' \\\\    ",
            'id'=>123,
        ];
?>
<span style="display: none;" class="ajax-data"><?=json_encode($_POST??$data)?></span>
<script type="text/javascript">
    /* Error */
    // var json = JSON.parse('<?=json_encode($data)?>');
    /* Error solved */
    var json = JSON.parse($('.ajax-data').html());
    console.log(json)
    /* automatically assigned value by name attr */
    for(x in json){
        $('[name="'+x+'"]').val(json[x]);
    }
</script>

jQuery - How to dynamically add a validation rule

You need to call .validate() before you can add rules this way, like this:

$("#myForm").validate(); //sets up the validator
$("input[id*=Hours]").rules("add", "required");

The .validate() documentation is a good guide, here's the blurb about .rules("add", option):

Adds the specified rules and returns all rules for the first matched element. Requires that the parent form is validated, that is, $("form").validate() is called first.

In R, how to find the standard error of the mean?

You can use the function stat.desc from pastec package.

library(pastec)
stat.desc(x, BASIC =TRUE, NORMAL =TRUE)

you can find more about it from here: https://www.rdocumentation.org/packages/pastecs/versions/1.3.21/topics/stat.desc

How to put a jar in classpath in Eclipse?

Right click on the project in which you want to put jar file. A window will open like this

enter image description here

Click on the AddExternal Jars there you can give the path to that jar file

Can we call the function written in one JavaScript in another JS file?

Well, I came across another sweet solution.

window['functioName'](params);

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

How to set a CMake option() at command line

An additional option is to go to your build folder and use the command ccmake .

This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.

The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .

Get The Current Domain Name With Javascript (Not the path, etc.)

What about this function?

window.location.hostname.match(/\w*\.\w*$/gi)[0]

This will match only the domain name regardless if its a subdomain or a main domain

RESTful web service - how to authenticate requests from other services?

Besides authentication, I suggest you think about the big picture. Consider make your backend RESTful service without any authentication; then put some very simple authentication required middle layer service between the end user and the backend service.

How can I check if a string contains a character in C#?

here is an example what most of have done

using System;

class Program
{
    static void Main()
    {
        Test("Dot Net Perls");
        Test("dot net perls");
    }

    static void Test(string input)
    {
        Console.Write("--- ");
        Console.Write(input);
        Console.WriteLine(" ---");
        //
        // See if the string contains 'Net'
        //
        bool contains = input.Contains("Net");
        //
        // Write the result
        //
        Console.Write("Contains 'Net': ");
        Console.WriteLine(contains);
        //
        // See if the string contains 'perls' lowercase
        //
        if (input.Contains("perls"))
        {
            Console.WriteLine("Contains 'perls'");
        }
        //
        // See if the string contains 'Dot'
        //
        if (!input.Contains("Dot"))
        {
            Console.WriteLine("Doesn't Contain 'Dot'");
        }
    }
}

Java Programming: call an exe from Java and passing parameters

You're on the right track. The two constructors accept arguments, or you can specify them post-construction with ProcessBuilder#command(java.util.List) and ProcessBuilder#command(String...).

How do I change the owner of a SQL Server database?

Here is a way to change the owner on ALL DBS (excluding System)

EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
 exec sp_changedbowner ''sa''
END
'

Angular 2 Sibling Component Communication

Behaviour subjects. I wrote a blog about that.

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
private noId = new BehaviorSubject<number>(0); 
  defaultId = this.noId.asObservable();

newId(urlId) {
 this.noId.next(urlId); 
 }

In this example i am declaring a noid behavior subject of type number. Also it is an observable. And if "something happend" this will change with the new(){} function.

So, in the sibling's components, one will call the function, to make the change, and the other one will be affected by that change, or vice-versa.

For example, I get the id from the URL and update the noid from the behavior subject.

public getId () {
  const id = +this.route.snapshot.paramMap.get('id'); 
  return id; 
}

ngOnInit(): void { 
 const id = +this.getId ();
 this.taskService.newId(id) 
}

And from the other side, I can ask if that ID is "what ever i want" and make a choice after that, in my case if i want to delte a task, and that task is the current url, it have to redirect me to the home:

delete(task: Task): void { 
  //we save the id , cuz after the delete function, we  gonna lose it 
  const oldId = task.id; 
  this.taskService.deleteTask(task) 
      .subscribe(task => { //we call the defaultId function from task.service.
        this.taskService.defaultId //here we are subscribed to the urlId, which give us the id from the view task 
                 .subscribe(urlId => {
            this.urlId = urlId ;
                  if (oldId == urlId ) { 
                // Location.call('/home'); 
                this.router.navigate(['/home']); 
              } 
          }) 
    }) 
}

Is it possible to opt-out of dark mode on iOS 13?

import UIKit

extension UIViewController {

    override open func awakeFromNib() {

        super.awakeFromNib()

        if #available(iOS 13.0, *) {

            overrideUserInterfaceStyle = .light

        }

    }
}

How to add target="_blank" to JavaScript window.location?

I have created a function that allows me to obtain this feature:

function redirect_blank(url) {
  var a = document.createElement('a');
  a.target="_blank";
  a.href=url;
  a.click();
}

How to set selected value on select using selectpicker plugin from bootstrap

Well another way to do it is, with this keyword, you can simply get the object in this and manipulate it's value. Eg :

$("select[name=selValue]").click(
    function() {
        $(this).val(1);
    });

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I ran into this issue due to a silly mistake. Make sure the date actually exists!

For example:

September 31, 2015 does not exist.

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150931'

So this fails with the message:

Error converting data type varchar to datetime.

To fix it, input a valid date:

EXEC dbo.SearchByDateRange @Start = '20150901' , @End = '20150930'

And it executes just fine.

Div width 100% minus fixed amount of pixels

While Guffa's answer works in many situations, in some cases you may not want the left and/or right pieces of padding to be the parent of the center div. In these cases, you can use a block formatting context on the center and float the padding divs left and right. Here's the code

The HTML:

<div class="container">
    <div class="left"></div>
    <div class="right"></div>
    <div class="center"></div>
</div>

The CSS:

.container {
    width: 100px;
    height: 20px;
}

.left, .right {
    width: 20px;
    height: 100%;
    float: left;
    background: black;   
}

.right {
    float: right;
}

.center {
    overflow: auto;
    height: 100%;
    background: blue;
}

I feel that this element hierarchy is more natural when compared to nested nested divs, and better represents what's on the page. Because of this, borders, padding, and margin can be applied normally to all elements (ie: this 'naturality' goes beyond style and has ramifications).

Note that this only works on divs and other elements that share its 'fill 100% of the width by default' property. Inputs, tables, and possibly others will require you to wrap them in a container div and add a little more css to restore this quality. If you're unlucky enough to be in that situation, contact me and I'll dig up the css.

jsfiddle here: jsfiddle.net/RgdeQ

Enjoy!

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

How do I find the authoritative name-server for a domain name?

You can use the whois service. On a UNIX like operating system you would execute the following command. Alternatively you can do it on the web at http://www.internic.net/whois.html.

whois stackoverflow.com

You would get the following response.

...text removed here...

Domain servers in listed order: NS51.DOMAINCONTROL.COM NS52.DOMAINCONTROL.COM

You can use nslookup or dig to find out more information about records for a given domain. This might help you resolve the conflicts you have described.